Commit graph

3736 commits

Author SHA1 Message Date
François
3900b48c88 update winit to 0.28 (#7480)
# Objective

- Update winit to 0.28

## Solution

- Small API change 
- A security advisory has been added for a unmaintained crate used by a dependency of winit build script for wayland

I didn't do anything for Android support in this PR though it should be fixable, it should be done in a separate one, maybe https://github.com/bevyengine/bevy/pull/6830 

---

## Changelog

- `window.always_on_top` has been removed, you can now use `window.window_level`

## Migration Guide

before:
```rust
    app.new()
        .add_plugins(DefaultPlugins.set(WindowPlugin {
            primary_window: Some(Window {
                always_on_top: true,
                ..default()
            }),
            ..default()
        }));
```

after:
```rust
    app.new()
        .add_plugins(DefaultPlugins.set(WindowPlugin {
            primary_window: Some(Window {
                window_level: bevy:🪟:WindowLevel::AlwaysOnTop,
                ..default()
            }),
            ..default()
        }));
```
2023-02-03 16:41:39 +00:00
JoJoJet
44a572e4e6 Fix ignored lifetimes in #[derive(SystemParam)] (#7458)
# Objective

Fix #7447.

The `SystemParam` derive uses the wrong lifetimes for ignored fields.

## Solution

Use type inference instead of explicitly naming the types of ignored fields. This allows the compiler to automatically use the correct lifetime.
2023-02-03 09:17:48 +00:00
Mike
ff7d5ff444 Stageless: close the finish channel so executor doesn't deadlock (#7448)
# Objective

- Fix panic_when_hierachy_cycle test hanging
- The problem is that the scope only awaits one task at a time in get_results. In stageless this task is the multithreaded executor. That tasks hangs when a system panics and cannot make anymore progress. This wasn't a problem before because the executor was spawned after all the system tasks had been spawned. But in stageless the executor is spawned before all the system tasks are spawned.

## Solution

- We can catch unwind on each system and close the finish channel if one panics. This then causes the receiver end of the finish channel to panic too.
- this might have a small perf impact, but when running many_foxes it seems to be within the noise. So less than 40us.

## Other possible solutions

- It might be possible to fairly poll all the tasks in get_results in the scope. If we could do that then the scope could panic whenever one of tasks panics. It would require a data structure that we could both poll the futures through a shared ref and also push to it. I tried FuturesUnordered, but it requires an exclusive ref to poll it.
- The catch unwind could be moved onto when we create the tasks for scope instead. We would then need something like a oneshot async channel to inform get_results if a task panics.
2023-02-03 07:16:02 +00:00
Jakub Łabor
e1d741aa19 bevy_ecs: ReflectComponentFns without World (#7206)
# Objective

Ability to use `ReflectComponent` methods in dynamic type contexts with no access to `&World`.

This problem occurred to me when wanting to apply reflected types to an entity where the `&World` reference was already consumed by query iterator leaving only `EntityMut`.

## Solution

- Remove redundant `EntityMut` or `EntityRef` lookup from `World` and `Entity` in favor of taking `EntityMut` directly in `ReflectComponentFns`.
- Added `RefectComponent::contains` to determine without panic whether `apply` can be used.

## Changelog

- Changed function signatures of `ReflectComponent` methods, `apply`, `remove`, `contains`, and `reflect`.

## Migration Guide

- Call `World::entity` before calling into the changed `ReflectComponent` methods, most likely user already has a `EntityRef` or `EntityMut` which was being queried redundantly.
2023-02-03 05:53:58 +00:00
Mike
4f3ed196fa Stageless: move MainThreadExecutor to schedule_v3 (#7444)
# Objective

- Trying to move some of the fixes from https://github.com/bevyengine/bevy/pull/7267 to make that one easier to review
- The MainThreadExecutor is how the render world runs nonsend systems on the main thread for pipelined rendering.
- The multithread executor for stageless wasn't using the MainThreadExecutor.
- MainThreadExecutor was declared in the old executor_parallel module that is getting deleted.
- The way the MainThreadExecutor was getting passed to the scope was actually unsound as the resource could be dropped from the World while the schedule was running

## Solution

- Move MainThreadExecutor to the new multithreaded_executor's file.
- Make the multithreaded executor use the MainThreadExecutor
- Clone the MainThreadExecutor onto the stack and pass that ref in

## Changelog

- Move MainThreadExecutor for stageless migration.
2023-02-03 03:19:41 +00:00
Mike
27e20df6de Stageless: move final apply outside of spawned executor (#7445)
# Objective

- After the multithreaded executor finishes running all the systems, we apply the buffers for any system that hasn't applied it's buffers. This is a courtesy apply for users who forget to order their systems before a apply_system_buffers. When checking stageless, it was found that this apply_system_buffers was running on the executor thread instead of the world's thread. This is a problem because anything with world access should be able to access nonsend resources.

## Solution

- Move the final apply_system_buffers outside of the executor and outside of the scope, so it runs on the same thread that schedule.run is called on.
2023-02-03 02:35:20 +00:00
ickshonpe
36320762f4 change the default width and height of Size to Val::Auto (#7475)
# Objective

In CSS Flexbox width and height are auto by default, whereas in Bevy their default is `Size::Undefined`.
This means that, unlike in CSS, if you elide a height or width value for a node it will be given zero length (unless it has an explicitly sized child node). This has misled users into falsely assuming that they have to explicitly set a value for both height and width all the time.

relevant issue: #7120

## Solution

Change the `Size` `width` and `height` default values to `Val::Auto`

## Changelog

* Changed the `Size` `width` and `height` default values to `Val::Auto`

## Migration Guide

The default values for `Size` `width` and `height` have been changed from `Val::Undefined` to `Val::Auto`.
It's unlikely to cause any issues with existing code.
2023-02-03 01:35:06 +00:00
Mike
3ff68b6ddb Stageless: fix unapplied systems (#7446)
# Objective

- The stageless executor keeps track of systems that have run, but have not applied their system buffers. The bitset for that was being cloned into apply_system_buffers and cleared in that function, but we need to clear the original version instead of the cloned version

## Solution

- move the clear out of the apply_system_buffers function.

Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2023-02-03 01:20:11 +00:00
ira
9481a2c8a7 Optimise EventReader::clear() and improve documentation (#7471)
# Objective

Clearing the reader doesn't require iterating the events. Updating the `last_event_count` of the reader is enough.

I rewrote part of the documentation as some of it was incorrect or harder to understand than necessary.

## Changelog

Added `ManualEventReader::clear()`

Co-authored-by: devil-ira <justthecooldude@gmail.com>
2023-02-03 01:03:56 +00:00
ickshonpe
00ff8adfd6 Size::height sets width not height (#7478)
# Objective
```rust
pub const fn height(width: Val) -> Self {
        Self {
            width,
            height: Val::DEFAULT,
        }
    }
```
😓

## Solution
Swap `width` and `height`.
2023-02-02 22:09:21 +00:00
Stephen Martindale
be46d1502b Increment FrameCount in CoreStage::Last. (#7477)
# Objective

During testing, I observed that the `FrameCount` resource (`bevy_core`) was being incremented by `FrameCountPlugin` non-deterministically, during update, subject to the whims of the execution order.

The effect was that the counter could and did change while a frame was still in flight, while user-systems were still executing.

## Solution

I have delayed the incrementing of the `FrameCount` resource to `CoreStage::Last`. The resource was described in the documentation as "*a count of rendered frames*" and, after my change, it actually will match that description.

## Changes

- `CoreStage::Last` was chosen so that the counter will be `0` during all earlier stages of the very first execution of the schedule.
- Documentation added declaring *when* the counter is incremented.
- Hint added, directing users towards `u32::wrapping_sub()` because integer overflow is reasonable to expect.

## Note

Even though this change might have a short time-to-live in light of the upcoming *Stageless* changes, I think this is worthwhile – at least as an in-code reminder that this counter should behave predictably.
2023-02-02 21:06:29 +00:00
MinerSebas
e03982583d Resolve Warnings in Action Summary (#7473)
# Objective

- The CI Summary shows several fixable Warnings.
Example from https://github.com/bevyengine/bevy/actions/runs/4075078887:
![Screenshot_20230202_152644](https://user-images.githubusercontent.com/66798382/216352644-62e9664b-c881-4bc5-9a80-694cef25df76.png)

- The Job `check-compiles` provided an invalid input.
- The Job `check-doc` uses an outdated Version of `actions/cache`.

## Solution

- Remove the invalid `override` input.
- Update `actions/cache@v2` to `actions/cache@v3`.
2023-02-02 16:40:42 +00:00
MinerSebas
1a18ab34c4 Remove unnecessary Default impl of HandleType (#7472)
# Objective

- Resolve a Fixme to remove the `Default` impl for `HandleType`, once Reflection no longer requires it.
- Presumebly this Comment was made before the `FromReflect` Derive used the `#[reflect(Default)]`, to substitute for the requirment that a ignored field has a `Default`.

## Solution

- Just remove the `Default` derive and comment.
2023-02-02 15:09:06 +00:00
ickshonpe
fbd569c791 Add width, height and all constructor functions to Size (#7468)
## Objective

A common easy to miss mistake is to write something like:
``` rust
Size::new(Val::Percent(100.), Val::Px(100.));
```

`UiRect` has the `left`, `right`, `all`, `vertical`, etc constructor functions, `Size` is used a lot more frequently but lacks anything similar.

## Solution

Implement `all`, `width` and `height` functions for `Size`.

## Changelog

* Added `all`, `width` and `height` functions to `Size`.
2023-02-02 14:29:39 +00:00
MinerSebas
e5b522064c Follow up on Todo in bevy_reflect_derive (#7461)
# Objective

Follow up on Todo in bevy_reflect_derive

## Solution

- Replaced all Instances that do the same as `ident_or_index` with a call to it.
- Only the following Line wasn't replaced, as it only wants the index, and not the ident:
[69fc8c6b70/crates/bevy_reflect/bevy_reflect_derive/src/impls/tuple_structs.rs (L18))
2023-02-02 04:37:32 +00:00
Nicola Papale
6beb4634f6 Cleanup many sprites stress tests (#7436)
Since the new renderer, no frustum culling is applied to 2d components
(be it Sprite or Mesh2d), the stress_tests docs is therefore misleading
and should be updated.

Furthermore, the `many_animated_sprites` example, unlike `many_sprites`
kept vsync enabled, making the stress test less useful than it could be.
We now disable vsync for `many_animated_sprites`.

Also, `many_animated_sprites` didn't have the stress_tests warning
message, instead, it had a paragraph in the module doc. I replaced the
module doc paragraph by the warning message, to be more in line with
other examples.

## Solution

- Remove the paragraph about frustum culling in the `many_sprites`
  and `many_animated_sprites` stress tests
2023-02-01 21:07:11 +00:00
François
69fc8c6b70 add timeouts to CI jobs (#7453)
# Objective

- Avoid hitting the 6 hours default timeout
- Waiting for 6 hours for a job to fail is wasteful and slow down CI for other PRs

## Solution

- Put shorter timeouts on all jobs
2023-02-01 15:08:31 +00:00
ickshonpe
f3b8ff6549 Rename the background_color of 'ExtractedUiNode to color` (#7452)
# Problem
The field is called `background_color` but it is also used to hold the colors of text glyphs and images.
It's mildly confusing and longer to type than just `color`.

## Solution
Rename `background_color` to `color`.

## Changelog
* Renamed the `background_color` field of `ExtractedUiNode` to `color`.

## Migration Guide
* The `background_color` field of `ExtractedUiNode` is now named `color`.
2023-02-01 00:24:25 +00:00
Elbert Ronnie
615d3d2157 Add constructor new to ArrayIter (#7449)
# Objective

- Fixes #7430.

## Solution

- Changed fields of `ArrayIter` to be private.
- Add a constructor `new` to `ArrayIter`.
- Replace normal struct creation with `new`.

---

## Changelog

- Add a constructor `new` to `ArrayIter`.


Co-authored-by: Elbert Ronnie <103196773+elbertronnie@users.noreply.github.com>
2023-01-31 23:19:19 +00:00
ickshonpe
a441939ba5 Remove QueuedText (#7414)
## Objective

Remove `QueuedText`.

`QueuedText` isn't useful. It's exposed in the `bevy_ui` public interface but can't be used for anything because its `entities` field is private.

## Solution

Remove the `QueuedText` struct and use a `Local<Vec<Entity>` in its place.

## Changelog

* Removed `QueuedText`
2023-01-31 18:42:22 +00:00
Alice Cecile
5d514fb24f Reduce internal system order ambiguities, and add an example explaining them (#7383)
# Objective

- Bevy should not have any "internal" execution order ambiguities. These clutter the output of user-facing error reporting, and can result in nasty, nondetermistic, very difficult to solve bugs.
- Verifying this currently involves repeated non-trivial manual work. 

## Solution

- [x] add an example to quickly check this
- ~~[ ] ensure that this example panics if there are any unresolved ambiguities~~
- ~~[ ] run the example in CI 😈~~

There's one tricky ambiguity left, between UI and animation. I don't have the tools to fix this without system set configuration, so the remaining work is going to be left to #7267 or another PR after that.

```
2023-01-27T18:38:42.989405Z  INFO bevy_ecs::schedule::ambiguity_detection: Execution order ambiguities detected, you might want to add an explicit dependency relation between some of these systems:
 * Parallel systems:
 -- "bevy_animation::animation_player" and "bevy_ui::flex::flex_node_system"
    conflicts: ["bevy_transform::components::transform::Transform"]
  ```

## Changelog

Resolved internal execution order ambiguities for:
1. Transform propagation (ignored, we need smarter filter checking).
2. Gamepad processing (fixed).
3. bevy_winit's window handling (fixed).
4. Cascaded shadow maps and perspectives (fixed).

Also fixed a desynchronized state bug that could occur when the `Window` component is removed and then added to the same entity in a single frame.
2023-01-31 01:47:00 +00:00
Robert Swain
cfc56cca2f bevy_pbr: Clear fog DynamicUniformBuffer before populating each frame (#7432)
# Objective

- Fix a bug causing performance to drop over time because the GPU fog buffer was endlessly growing

## Solution

- Clear the fog buffer every frame before populating it
2023-01-30 23:09:38 +00:00
Robert Swain
8b7ebe1738 Fix post_processing and shader_prepass examples (#7419)
# Objective

- Fix `post_processing` and `shader_prepass` examples as they fail when compiling shaders due to missing shader defs
- Fixes #6799
- Fixes #6996
- Fixes #7375 
- Supercedes #6997
- Supercedes #7380 

## Solution

- The prepass was broken due to a missing `MAX_CASCADES_PER_LIGHT` shader def. Add it.
- The shader used in the `post_processing` example is applied to a 2D mesh, so use the correct mesh2d_view_bindings shader import.
2023-01-30 22:53:08 +00:00
Aceeri
937fc039b1 Convenience method for entity naming (#7186)
# Objective
- Trying to make it easier to have a more user friendly debugging name for when you want to print out an entity.

## Solution
- Add a new `WorldQuery` struct `DebugName` to format the `Name` if the entity has one, otherwise formats the `Entity` id.
This means we can do this and get more descriptive errors without much more effort:
```rust
fn my_system(moving: Query<(DebugName, &mut Position, &Velocity)>) {
    for (name, mut position, velocity) in &mut moving {
        position += velocity; 
        if position.is_nan() {
            error!("{:?} has an invalid position state", name);
        }
    }
}
```

---

## Changelog
- Added `DebugName` world query for more human friendly debug names of entities.
2023-01-30 20:50:46 +00:00
Rob Parrett
ca2d91e7ab Fix CI welcome message (#7428)
# Objective

Fixes #7424

## Solution

https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#pull_request_target
> By default, a workflow only runs when a pull_request_target event's activity type is opened, synchronize, or reopened.

Specify `opened` so that this only runs when a PR is opened

While I was in there, I fixed a couple other issues:
- extra indentation that was causing the welcome message to be put in a code block.
- broken relative link in message (was resolving to <https://github.com/bevyengine/bevy/pull/CONTRIBUTING.md>)
- fixed a few other minor typos in the message

cc @mockersf
2023-01-30 20:21:06 +00:00
Jerome Humbert
1dd3fe0d9c Derive Copy for Aabb (#7401)
# Objective

Derive `Copy` for `Aabb`

## Solution

Just do it :)

---

## Changelog

- The `Aabb` type now derives `Copy`.
2023-01-30 18:27:58 +00:00
Torstein Grindvik
67aa2953d0 Extract component derive (#7399)
# Objective

In simple cases we might want to derive the `ExtractComponent` trait.
This adds symmetry to the existing `ExtractResource` derive.

## Solution

Add an implementation of `#[derive(ExtractComponent)]`.
The implementation is adapted from the existing `ExtractResource` derive macro.

Additionally, there is an attribute called `extract_component_filter`. This allows specifying a query filter type used when extracting.
If not specified, no filter (equal to `()`) is used.

So:

```rust
#[derive(Component, Clone, ExtractComponent)]
#[extract_component_filter(With<Fuel>)]
pub struct Car {
    pub wheels: usize,
}
```

would expand to (a bit cleaned up here):

```rust
impl ExtractComponent for Car
{
    type Query = &'static Self;
    type Filter = With<Fuel>;
    type Out = Self;
    fn extract_component(item: QueryItem<'_, Self::Query>) -> Option<Self::Out> {
        Some(item.clone())
    }
}
```

---

## Changelog

- Added the ability to `#[derive(ExtractComponent)]` with an optional filter.
2023-01-30 18:12:16 +00:00
Robert Swain
c9a53bf5dd Fix KTX2 R8_SRGB, R8_UNORM, R8G8_SRGB, R8G8_UNORM, R8G8B8_SRGB, R8G8B8_UNORM support (#4594)
# Objective

- Fixes #4592

## Solution

- Implement `SrgbColorSpace` for `u8` via `f32`
- Convert KTX2 R8 and R8G8 non-linear sRGB to wgpu `R8Unorm` and `Rg8Unorm` as non-linear sRGB are not supported by wgpu for these formats
- Convert KTX2 R8G8B8 formats to `Rgba8Unorm` and `Rgba8UnormSrgb` by adding an alpha channel as the Rgb variants don't exist in wgpu

---

## Changelog

- Added: Support for KTX2 `R8_SRGB`, `R8_UNORM`, `R8G8_SRGB`, `R8G8_UNORM`, `R8G8B8_SRGB`, `R8G8B8_UNORM` formats by converting to supported wgpu formats as appropriate
2023-01-30 09:04:08 +00:00
François
daa45ebb4d remove spancmp (#7409)
# Objective

- This tool get less use than I hoped, as we gained more proficiency with other tracing tools like tracy

## Solution

- Remove it
2023-01-30 05:50:28 +00:00
Jerome Humbert
a61bf35c97 Derive FromReflect for Aabb (#7396)
# Objective

Add a `FromReflect` derive to the `Aabb` type, like all other math types, so we can reflect `Vec<Aabb>`.

## Solution

Just add it :)

---

## Changelog

### Added

- Implemented `FromReflect` for `Aabb`.
2023-01-30 03:54:52 +00:00
Rob Parrett
c673343e05 Fix missing import in array_texture example (#7418)
# Objective

Fixes #7417 

## Solution

Just adds the missing `bevy_pbr::fog` import.
2023-01-30 03:22:29 +00:00
François
1e591bf7a5 Fix ci error comments (#7416)
# Objective

- Fix a few errors on the workflow for leaving comments after ci failures
2023-01-29 23:05:33 +00:00
Elabajaba
bfd1d4b0a7 Wgpu 0.15 (#7356)
# Objective

Update Bevy to wgpu 0.15.

## Changelog

- Update to wgpu 0.15, wgpu-hal 0.15.1, and naga 0.11
- Users can now use the [DirectX Shader Compiler](https://github.com/microsoft/DirectXShaderCompiler) (DXC) on Windows with DX12 for faster shader compilation and ShaderModel 6.0+ support (requires `dxcompiler.dll` and `dxil.dll`, which are included in DXC downloads from [here](https://github.com/microsoft/DirectXShaderCompiler/releases/latest))

## Migration Guide

### WGSL Top-Level `let` is now `const`

All top level constants are now declared with `const`, catching up with the wgsl spec.

`let` is no longer allowed at the global scope, only within functions.

```diff
-let SOME_CONSTANT = 12.0;
+const SOME_CONSTANT = 12.0;
```

#### `TextureDescriptor` and `SurfaceConfiguration` now requires a `view_formats` field

The new `view_formats` field in the `TextureDescriptor` is used to specify a list of formats the texture can be re-interpreted to in a texture view. Currently only changing srgb-ness is allowed (ex. `Rgba8Unorm` <=> `Rgba8UnormSrgb`). You should set `view_formats` to `&[]` (empty) unless you have a specific reason not to.

#### The DirectX Shader Compiler (DXC) is now supported on DX12

DXC is now the default shader compiler when using the DX12 backend. DXC is Microsoft's replacement for their legacy FXC compiler, and is faster, less buggy, and allows for modern shader features to be used (ShaderModel 6.0+). DXC requires `dxcompiler.dll` and `dxil.dll` to be available, otherwise it will log a warning and fall back to FXC.

You can get `dxcompiler.dll` and `dxil.dll` by downloading the latest release from [Microsoft's DirectXShaderCompiler github repo](https://github.com/microsoft/DirectXShaderCompiler/releases/latest) and copying them into your project's root directory. These must be included when you distribute your Bevy game/app/etc if you plan on supporting the DX12 backend and are using DXC.

`WgpuSettings` now has a `dx12_shader_compiler` field which can be used to choose between either FXC or DXC (if you pass None for the paths for DXC, it will check for the .dlls in the working directory).
2023-01-29 20:27:30 +00:00
François
3999365bc1 add Input Method Editor support (#7325)
# Objective

- Fix #7315
- Add IME support

## Solution

- Add two new fields to `Window`, to control if IME is enabled and the candidate box position

This allows the use of dead keys which are needed in French, or the full IME experience to type using Pinyin

I also added a basic general text input example that can handle IME input.

https://user-images.githubusercontent.com/8672791/213941353-5ed73a73-5dd1-4e66-a7d6-a69b49694c52.mp4
2023-01-29 20:27:29 +00:00
Asier Illarramendi
477ef70936 Fix small typo in gamepad.rs docs (#7411)
Fix typo, change: `girls` to `gilrs`.
2023-01-29 20:11:46 +00:00
François
9d52aaede3 Make CI friendlier (#7398)
# Objective

- Make CI friendlier

## Solution

- CI now says hello to new contributor
- for some jobs with non obvious solutions to failures, give more context
  - example run should say which example failed
  - example doc should say the next action to do (add metadata or run the update script)
  - MSRV will say when it needs updating

I'm not completely sure everything is working and will try to trigger failures in this PR
2023-01-29 17:16:29 +00:00
Marco Buono
1a96d820fd Add Distance and Atmospheric Fog support (#6412)
<img width="1392" alt="image" src="https://user-images.githubusercontent.com/418473/203873533-44c029af-13b7-4740-8ea3-af96bd5867c9.png">
<img width="1392" alt="image" src="https://user-images.githubusercontent.com/418473/203873549-36be7a23-b341-42a2-8a9f-ceea8ac7a2b8.png">


# Objective

- Add support for the “classic” distance fog effect, as well as a more advanced atmospheric fog effect.

## Solution

This PR:

- Introduces a new `FogSettings` component that controls distance fog per-camera. 
- Adds support for three widely used “traditional” fog falloff modes: `Linear`, `Exponential` and `ExponentialSquared`, as well as a more advanced `Atmospheric` fog;
- Adds support for directional light influence over fog color;
- Extracts fog via `ExtractComponent`, then uses a prepare system that sets up a new dynamic uniform struct (`Fog`), similar to other mesh view types;
- Renders fog in PBR material shader, as a final adjustment to the `output_color`, after PBR is computed (but before tone mapping);
- Adds a new `StandardMaterial` flag to enable fog; (`fog_enabled`)
- Adds convenience methods for easier artistic control when creating non-linear fog types;
- Adds documentation around fog.

---

## Changelog

### Added

- Added support for distance-based fog effects for PBR materials, controllable per-camera via the new `FogSettings` component;
- Added `FogFalloff` enum for selecting between three widely used “traditional” fog falloff modes: `Linear`, `Exponential` and `ExponentialSquared`, as well as a more advanced `Atmospheric` fog;
2023-01-29 15:28:56 +00:00
研究社交
adae877be2 Use only one sampler in the array texture example. (#7405)
# Objective

Fixes #7373 

## Solution

Use only one sampler instead of an array of samplers.
2023-01-29 15:08:21 +00:00
JoJoJet
209f6f8e83 Fix unsoundness in EntityMut::world_scope (#7387)
# Objective

Found while working on #7385.

The struct `EntityMut` has the safety invariant that it's cached `EntityLocation` must always accurately specify where the entity is stored. Thus, any time its location might be invalidated (such as by calling `EntityMut::world_mut` and moving archetypes), the cached location *must* be updated by calling `EntityMut::update_location`.

The method `world_scope` encapsulates this pattern in safe API by requiring world mutations to be done in a closure, after which `update_location` will automatically be called. However, this method has a soundness hole: if a panic occurs within the closure, then `update_location` will never get called. If the panic is caught in an outer scope, then the `EntityMut` will be left with an outdated location, which is undefined behavior.

An example of this can be seen in the unit test `entity_mut_world_scope_panic`, which has been added to this PR as a regression test. Without the other changes in this PR, that test will invoke undefined behavior in safe code.

## Solution

Call `EntityMut::update_location()` from within a `Drop` impl, which ensures that it will get executed even if `EntityMut::world_scope` unwinds.
2023-01-29 00:10:45 +00:00
François
bfafa781c1 re-enable tests on apple silicon (#7400)
# Objective

- Fixes #6687

## Solution

- The future is now! Rust 1.67 was released with the fix
2023-01-28 19:00:27 +00:00
JoJoJet
299bd37752 Add Ref to the prelude (#7392)
# Objective

Add the change-detection wrapper type `Ref<T>` (originally added in #7097) to `bevy_ecs::prelude`.
2023-01-28 09:28:47 +00:00
JoJoJet
5d912a2f35 Speed up CommandQueue by storing commands more densely (#6391)
# Objective

* Speed up inserting and applying commands. 
* Halve the stack size of `CommandQueue` to 24 bytes.
* Require fewer allocations.

## Solution

Store commands and metadata densely within the same buffer. Each command takes up 1 `usize` of metadata, plus the bytes to store the command itself. Zero-sized types take up no space except for the metadata.

# Benchmarks

All of the benchmarks related to commands.

| Bench                                  | Time      |  % Change         |    p-value |
|----------------------------------------|-----------|--------------|-----------------|
| empty_commands/0_entities              | 4.7780 ns | -18.381% | 0.00  |
| spawn_commands/2000_entities           | 233.11 us | -0.9961%     | 0.00  |
| spawn_commands/4000_entities           | 448.38 us | -3.1466%     | 0.00  |
| spawn_commands/6000_entities           | 693.12 us | -0.3978%     | _0.52_ |
| spawn_commands/8000_entities           | 889.48 us | -2.8802%     | 0.00  |
| insert_commands/insert                 | 609.95 us | -4.8604%     | 0.00  |
| insert_commands/insert_batch           | 355.54 us | -2.8165%     |  0.00 |
| fake_commands/2000_commands            | 4.8018 us | **-17.802%** | 0.00  |
| fake_commands/4000_commands            | 9.5969 us | **-17.337%** | 0.00  |
| fake_commands/6000_commands            | 14.421 us | **-18.454%** | 0.00  |
| fake_commands/8000_commands            | 19.192 us | **-18.261%** | 0.00 |
| sized_commands_0_bytes/2000_commands   | 4.0593 us | -4.7145%     |  0.00 |
| sized_commands_0_bytes/4000_commands   | 8.1541 us | -4.9470%     |  0.00  |
| sized_commands_0_bytes/6000_commands   | 12.806 us | -12.017%     | 0.00 |
| sized_commands_0_bytes/8000_commands   | 17.096 us | -14.070% |  0.00 |
| sized_commands_12_bytes/2000_commands  | 5.3425 us | **-27.632%** | 0.00 |
| sized_commands_12_bytes/4000_commands  | 10.283 us | **-31.158%** |  0.00  |
| sized_commands_12_bytes/6000_commands  | 15.339 us | **-31.418%** |  0.00 |
| sized_commands_12_bytes/8000_commands  | 20.206 us | **-33.133%** |  0.00 |
| sized_commands_512_bytes/2000_commands | 99.118 us | -9.9655%     |  0.00  |
| sized_commands_512_bytes/4000_commands | 201.96 us | -8.8235%     |  0.00 |
| sized_commands_512_bytes/6000_commands | 300.95 us | -9.2344%     |  0.00  |
| sized_commands_512_bytes/8000_commands | 404.69 us | -8.4578%     |  0.00  |
2023-01-28 01:15:51 +00:00
Charles Bournhonesque
cbb4c26cad Enable deriving Reflect on structs with generic types (#7364)
# Objective

I recently had an issue, where I have a struct:
```
struct Property {
   inner: T
}
```
that I use as a wrapper for internal purposes.
I don't want to update my struct definition to 
```
struct Property<T: Reflect>{
   inner: T
}
```
because I still want to be able to build `Property<T>` for types `T` that are not `Reflect`. (and also because I don't want to update my whole code base with `<T: Reflect>` bounds)

I still wanted to have reflection on it (for `bevy_inspector_egui`), but adding `derive(Reflect)` fails with the error:
`T cannot be sent between threads safely. T needs to implement Sync.`

I believe that `bevy_reflect` should adopt the model of other derives in the case of generics, which is to add the `Reflect` implementation only if the generics also implement `Reflect`. (That is the behaviour of other macros such as `derive(Clone)` or `derive(Debug)`.

It's also the current behavior of `derive(FromReflect)`.

Basically doing something like:
```
impl<T> Reflect for Foo<T>
where T: Reflect
```


## Solution

- I updated the derive macros for `Structs` and `TupleStructs` to add extra `where` bounds.
   -  Every type that is reflected will need a `T: Reflect` bound
   -  Ignored types will need a `T: 'static + Send + Sync` bound. Here's the reason. For cases like this:
```
#[derive(Reflect)]
struct Foo<T, U>{
   a: T
   #[reflect(ignore)]
   b: U
}
```
I had to add the bound `'static + Send + Sync` to ignored generics like `U`.
The reason is that we want `Foo<T, U>` to be `Reflect: 'static + Send + Sync`, so `Foo<T, U>` must be able to implement those auto-traits. `Foo<T, U>` will only implement those auto-traits if every generic type implements them, including ignored types.
This means that the previously compile-fail case now compiles:
```
#[derive(Reflect)]
struct Foo<'a> {
    #[reflect(ignore)]
    value: &'a str,
}
```
But `Foo<'a>` will only be useable in the cases where `'a: 'static` and panic if we don't have `'a: 'static`, which is what we want (nice bonus from this PR ;) )



---

## Changelog

> This section is optional. If this was a trivial fix, or has no externally-visible impact, you can delete this section.

### Added
Possibility to add `derive(Reflect)` to structs and enums that contain generic types, like so:
```
#[derive(Reflect)]
struct Foo<T>{
   a: T
}
```
Reflection will only be available if the generic type T also implements `Reflect`.
(previously, this would just return a compiler error)
2023-01-28 00:12:06 +00:00
JoJoJet
9ffba9bb1a Allow returning a value from EntityMut::world_scope (#7385)
# Objective

The function `EntityMut::world_scope` is a safe abstraction that allows you to temporarily get mutable access to the underlying `World` of an `EntityMut`. This function is purely stateful, meaning it is not easily possible to return a value from it.

## Solution

Allow returning a computed value from the closure. This is similar to how `World::resource_scope` works.

---

## Changelog

- The function `EntityMut::world_scope` now allows returning a value from the immediately-computed closure.
2023-01-27 19:42:10 +00:00
ickshonpe
27c4eaae24 UI text layout example (#7359)
## Objective

An example that demonstrates how the `AlignItems` and `JustifyContent` properties can be composed to layout text.

<img width="654" alt="text_layout_example" src="https://user-images.githubusercontent.com/27962798/215116345-daa8ef60-634b-40c6-9b6d-356de3af620c.png">
2023-01-27 19:07:48 +00:00
Torstein Grindvik
b6376ce654 Add main_texture_other (#7343)
# Objective

## Use Case

A render node which calls `post_process_write()` on a `ViewTarget` multiple times during a single run of the node means both main textures of this view target is accessed.

If the source texture (which alternate between main textures **a** and **b**) is accessed in a shader during those iterations it means that those textures have to be bound using bind groups.

Preparing bind groups for both main textures ahead of time is desired, which means having access to the _other_ main texture is needed.

## Solution

Add a method on `ViewTarget` for accessing the other main texture.

---

## Changelog

### Added

- `main_texture_other` API on `ViewTarget`
2023-01-27 18:41:01 +00:00
wackbyte
0ff839be1d Fix formatting in Name docs (#7384)
# Objective

There's no period at the end of the first line of the `Name` documentation, and this messes up the grammar of the summary rustdoc creates:
```
                                                                          ↓
Component used to identify an entity. Stores a hash for faster comparisons The hash is eagerly re-computed upon each update to the name.
```

## Solution

I added it.
2023-01-27 17:49:11 +00:00
Chris Ohk
3281aea5c2 Fix minor typos in code and docs (#7378)
# Objective

I found several words in code and docs are incorrect. This should be fixed.

## Solution

- Fix several minor typos

Co-authored-by: Chris Ohk <utilforever@gmail.com>
2023-01-27 12:12:53 +00:00
James Liu
70e51179bf Bump MSRV to 1.67 (#7379)
# Objective
Bump the MSRV to 1.67. Enable cleanup PRs like #7346 to work.

## Solution
Bump it to 1.67

---

## Changelog
Changed: The MSRV of the engine is now 1.67.
2023-01-27 05:26:58 +00:00
Jakob Hellermann
0cb0d8b55d add UnsafeWorldCell abstraction (#6404)
alternative to #5922, implements #5956 
builds on top of https://github.com/bevyengine/bevy/pull/6402

# Objective

https://github.com/bevyengine/bevy/issues/5956 goes into more detail, but the TLDR is:
- bevy systems ensure disjoint accesses to resources and components, and for that to work there are methods `World::get_resource_unchecked_mut(&self)`, ..., `EntityRef::get_mut_unchecked(&self)` etc.
- we don't have these unchecked methods for `by_id` variants, so third-party crate authors cannot build their own safe disjoint-access abstractions with these
- having `_unchecked_mut` methods is not great, because in their presence safe code can accidentally violate subtle invariants. Having to go through `world.as_unsafe_world_cell().unsafe_method()` forces you to stop and think about what you want to write in your `// SAFETY` comment.

The alternative is to keep exposing `_unchecked_mut` variants for every operation that we want third-party crates to build upon, but we'd prefer to avoid using these methods alltogether: https://github.com/bevyengine/bevy/pull/5922#issuecomment-1241954543

Also, this is something that **cannot be implemented outside of bevy**, so having either this PR or #5922 as an escape hatch with lots of discouraging comments would be great.

## Solution

- add `UnsafeWorldCell` with `unsafe fn get_resource(&self)`, `unsafe fn get_resource_mut(&self)`
- add `fn World::as_unsafe_world_cell(&mut self) -> UnsafeWorldCell<'_>` (and `as_unsafe_world_cell_readonly(&self)`)
- add `UnsafeWorldCellEntityRef` with `unsafe fn get`, `unsafe fn get_mut` and the other utilities on `EntityRef` (no methods for spawning, despawning, insertion)
- use the `UnsafeWorldCell` abstraction in `ReflectComponent`, `ReflectResource` and `ReflectAsset`, so these APIs are easier to reason about
- remove `World::get_resource_mut_unchecked`, `EntityRef::get_mut_unchecked` and use `unsafe { world.as_unsafe_world_cell().get_mut() }` and `unsafe { world.as_unsafe_world_cell().get_entity(entity)?.get_mut() }` instead

This PR does **not** make use of `UnsafeWorldCell` for anywhere else in `bevy_ecs` such as `SystemParam` or `Query`. That is a much larger change, and I am convinced that having `UnsafeWorldCell` is already useful for third-party crates.

Implemented API:

```rust
struct World { .. }
impl World {
  fn as_unsafe_world_cell(&self) -> UnsafeWorldCell<'_>;
}

struct UnsafeWorldCell<'w>(&'w World);
impl<'w> UnsafeWorldCell {
  unsafe fn world(&self) -> &World;

  fn get_entity(&self) -> UnsafeWorldCellEntityRef<'w>; // returns 'w which is `'self` of the `World::as_unsafe_world_cell(&'w self)`

  unsafe fn get_resource<T>(&self) -> Option<&'w T>;
  unsafe fn get_resource_by_id(&self, ComponentId) -> Option<&'w T>;
  unsafe fn get_resource_mut<T>(&self) -> Option<Mut<'w, T>>;
  unsafe fn get_resource_mut_by_id(&self) -> Option<MutUntyped<'w>>;
  unsafe fn get_non_send_resource<T>(&self) -> Option<&'w T>;
  unsafe fn get_non_send_resource_mut<T>(&self) -> Option<Mut<'w, T>>>;

  // not included: remove, remove_resource, despawn, anything that might change archetypes
}

struct UnsafeWorldCellEntityRef<'w> { .. }
impl UnsafeWorldCellEntityRef<'w> {
  unsafe fn get<T>(&self, Entity) -> Option<&'w T>;
  unsafe fn get_by_id(&self, Entity, ComponentId) -> Option<Ptr<'w>>;
  unsafe fn get_mut<T>(&self, Entity) -> Option<Mut<'w, T>>;
  unsafe fn get_mut_by_id(&self, Entity, ComponentId) -> Option<MutUntyped<'w>>;
  unsafe fn get_change_ticks<T>(&self, Entity) -> Option<Mut<'w, T>>;
  // fn id, archetype, contains, contains_id, containts_type_id
}
```

<details>
<summary>UnsafeWorldCell docs</summary>

Variant of the [`World`] where resource and component accesses takes a `&World`, and the responsibility to avoid
aliasing violations are given to the caller instead of being checked at compile-time by rust's unique XOR shared rule.

### Rationale
In rust, having a `&mut World` means that there are absolutely no other references to the safe world alive at the same time,
without exceptions. Not even unsafe code can change this.

But there are situations where careful shared mutable access through a type is possible and safe. For this, rust provides the [`UnsafeCell`](std::cell::UnsafeCell)
escape hatch, which allows you to get a `*mut T` from a `&UnsafeCell<T>` and around which safe abstractions can be built.

Access to resources and components can be done uniquely using [`World::resource_mut`] and [`World::entity_mut`], and shared using [`World::resource`] and [`World::entity`].
These methods use lifetimes to check at compile time that no aliasing rules are being broken.

This alone is not enough to implement bevy systems where multiple systems can access *disjoint* parts of the world concurrently. For this, bevy stores all values of
resources and components (and [`ComponentTicks`](crate::component::ComponentTicks)) in [`UnsafeCell`](std::cell::UnsafeCell)s, and carefully validates disjoint access patterns using
APIs like [`System::component_access`](crate::system::System::component_access).

A system then can be executed using [`System::run_unsafe`](crate::system::System::run_unsafe) with a `&World` and use methods with interior mutability to access resource values.
access resource values.

### Example Usage

[`UnsafeWorldCell`] can be used as a building block for writing APIs that safely allow disjoint access into the world.
In the following example, the world is split into a resource access half and a component access half, where each one can
safely hand out mutable references.

```rust
use bevy_ecs::world::World;
use bevy_ecs::change_detection::Mut;
use bevy_ecs::system::Resource;
use bevy_ecs::world::unsafe_world_cell_world::UnsafeWorldCell;

// INVARIANT: existance of this struct means that users of it are the only ones being able to access resources in the world
struct OnlyResourceAccessWorld<'w>(UnsafeWorldCell<'w>);
// INVARIANT: existance of this struct means that users of it are the only ones being able to access components in the world
struct OnlyComponentAccessWorld<'w>(UnsafeWorldCell<'w>);

impl<'w> OnlyResourceAccessWorld<'w> {
    fn get_resource_mut<T: Resource>(&mut self) -> Option<Mut<'w, T>> {
        // SAFETY: resource access is allowed through this UnsafeWorldCell
        unsafe { self.0.get_resource_mut::<T>() }
    }
}
// impl<'w> OnlyComponentAccessWorld<'w> {
//     ...
// }

// the two interior mutable worlds borrow from the `&mut World`, so it cannot be accessed while they are live
fn split_world_access(world: &mut World) -> (OnlyResourceAccessWorld<'_>, OnlyComponentAccessWorld<'_>) {
    let resource_access = OnlyResourceAccessWorld(unsafe { world.as_unsafe_world_cell() });
    let component_access = OnlyComponentAccessWorld(unsafe { world.as_unsafe_world_cell() });
    (resource_access, component_access)
}
```


</details>
2023-01-27 00:12:13 +00:00