Commit graph

403 commits

Author SHA1 Message Date
Carter Anderson
aefe1f0739
Schedule-First: the new and improved add_systems (#8079)
Co-authored-by: Mike <mike.hsu@gmail.com>
2023-03-18 01:45:34 +00:00
ickshonpe
52b91ac15b
Skip the UV calculations for untextured UI nodes (#7809) 2023-03-17 08:49:40 +00:00
Asier Illarramendi
cb100ba78f
Improve UI stack docs and other small tweaks (#8094) 2023-03-16 12:54:52 +00:00
ickshonpe
e77eb003ec
Perform text scaling calculations per text, not per glyph (#7819) 2023-03-14 00:01:27 +00:00
ickshonpe
87dda354dd
Remove Val::Undefined (#7485) 2023-03-13 15:17:00 +00:00
JoJoJet
fd1af7c8b8
Replace multiple calls to add_system with add_systems (#8001) 2023-03-10 18:15:22 +00:00
ickshonpe
f554700108
Add methods for calculating the size and postion of UI nodes (#7930)
Co-authored-by: François <mockersf@gmail.com>
2023-03-09 14:12:54 +00:00
Nico Burns
872a609a3a
Upgrade Taffy requirement to v0.3.5 (#7959) 2023-03-07 22:10:35 +00:00
Rob Parrett
54dec6079f
Fix min and max size using size value (#7948) 2023-03-07 20:59:02 +00:00
Nico Burns
31d02d45ec
Upgrade Taffy to 0.3.4 (#7953) 2023-03-07 20:01:45 +00:00
github-actions[bot]
6898351348
chore: Release (#7920)
Co-authored-by: Bevy Auto Releaser <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-06 05:13:36 +00:00
github-actions[bot]
b44af49200 Release 0.10.0 (#7919)
Preparing next release
This PR has been auto-generated
2023-03-06 03:53:02 +00:00
github-actions[bot]
8eb67932f1 Bump Version after Release (#7918)
Bump version after release
This PR has been auto-generated
2023-03-06 02:10:30 +00:00
ickshonpe
cfc280cbef Change the Node doc comments to state that it stores the size in logical pixels (#7896)
# Objective

Current `Node` doc comment:
```rust
/// The size of the node as width and height in pixels
/// automatically calculated by [`super::flex::flex_node_system`]
```

It should be changed to make it clear that `Node` stores the size in logical pixels, not physical.
2023-03-04 19:24:56 +00:00
ickshonpe
76058bcf33 Upgrade to Taffy 0.3.3 (#7859)
# Objective

Upgrade to Taffy 0.3.3

Fixes: #7712

## Solution

Upgrade to Taffy 0.3.3 with the `grid` feature disabled.

---

## Changelog
* Changed Taffy version to 0.3.3 and disabled its `grid` feature. 
* Added the `Start` and `End` variants to `AlignItems`, `AlignSelf`, `AlignContent` and `JustifyContent`.
* Added the `SpaceEvenly` variant to `AlignContent`.
* Updated `from_style` for Taffy 0.3.3.
2023-03-04 14:09:47 +00:00
TimJentzsch
73c1ab1d42 Fix bevy_ui compile error without bevy_text (#7877)
# Objective

- Fixes #7874.
- The `bevy_text` dependency is optional for `bevy_ui`, but the `accessibility` module depended on it.

## Solution

- Guard the `accessibility` module behind the `bevy_text` feature and only add the plugin when it's enabled.
2023-03-02 22:44:12 +00:00
ickshonpe
9153bd0e78 Document the border field of Style. (#7868)
# Objective

Document the `border` field of `Style`.
2023-03-02 17:37:09 +00:00
Nolan Darilek
8d1f6ff7fa Integrate AccessKit (#6874)
# Objective

UIs created for Bevy cannot currently be made accessible. This PR aims to address that.

## Solution

Integrate AccessKit as a dependency, adding accessibility support to existing bevy_ui widgets.

## Changelog

### Added

* Integrate with and expose [AccessKit](https://accesskit.dev) for platform accessibility.
* Add `Label` for marking text specifically as a label for UI controls.
2023-03-01 22:45:04 +00:00
ickshonpe
f420c518c0 Document how padding and margin behave with percentage values (#7785)
# Objective

Add a comment explaining that percentage padding is calculated based on the width of the parent node.
2023-02-25 16:38:03 +00:00
JoJoJet
b8263b55fb Support system.in_schedule() and system.on_startup() (#7790)
# Objective

Support the following syntax for adding systems:

```rust
App::new()
    .add_system(setup.on_startup())
    .add_systems((
        show_menu.in_schedule(OnEnter(GameState::Paused)),
        menu_ssytem.in_set(OnUpdate(GameState::Paused)),
        hide_menu.in_schedule(OnExit(GameState::Paused)),
    ))
```

## Solution

Add the traits `IntoSystemAppConfig{s}`, which provide the extension methods necessary for configuring which schedule a system belongs to. These extension methods return `IntoSystemAppConfig{s}`, which `App::add_system{s}` uses to choose which schedule to add systems to.

---

## Changelog

+ Added the extension methods `in_schedule(label)` and  `on_startup()` for configuring the schedule a system belongs to.

## Future Work

* Replace all uses of `add_startup_system` in the engine.
* Deprecate this method
2023-02-24 18:33:55 +00:00
François
1bd7306a3a make bevy_text optional again (#7801)
# Objective

- `bevy_text` used to be "optional". the feature could be disabled, which meant that the systems were not added but `bevy_text` was still compiled because of a hard dependency in `bevy_ui`
- Running something without `bevy_text` enabled and with `bevy_ui` enabled now crashes:
```
thread 'main' panicked at 'called `Option::unwrap()` on a `None` value', /bevy/crates/bevy_ecs/src/schedule/schedule.rs:1147:34
```
- This is because `bevy_ui` declares some of its systems in ambiguity sets with systems from `bevy_text`, which were not added if `bevy_text` is disabled

## Solution

- Make `bevy_text` completely optional

## Migration Guide

- feature `bevy_text` now completely removes `bevy_text` from the dependencies when not enabled. Enable feature `bevy_text` if you use Bevy to render text
2023-02-24 02:21:07 +00:00
Rob Parrett
5bd1907517 Re-enable taffy send+sync assert (#7769)
# Objective

Fix up a `FIXME` comment

## Solution

It looks like the linked issue has been resolved and we can re-enable the "assertion."
2023-02-21 02:36:05 +00:00
Rob Parrett
da8bf66cf8 Remove unnecessary clippy allows (#7768)
# Objective

I think that these allows are no longer necessary after #6534.

## Solution

Let's remove them and see if clippy complains.
2023-02-20 23:59:03 +00:00
ickshonpe
c4f0de52eb Add a BackgroundColor component to TextBundle (#7596)
# Objective

`TextBundle` should have a `BackgroundColor` component.

Apart from adding emphasis etc to text, adding a background color to text nodes can be extremely useful for understanding how Bevy aligns, sizes and positions text, and identifying and debugging problems.

It's easy for users to insert the `BackgroundColor` component themselves but not immediately obvious or discoverable that it's possible. A `BackgroundColor` component allows us to add a `with_background_color` helper function to `TextBundle`.

related issue: #5935

## Solution

Add a `BackgroundColor` component to `TextBundle`.

---

## Changelog

* Added a `BackgroundColor` component to `TextBundle`.
* Added a helper method `with_background_color` to `TextBundle`.

## Migration Guide
`TextBundle` now has a `BackgroundColor` component. 

Use `TextBundle`'s `background_color` field or the `with_background_color` method to set a background color for text when spawning a text node, in place of manual insertion of a `BackgroundColor` component.
2023-02-20 22:42:46 +00:00
Griffin
912fb58869 Initial tonemapping options (#7594)
# Objective

Splits tone mapping from https://github.com/bevyengine/bevy/pull/6677 into a separate PR.
Address https://github.com/bevyengine/bevy/issues/2264.
Adds tone mapping options:
- None: Bypasses tonemapping for instances where users want colors output to match those set.
- Reinhard
- Reinhard Luminance: Bevy's exiting tonemapping
- [ACES](https://github.com/TheRealMJP/BakingLab/blob/master/BakingLab/ACES.hlsl) (Fitted version, based on the same implementation that Godot 4 uses) see https://github.com/bevyengine/bevy/issues/2264
- [AgX](https://github.com/sobotka/AgX)
- SomewhatBoringDisplayTransform
- TonyMcMapface
- Blender Filmic

This PR also adds support for EXR images so they can be used to compare tonemapping options with reference images.

## Migration Guide
- Tonemapping is now an enum with NONE and the various tonemappers.
- The DebandDither is now a separate component.




Co-authored-by: JMS55 <47158642+JMS55@users.noreply.github.com>
2023-02-19 20:38:13 +00:00
Zhixing Zhang
16feb9acb7 Add push contant config to layout (#7681)
# Objective

Allow for creating pipelines that use push constants. To be able to use push constants. Fixes #4825

As of right now, trying to call `RenderPass::set_push_constants` will trigger the following error:

```
thread 'main' panicked at 'wgpu error: Validation Error

Caused by:
    In a RenderPass
      note: encoder = `<CommandBuffer-(0, 59, Vulkan)>`
    In a set_push_constant command
    provided push constant is for stage(s) VERTEX | FRAGMENT | VERTEX_FRAGMENT, however the pipeline layout has no push constant range for the stage(s) VERTEX | FRAGMENT | VERTEX_FRAGMENT
```
## Solution

Add a field push_constant_ranges to` RenderPipelineDescriptor` and `ComputePipelineDescriptor`.

This PR supersedes #4908 which now contains merge conflicts due to significant changes to `bevy_render`.

Meanwhile, this PR also made the `layout` field of `RenderPipelineDescriptor` and `ComputePipelineDescriptor` non-optional. If the user do not need to specify the bind group layouts, they can simply supply an empty vector here. No need for it to be optional.

---

## Changelog
- Add a field push_constant_ranges to RenderPipelineDescriptor and ComputePipelineDescriptor
- Made the `layout` field of RenderPipelineDescriptor and ComputePipelineDescriptor non-optional.


## Migration Guide

- Add push_constant_ranges: Vec::new() to every `RenderPipelineDescriptor` and `ComputePipelineDescriptor`
- Unwrap the optional values on the `layout` field of `RenderPipelineDescriptor` and `ComputePipelineDescriptor`. If the descriptor has no layout, supply an empty vector.


Co-authored-by: Zhixing Zhang <me@neoto.xin>
2023-02-17 06:20:16 +00:00
ickshonpe
11c7e5807a Improve the documentation for flex-basis (#7685)
# Objective

The current doc comment for `flex-basis` states that it is "The initial size of the item", which is a bit confusing since size in Bevy is mostly used to refer to two-dimensional extents but `flex-basis` is a one-dimensional value.

It also needs to explain that:
* `flex-basis` sets the initial length of the main axis.
* Overrides `size` on the main axis.
* Obeys the `min_size` and `max_size` constraints.
2023-02-15 13:58:01 +00:00
ickshonpe
e950b1e09b Changes in the size of a text node should trigger recomputation of its text (#7674)
# Objective

The text contained by a text node is only recomputed when its `Style` or `Text` components change, or when the scale factor changes. Not when the geometry of the text node is modified.

Make it so that any change in text node size triggers a text recomputation.

## Solution

Change `text_system` so that it queries for text nodes with changed `Node` components and recomputes their text. 

---

Most users won't notice any difference but it should fix some confusing edge cases in more complicated and interactive layouts.

## Changelog

* Added `Changed<Node>` to the change detection query of `text_system`. This ensures that any change in the size of a text node will cause any text it contains to be recomputed.
2023-02-14 14:46:28 +00:00
ickshonpe
39bf45cf5e Add doc tests for the Size constructor functions (#7658)
# Objective

Add doc tests for the `Size` constructor functions.

Also changed the function descriptions so they explicitly state the values that elided values are given.

## Changelog
* Added doc tests for the `Size` constructor functions.
2023-02-13 18:20:34 +00:00
ickshonpe
5a71831b31 The size field of CalculatedSize should not be a Size (#7641)
# Objective

The `size` field of `CalculatedSize` shouldn't be a `Size` as it only ever stores (unscaled) pixel values. By default its fields are `Val::Auto` but these are converted to `0`s before being sent to Taffy.

## Solution

Change the `size` field of `CalculatedSize` to a Vec2.

## Changelog

* Changed the `size` field of `CalculatedSize` to a Vec2.
* Removed the `Val` <-> `f32`  conversion code for  `CalculatedSize`.

## Migration Guide

* The size field of `CalculatedSize` has been changed to a `Vec2`.
2023-02-13 18:20:29 +00:00
ickshonpe
eaac730617 Fix the Size helper functions using the wrong default value and improve the UI examples (#7626)
# Objective
`Size::width` sets the `height` field to `Val::DEFAULT` which is `Val::Undefined`, but the default for `Size` `height` is `Val::Auto`. 
`Size::height` has the same problem, but with the `width` field. 

The UI examples specify numeric values in many places where they could either be elided or replaced by composition of the Flex enum properties.

related: https://github.com/bevyengine/bevy/pull/7468
fixes: https://github.com/bevyengine/bevy/issues/6498

## Solution
Change `Size::width` so it sets `height` to `Val::AUTO` and change `Size::height` so it sets `width` to `Val::AUTO`.
Added some tests so this doesn't happen again.

## Changelog
Changed `Size::width` so it sets the `height` to `Val::AUTO`.
Changed `Size::height` so it sets the `width` to `Val::AUTO`.
Added tests to `geometry.rs` for `Size` and `UiRect` to ensure correct behaviour.
Simplified the UI examples. Replaced numeric values with the Flex property enums or elided them where possible, and removed the remaining use of auto margins.

## Migration Guide
The `Size::width` constructor function now sets the `height` to `Val::Auto` instead of `Val::Undefined`.
The `Size::height` constructor function now sets the `width` to `Val::Auto` instead of `Val::Undefined`.
2023-02-11 23:07:16 +00:00
Torstein Grindvik
38766faccb Refactor Globals and View structs into separate shaders (#7512)
fixes #6799 

# Objective

We should be able to reuse the `Globals` or `View` shader struct definitions from anywhere (including third party plugins) without needing to worry about defining unrelated shader defs.
Also we'd like to refactor these structs to not be repeatedly defined.

## Solution

Refactor both `Globals` and `View` into separate importable shaders.
Use the imports throughout.

Co-authored-by: Torstein Grindvik <52322338+torsteingrindvik@users.noreply.github.com>
2023-02-11 17:55:18 +00:00
ickshonpe
16ce3859e3 Document how Style's size constraints interact (#7613)
# Objective

Document how `Style`'s size constraints interact.

# Changelog
* Added extra doc comments to `Style`'s size fields.
2023-02-10 23:50:28 +00:00
ickshonpe
2d1dcbff7b Fix the AlignSelf documentation (#7577)
# Objective

The current `AlignSelf` doc comments: 

```rust
pub enum AlignSelf {
    /// Use the value of [`AlignItems`]
    Auto,
    /// If the parent has [`AlignItems::Center`] only this item will be at the start
    FlexStart,
    /// If the parent has [`AlignItems::Center`] only this item will be at the end
    FlexEnd,
    /// If the parent has [`AlignItems::FlexStart`] only this item will be at the center
    Center,
    /// If the parent has [`AlignItems::Center`] only this item will be at the baseline
    Baseline,
    /// If the parent has [`AlignItems::Center`] only this item will stretch along the whole cross axis
    Stretch,
}
```

Actual behaviour of `AlignSelf` in Bevy main:

<img width="642" alt="align_self" src="https://user-images.githubusercontent.com/27962798/217795178-7a82638f-118d-4474-b7f9-ca27f204731d.PNG">

The white label at the top of each column is the parent node's `AlignItems` setting.
`AlignSelf` is always applied, not (as the documentation states) only when the parent has `AlignItems::Center` or `AlignItems::FlexStart` set.

```rust
use bevy::prelude::*;

fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        .add_startup_system(setup)
        .run();
}

fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
    commands.spawn(Camera2dBundle::default());
    commands.spawn(NodeBundle {
        style: Style {
            justify_content: JustifyContent::SpaceAround,
            align_items: AlignItems::Center,
            size: Size::new(Val::Percent(100.), Val::Percent(100.)),
            ..Default::default()
        },
        background_color: BackgroundColor(Color::NAVY),
        ..Default::default()
    }).with_children(|builder| {
        for align_items in [
            AlignItems::Baseline,
            AlignItems::FlexStart,
            AlignItems::Center,
            AlignItems::FlexEnd,
            AlignItems::Stretch,
        ] {
            builder.spawn(NodeBundle {
                style: Style {
                    align_items,
                    flex_direction: FlexDirection::Column,
                    justify_content: JustifyContent::SpaceBetween,
                    size: Size::new(Val::Px(150.), Val::Px(500.)),
                    ..Default::default()
                },
                background_color: BackgroundColor(Color::DARK_GRAY),
                ..Default::default()
            }).with_children(|builder| {
                builder.spawn((
                    TextBundle {
                        text: Text::from_section(
                            format!("AlignItems::{align_items:?}"),
                            TextStyle {
                                font: asset_server.load("fonts/FiraSans-Regular.ttf"),
                                font_size: 16.0,
                                color: Color::BLACK,
                            },
                        ),
                        style: Style {
                            align_self: AlignSelf::Stretch,
                            ..Default::default()
                        },
                        ..Default::default()
                    },
                    BackgroundColor(Color::WHITE),
                ));

                for align_self in [
                    AlignSelf::Auto,
                    AlignSelf::FlexStart,
                    AlignSelf::Center,
                    AlignSelf::FlexEnd,
                    AlignSelf::Baseline,
                    AlignSelf::Stretch,
                ] {
                    builder.spawn((
                        TextBundle {
                            text: Text::from_section(
                                format!("AlignSelf::{align_self:?}"),
                                TextStyle {
                                    font: asset_server.load("fonts/FiraSans-Regular.ttf"),
                                    font_size: 16.0,
                                    color: Color::WHITE,
                                },
                            ),
                            style: Style {
                                align_self,
                                ..Default::default()
                            },
                            ..Default::default()
                        },
                        BackgroundColor(Color::BLACK),
                    ));
                }
            });
        }
    });
}
```
2023-02-09 20:00:11 +00:00
ira
f69f1329e0 Fix Window feedback loop between the OS and Bevy (#7517)
# Objective

Fix #7377
Fix #7513

## Solution

Record the changes made to the Bevy `Window` from `winit` as 'canon' to avoid Bevy sending those changes back to `winit` again, causing a feedback loop.

## Changelog

* Removed `ModifiesWindows` system label.
  Neither `despawn_window` nor `changed_window` actually modify the `Window` component so all the `.after(ModifiesWindows)` shouldn't be necessary.
* Moved `changed_window` and `despawn_window` systems to `CoreStage::Last` to avoid systems making changes to the `Window` between `changed_window` and the end of the frame as they would be ignored.

## Migration Guide
The `ModifiesWindows` system label was removed.


Co-authored-by: devil-ira <justthecooldude@gmail.com>
2023-02-07 14:18:13 +00:00
张林伟
aa4170d9a4 Rename schedule v3 to schedule (#7519)
# Objective

- Follow up of https://github.com/bevyengine/bevy/pull/7267

## Solution

- Rename schedule_v3 to schedule
- Suppress "module inception" lint
2023-02-06 18:44:40 +00:00
Carter Anderson
dcc03724a5 Base Sets (#7466)
# Objective

NOTE: This depends on #7267 and should not be merged until #7267 is merged. If you are reviewing this before that is merged, I highly recommend viewing the Base Sets commit instead of trying to find my changes amongst those from #7267.

"Default sets" as described by the [Stageless RFC](https://github.com/bevyengine/rfcs/pull/45) have some [unfortunate consequences](https://github.com/bevyengine/bevy/discussions/7365).

## Solution

This adds "base sets" as a variant of `SystemSet`:

A set is a "base set" if `SystemSet::is_base` returns `true`. Typically this will be opted-in to using the `SystemSet` derive:

```rust
#[derive(SystemSet, Clone, Hash, Debug, PartialEq, Eq)]
#[system_set(base)]
enum MyBaseSet {
  A,
  B,
}
``` 

**Base sets are exclusive**: a system can belong to at most one "base set". Adding a system to more than one will result in an error. When possible we fail immediately during system-config-time with a nice file + line number. For the more nested graph-ey cases, this will fail at the final schedule build. 

**Base sets cannot belong to other sets**: this is where the word "base" comes from

Systems and Sets can only be added to base sets using `in_base_set`. Calling `in_set` with a base set will fail. As will calling `in_base_set` with a normal set.

```rust
app.add_system(foo.in_base_set(MyBaseSet::A))
       // X must be a normal set ... base sets cannot be added to base sets
       .configure_set(X.in_base_set(MyBaseSet::A))
```

Base sets can still be configured like normal sets:

```rust
app.add_system(MyBaseSet::B.after(MyBaseSet::Ap))
``` 

The primary use case for base sets is enabling a "default base set":

```rust
schedule.set_default_base_set(CoreSet::Update)
  // this will belong to CoreSet::Update by default
  .add_system(foo)
  // this will override the default base set with PostUpdate
  .add_system(bar.in_base_set(CoreSet::PostUpdate))
```

This allows us to build apis that work by default in the standard Bevy style. This is a rough analog to the "default stage" model, but it use the new "stageless sets" model instead, with all of the ordering flexibility (including exclusive systems) that it provides.

---

## Changelog

- Added "base sets" and ported CoreSet to use them.

## Migration Guide

TODO
2023-02-06 03:10:08 +00:00
Alice Cecile
206c7ce219 Migrate engine to Schedule v3 (#7267)
Huge thanks to @maniwani, @devil-ira, @hymm, @cart, @superdump and @jakobhellermann for the help with this PR.

# Objective

- Followup #6587.
- Minimal integration for the Stageless Scheduling RFC: https://github.com/bevyengine/rfcs/pull/45

## Solution

- [x]  Remove old scheduling module
- [x] Migrate new methods to no longer use extension methods
- [x] Fix compiler errors
- [x] Fix benchmarks
- [x] Fix examples
- [x] Fix docs
- [x] Fix tests

## Changelog

### Added

- a large number of methods on `App` to work with schedules ergonomically
- the `CoreSchedule` enum
- `App::add_extract_system` via the `RenderingAppExtension` trait extension method
- the private `prepare_view_uniforms` system now has a public system set for scheduling purposes, called `ViewSet::PrepareUniforms`

### Removed

- stages, and all code that mentions stages
- states have been dramatically simplified, and no longer use a stack
- `RunCriteriaLabel`
- `AsSystemLabel` trait
- `on_hierarchy_reports_enabled` run criteria (now just uses an ad hoc resource checking run condition)
- systems in `RenderSet/Stage::Extract` no longer warn when they do not read data from the main world
- `RunCriteriaLabel`
- `transform_propagate_system_set`: this was a nonstandard pattern that didn't actually provide enough control. The systems are already `pub`: the docs have been updated to ensure that the third-party usage is clear.

### Changed

- `System::default_labels` is now `System::default_system_sets`.
- `App::add_default_labels` is now `App::add_default_sets`
- `CoreStage` and `StartupStage` enums are now `CoreSet` and `StartupSet`
- `App::add_system_set` was renamed to `App::add_systems`
- The `StartupSchedule` label is now defined as part of the `CoreSchedules` enum
-  `.label(SystemLabel)` is now referred to as `.in_set(SystemSet)`
- `SystemLabel` trait was replaced by `SystemSet`
- `SystemTypeIdLabel<T>` was replaced by `SystemSetType<T>`
- The `ReportHierarchyIssue` resource now has a public constructor (`new`), and implements `PartialEq`
- Fixed time steps now use a schedule (`CoreSchedule::FixedTimeStep`) rather than a run criteria.
- Adding rendering extraction systems now panics rather than silently failing if no subapp with the `RenderApp` label is found.
- the `calculate_bounds` system, with the `CalculateBounds` label, is now in `CoreSet::Update`, rather than in `CoreSet::PostUpdate` before commands are applied. 
- `SceneSpawnerSystem` now runs under `CoreSet::Update`, rather than `CoreStage::PreUpdate.at_end()`.
- `bevy_pbr::add_clusters` is no longer an exclusive system
- the top level `bevy_ecs::schedule` module was replaced with `bevy_ecs::scheduling`
- `tick_global_task_pools_on_main_thread` is no longer run as an exclusive system. Instead, it has been replaced by `tick_global_task_pools`, which uses a `NonSend` resource to force running on the main thread.

## Migration Guide

- Calls to `.label(MyLabel)` should be replaced with `.in_set(MySet)`
- Stages have been removed. Replace these with system sets, and then add command flushes using the `apply_system_buffers` exclusive system where needed.
- The `CoreStage`, `StartupStage, `RenderStage` and `AssetStage`  enums have been replaced with `CoreSet`, `StartupSet, `RenderSet` and `AssetSet`. The same scheduling guarantees have been preserved.
  - Systems are no longer added to `CoreSet::Update` by default. Add systems manually if this behavior is needed, although you should consider adding your game logic systems to `CoreSchedule::FixedTimestep` instead for more reliable framerate-independent behavior.
  - Similarly, startup systems are no longer part of `StartupSet::Startup` by default. In most cases, this won't matter to you.
  - For example, `add_system_to_stage(CoreStage::PostUpdate, my_system)` should be replaced with 
  - `add_system(my_system.in_set(CoreSet::PostUpdate)`
- When testing systems or otherwise running them in a headless fashion, simply construct and run a schedule using `Schedule::new()` and `World::run_schedule` rather than constructing stages
- Run criteria have been renamed to run conditions. These can now be combined with each other and with states.
- Looping run criteria and state stacks have been removed. Use an exclusive system that runs a schedule if you need this level of control over system control flow.
- For app-level control flow over which schedules get run when (such as for rollback networking), create your own schedule and insert it under the `CoreSchedule::Outer` label.
- Fixed timesteps are now evaluated in a schedule, rather than controlled via run criteria. The `run_fixed_timestep` system runs this schedule between `CoreSet::First` and `CoreSet::PreUpdate` by default.
- Command flush points introduced by `AssetStage` have been removed. If you were relying on these, add them back manually.
- Adding extract systems is now typically done directly on the main app. Make sure the `RenderingAppExtension` trait is in scope, then call `app.add_extract_system(my_system)`.
- the `calculate_bounds` system, with the `CalculateBounds` label, is now in `CoreSet::Update`, rather than in `CoreSet::PostUpdate` before commands are applied. You may need to order your movement systems to occur before this system in order to avoid system order ambiguities in culling behavior.
- the `RenderLabel` `AppLabel` was renamed to `RenderApp` for clarity
- `App::add_state` now takes 0 arguments: the starting state is set based on the `Default` impl.
- Instead of creating `SystemSet` containers for systems that run in stages, simply use `.on_enter::<State::Variant>()` or its `on_exit` or `on_update` siblings.
- `SystemLabel` derives should be replaced with `SystemSet`. You will also need to add the `Debug`, `PartialEq`, `Eq`, and `Hash` traits to satisfy the new trait bounds.
- `with_run_criteria` has been renamed to `run_if`. Run criteria have been renamed to run conditions for clarity, and should now simply return a bool.
- States have been dramatically simplified: there is no longer a "state stack". To queue a transition to the next state, call `NextState::set`

## TODO

- [x] remove dead methods on App and World
- [x] add `App::add_system_to_schedule` and `App::add_systems_to_schedule`
- [x] avoid adding the default system set at inappropriate times
- [x] remove any accidental cycles in the default plugins schedule
- [x] migrate benchmarks
- [x] expose explicit labels for the built-in command flush points
- [x] migrate engine code
- [x] remove all mentions of stages from the docs
- [x] verify docs for States
- [x] fix uses of exclusive systems that use .end / .at_start / .before_commands
- [x] migrate RenderStage and AssetStage
- [x] migrate examples
- [x] ensure that transform propagation is exported in a sufficiently public way (the systems are already pub)
- [x] ensure that on_enter schedules are run at least once before the main app
- [x] re-enable opt-in to execution order ambiguities
- [x] revert change to `update_bounds` to ensure it runs in `PostUpdate`
- [x] test all examples
  - [x] unbreak directional lights
  - [x] unbreak shadows (see 3d_scene, 3d_shape, lighting, transparaency_3d examples)
  - [x] game menu example shows loading screen and menu simultaneously
  - [x] display settings menu is a blank screen
  - [x] `without_winit` example panics
- [x] ensure all tests pass
  - [x] SubApp doc test fails
  - [x] runs_spawn_local tasks fails
  - [x] [Fix panic_when_hierachy_cycle test hanging](https://github.com/alice-i-cecile/bevy/pull/120)

## Points of Difficulty and Controversy

**Reviewers, please give feedback on these and look closely**

1.  Default sets, from the RFC, have been removed. These added a tremendous amount of implicit complexity and result in hard to debug scheduling errors. They're going to be tackled in the form of "base sets" by @cart in a followup.
2. The outer schedule controls which schedule is run when `App::update` is called.
3. I implemented `Label for `Box<dyn Label>` for our label types. This enables us to store schedule labels in concrete form, and then later run them. I ran into the same set of problems when working with one-shot systems. We've previously investigated this pattern in depth, and it does not appear to lead to extra indirection with nested boxes.
4. `SubApp::update` simply runs the default schedule once. This sucks, but this whole API is incomplete and this was the minimal changeset.
5. `time_system` and `tick_global_task_pools_on_main_thread` no longer use exclusive systems to attempt to force scheduling order
6. Implemetnation strategy for fixed timesteps
7. `AssetStage` was migrated to `AssetSet` without reintroducing command flush points. These did not appear to be used, and it's nice to remove these bottlenecks.
8. Migration of `bevy_render/lib.rs` and pipelined rendering. The logic here is unusually tricky, as we have complex scheduling requirements.

## Future Work (ideally before 0.10)

- Rename schedule_v3 module to schedule or scheduling
- Add a derive macro to states, and likely a `EnumIter` trait of some form
- Figure out what exactly to do with the "systems added should basically work by default" problem
- Improve ergonomics for working with fixed timesteps and states
- Polish FixedTime API to match Time
- Rebase and merge #7415
- Resolve all internal ambiguities (blocked on better tools, especially #7442)
- Add "base sets" to replace the removed default sets.
2023-02-06 02:04:50 +00:00
DanielJin21
2e53f3b775 Don't ignore UI scale for text (#7510)
# Objective

Fixes #7476. UI scale was being incorrectly ignored when a primary window exists.

## Solution

Always take into account UI scale, regardless of whether a primary window exists.

Tested locally on @forbjok 's minimal repro project https://github.com/forbjok/bevy_ui_repro with this patch, and the issue is fixed on my machine.
2023-02-05 18:15:22 +00:00
ira
32023a5f6a Remove broken DoubleEndedIterator impls on event iterators (#7469)
The `DoubleEndedIterator` impls produce incorrect results on subsequent calls to `iter()` if the iterator is only partially consumed.

The following code shows what happens
```rust

fn next_back_is_bad() {
    let mut events = Events::<TestEvent>::default();
    events.send(TestEvent { i: 0 });
    events.send(TestEvent { i: 1 });
    events.send(TestEvent { i: 2 });
    let mut reader = events.get_reader();
    let mut iter = reader.iter(&events);
    assert_eq!(iter.next_back(), Some(&TestEvent { i: 2 }));
    assert_eq!(iter.next(), Some(&TestEvent { i: 0 }));
    
    let mut iter = reader.iter(&events);
    // `i: 2` event is returned twice! The `i: 1` event is missed. 
    assert_eq!(iter.next(), Some(&TestEvent { i: 2 }));
    assert_eq!(iter.next(), None);
}
```

I don't think this can be fixed without adding some very convoluted bookkeeping.

## Migration Guide
`ManualEventIterator` and `ManualEventIteratorWithId` are no longer `DoubleEndedIterator`s.



Co-authored-by: devil-ira <justthecooldude@gmail.com>
2023-02-05 15:18:19 +00:00
Aceeri
67826b21d4 Replace RemovedComponents<T> backing with Events<Entity> (#5680)
# Objective
Removal events are unwieldy and require some knowledge of when to put systems that need to catch events for them, it is very easy to end up missing one and end up with memory leak-ish issues where you don't clean up after yourself.

## Solution
Consolidate removals with the benefits of `Events<...>` (such as double buffering and per system ticks for reading the events) and reduce the special casing of it, ideally I was hoping to move the removals to a `Resource` in the world, but that seems a bit more rough to implement/maintain because of double mutable borrowing issues.

This doesn't go the full length of change detection esque removal detection a la https://github.com/bevyengine/rfcs/pull/44.
Just tries to make the current workflow a bit more user friendly so detecting removals isn't such a scheduling nightmare.

---

## Changelog
- RemovedComponents<T> is now backed by an `Events<Entity>` for the benefits of double buffering.

## Migration Guide
- Add a `mut` for `removed: RemovedComponents<T>` since we are now modifying an event reader internally.
- Iterating over removed components now requires `&mut removed_components` or `removed_components.iter()` instead of `&removed_components`.
2023-02-04 20:53:37 +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
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
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
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
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
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
Daniel Chia
c3a46822e1 Cascaded shadow maps. (#7064)
Co-authored-by: Robert Swain <robert.swain@gmail.com>

# Objective

Implements cascaded shadow maps for directional lights, which produces better quality shadows without needing excessively large shadow maps.

Fixes #3629

Before
![image](https://user-images.githubusercontent.com/1222141/210061203-bbd965a4-8d11-4cec-9a88-67fc59d0819f.png)

After
![image](https://user-images.githubusercontent.com/1222141/210061334-2ff15334-e6d7-4a31-9314-f34a7805cac6.png)


## Solution

Rather than rendering a single shadow map for directional light, the view frustum is divided into a series of cascades, each of which gets its own shadow map. The correct cascade is then sampled for shadow determination.

---

## Changelog

Directional lights now use cascaded shadow maps for improved shadow quality.


## Migration Guide

You no longer have to manually specify a `shadow_projection` for a directional light, and these settings should be removed. If customization of how cascaded shadow maps work is desired, modify the `CascadeShadowConfig` component instead.
2023-01-25 12:35:39 +00:00
ickshonpe
cf612c8349 fix upsert_leaf not setting a MeasureFunc for new leaf nodes (#7351)
# Problem

The `upsert_leaf` method creates a new `MeasureFunc` and, if required, a new leaf node, but then it only adds the new `MeasureFunc` to existing leaf nodes.

## Solution

Add the `MeasureFunc` to new leaf nodes as well.
2023-01-24 16:09:52 +00:00
James Liu
7a176ae0a8 Optimize color computation in prepare_uinodes (#7311)
# Objective
Speed up `prepare_uinodes`. The color `[f32; 4]` is being computed separately for every vertex in the UI, even though the color is the same for all 6 verticies.

## Solution
Avoid recomputing the color and cache it for all 6 verticies.

## Performance
On `many_buttons`, this shaved off 33% of the time in `prepare_uinodes` (7.67ms -> 5.09ms) on my local machine.
![image](https://user-images.githubusercontent.com/3137680/213862448-236ac6e4-040a-4c86-a801-b947d99cc581.png)
2023-01-22 06:51:31 +00:00