Commit graph

3384 commits

Author SHA1 Message Date
Carter Anderson
5718a7e74c Release 0.9.1 2022-11-30 17:18:04 -08:00
Carter Anderson
9d33846810 Cherry pick "bevy_reflect: Register missing reflected types for bevy_render (#6725)" (#6811)
This had merge conflicts with the 0.9.1 release branch, so this had to be merged manually. Creating a PR for visibility + a final review.
2022-12-01 00:44:58 +00:00
Mike
4f975d726f try to fix run-examples (#6810)
# Objective

- run examples is failing with `xvfb-run: error: Xvfb failed to start`

## Solution

- rollback ubuntu version for run-examples to 20.04. latest is 22.04

## Notes

- this is just a quick fix and someone should probably get it working on 22.04. I'll make an issue for that if this gets merged.
2022-11-30 16:43:39 -08:00
François
cfbf671267 Move Android example to its own package (#6759)
# Objective

- Fix CI issue with updated `cargo-app`

## Solution

- Move the Android example to its own package. It's not necessary for the CI fix, but it's cleaner, mimic the iOS example, and easier to reuse for someone wanting to setup android support in their project
- Build the package in CI instead of the example


The Android example is still working on my android device with this change 👍
2022-11-30 16:37:49 -08:00
Griffin
4f17cd9754 Add support for Rgb9e5Ufloat textures (#6781)
# Objective

- Support textures in `Rgb9e5Ufloat` format.

## Solution

- Add `TextureFormatPixelInfo` for `Rgb9e5Ufloat`.

Tested this with a `Rgb9e5Ufloat` encoded KTX2 texture.
2022-11-30 13:55:37 -08:00
Hennadii Chernyshchyk
93dc878a69 Fix reflection for PathBuf and OsString (#6776)
# Objective

- `PathBuf` and `OsString` not reflected correctly.

## Solution

- Add missing registrations.
- Add FromReflect impls.
- Always implement `Reflect` for `OsString` just skip `Serialize` and `Deserialize` for unsupported platforms.

---

## Changelog

## Fixed

- Fix reflection for `PathBuf` and `OsString`.
2022-11-30 13:55:27 -08:00
IceSentry
29b09823ee Fix set_cursor_grab_mode to try an alternative mode before giving an error (#6599)
# Objective

- Closes https://github.com/bevyengine/bevy/issues/6590
- The grab mode is platform dependent, this is problematic for bevy users since we can't easily use the recommended way to detect if the feature works like the winit docs recommend https://docs.rs/winit/0.27.5/winit/window/struct.Window.html#method.set_cursor_grab

## Solution

Try to use the grab mode that was requested, if it fails use the other one. Only then log an error if it fails after this step.
2022-11-30 13:55:18 -08:00
Rob Parrett
6733102093 Warn instead of erroring when max_font_atlases is exceeded (#6673)
# Objective

Fixes #6642

In a way that doesn't create any breaking changes, as a possible way to fix the above in a patch release.

## Solution

Don't actually remove font atlases when `max_font_atlases` is exceeded. Add a warning instead.

Keep `TextError::ExceedMaxTextAtlases` and `TextSettings` as-is so we don't break anything.

This is a bit of a cop-out, but the problems revealed by #6642 seem very challenging to fix properly.

Maybe follow up later with something more like https://github.com/rparrett/bevy/commits/remove-max-font-atlases later, if this is the direction we want to go.

## Note

See previous attempt at a "simple fix" that only solved some of the issues: #6666
2022-11-30 13:55:02 -08:00
JoJoJet
fb5c17ab29 impl Reflect for &'static Path (#6755)
# Objective

Fixes #6739 

## Solution

Implement the required traits. They cannot be implemented for `Path` directly, since it is a dynamically-sized type.
2022-11-30 13:54:48 -08:00
Gino Valente
8c204fcdf2 bevy_reflect: Remove ReflectSerialize and ReflectDeserialize registrations from most glam types (#6580)
# Objective

> Part of #6573

When serializing a `DynamicScene` we end up treating almost all non-value types as though their type data doesn't exist. This is because when creating the `DynamicScene` we call `Reflect::clone_value` on the components, which generates a Dynamic type for all non-value types.

What this means is that the `glam` types are treated as though their `ReflectSerialize` registrations don't exist. However, the deserializer _does_ pick up the registration and attempts to use that instead. This results in the deserializer trying to operate on "malformed" data, causing this error:

```
WARN bevy_asset::asset_server: encountered an error while loading an asset: Expected float
```

## Solution

Ideally, we should better handle the serialization of possibly-Dynamic types. However, this runs into issues where the `ReflectSerialize` expects the concrete type and not a Dynamic representation, resulting in a panic:

0aa4147af6/crates/bevy_reflect/src/type_registry.rs (L402-L413)

Since glam types are so heavily used in Bevy (specifically in `Transform` and `GlobalTransform`), it makes sense to just a quick fix in that enables them to be used properly in scenes while a proper solution is found.

This PR simply removes all `ReflectSerialize` and `ReflectDeserialize` registrations from the glam types that are reflected as structs.

---

## Changelog

- Remove `ReflectSerialize` and `ReflectDeserialize` registrations from most glam types

## Migration Guide

This PR removes `ReflectSerialize` and `ReflectDeserialize` registrations from most glam types. This means any code relying on either of those type data existing for those glam types will need to not do that.

This also means that some serialized glam types will need to be updated. For example, here is `Affine3A`:

```rust
// BEFORE
(
  "glam::f32::affine3a::Affine3A": (1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0),

// AFTER
  "glam::f32::affine3a::Affine3A": (
    matrix3: (
      x_axis: (
        x: 1.0,
        y: 0.0,
        z: 0.0,
      ),
      y_axis: (
        x: 0.0,
        y: 1.0,
        z: 0.0,
      ),
      z_axis: (
        x: 0.0,
        y: 0.0,
        z: 1.0,
      ),
    ),
    translation: (
      x: 0.0,
      y: 0.0,
      z: 0.0,
    ),
  )
)
```
2022-11-30 13:54:34 -08:00
Mike
90e76a1c45 await tasks to cancel (#6696)
# Objective

- Fixes https://github.com/bevyengine/bevy/issues/6603

## Solution

- `Task`s will cancel when dropped, but wait until they return Pending before they actually get canceled. That means that if a task panics, it's possible for that error to get propagated to the scope and the scope gets dropped, while scoped tasks in other threads are still running. This is a big problem since scoped task can hold life-timed values that are dropped as the scope is dropped leading to UB.

---

## Changelog

- changed `Scope` to use `FallibleTask` and await the cancellation of all remaining tasks when it's dropped.
2022-11-30 13:54:19 -08:00
Alice Cecile
c7ad98ae19 Remove warning about missed events due to false positives (#6730)
# Objective

- Reverts #5730.
- Fixes #6173, fixes #6596.

## Solution

Remove the warning entirely.

## Changelog

You will no longer be spammed about

> Missed 31 `bevy_input:🐭:MouseMotion` events. Consider
reading from the `EventReader` more often (generally the best
solution) or calling Events::update() less frequently
(normally this is called once per frame). This problem is most
likely due to run criteria/fixed timesteps or consuming events
conditionally. See the Events documentation for
more information.

when you miss events. These warnings were often (but not always) a false positive. You can still check this manually by using `ManualEventReader::missed_events`
2022-11-30 13:51:09 -08:00
Gino Valente
7c17f3f0a0 bevy_reflect: Fix binary deserialization not working for unit structs (#6722)
# Objective 

Fixes #6713

Binary deserialization is failing for unit structs as well as structs with all ignored/skipped fields.

## Solution

Add a check for the number of possible fields in a struct before deserializing. If empty, don't attempt to deserialize any fields (as there will be none).

Note: ~~This does not apply to enums as they do not properly handle skipped fields (see #6721).~~ Enums still do not properly handle skipped fields, but I decided to include the logic for it anyways to account for `#[reflect(ignore)]`'d fields in the meantime.

---

## Changelog

- Fix bug where deserializing unit structs would fail for non-self-describing formats
2022-11-30 13:50:27 -08:00
Aevyrie
0df3b19757 Fix missing sRGB conversion for dithering non-HDR pipelines (#6707)
# Objective

- Fixes #6706 

Zoom in on the shadow in the following images:

## Current bevy/main

### HDR On - correct
![current-hdron](https://user-images.githubusercontent.com/2632925/202943151-ecad3cbe-a76e-46df-bac9-9e590a31a9f3.png)

### HDR Off - incorrect
![current-hdroff](https://user-images.githubusercontent.com/2632925/202943154-34e3f527-a00e-4546-931d-0691204cc6a4.png)

## This PR

### HDR On - correct
![new-hdron](https://user-images.githubusercontent.com/2632925/202943383-081990de-9a14-45bd-ac52-febcc4289079.png)

### HDR Off - corrected
![new-hdroff](https://user-images.githubusercontent.com/2632925/202943388-a3b05d79-a0f3-4b1e-b114-0a9f03efe351.png)

## Close-up comparison

### New
![Screenshot from 2022-11-20 17-46-46](https://user-images.githubusercontent.com/2632925/202943552-d45c3a48-841e-47a6-981f-776c5a9563f6.png)

### Old
![Screenshot from 2022-11-20 17-46-41](https://user-images.githubusercontent.com/2632925/202943562-555cb5a2-2b20-45f9-b250-89f2bc87af5f.png)

## Solution

- It turns out there was an outright missing sRGB conversion for dithering non-HDR cameras.
- I also tried using a precise sRGB conversion, but it had no apparent effect on the final image.

---

## Changelog

- Fix deband dithering intensity for non-HDR pipelines.
2022-11-30 13:50:14 -08:00
Jakob Hellermann
3643074f21 fix mutable aliases for a very short time if WorldCell is already borrowed (#6639)
# Objective

Consider the test
```rust
let cell = world.cell();
let _value_a = cell.resource_mut::<A>();
let _value_b = cell.resource_mut::<A>();
```

Currently, this will roughly execute

```rust
// first call
let value = unsafe {
    self.world
    .get_non_send_unchecked_mut_with_id(component_id)?
};
return Some(WorldBorrowMut::new(value, archetype_component_id, self.access)))

// second call
let value = unsafe {
    self.world
    .get_non_send_unchecked_mut_with_id(component_id)?
};
return Some(WorldBorrowMut::new(value, archetype_component_id, self.access)))
```
where `WorldBorrowMut::new` will panic if the resource is already borrowed.

This means, that `_value_a` will be created, the access checked (OK), then `value_b` will be created, and the access checked (`panic`).
For a moment, both `_value_a` and `_value_b` existed as `&mut T` to the same location, which is insta-UB as far as I understand it.

## Solution
Flip the order so that `WorldBorrowMut::new` first checks the access, _then_ fetches creates the value. To do that, we pass a `impl FnOnce() -> Mut<T>` instead of the `Mut<T>` directly:

```rust
let get_value = || unsafe {
    self.world
    .get_non_send_unchecked_mut_with_id(component_id)?
};
return Some(WorldBorrowMut::new(get_value, archetype_component_id, self.access)))
```
2022-11-30 13:50:03 -08:00
Ida Iyes
5265b47c68 Fix PipeSystem panicking with exclusive systems (#6698)
Without this fix, piped systems containing exclusive systems fail to run, giving a runtime panic.
With this PR, running piped systems that contain exclusive systems now works.

## Explanation of the bug

This is because, unless overridden, the default implementation of `run` from the `System` trait simply calls `run_unsafe`. That is not valid for exclusive systems. They must always be called via `run`, as `run_unsafe` takes `&World` instead of `&mut World`.

Trivial reproduction example:
```rust
fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        .add_system(exclusive.pipe(another))
        .run();
}

fn exclusive(_world: &mut World) {}
fn another() {}
```
If you run this, you will get a panic 'Cannot run exclusive systems with a shared World reference' and the backtrace shows how bevy (correctly) tries to call the `run` method (because the system is exclusive), but it is the implementation from the `System` trait (because `PipeSystem` does not have its own), which calls `run_unsafe` (incorrect):
 - 3: <bevy_ecs::system::system_piping::PipeSystem<SystemA,SystemB> as bevy_ecs::system::system::System>::run_unsafe
 - 4: bevy_ecs::system::system::System::run
2022-11-30 13:49:47 -08:00
James Liu
efbeacfa69 Fix panicking on another scope (#6524)
# Objective
Fix #6453. 

## Solution
Use the solution mentioned in the issue by catching the unwind and dropping the error. Wrap the `executor.try_tick` calls with `std::catch::unwind`.

Ideally this would be moved outside of the hot loop, but the mut ref to the `spawned` future is not `UnwindSafe`.

This PR only addresses the bug, we can address the perf issues (should there be any) later.
2022-11-30 13:49:35 -08:00
Nicola Papale
a2c0f65a71 Fix size_hint for partially consumed QueryIter and QueryCombinationIter (#5214)
# Objective

Fix #5149

## Solution

Instead of returning the **total count** of elements in the `QueryIter` in
`size_hint`, we return the **count of remaining elements**. This
Fixes #5149 even when #5148 gets merged.

- https://github.com/bevyengine/bevy/issues/5149
- https://github.com/bevyengine/bevy/pull/5148

---

## Changelog

- Fix partially consumed `QueryIter` and `QueryCombinationIter` having invalid `size_hint`


Co-authored-by: Nicola Papale <nicopap@users.noreply.github.com>
2022-11-30 13:49:20 -08:00
Patrick Towles
49ff9bb156 Removed Mobile Touch event y-axis flip (#6597)
# Objective

Fix android touch events being flipped.  Only removed test for android, don't have ios device to test with.  Tested with emulator and physical device.

## Solution

Remove check, no longer needed with coordinate change in 0.9
2022-11-30 13:49:08 -08:00
研究社交
abad737363 Make Core Pipeline Graph Nodes Public (#6605)
# Objective

Make core pipeline graphic nodes, including `BloomNode`, `FxaaNode`, `TonemappingNode` and `UpscalingNode` public.
This will allow users to construct their own render graphs with these build-in nodes.

## Solution

Make them public.
Also put node names into bevy's core namespace (`core_2d::graph::node`, `core_3d::graph::node`) which makes them consistent.
2022-11-30 13:48:54 -08:00
François
fd08c7de58 wasm: pad globals uniform also in 2d (#6643)
# Objective

- Fix a panic in wasm when using globals in a shader

## Solution

- Similar to #6460
2022-11-30 13:48:24 -08:00
James Liu
dbbd023a1b Replace BlobVec's swap_scratch with a swap_nonoverlapping (#4853)
# Objective
BlobVec currently relies on a scratch piece of memory allocated at initialization to make a temporary copy of a component when using `swap_remove_and_{forget/drop}`. This is potentially suboptimal as it writes to a, well-known, but random part of memory instead of using the stack.

## Solution
As the `FIXME` in the file states, replace `swap_scratch` with a call to `swap_nonoverlapping::<u8>`. The swapped last entry is returned as a `OwnedPtr`.

In theory, this should be faster as the temporary swap is allocated on the stack, `swap_nonoverlapping` allows for easier vectorization for bigger types, and the same memory is used between the swap and the returned `OwnedPtr`.
2022-11-30 13:47:06 -08:00
Nicola Papale
f47c65e640 Fix FilteredAccessSet get_conflicts inconsistency (#5105)
# Objective

* Enable `Res` and `Query` parameter mutual exclusion
* Required for https://github.com/bevyengine/bevy/pull/5080

The `FilteredAccessSet::get_conflicts` methods didn't work properly with
`Res` and `ResMut` parameters. Because those added their access by using
the `combined_access_mut` method and directly modifying the global
access state of the FilteredAccessSet. This caused an inconsistency,
because get_conflicts assumes that ALL added access have a corresponding
`FilteredAccess` added to the `filtered_accesses` field.

In practice, that means that SystemParam that adds their access through
the `Access` returned by `combined_access_mut` and the ones that add
their access using the `add` method lived in two different universes. As
a result, they could never be mutually exclusive.

## Solution

This commit fixes it by removing the `combined_access_mut` method. This
ensures that the `combined_access` field of FilteredAccessSet is always
updated consistently with the addition of a filter. When checking for
filtered access, it is now possible to account for `Res` and `ResMut`
invalid access. This is currently not needed, but might be in the
future.

We add the `add_unfiltered_{read,write}` methods to replace previous
usages of `combined_access_mut`.

We also add improved Debug implementations on FixedBitSet so that their
meaning is much clearer in debug output.


---

## Changelog

* Fix `Res` and `Query` parameter never being mutually exclusive.

## Migration Guide

Note: this mostly changes ECS internals, but since the API is public, it is technically breaking:
* Removed `FilteredAccessSet::combined_access_mut`
  * Replace _immutable_ usage of those by `combined_access`
  * For _mutable_ usages, use the new `add_unfiltered_{read,write}` methods instead of `combined_access_mut` followed by `add_{read,write}`
2022-11-30 13:46:27 -08:00
James Liu
e30019bbec Bump gilrs version to 0.10 (#6558)
# Objective
Fix #6555.

## Solution
Bump `gilrs` version to 0.10.
2022-11-30 13:46:11 -08:00
James Liu
97d94b66c0 Fix get_unchecked_manual using archetype index instead of table row. (#6625)
# Objective
Fix #6623.

## Solution
Use the right table row instead of the `EntityLocation` archetype index.
2022-11-30 13:45:54 -08:00
Gino Valente
aaf806d089 bevy_scene: Add missing registration for SmallVec<[Entity; 8]> (#6578)
# Objective

> Part of #6573

`Children` was not being properly deserialized in scenes. This was due to a missing registration on `SmallVec<[Entity; 8]>`, which is used by `Children`.

## Solution

Register `SmallVec<[Entity; 8]>`.

---

## Changelog

- Registered `SmallVec<[Entity; 8]>`
2022-11-30 13:45:41 -08:00
Jakob Hellermann
4c8b85c188 add Resources::iter to iterate over all resource IDs (#6592)
# Objective

In bevy 0.8 you could list all resources using `world.archetypes().resource().components()`. As far as I can tell the resource archetype has been replaced with the `Resources` storage, and it would be nice if it could be used to iterate over all resource component IDs as well.

## Solution

- add `fn Resources::iter(&self) -> impl Iterator<Item = (ComponentId, &ResourceData)>`
2022-11-30 13:45:14 -08:00
JoJoJet
73837839d3 Respect alignment for zero-sized types stored in the world (#6618)
# Objective

Fixes #6615.

`BlobVec` does not respect alignment for zero-sized types, which results in UB whenever a ZST with alignment other than 1 is used in the world.

## Solution

Add the fn `bevy_ptr::dangling_with_align`.

---

## Changelog

+ Added the function `dangling_with_align` to `bevy_ptr`, which creates a well-aligned dangling pointer to a type whose alignment is not known at compile time.
2022-11-30 13:44:52 -08:00
github-actions[bot]
920543c824 Release 0.9.0 (#6568)
Preparing next release
This PR has been auto-generated
2022-11-12 20:01:29 +00:00
Carter Anderson
d0fe37609a Add 0.9.0 changelog (#6567) 2022-11-12 19:45:30 +00:00
James Liu
2179a3ebf4 Make Entity::to_bits const (#6559)
# Objective
Fix #6548. Most of these methods were already made `const` in #5688. `Entity::to_bits` is the only one that remained.

## Solution
Make it const.
2022-11-12 16:15:04 +00:00
Aevyrie
c3c4088317 Fix instancing example for hdr (#6554)
# Objective

- Using the instancing example as reference, I found it was breaking when enabling HDR on the camera. I found that this was because, unlike in internal code, this was not updating the specialization key with `view.hdr`.

## Solution

- Add the missing HDR bit.
2022-11-12 09:31:03 +00:00
Nicola Papale
ffa489a846 Ignore Timeout errors on Linux AMD & Intel (#5957)
# Objective

- Fix #3606
- Fix #4579
- Fix #3380

## Solution

When running on a Linux machine with some AMD or Intel device, when calling
`surface.get_current_texture()`, ignore `wgpu::SurfaceError::Timeout` errors.


## Alternative

An alternative solution found in the `wgpu` examples is:

```rust
let frame = surface
    .get_current_texture()
    .or_else(|_| {
        render_device.configure_surface(surface, &swap_chain_descriptor);
        surface.get_current_texture()
    })
    .expect("Error reconfiguring surface");
window.swap_chain_texture = Some(TextureView::from(frame));
```

See: <94ce76391b/wgpu/examples/framework.rs (L362-L370)>

Veloren [handles the Timeout error the way this PR proposes to handle it](https://github.com/gfx-rs/wgpu/issues/1218#issuecomment-1092056971).

The reason I went with this PR's solution is that `configure_surface` seems to be quite an expensive operation, and it would run every frame with the wgpu framework solution, despite the fact it works perfectly fine without `configure_surface`.

I know this looks super hacky with the linux-specific line and the AMD check, but my understanding is that the `Timeout` occurrence is specific to a quirk of some AMD drivers on linux, and if otherwise met should be considered a bug.


Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2022-11-12 08:06:56 +00:00
ira
7ced5336e6 Fix panic when the primary window is closed (#6545)
Issue introduced by #6533.

Co-authored-by: devil-ira <justthecooldude@gmail.com>
2022-11-12 01:28:31 +00:00
François
4ef192b91a Better bloom default settings (#6546)
# Objective

- Use better defaults for bloom

## Solution

- Divide the intensity by 3. It's still noticeable
- Change the mip level? (not sure about that change, it's from a discussion with @superdump)


### bloom example
main:
<img width="1392" alt="Screenshot 2022-11-11 at 01 09 26" src="https://user-images.githubusercontent.com/8672791/201232996-20d6cf65-2511-41bc-979b-f2c193e4e4e6.png">
this pr:
<img width="1392" alt="Screenshot 2022-11-11 at 01 08 00" src="https://user-images.githubusercontent.com/8672791/201232987-b1ebad2a-4ebf-4296-a91b-aab898544a9d.png">


### bistro scene
main:
<img width="1392" alt="Screenshot 2022-11-11 at 01 16 42" src="https://user-images.githubusercontent.com/8672791/201233028-526999a3-0060-44f7-b0dd-f78666b06c1d.png">
this pr:
<img width="1392" alt="Screenshot 2022-11-11 at 01 15 12" src="https://user-images.githubusercontent.com/8672791/201233044-50201034-e881-40e1-8455-76cabc621a9b.png">
2022-11-11 23:46:45 +00:00
Aevyrie
72fbcc7633 Fix color banding by dithering image before quantization (#5264)
# Objective

- Closes #5262 
- Fix color banding caused by quantization.

## Solution

- Adds dithering to the tonemapping node from #3425.
- This is inspired by Godot's default "debanding" shader: https://gist.github.com/belzecue/
- Unlike Godot:
  - debanding happens after tonemapping. My understanding is that this is preferred, because we are running the debanding at the last moment before quantization (`[f32, f32, f32, f32]` -> `f32`). This ensures we aren't biasing the dithering strength by applying it in a different (linear) color space.
  - This code instead uses and reference the origin source, Valve at GDC 2015

![Screenshot from 2022-11-10 13-44-46](https://user-images.githubusercontent.com/2632925/201218880-70f4cdab-a1ed-44de-a88c-8759e77197f1.png)
![Screenshot from 2022-11-10 13-41-11](https://user-images.githubusercontent.com/2632925/201218883-72393352-b162-41da-88bb-6e54a1e26853.png)


## Additional Notes 

Real time rendering to standard dynamic range outputs is limited to 8 bits of depth per color channel. Internally we keep everything in full 32-bit precision (`vec4<f32>`) inside passes and 16-bit between passes until the image is ready to be displayed, at which point the GPU implicitly converts our `vec4<f32>` into a single 32bit value per pixel, with each channel (rgba) getting 8 of those 32 bits.

### The Problem

8 bits of color depth is simply not enough precision to make each step invisible - we only have 256 values per channel! Human vision can perceive steps in luma to about 14 bits of precision. When drawing a very slight gradient, the transition between steps become visible because with a gradient, neighboring pixels will all jump to the next "step" of precision at the same time.

### The Solution

One solution is to simply output in HDR - more bits of color data means the transition between bands will become smaller. However, not everyone has hardware that supports 10+ bit color depth. Additionally, 10 bit color doesn't even fully solve the issue, banding will result in coherent bands on shallow gradients, but the steps will be harder to perceive.

The solution in this PR adds noise to the signal before it is "quantized" or resampled from 32 to 8 bits. Done naively, it's easy to add unneeded noise to the image. To ensure dithering is correct and absolutely minimal, noise is adding *within* one step of the output color depth. When converting from the 32bit to 8bit signal, the value is rounded to the nearest 8 bit value (0 - 255). Banding occurs around the transition from one value to the next, let's say from 50-51. Dithering will never add more than +/-0.5 bits of noise, so the pixels near this transition might round to 50 instead of 51 but will never round more than one step. This means that the output image won't have excess variance:
  - in a gradient from 49 to 51, there will be a step between each band at 49, 50, and 51.
  - Done correctly, the modified image of this gradient will never have a adjacent pixels more than one step (0-255) from each other.
  - I.e. when scanning across the gradient you should expect to see:
```
                  |-band-| |-band-| |-band-|
Baseline:         49 49 49 50 50 50 51 51 51
Dithered:         49 50 49 50 50 51 50 51 51
Dithered (wrong): 49 50 51 49 50 51 49 51 50
```

![Screenshot from 2022-11-10 14-12-36](https://user-images.githubusercontent.com/2632925/201219075-ab3f46be-d4e9-4869-b66b-a92e1706f49e.png)
![Screenshot from 2022-11-10 14-11-48](https://user-images.githubusercontent.com/2632925/201219079-ec5d2add-817d-487a-8fc1-84569c9cda73.png)




You can see from above how correct dithering "fuzzes" the transition between bands to reduce distinct steps in color, without adding excess noise.

### HDR

The previous section (and this PR) assumes the final output is to an 8-bit texture, however this is not always the case. When Bevy adds HDR support, the dithering code will need to take the per-channel depth into account instead of assuming it to be 0-255. Edit: I talked with Rob about this and it seems like the current solution is okay. We may need to revisit once we have actual HDR final image output.

---

## Changelog

### Added

- All pipelines now support deband dithering. This is enabled by default in 3D, and can be toggled in the `Tonemapping` component in camera bundles. Banding is a graphical artifact created when the rendered image is crunched from high precision (f32 per color channel) down to the final output (u8 per channel in SDR). This results in subtle gradients becoming blocky due to the reduced color precision. Deband dithering applies a small amount of noise to the signal before it is "crunched", which breaks up the hard edges of blocks (bands) of color. Note that this does not add excess noise to the image, as the amount of noise is less than a single step of a color channel - just enough to break up the transition between color blocks in a gradient.


Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2022-11-11 19:43:45 +00:00
Robert Swain
c4e791d628 bevy_pbr: Normalize skinned normals (#6543)
# Objective

- Make the many foxes not unnecessarily bright. Broken since #5666.
- Fixes #6528 

## Solution

- In #5666 normalisation of normals was moved from the fragment stage to the vertex stage. However, it was not added to the vertex stage for skinned normals. The many foxes are skinned and their skinned normals were not unit normals. which made them brighter. Normalising the skinned normals fixes this.

---

## Changelog

- Fixed: Non-unit length skinned normals are now normalized.
2022-11-11 03:31:57 +00:00
ira
99c815fd00 Move the cursor's origin back to the bottom-left (#6533)
This reverts commit 8429b6d6ca as discussed in #6522.

I tested that the game_menu example works as it should.

Co-authored-by: devil-ira <justthecooldude@gmail.com>
2022-11-10 20:10:51 +00:00
ira
9b56b549ad Reuse ndc_to_world matrix in Camera::viewport_to_world (#6532)
# Objective

Solve #6531.


Co-authored-by: devil-ira <justthecooldude@gmail.com>
2022-11-10 16:55:53 +00:00
dataphract
1914a3f288 fix: explicitly specify required version of async-task (#6509)
# Objective

Attempting to build `bevy_tasks` produces the following error:

```
error[E0599]: no method named `is_finished` found for struct `async_executor::Task` in the current scope
  --> /[...]]/bevy/crates/bevy_tasks/src/task.rs:51:16
   |
51 |         self.0.is_finished()
   |                ^^^^^^^^^^^ method not found in `async_executor::Task<T>`

```

It looks like this was introduced along with `Task::is_finished`, which delegates to `async_task::Task::is_finished`. However, the latter was only introduced in `async-task` 4.2.0; `bevy_tasks` does not explicitly depend on `async-task` but on `async-executor` ^1.3.0, which in turn depends on `async-task` ^4.0.0.

## Solution

Add an explicit dependency on `async-task` ^4.2.0.
2022-11-07 21:43:07 +00:00
ira
d688ba5f29 Add send_event and friends to WorldCell (#6515)
# Objective

Copy `send_event` and friends from `World` to `WorldCell`.

Clean up `bevy_winit` using `WorldCell::send_event`.

## Changelog

Added `send_event`, `send_event_default`, and `send_event_batch` to `WorldCell`.

Co-authored-by: devil-ira <justthecooldude@gmail.com>
2022-11-07 21:25:31 +00:00
Jakob Hellermann
4ad621fe0f Reflect for Tonemapping and ClusterConfig (#6488)
# Objective

- it would be useful to inspect these structs using reflection

## Solution

- derive and register reflect
- Note that `#[reflect(Component)]` requires `Default` (or `FromWorld`) until #6060, so I implemented `Default` for `Tonemapping` with `is_enabled: false`
2022-11-07 19:44:17 +00:00
研究社交
0aa17d0aca Macro for Loading Internal Binary Assets (#6478)
# Objective

The `load_internal_asset` macro is helpful when creating rendering plugins, but it doesn't support load binary assets (like those compiled as spir-v).

## Solution

Add a `load_internal_binary_asset` macro that use `include_bytes!`.
2022-11-07 19:44:15 +00:00
Rob Parrett
1170b30785 Fix panic when using globals uniform in wasm builds (#6460)
# Objective

Fixes #5393 

## Solution

- Add padding to `GlobalsUniform` / `Globals` to make it 16-byte aligned.

Still not super clear on whether this is a `naga` thing or an `encase` thing or what. But now that we're offering `globals` up to users and #5393 is not just breaking an example, maybe we should do this sort of workaround?
2022-11-07 19:44:14 +00:00
François
0aab699a84 Update glam 0.22, hexasphere 8.0, encase 0.4 (#6427)
# Objective

- Update glam to 0.22, hexasphere to 8.0, encase to 0.4

## Solution

- Update glam to 0.22, hexasphere to 8.0, encase to 0.4
- ~~waiting on https://github.com/teoxoy/encase/pull/17 and https://github.com/OptimisticPeach/hexasphere/pull/13~~
2022-11-07 19:44:13 +00:00
ira
944b311c67 Improve logging consistency for entity despawning (#6501)
* Move the despawn debug log from `World::despawn` to `EntityMut::despawn`.
 * Move the despawn non-existent warning log from `Commands::despawn` to `World::despawn`.

This should make logging consistent regardless of which of the three `despawn` methods is used.

Co-authored-by: devil-ira <justthecooldude@gmail.com>
2022-11-07 19:23:34 +00:00
Gino Valente
02fbf16c80 bevy_reflect: Add Reflect::into_reflect (#6502)
# Objective

Using `Reflect` we can easily switch between a specific reflection trait object, such as a `dyn Struct`, to a `dyn Reflect` object via `Reflect::as_reflect` or `Reflect::as_reflect_mut`.

```rust
fn do_something(value: &dyn Reflect) {/* ... */}

let foo: Box<dyn Struct> = Box::new(Foo::default());
do_something(foo.as_reflect());
```

However, there is no way to convert a _boxed_ reflection trait object to a `Box<dyn Reflect>`.

## Solution

Add a `Reflect::into_reflect` method which allows converting a boxed reflection trait object back into a boxed `Reflect` trait object.

```rust
fn do_something(value: Box<dyn Reflect>) {/* ... */}

let foo: Box<dyn Struct> = Box::new(Foo::default());
do_something(foo.into_reflect());
```

---

## Changelog

- Added `Reflect::into_reflect`
2022-11-07 02:11:16 +00:00
François
33299f0bad update allowed duplicate dependencies (#6500)
# Objective

- Fix deny issues

## Solution

- Allow new duplicated dependencies
2022-11-06 22:43:52 +00:00
Hennadii Chernyshchyk
efc111c7f2 Add CameraRenderGraph::set (#6470)
# Objective

Some render plugins, like [bevy-hikari](https://github.com/cryscan/bevy-hikari) require to set `CameraRenderGraph`. In order to switch between render graphs I need to insert a new `CameraRenderGraph` component. It's not very ergonomic.

## Solution

Add `CameraRenderGraph::set` like in [Name](https://docs.rs/bevy/latest/bevy/core/struct.Name.html).

---

## Changelog

### Added

- `CameraRenderGraph::set`.
2022-11-06 17:14:10 +00:00
Hennadii Chernyshchyk
feebbc5ea9 Add reflect_owned (#6494)
# Objective

There is no way to gen an owned value of `Reflect`.

## Solution

Add it! This was originally a part of #6421, but @MrGVSV asked me to create a separate for it to implement reflect diffing.

---

## Changelog

### Added

- `Reflect::reflect_owned` to get an owned version of `Reflect`.
2022-11-06 16:58:38 +00:00