# Objective
- #10572
There is no 2D primitive available for the common shape of an annulus
(ring).
## Solution
This PR introduces a new type to the existing math primitives:
- `Annulus`: the region between two concentric circles
---
## Changelog
### Added
- `Annulus` primitive to the `bevy_math` crate
- `Annulus` tests (`diameter`, `thickness`, `area`, `perimeter` and
`closest_point` methods)
---------
Co-authored-by: Joona Aalto <jondolf.dev@gmail.com>
# Objective
I found that some .rs files are unnecessarily executable.
Rust source files may start with a shebang-like statement `#!`, so let's
make sure they are not executable just in case.
Here is the result of the `find` commend that lists executable .rs files
as of main branch `86bd648`.
```console
$ find -name \*.rs -type f -executable
./crates/bevy_gizmos/src/lib.rs
./crates/bevy_tasks/src/lib.rs
./crates/bevy_time/src/lib.rs
./crates/bevy_transform/src/lib.rs
./src/lib.rs
```
It appears that the permissions of those files were originally 644, but
were unexpectedly changed to 755 by commit
52e3f2007b.
## Solution
Make them not executable by using this command;
`find -name \*.rs -type f -executable -exec chmod --verbose a-x -- {}
\+`
# Objective
Fix the regression for Root Node's Layout behavior introduced in
https://github.com/bevyengine/bevy/pull/12268
- Add regression test for Root Node Layout's behaving as they did before
0.13.1
- Restore pre 0.13.1 Root Node Layout behavior (fixes
https://github.com/bevyengine/bevy/issues/12624)
## Solution
This implements [@nicoburns suggestion
](https://discord.com/channels/691052431525675048/743663673393938453/1221593626476548146),
where instead of adding the camera to the taffy node tree, we revert
back to adding a new "parent" node for each root node while maintaining
their relationship with the camera.
> If you can do the ecs change detection to move the node to the correct
Taffy instance for the camera then you should also be able to move it to
a `Vec` of root nodes for that camera.
---
## Changelog
Fixed https://github.com/bevyengine/bevy/issues/12624 - Restores pre
0.13.1 Root Node Layout behavior
## Migration Guide
If you were affected by the 0.13.1 regression and added `position_type:
Absolute` to all your root nodes you might be able to reclaim some LOC
by removing them now that the 0.13 behavior is restored.
# Objective
- Adds line styles to bevy gizmos, suggestion of #9400
- Currently solid and dotted lines are implemented but this can easily
be extended to support dashed lines as well if that is wanted.
## Solution
- Adds the enum `GizmoLineStyle` and uses it in each `GizmoConfig` to
configure the style of the line.
- Each "dot" in a dotted line has the same width and height as the
`line_width` of the corresponding line.
---
## Changelog
- Added `GizmoLineStyle` to `bevy_gizmos`
- Added a `line_style: GizmoLineStyle ` attribute to `GizmoConfig`
- Updated the `lines.wgsl` shader and the pipelines accordingly.
## Migration Guide
- Any manually created `GizmoConfig` must now include the `line_style`
attribute
## Additional information
Some pretty pictures :)
This is the 3d_gizmos example with/without `line_perspective`:
<img width="1440" alt="Screenshot 2024-03-09 at 23 25 53"
src="https://github.com/bevyengine/bevy/assets/62256001/b1b97311-e78d-4de3-8dfe-9e48a35bb27d">
<img width="1440" alt="Screenshot 2024-03-09 at 23 25 39"
src="https://github.com/bevyengine/bevy/assets/62256001/50ee8ecb-5290-484d-ba36-7fd028374f7f">
And the 2d example:
<img width="1440" alt="Screenshot 2024-03-09 at 23 25 06"
src="https://github.com/bevyengine/bevy/assets/62256001/4452168f-d605-4333-bfa5-5461d268b132">
---------
Co-authored-by: BD103 <59022059+BD103@users.noreply.github.com>
# Objective
This gets Bevy building on Wasm when the `atomics` flag is enabled. This
does not yet multithread Bevy itself, but it allows Bevy users to use a
crate like `wasm_thread` to spawn their own threads and manually
parallelize work. This is a first step towards resolving #4078 . Also
fixes#9304.
This provides a foothold so that Bevy contributors can begin to think
about multithreaded Wasm's constraints and Bevy can work towards changes
to get the engine itself multithreaded.
Some flags need to be set on the Rust compiler when compiling for Wasm
multithreading. Here's what my build script looks like, with the correct
flags set, to test out Bevy examples on web:
```bash
set -e
RUSTFLAGS='-C target-feature=+atomics,+bulk-memory,+mutable-globals' \
cargo build --example breakout --target wasm32-unknown-unknown -Z build-std=std,panic_abort --release
wasm-bindgen --out-name wasm_example \
--out-dir examples/wasm/target \
--target web target/wasm32-unknown-unknown/release/examples/breakout.wasm
devserver --header Cross-Origin-Opener-Policy='same-origin' --header Cross-Origin-Embedder-Policy='require-corp' --path examples/wasm
```
A few notes:
1. `cpal` crashes immediately when the `atomics` flag is set. That is
patched in https://github.com/RustAudio/cpal/pull/837, but not yet in
the latest crates.io release.
That can be temporarily worked around by patching Cpal like so:
```toml
[patch.crates-io]
cpal = { git = "https://github.com/RustAudio/cpal" }
```
2. When testing out `wasm_thread` you need to enable the `es_modules`
feature.
## Solution
The largest obstacle to compiling Bevy with `atomics` on web is that
`wgpu` types are _not_ Send and Sync. Longer term Bevy will need an
approach to handle that, but in the near term Bevy is already configured
to be single-threaded on web.
Therefor it is enough to wrap `wgpu` types in a
`send_wrapper::SendWrapper` that _is_ Send / Sync, but panics if
accessed off the `wgpu` thread.
---
## Changelog
- `wgpu` types that are not `Send` are wrapped in
`send_wrapper::SendWrapper` on Wasm + 'atomics'
- CommandBuffers are not generated in parallel on Wasm + 'atomics'
## Questions
- Bevy should probably add CI checks to make sure this doesn't regress.
Should that go in this PR or a separate PR? **Edit:** Added checks to
build Wasm with atomics
---------
Co-authored-by: François <mockersf@gmail.com>
Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
Co-authored-by: daxpedda <daxpedda@gmail.com>
Co-authored-by: François <francois.mockers@vleue.com>
# Objective
This PR fixes#12125
## Solution
The logic in this PR was borrowed from gloo-net and essentially probes
the global Javascript context to see if we are in a window or a worker
before calling `fetch_with_str`.
---------
Co-authored-by: Zachary Harrold <zac@harrold.com.au>
# Objective
Currently the built docs only shows the logo and favicon for the top
level `bevy` crate. This makes views like
https://docs.rs/bevy_ecs/latest/bevy_ecs/ look potentially unrelated to
the project at first glance.
## Solution
Reproduce the docs attributes for every crate that Bevy publishes.
Ideally this would be done with some workspace level Cargo.toml control,
but AFAICT, such support does not exist.
# Objective
Make it easy to get the ids of all the components in a bundle (and
initialise any components not yet initialised). This is fairly similar
to the `Bundle::get_component_ids()` method added in the observers PR
however that will return none for any non-initialised components. This
is exactly the API space covered by `Bundle::component_ids()` however
that isn't possible to call outside of `bevy_ecs` as it requires `&mut
Components` and `&mut Storages`.
## Solution
Added `World.init_bundle<B: Bundle>()` which similarly to
`init_component` and `init_resource`, initialises all components in the
bundle and returns a vector of their component ids.
---
## Changelog
Added the method `init_bundle` to `World` as a counterpart to
`init_component` and `init_resource`.
---------
Co-authored-by: James Liu <contact@jamessliu.com>
# Objective
- Add serialize feature to bevy_color
- "Fixes #12527".
## Solution
- Added feature for serialization
---
## Changelog
- Serde serialization is now optional, with flag 'serialize'
## Migration Guide
- If user wants color data structures to be serializable, then
application needs to be build with flag 'serialize'
# Objective
- Tiny PR to clarify that `self.world.bundles.init_info::<T>` must have
been called so that the BundleInfo is present in the World
---------
Co-authored-by: James Liu <contact@jamessliu.com>
# Objective
We already collect a lot of system information on startup when possible
but we don't make this information available. With the upcoming work on
a diagnostic overlay it would be useful to be able to display this
information.
## Solution
Make the already existing SystemInfo a Resource
---
## Changelog
Added `SystemInfo` Resource
---------
Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
Co-authored-by: Afonso Lage <lage.afonso@gmail.com>
# Objective
get_asset_paths tries to check whether a folder is empty, and if so
delete it. However rather than checking whether any subfolder contains
files it checks whether _all_ subfolders have files.
Also cleanup various BoxedFutures in async recursive functions like
these, rust 1.77 now allows recursive async functions (albeit still by
boxing), hurray! This is a followup to #12550 (sorta). More BoxedFuture
stuff can be removed now that rust 1.77 is out, which can use async
recursive functions! This is mainly just cleaner code wise - the
recursion still boxes the future so not much to win there.
PR is mainly whitespace changes so do disable whitespace diffs for
easier review.
# Objective
Follow up from PR #12369 to extract lighting structs from light/mod.rs
into their own file.
Part of the Purdue Refactoring Team's goals issue #12349
## Solution
- Moved PointLight from light/mod.rs to light/point_light.rs
- Moved SpotLight from light/mod.rs to light/spot_light.rs
- Moved DirectionalLight from light/mod.rs to light/directional_light.rs
# Objective
Remove color specialization from `SpritePipeline` after it became
useless in #9597
## Solution
Removed the `COLORED` flag from the pipeline key and removed the
specializing the pipeline over it.
---
## Changelog
### Removed
- `SpritePipelineKey` no longer contains the `COLORED` flag. The flag
has had no effect on how the pipeline operates for a while.
## Migration Guide
- The raw values for the `HDR`, `TONEMAP_IN_SHADER` and `DEBAND_DITHER`
flags have changed, so if you were constructing the pipeline key from
raw `u32`s you'll have to account for that.
# Objective
I was reading some of the Archetype and Bundle code and was getting
confused a little bit in some places (is the `archetype_id` in
`AddBundle` the source or the target archetype id?).
Small PR that adds some docstrings to make it easier for first-time
readers.
# Objective
* Adopted #12025 to fix merge conflicts
* In some cases we used manual impls for certain types, though they are
(at least, now) unnecessary.
## Solution
* Use macros and reflecting-by-value to avoid this clutter.
* Though there were linker issues with Reflect and the CowArc in
AssetPath (see https://github.com/bevyengine/bevy/issues/9747), I
checked these are resolved by using #[reflect_value].
---------
Co-authored-by: soqb <cb.setho@gmail.com>
Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
Co-authored-by: James Liu <contact@jamessliu.com>
# Objective
- Clarify that `ButtonInput::just_release` and
`ButtonInput::just_pressed` don't imply information about the state of
`ButtonInput::pressed` or their counterparts.
Fixes#12600
## Solution
Removed Into<AssetId<T>> for Handle<T> as proposed in Issue
conversation, fixed dependent code
## Migration guide
If you use passing Handle by value as AssetId, you should pass reference
or call .id() method on it
Before (0.13):
`assets.insert(handle, value);`
After (0.14):
`assets.insert(&handle, value);`
or
`assets.insert(handle.id(), value);`
# Objective
- Implements maths and `Animatable` for `Srgba` as suggested
[here](https://github.com/bevyengine/bevy/issues/12617#issuecomment-2013494774).
## Solution
- Implements `Animatable` and maths for `Srgba` just like their
implemented for other colors.
---
## Changelog
- Updated the example to mention `Srgba`.
## Migration Guide
- The previously existing implementation of mul/div for `Srgba` did not
modify `alpha` but these operations do modify `alpha` now. Users need to
be aware of this change.
# Objective
- Allow registering of systems from Commands with
`Commands::register_one_shot_system`
- Make registering of one shot systems more easy
## Solution
- Add the Command `RegisterSystem` for Commands use.
- Creation of SystemId based on lazy insertion of the System
- Changed the privacy of the fields in SystemId so Commands can return
the SystemId
---
## Changelog
### Added
- Added command `RegisterSystem`
- Added function `Commands::register_one_shot_system`
- Added function `App::register_one_shot_system`
### Changed
- Changed the privacy and the type of struct tuple to regular struct of
SystemId
## Migration Guide
- Changed SystemId fields from tuple struct to a normal struct
If you want to access the entity field, you should use
`SystemId::entity` instead of `SystemId::0`
## Showcase
> Before, if you wanted to register a system with `Commands`, you would
need to do:
```rust
commands.add(|world: &mut World| {
let id = world.register_system(your_system);
// You would need to insert the SystemId inside an entity or similar
})
```
> Now, you can:
```rust
let id = commands.register_one_shot_system(your_system);
// Do what you want with the Id
```
---------
Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
Co-authored-by: Pablo Reinhardt <pabloreinhardt@gmail.com>
# Context
[GitHub Discussion
Link](https://github.com/bevyengine/bevy/discussions/12506)
# Objective
- **Clarity:** More explicit representation of a common geometric
primitive.
- **Convenience:** Provide methods tailored to 3D triangles (area,
perimeters, etc.).
## Solution
- Adding the `Triangle3d` primitive into the `bevy_math` crate.
---
## Changelog
### Added
- `Triangle3d` primitive to the `bevy_math` crate
### Changed
- `Triangle2d::reverse`: the first and last vertices are swapped instead
of the second and third.
---------
Co-authored-by: Miles Silberling-Cook <NthTensor@users.noreply.github.com>
Co-authored-by: Joona Aalto <jondolf.dev@gmail.com>
# Objective
I'm reading through the ecs query code for the first time, and updating
the docs:
- fixed some typos
- added some docs about things I was confused about (in particular what
the difference between `matches_component_set` and
`update_component_access` was)
# Objective
Fixes#12200 .
## Solution
I added a Hue Trait with the rotate_hue method to enable hue rotation.
Additionally, I modified the implementation of animations in the
animated_material sample.
---
## Changelog
- Added a `Hue` trait to `bevy_color/src/color_ops.rs`.
- Added the `Hue` trait implementation to `Hsla`, `Hsva`, `Hwba`,
`Lcha`, and `Oklcha`.
- Updated animated_material sample.
## Migration Guide
Users of Oklcha need to change their usage to use the with_hue method
instead of the with_h method.
---------
Co-authored-by: Pablo Reinhardt <126117294+pablo-lua@users.noreply.github.com>
Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
# Objective
- Fixes#12202
## Solution
- Implements `Animatable` for all color types implementing arithmetic
operations.
- the colors returned by `Animatable`s methods are already clamped.
- Adds a `color_animation.rs` example.
- Implements the `*Assign` operators for color types that already had
the corresponding operators. This is just a 'nice to have' and I am
happy to remove this if it's not wanted.
---
## Changelog
- `bevy_animation` now depends on `bevy_color`.
- `LinearRgba`, `Laba`, `Oklaba` and `Xyza` implement `Animatable`.
---------
Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
Co-authored-by: Zachary Harrold <zac@harrold.com.au>
# Objective
- It can be useful to have access to the path of the current asset being
processed, for example if you want to need a second file that is
relative to the current file being processed.
## Solution
- I added a `path()` function to the `ProcessContext`
# Objective
- Fixes#12570
## Solution
Previously, cardinal splines constructed by `CubicCardinalSpline` would
leave out their endpoints when constructing the cubic curve segments
connecting their points. (See the linked issue for details.)
Now, cardinal splines include the endpoints. For instance, the provided
usage example
```rust
let points = [
vec2(-1.0, -20.0),
vec2(3.0, 2.0),
vec2(5.0, 3.0),
vec2(9.0, 8.0),
];
let cardinal = CubicCardinalSpline::new(0.3, points).to_curve();
let positions: Vec<_> = cardinal.iter_positions(100).collect();
```
will actually produce a spline that connects all four of these points
instead of just the middle two "interior" points.
Internally, this is achieved by duplicating the endpoints of the vector
of control points before performing the construction of the associated
`CubicCurve`. This amounts to specifying that the tangents at the
endpoints `P_0` and `P_n` (say) should be parallel to `P_1 - P_0` and
`P_n - P_{n-1}`.
---
## Migration Guide
Any users relying on the old behavior of `CubicCardinalSpline` will have
to truncate any parametrizations they used in order to access a curve
identical to the one they had previously. This would be done by chopping
off a unit-distance segment from each end of the parametrizing interval.
For instance, if a user's existing code looks as follows
```rust
fn interpolate(t: f32) -> Vec2 {
let points = [
vec2(-1.0, -20.0),
vec2(3.0, 2.0),
vec2(5.0, 3.0),
vec2(9.0, 8.0),
];
let my_curve = CubicCardinalSpline::new(0.3, points).to_curve();
my_curve.position(t)
}
```
then in order to obtain similar behavior, `t` will need to be shifted up
by 1, since the output of `CubicCardinalSpline::to_curve` has introduced
a new segment in the interval [0,1], displacing the old segment from
[0,1] to [1,2]:
```rust
fn interpolate(t: f32) -> Vec2 {
let points = [
vec2(-1.0, -20.0),
vec2(3.0, 2.0),
vec2(5.0, 3.0),
vec2(9.0, 8.0),
];
let my_curve = CubicCardinalSpline::new(0.3, points).to_curve();
my_curve.position(t+1)
}
```
(Note that this does not provide identical output for values of `t`
outside of the interval [0,1].)
On the other hand, any user who was specifying additional endpoint
tangents simply to get the curve to pass through the right points (i.e.
not requiring exactly the same output) can simply omit the endpoints
that were being supplied only for control purposes.
---
## Discussion
### Design considerations
This is one of the two approaches outlined in #12570 — in this PR, we
are basically declaring that the docs are right and the implementation
was flawed.
One semi-interesting question is how the endpoint tangents actually
ought to be defined when we include them, and another option considered
was mirroring the control points adjacent to the endpoints instead of
duplicating them, which would have had the advantage that the expected
length of the corresponding difference should be more similar to that of
the other difference-tangents, provided that the points are equally
spaced.
In this PR, the duplication method (which produces smaller tangents) was
chosen for a couple reasons:
- It seems to be more standard
- It is exceptionally simple to implement
- I was a little concerned that the aforementioned alternative would
result in some over-extrapolation
### An annoyance
If you look at the code, you'll see I was unable to find a satisfactory
way of doing this without allocating a new vector. This doesn't seem
like a big problem given the context, but it does bother me. In
particular, if there is some easy parallel to `slice::windows` for
iterators that doesn't pull in an external dependency, I would love to
know about it.
# Objective
Lets say I have the following `.meta` file:
```RON
(
meta_format_version: "1.0",
asset: Ignore,
)
```
When a file is inside the `assets` directory and processing is enabled,
the processor will copy the file into `imported_assets` although it
should be ignored and therefore not copied.
## Solution
- I added a simple check that does not copy the assets if the
AssetAction is `Ignore`.
## Migration Guide
- The public `ProcessResult` enum now has a `ProcessResult::Ignore`
variant that must be handled.
# Objective
Fix Pr CI failing over dead code in tests and main branch CI failing
over a missing semicolon. Fixes#12620.
## Solution
Add dead_code annotations and a semicolon.
# Objective
- #12500 use the primary window resolution to do all its calculation.
This means bad support for multiple windows or multiple ui camera
## Solution
- Use camera driven UI (https://github.com/bevyengine/bevy/pull/10559)
# Objective
- since #12500, text is a little bit more gray in UI
## Solution
- don't multiply color by alpha. I think this was done in the original
PR (#8973) for shadows which were not added in #12500
# Objective
- Currently the fps_overlay affects any other ui node spawned. This
should not happen
## Solution
- Use position absolute and a ZIndex of `i32::MAX - 32`
- I also modified the example a little bit to center it correctly. It
only worked previously because the overlay was pushing it down. I also
took the opportunity to simplify the text spawning code a little bit.
# Objective
- #12500 broke images and background colors in UI. Try examples
`overflow`, `ui_scaling` or `ui_texture_atlas`
## Solution
- Makes the component `BorderRadius` optional in the query, as it's not
always present. Use `[0.; 4]` as border radius in the extracted node
when none was found
# Objective
Fixes#12224.
## Solution
- Expand `with_` methods for the `Oklch` to their full names.
- Expand `l` to `lightness` in `Oklaba` comments.
## Migration Guide
The following methods have been renamed for the `Oklch` color space:
- `with_l` -> `with_lightness`.
- `with_c` -> `with_chroma`.
- `with_h` -> `with_hue`.
# Objective
- Many types in bevy_render doesn't reflect Default even if it could.
## Solution
- Reflect it.
---
---------
Co-authored-by: Pablo Reinhardt <pabloreinhardt@gmail.com>
# Objective
- Fixes#12202
## Solution
- This PR implements componentwise (including alpha) addition,
subtraction and scalar multiplication/division for some color types.
- The mentioned color types are `Laba`, `Oklaba`, `LinearRgba` and
`Xyza` as all of them are either physically or perceptually linear as
mentioned by @alice-i-cecile in the issue.
---
## Changelog
- Scalar mul/div for `LinearRgba` may modify alpha now.
## Migration Guide
- Users of scalar mul/div for `LinearRgba` need to be aware of the
change and maybe use the `.clamp()` methods or manually set the `alpha`
channel.
# Objective
Implements border radius for UI nodes. Adopted from #8973, but excludes
shadows.
## Solution
- Add a component `BorderRadius` which contains a radius value for each
corner of the UI node.
- Use a fragment shader to generate the rounded corners using a signed
distance function.
<img width="50%"
src="https://github.com/bevyengine/bevy/assets/26204416/16b2ba95-e274-4ce7-adb2-34cc41a776a5"></img>
## Changelog
- `BorderRadius`: New component that holds the border radius values.
- `NodeBundle` & `ButtonBundle`: Added a `border_radius: BorderRadius`
field.
- `extract_uinode_borders`: Stripped down, most of the work is done in
the shader now. Borders are no longer assembled from multiple rects,
instead the shader uses a signed distance function to draw the border.
- `UiVertex`: Added size, border and radius fields.
- `UiPipeline`: Added three vertex attributes to the vertex buffer
layout, to accept the UI node's size, border thickness and border
radius.
- Examples: Added rounded corners to the UI element in the `button`
example, and a `rounded_borders` example.
---------
Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
Co-authored-by: Zachary Harrold <zac@harrold.com.au>
Co-authored-by: Pablo Reinhardt <126117294+pablo-lua@users.noreply.github.com>
# Objective
- Allow configuring of platform-specific panic handlers.
- Remove the silent overwrite of the WASM panic handler
- Closes#12546
## Solution
- Separates the panic handler to a new plugin, `PanicHandlerPlugin`.
- `PanicHandlerPlugin` was added to `DefaultPlugins`.
- Can be disabled on `DefaultPlugins`, in the case someone needs to
configure custom panic handlers.
---
## Changelog
### Added
- A `PanicHandlerPlugin` was added to the `DefaultPlugins`, which now
sets sensible target-specific panic handlers.
### Changed
- On WASM, the panic stack trace was output to the console through the
`BevyLogPlugin`. Since this was separated out into `PanicHandlerPlugin`,
you may need to add the new `PanicHandlerPlugin` (included in
`DefaultPlugins`).
## Migration Guide
- If you used `MinimalPlugins` with `LogPlugin` for a WASM-target build,
you will need to add the new `PanicHandlerPlugin` to set the panic
behavior to output to the console. Otherwise, you will see the default
panic handler (opaque, `unreachable` errors in the console).
# Objective
- This is an adopted version of #10420
- The objective is to help debugging the Ui layout tree with helpful
outlines, that can be easily enabled/disabled
## Solution
- Like #10420, the solution is using the bevy_gizmos in outlining the
nodes
---
## Changelog
### Added
- Added debug_overlay mod to `bevy_dev_tools`
- Added bevy_ui_debug feature to `bevy_dev_tools`
## How to use
- The user must use `bevy_dev_tools` feature in TOML
- The user must use the plugin UiDebugPlugin, that can be found on
`bevy::dev_tools::debug_overlay`
- Finally, to enable the function, the user must set
`UiDebugOptions::enabled` to true
Someone can easily toggle the function with something like:
```rust
fn toggle_overlay(input: Res<ButtonInput<KeyCode>>, options: ResMut<UiDebugOptions>) {
if input.just_pressed(KeyCode::Space) {
// The toggle method will enable if disabled and disable if enabled
options.toggle();
}
}
```
Note that this feature can be disabled from dev_tools, as its in fact
behind a default feature there, being the feature bevy_ui_debug.
# Limitations
Currently, due to limitations with gizmos itself, it's not possible to
support this feature to more the one window, so this tool is limited to
the primary window only.
# Showcase
![image](https://github.com/bevyengine/bevy/assets/126117294/ce9d70e6-0a57-4fa9-9753-ff5a9d82c009)
Ui example with debug_overlay enabled
![image](https://github.com/bevyengine/bevy/assets/126117294/e945015c-5bab-4d7f-9273-472aabaf25a9)
And disabled
---------
Co-authored-by: Nicola Papale <nico@nicopap.ch>
Co-authored-by: Pablo Reinhardt <pabloreinhardt@gmail.com>
Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
# Objective
Give Bevy a well-designed built-in color palette for users to use while
prototyping or authoring Bevy examples.
## Solution
Generate
([playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=f7b3a3002fb7727db15c1197e0a1a373),
[gist](https://gist.github.com/rust-play/f7b3a3002fb7727db15c1197e0a1a373))
consts from [Tailwind](https://tailwindcss.com/docs/customizing-colors)
(mit license) json.
## Discussion
Are there other popular alternatives we should be looking at? Something
new and fancy involving a really long acronym like CIELUVLCh? I'm not a
tailwind user or color expert, but I really like the way it's broken up
into distinct but plentiful hue and lightness groups.
It beats needing some shades of red, scrolling through the [current
palette](https://docs.rs/bevy/latest/bevy/prelude/enum.Color.html),
choosing a few of `CRIMSON`, `MAROON`, `RED`, `TOMATO` at random and
calling it a day.
The best information I was able to dig up about the Tailwind palette is
from this thread:
https://twitter.com/steveschoger/status/1303795136703410180. Here are
some key excerpts:
> Tried to the "perceptually uniform" thing for Tailwind UI.
> Ultimately, it just resulted in a bunch of useless shades for colors
like yellow and green that are inherently brighter.
> With that said you're guaranteed to get a contrast ratio of 4.5:1 when
using any 700 shade (in some cases 600) on a 100 shade of the same hue.
> We just spent a lot of time looking at sites to figure out which
colors are popular and tried to fill all the gaps.
> Even the lime green is questionable but felt there needed to be
something in between the jump from yellow to green 😅
---------
Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
# Objective
Simplify implementing some asset traits without Box::pin(async move{})
shenanigans.
Fixes (in part) https://github.com/bevyengine/bevy/issues/11308
## Solution
Use async-fn in traits when possible in all traits. Traits with return
position impl trait are not object safe however, and as AssetReader and
AssetWriter are both used with dynamic dispatch, you need a Boxed
version of these futures anyway.
In the future, Rust is [adding
](https://blog.rust-lang.org/2023/12/21/async-fn-rpit-in-traits.html)proc
macros to generate these traits automatically, and at some point in the
future dyn traits should 'just work'. Until then.... this seemed liked
the right approach given more ErasedXXX already exist, but, no clue if
there's plans here! Especially since these are public now, it's a bit of
an unfortunate API, and means this is a breaking change.
In theory this saves some performance when these traits are used with
static dispatch, but, seems like most code paths go through dynamic
dispatch, which boxes anyway.
I also suspect a bunch of the lifetime annotations on these function
could be simplified now as the BoxedFuture was often the only thing
returned which needed a lifetime annotation, but I'm not touching that
for now as traits + lifetimes can be so tricky.
This is a revival of
[pull/11362](https://github.com/bevyengine/bevy/pull/11362) after a
spectacular merge f*ckup, with updates to the latest Bevy. Just to recap
some discussion:
- Overall this seems like a win for code quality, especially when
implementing these traits, but a loss for having to deal with ErasedXXX
variants.
- `ConditionalSend` was the preferred name for the trait that might be
Send, to deal with wasm platforms.
- When reviewing be sure to disable whitespace difference, as that's 95%
of the PR.
## Changelog
- AssetReader, AssetWriter, AssetLoader, AssetSaver and Process now use
async-fn in traits rather than boxed futures.
## Migration Guide
- Custom implementations of AssetReader, AssetWriter, AssetLoader,
AssetSaver and Process should switch to async fn rather than returning a
bevy_utils::BoxedFuture.
- Simultaniously, to use dynamic dispatch on these traits you should
instead use dyn ErasedXXX.
# Objective
- Not all materials need shadow, but a queue_shadows system is always
added to the `Render` schedule and executed
## Solution
- Make a setting for shadows, it defaults to true
## Changelog
- Added `shadows_enabled` setting to `MaterialPlugin`
## Migration Guide
- `MaterialPlugin` now has a `shadows_enabled` setting, if you didn't
spawn the plugin using `::default()` or `..default()`, you'll need to
set it. `shadows_enabled: true` is the same behavior as the previous
version, and also the default value.
# Objective
Currently in order to retrieve the inner values from direction types is
that you need to use the `Deref` trait or `From`/`Into`. `Deref` that is
currently implemented is an anti-pattern that I believe should be less
relied upon.
This pull-request add getters for retrieving the inner values for
direction types.
Advantages of getters:
- Let rust-analyzer to list out available methods for users to
understand better to on how to get the inner value. (This happens to me.
I really don't know how to get the value until I look through the source
code.)
- They are simple.
- Generally won't be ambiguous in most context. Traits such as
`From`/`Into` will require fully qualified syntax from time to time.
- Unsurprising result.
Disadvantages of getters:
- More verbose
Advantages of deref polymorphism:
- You reduce boilerplate for getting the value and call inner methods
by:
```rust
let dir = Dir3::new(Vec3::UP).unwrap();
// getting value
let value = *dir;
// instead of using getters
let value = dir.vec3();
// calling methods for the inner vector
dir.xy();
// instead of using getters
dir.vec3().xy();
```
Disadvantages of deref polymorphism:
- When under more level of indirection, it will requires more
dereferencing which will get ugly in some part:
```rust
// getting value
let value = **dir;
// instead of using getters
let value = dir.vec3();
// calling methods for the inner vector
dir.xy();
// instead of using getters
dir.vec3().xy();
```
[More detail
here](https://rust-unofficial.github.io/patterns/anti_patterns/deref.html).
Edit: Update information for From/Into trait.
Edit: Advantages and disadvantages.
## Solution
Add `vec2` method for Dir2.
Add `vec3` method for Dir3.
Add `vec3a` method for Dir3A.
# Objective
prevent gpu buffer allocations when running `as_bind_group` for assets
with texture dependencies that are not yet available.
## Solution
reorder the binding creation so that fallible items are created first.
# Objective
Resolves#12431.
## Solution
Added a `skip_taskbar` field to the `Window` struct (defaults to
`false`). Used in `create_windows` if the target OS is Windows.
Updates the requirements on
[base64](https://github.com/marshallpierce/rust-base64) to permit the
latest version.
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a
href="https://github.com/marshallpierce/rust-base64/blob/master/RELEASE-NOTES.md">base64's
changelog</a>.</em></p>
<blockquote>
<h1>0.22.0</h1>
<ul>
<li><code>DecodeSliceError::OutputSliceTooSmall</code> is now
conservative rather than precise. That is, the error will only occur if
the decoded output <em>cannot</em> fit, meaning that
<code>Engine::decode_slice</code> can now be used with exactly-sized
output slices. As part of this, <code>Engine::internal_decode</code> now
returns <code>DecodeSliceError</code> instead of
<code>DecodeError</code>, but that is not expected to affect any
external callers.</li>
<li><code>DecodeError::InvalidLength</code> now refers specifically to
the <em>number of valid symbols</em> being invalid (i.e. <code>len % 4
== 1</code>), rather than just the number of input bytes. This avoids
confusing scenarios when based on interpretation you could make a case
for either <code>InvalidLength</code> or <code>InvalidByte</code> being
appropriate.</li>
<li>Decoding is somewhat faster (5-10%)</li>
</ul>
<h1>0.21.7</h1>
<ul>
<li>Support getting an alphabet's contents as a str via
<code>Alphabet::as_str()</code></li>
</ul>
<h1>0.21.6</h1>
<ul>
<li>Improved introductory documentation and example</li>
</ul>
<h1>0.21.5</h1>
<ul>
<li>Add <code>Debug</code> and <code>Clone</code> impls for the general
purpose Engine</li>
</ul>
<h1>0.21.4</h1>
<ul>
<li>Make <code>encoded_len</code> <code>const</code>, allowing the
creation of arrays sized to encode compile-time-known data lengths</li>
</ul>
<h1>0.21.3</h1>
<ul>
<li>Implement <code>source</code> instead of <code>cause</code> on Error
types</li>
<li>Roll back MSRV to 1.48.0 so Debian can continue to live in a time
warp</li>
<li>Slightly faster chunked encoding for short inputs</li>
<li>Decrease binary size</li>
</ul>
<h1>0.21.2</h1>
<ul>
<li>Rollback MSRV to 1.57.0 -- only dev dependencies need 1.60, not the
main code</li>
</ul>
<h1>0.21.1</h1>
<ul>
<li>Remove the possibility of panicking during decoded length
calculations</li>
<li><code>DecoderReader</code> no longer sometimes erroneously ignores
padding <a
href="https://redirect.github.com/marshallpierce/rust-base64/issues/226">#226</a></li>
</ul>
<h2>Breaking changes</h2>
<ul>
<li><code>Engine.internal_decode</code> return type changed</li>
<li>Update MSRV to 1.60.0</li>
</ul>
<h1>0.21.0</h1>
<h2>Migration</h2>
<h3>Functions</h3>
<!-- raw HTML omitted -->
</blockquote>
<p>... (truncated)</p>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="5d70ba7576"><code>5d70ba7</code></a>
Merge pull request <a
href="https://redirect.github.com/marshallpierce/rust-base64/issues/269">#269</a>
from marshallpierce/mp/decode-precisely</li>
<li><a
href="efb6c006c7"><code>efb6c00</code></a>
Release notes</li>
<li><a
href="2b91084a31"><code>2b91084</code></a>
Add some tests to boost coverage</li>
<li><a
href="9e9c7abe65"><code>9e9c7ab</code></a>
Engine::internal_decode now returns DecodeSliceError</li>
<li><a
href="a8a60f43c5"><code>a8a60f4</code></a>
Decode main loop improvements</li>
<li><a
href="a25be0667c"><code>a25be06</code></a>
Simplify leftover output writes</li>
<li><a
href="9979cc33bb"><code>9979cc3</code></a>
Keep morsels as separate bytes</li>
<li><a
href="37670c5ec2"><code>37670c5</code></a>
Bump dev toolchain version (<a
href="https://redirect.github.com/marshallpierce/rust-base64/issues/268">#268</a>)</li>
<li><a
href="9652c78773"><code>9652c78</code></a>
v0.21.7</li>
<li><a
href="08deccf703"><code>08deccf</code></a>
provide as_str() method to return the alphabet characters (<a
href="https://redirect.github.com/marshallpierce/rust-base64/issues/264">#264</a>)</li>
<li>Additional commits viewable in <a
href="https://github.com/marshallpierce/rust-base64/compare/v0.21.5...v0.22.0">compare
view</a></li>
</ul>
</details>
<br />
Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.
[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)
---
<details>
<summary>Dependabot commands and options</summary>
<br />
You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot merge` will merge this PR after your CI passes on it
- `@dependabot squash and merge` will squash and merge this PR after
your CI passes on it
- `@dependabot cancel merge` will cancel a previously requested merge
and block automerging
- `@dependabot reopen` will reopen this PR if it is closed
- `@dependabot close` will close this PR and stop Dependabot recreating
it. You can achieve the same result by closing it manually
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore this major version` will close this PR and stop
Dependabot creating any more for this major version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop
Dependabot creating any more for this minor version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop
Dependabot creating any more for this dependency (unless you reopen the
PR or upgrade to it yourself)
</details>
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
# Objective
Fixes#12549. WorldCell's support of everything a World can do is
incomplete, and represents an alternative, potentially confusing, and
less performant way of pulling multiple fetches from a `World`. The
typical approach is to use `SystemState` for a runtime cached and safe
way, or `UnsafeWorldCell` if the use of `unsafe` is tolerable.
## Solution
Remove it!
---
## Changelog
Removed: `WorldCell`
Removed: `World::cell`
## Migration Guide
`WorldCell` has been removed. If you were using it to fetch multiple
distinct values from a `&mut World`, use `SystemState` by calling
`SystemState::get` instead. Alternatively, if `SystemState` cannot be
used, `UnsafeWorldCell` can instead be used in unsafe contexts.
# Objective
- working with UI components in Bevy, I found myself wanting some of
these common traits, like `PartialEq` for comparing simple types
## Solution
- I added only (hopefully) uncontroversial `derive`s for some common UI
types
Note that many types, unfortunately, can't have `PartialEq` `derive`d
for them, because they contain `f32`s and / or `Vec`s.
# Objective
I wanted to have reflection for BinaryHeap for a personal project.
I'm running into some issues:
- I wanted to represent BinaryHeap as a reflect::List type since it's
essentially a wrapper around a Vec, however there's no public way to
access the underlying Vec, which makes it hard to implement the
reflect::List methods. I have omitted the reflect::List methods for
now.. I'm not sure if that's a blocker?
- what would be the alternatives? Simply not implement `reflect::List`?
It is possible to implement `FromReflect` without it. Would the type be
`Struct` then?
---------
Co-authored-by: Charles Bournhonesque <cbournhonesque@snapchat.com>
# Objective
Provide component access to `&'w T`, `Ref<'w, T>`, `Mut<'w, T>`,
`Ptr<'w>` and `MutUntyped<'w>` from `EntityMut<'w>`/`EntityWorldMut<'w>`
with the world `'w` lifetime instead of `'_`.
Fixes#12417
## Solution
Add `into_` prefixed methods for `EntityMut<'w>`/`EntityWorldMut<'w>`
that consume `self` and returns component access with the world `'w`
lifetime unlike the `get_` prefixed methods that takes `&'a self` and
returns component access with `'a` lifetime.
Methods implemented:
- EntityMut::into_borrow
- EntityMut::into_ref
- EntityMut::into_mut
- EntityMut::into_borrow_by_id
- EntityMut::into_mut_by_id
- EntityWorldMut::into_borrow
- EntityWorldMut::into_ref
- EntityWorldMut::into_mut
- EntityWorldMut::into_borrow_by_id
- EntityWorldMut::into_mut_by_id
# Objective
fix#12344
## Solution
use existing machinery in track_assets to determine if the asset is
unused before firing Asset::Unused event
~~most extract functions use `AssetEvent::Removed` to schedule deletion
of render world resources. `RenderAssetPlugin` was using
`AssetEvent::Unused` instead.
`Unused` fires when the last strong handle is dropped, even if a new one
is created. `Removed` only fires when a new one is not created.
as far as i can see, `Unused` is the same as `Removed` except for this
"feature", and that it also fires early if all handles for a loading
asset are dropped (`Removed` fires after the loading completes). note
that in that case, processing based on `Loaded` won't have been done
anyway.
i think we should get rid of `Unused` completely, it is not currently
used anywhere (except here, previously) and i think using it is probably
always a mistake.
i also am not sure why we keep loading assets that have been dropped
while loading, we should probably drop the loader task as well and
remove immediately.~~
# Objective
Whenever a nodes size gets changed, its texture slices get updated a
frame later. This results in visual glitches when animating the size of
a node with a texture slice. See this video:
[Screencast from 17-03-24
14:53:13.webm](https://github.com/bevyengine/bevy/assets/46689298/64e711f7-a1ec-41e3-b119-dc8d7e1a7669)
## Solution
Compute texture slices after the layout system has finished.
# Objective
- Resolves#12463
## Solution
- Added `ClampColor`
Due to consistency, `is_within_bounds` is a method of `ClampColor`, like
`is_fully_transparent` is a method of `Alpha`
---
## Changelog
### Added
- `ClampColor` trait
---------
Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
# Objective
It's useful to have access to render pipeline statistics, since they
provide more information than FPS alone. For example, the number of
drawn triangles can be used to debug culling and LODs. The number of
fragment shader invocations can provide a more stable alternative metric
than GPU elapsed time.
See also: Render node GPU timing overlay #8067, which doesn't provide
pipeline statistics, but adds a nice overlay.
## Solution
Add `RenderDiagnosticsPlugin`, which enables collecting pipeline
statistics and CPU & GPU timings.
---
## Changelog
- Add `RenderDiagnosticsPlugin`
- Add `RenderContext::diagnostic_recorder` method
---------
Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
# Objective
`QueryState::archetype_component_access` is only really ever used to
extend `SystemMeta`'s. It can be removed to save some memory for every
`Query` in an app.
## Solution
* Remove it.
* Have `new_archetype` pass in a `&mut Access<ArchetypeComponentId>`
instead and pull it from `SystemMeta` directly.
* Split `QueryState::new` from `QueryState::new_with_access` and a
common `QueryState::new_uninitialized`.
* Split `new_archetype` into an internal and public version. Call the
internal version in `update_archetypes`.
This should make it faster to construct new QueryStates, and by proxy
lenses and joins as well.
`matched_tables` also similarly is only used to deduplicate inserting
into `matched_table_ids`. If we can find another efficient way to do so,
it might also be worth removing.
The [generated
assembly](https://github.com/james7132/bevy_asm_tests/compare/main...remove-query-state-archetype-component-access#diff-496530101f0b16e495b7e9b77c0e906ae3068c8adb69ed36c92d5a1be5a9efbe)
reflects this well, with all of the access related updates in
`QueryState` being removed.
---
## Changelog
Removed: `QueryState::archetype_component_access`.
Changed: `QueryState::new_archetype` now takes a `&mut
Access<ArchetypeComponentId>` argument, which will be updated with the
new accesses.
Changed: `QueryState::update_archetype_component_access` now takes a
`&mut Access<ArchetypeComponentId>` argument, which will be updated with
the new accesses.
## Migration Guide
TODO
# Objective
Improve code quality involving fixedbitset.
## Solution
Update to fixedbitset 0.5. Use the new `grow_and_insert` function
instead of `grow` and `insert` functions separately.
This should also speed up most of the set operations involving
fixedbitset. They should be ~2x faster, but testing this against the
stress tests seems to show little to no difference. The multithreaded
executor doesn't seem to be all that much faster in many_cubes and
many_foxes. These use cases are likely dominated by other operations or
the bitsets aren't big enough to make them the bottleneck.
This introduces a duplicate dependency due to petgraph and wgpu, but the
former may take some time to update.
## Changelog
Removed: `Access::grow`
## Migration Guide
`Access::grow` has been removed. It's no longer needed. Remove all
references to it.
# Objective
Make `Transform` APIs more ergonomic by allowing users to pass `Dir3` as
an argument where a direction is needed. Fixes#12481.
## Solution
Accept `impl TryInto<Dir3>` instead of `Vec3` for direction/axis
arguments in `Transform` APIs
---
## Changelog
The following `Transform` methods now accept an `impl TryInto<Dir3>`
argument where they previously accepted directions as `Vec3`:
* `Transform::{look_to,looking_to}`
* `Transform::{look_at,looking_at}`
* `Transform::{align,aligned_by}`
## Migration Guide
This is not a breaking change since the arguments were previously `Vec3`
which already implements `TryInto<Dir3>`, and behavior is unchanged.
---------
Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
Co-authored-by: IQuick 143 <IQuick143cz@gmail.com>
# Objective
- Even if we have `Laba` and `Oklcha` colorspaces using lightness as the
L field name, `Oklaba` doesn't do the same
- The shorthand function for creating a new color should be named
`Oklaba::lab`, but is named `lch`
## Solution
- Rename field l in `Oklaba` to lightness
- Rename `Oklaba::lch` to `Oklaba::lab`
---
## Changelog
### Changed
- Changed name in l field in `Oklaba` to lightness
- Changed method name `Oklaba::lch` to `Oklaba::lab`
## Migration Guide
If you were creating a Oklaba instance directly, instead of using L, you
should use lightness
```rust
// Before
let oklaba = Oklaba { l: 1., ..Default::default() };
// Now
let oklaba = Oklaba { lightness: 1., ..Default::default() };
```
if you were using the function `Oklaba::lch`, now the method is named
`Oklaba::lab`
# Objective
Give easy methods for uniform point sampling in a variety of primitive
shapes (particularly useful for circles and spheres) because in a lot of
cases its quite easy to get wrong (non-uniform).
## Solution
Added the `ShapeSample` trait to `bevy_math` and implemented it for
`Circle`, `Sphere`, `Rectangle`, `Cuboid`, `Cylinder`, `Capsule2d` and
`Capsule3d`. There are a few other shapes it would be reasonable to
implement for like `Triangle`, `Ellipse` and `Torus` but I'm not
immediately sure how these would be implemented (other than rejection
which could be the best method, and could be more performant than some
of the solutions in this pr I'm not sure). This exposes the
`sample_volume` and `sample_surface` methods to get both a random point
from its interior or its surface. EDIT: Renamed `sample_volume` to
`sample_interior` and `sample_surface` to `sample_boundary`
This brings in `rand` as a default optional dependency (without default
features), and the methods take `&mut impl Rng` which allows them to use
any random source implementing `RngCore`.
---
## Changelog
### Added
Added the methods `sample_interior` and `sample_boundary` to a variety
of primitive shapes providing easy uniform point sampling.
# Objective
assets that don't load before they get removed are retried forever,
causing buffer churn and slowdown.
## Solution
stop trying to prepare dead assets.
# Objective
Originally proposed as part of #8973. Adds `with_` methods for each side
of `UiRect`
## Solution
Add `with_left`, `with_right`, `with_top`, `with_bottom` to `UiRect`.
# Objective
Add reflect for `std::any::TypeId`.
I couldn't add ReflectSerialize/ReflectDeserialize for it, it was giving
me an error. I don't really understand why, since it works for
`std::path::PathBuf`.
Co-authored-by: Charles Bournhonesque <cbournhonesque@snapchat.com>
# Objective
Fixes#12480
by removing the explicit mention of equally sized triangles from the doc
for icospheres
Co-authored-by: Emi <emanuel.boehm@gmail.com>
# Objective
Fixes#12139
## Solution
- Derive `Debug` impl for `Entity`
- Add impl `Display` for `Entity`
- Add `entity_display` test to check the output contains all required
info
I decided to go with `0v0|1234` format as opposed to the `0v0[1234]`
which was initially discussed in the issue.
My rationale for this is that `[1234]` may be confused for index values,
which may be common in logs, and so searching for entities by text would
become harder. I figured `|1234` would help the entity IDs stand out
more.
Additionally, I'm a little concerned that this change is gonna break
existing logging for projects because `Debug` is now going to be a
multi-line output. But maybe this is ok.
We could implement `Debug` to be a single-line output, but then I don't
see why it would be different from `Display` at all.
@alice-i-cecile Let me know if we'd like to make any changes based on
these points.
# Objective
- Closes#11793
- Introduces a general API for aligning local coordinates of Transforms
with given vectors.
## Solution
- We introduce `Transform::align`, which allows a rotation to be
specified by four pieces of alignment data, as explained by the
documentation:
````rust
/// Rotates this [`Transform`] so that the `main_axis` vector, reinterpreted in local coordinates, points
/// in the given `main_direction`, while `secondary_axis` points towards `secondary_direction`.
///
/// For example, if a spaceship model has its nose pointing in the X-direction in its own local coordinates
/// and its dorsal fin pointing in the Y-direction, then `align(Vec3::X, v, Vec3::Y, w)` will make the spaceship's
/// nose point in the direction of `v`, while the dorsal fin does its best to point in the direction `w`.
///
/// More precisely, the [`Transform::rotation`] produced will be such that:
/// * applying it to `main_axis` results in `main_direction`
/// * applying it to `secondary_axis` produces a vector that lies in the half-plane generated by `main_direction` and
/// `secondary_direction` (with positive contribution by `secondary_direction`)
///
/// [`Transform::look_to`] is recovered, for instance, when `main_axis` is `Vec3::NEG_Z` (the [`Transform::forward`]
/// direction in the default orientation) and `secondary_axis` is `Vec3::Y` (the [`Transform::up`] direction in the default
/// orientation). (Failure cases may differ somewhat.)
///
/// In some cases a rotation cannot be constructed. Another axis will be picked in those cases:
/// * if `main_axis` or `main_direction` is zero, `Vec3::X` takes its place
/// * if `secondary_axis` or `secondary_direction` is zero, `Vec3::Y` takes its place
/// * if `main_axis` is parallel with `secondary_axis` or `main_direction` is parallel with `secondary_direction`,
/// a rotation is constructed which takes `main_axis` to `main_direction` along a great circle, ignoring the secondary
/// counterparts
///
/// Example
/// ```
/// # use bevy_math::{Vec3, Quat};
/// # use bevy_transform::components::Transform;
/// let mut t1 = Transform::IDENTITY;
/// let mut t2 = Transform::IDENTITY;
/// t1.align(Vec3::ZERO, Vec3::Z, Vec3::ZERO, Vec3::X);
/// t2.align(Vec3::X, Vec3::Z, Vec3::Y, Vec3::X);
/// assert_eq!(t1.rotation, t2.rotation);
///
/// t1.align(Vec3::X, Vec3::Z, Vec3::X, Vec3::Y);
/// assert_eq!(t1.rotation, Quat::from_rotation_arc(Vec3::X, Vec3::Z));
/// ```
pub fn align(
&mut self,
main_axis: Vec3,
main_direction: Vec3,
secondary_axis: Vec3,
secondary_direction: Vec3,
) { //... }
````
- We introduce `Transform::aligned_by`, the returning-Self version of
`align`:
````rust
pub fn aligned_by(
mut self,
main_axis: Vec3,
main_direction: Vec3,
secondary_axis: Vec3,
secondary_direction: Vec3,
) -> Self { //... }
````
- We introduce an example (examples/transforms/align.rs) that shows the
usage of this API. It is likely to be mathier than most other
`Transform` APIs, so when run, the example demonstrates what the API
does in space:
<img width="1440" alt="Screenshot 2024-03-12 at 11 01 19 AM"
src="https://github.com/bevyengine/bevy/assets/2975848/884b3cc3-cbd9-48ae-8f8c-49a677c59dfe">
---
## Changelog
- Added methods `align`, `aligned_by` to `Transform`.
- Added transforms/align.rs to examples.
---
## Discussion
### On the form of `align`
The original issue linked above suggests an API similar to that of the
existing `Transform::look_to` method:
````rust
pub fn align_to(&mut self, direction: Vec3, up: Vec3) { //... }
````
Not allowing an input axis of some sort that is to be aligned with
`direction` would not really solve the problem in the issue, since the
user could easily be in a scenario where they have to compose with
another rotation on their own (undesirable). This leads to something
like:
````rust
pub fn align_to(&mut self, axis: Vec3, direction: Vec3, up: Vec3) { //... }
````
However, this still has two problems:
- If the vector that the user wants to align is parallel to the Y-axis,
then the API basically does not work (we cannot fully specify a
rotation)
- More generally, it does not give the user the freedom to specify which
direction is to be treated as the local "up" direction, so it fails as a
general alignment API
Specifying both leads us to the present situation, with two local axis
inputs (`main_axis` and `secondary_axis`) and two target directions
(`main_direction` and `secondary_direction`). This might seem a little
cumbersome for general use, but for the time being I stand by the
decision not to expand further without prompting from users. I'll expand
on this below.
### Additional APIs?
Presently, this PR introduces only `align` and `aligned_by`. Other
potentially useful bundles of API surface arrange into a few different
categories:
1. Inferring direction from position, a la `Transform::look_at`, which
might look something like this:
````rust
pub fn align_at(&mut self, axis: Vec3, target: Vec3, up: Vec3) {
self.align(axis, target - self.translation, Vec3::Y, up);
}
````
(This is simple but still runs into issues when the user wants to point
the local Y-axis somewhere.)
2. Filling in some data for the user for common use-cases; e.g.:
````rust
pub fn align_x(&mut self, direction: Vec3, up: Vec3) {
self.align(Vec3::X, direction, Vec3::Y, up);
}
````
(Here, use of the `up` vector doesn't lose any generality, but it might
be less convenient to specify than something else. This does naturally
leave open the question of what `align_y` would look like if we provided
it.)
Morally speaking, I do think that the `up` business is more pertinent
when the intention is to work with cameras, which the `look_at` and
`look_to` APIs seem to cover pretty well. If that's the case, then I'm
not sure what the ideal shape for these API functions would be, since it
seems like a lot of input would have to be baked into the function
definitions. For some cases, this might not be the end of the world:
````rust
pub fn align_x_z(&mut self, direction: Vec3, weak_direction: Vec3) {
self.align(Vec3::X, direction, Vec3::Z, weak_direction);
}
````
(However, this is not symmetrical in x and z, so you'd still need six
API functions just to support the standard positive coordinate axes, and
if you support negative axes then things really start to balloon.)
The reasons that these are not actually produced in this PR are as
follows:
1. Without prompting from actual users in the wild, it is unknown to me
whether these additional APIs would actually see a lot of use. Extending
these to our users in the future would be trivial if we see there is a
demand for something specific from the above-mentioned categories.
2. As discussed above, there are so many permutations of these that
could be provided that trying to do so looks like it risks unduly
ballooning the API surface for this feature.
3. Finally, and most importantly, creating these helper functions in
user-space is trivial, since they all just involve specializing `align`
to particular inputs; e.g.:
````rust
fn align_ship(ship_transform: &mut Transform, nose_direction: Vec3, dorsal_direction: Vec3) {
ship_transform.align(Ship::NOSE, nose_direction, Ship::DORSAL, dorsal_direction);
}
````
With that in mind, I would prefer instead to focus on making the
documentation and examples for a thin API as clear as possible, so that
users can get a grip on the tool and specialize it for their own needs
when they feel the desire to do so.
### `Dir3`?
As in the case of `Transform::look_to` and `Transform::look_at`, the
inputs to this function are, morally speaking, *directions* rather than
vectors (actually, if we're being pedantic, the input is *really really*
a pair of orthonormal frames), so it's worth asking whether we should
really be using `Dir3` as inputs instead of `Vec3`. I opted for `Vec3`
for the following reasons:
1. Specifying a `Dir3` in user-space is just more annoying than
providing a `Vec3`. Even in the most basic cases (e.g. providing a
vector literal), you still have to do error handling or call an unsafe
unwrap in your function invocations.
2. The existing API mentioned above uses `Vec3`, so we are just adhering
to the same thing.
Of course, the use of `Vec3` has its own downsides; it can be argued
that the replacement of zero-vectors with fixed ones (which we do in
`Transform::align` as well as `Transform::look_to`) more-or-less amounts
to failing silently.
### Future steps
The question of additional APIs was addressed above. For me, the main
thing here to handle more immediately is actually just upstreaming this
API (or something similar and slightly mathier) to `glam::Quat`. The
reason that this would be desirable for users is that this API currently
only works with `Transform`s even though all it's actually doing is
specifying a rotation. Upstreaming to `glam::Quat`, properly done, could
buy a lot basically for free, since a number of `Transform` methods take
a rotation as an input. Using these together would require a little bit
of mathematical savvy, but it opens up some good things (e.g.
`Transform::rotate_around`).
# Objective
- Addresses #12462
- When we serialize an enum, deserialize it, then reserialize it, the
correct variant should be selected.
## Solution
- Change `dynamic_enum.set_variant` to
`dynamic_enum.set_variant_with_index` in `EnumVisitor`
# Objective
- Adds 3d grids, suggestion of #9400
## Solution
- Added 3d grids (grids spanning all three dimensions, not flat grids)
to bevy_gizmos
---
## Changelog
- `gizmos.grid(...)` and `gizmos.grid_2d(...)` now return a
`GridBuilder2d`.
- Added `gizmos.grid_3d(...)` which returns a `GridBuilder3d`.
- The difference between them is basically only that `GridBuilder3d`
exposes some methods for configuring the z axis while the 2d version
doesn't.
- Allowed for drawing the outer edges along a specific axis by calling
`.outer_edges_x()`, etc. on the builder.
## Additional information
Please note that I have not added the 3d grid to any example as not to
clutter them.
Here is an image of what the 3d grid looks like:
<img width="1440" alt="Screenshot 2024-03-12 at 02 19 55"
src="https://github.com/bevyengine/bevy/assets/62256001/4cd3b7de-cf2c-4f05-8a79-920a4dd804b8">
---------
Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
# Objective
Beginning of refactoring of light.rs in bevy_pbr, as per issue #12349
Create and move light.rs to its own directory, and extract AmbientLight
struct.
## Solution
- moved light.rs to light/mod.rs
- extracted AmbientLight struct to light/ambient_light.rs
# Objective
Fixes#12064
## Solution
Prior to #11326, the "global physical" translation of text was rounded.
After #11326, only the "offset" is being rounded.
This moves things around so that the "global translation" is converted
to physical pixels, rounded, and then converted back to logical pixels,
which is what I believe was happening before / what the comments above
describe.
## Discussion
This seems to work and fix an obvious mistake in some code, but I don't
fully grok the ui / text pipelines / math here.
## Before / After and test example
<details>
<summary>Expand Code</summary>
```rust
use std::f32::consts::FRAC_PI_2;
use bevy::prelude::*;
use bevy_internal:🪟:WindowResolution;
const FONT_SIZE: f32 = 25.0;
const PADDING: f32 = 5.0;
fn main() {
App::new()
.add_plugins(
DefaultPlugins.set(WindowPlugin {
primary_window: Some(Window {
resolution: WindowResolution::default().with_scale_factor_override(1.0),
..default()
}),
..default()
}),
//.set(ImagePlugin::default_nearest()),
)
.add_systems(Startup, setup)
.run();
}
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
commands.spawn(Camera2dBundle::default());
let font = asset_server.load("fonts/FiraSans-Bold.ttf");
for x in [20.5, 140.0] {
for i in 1..10 {
text(
&mut commands,
font.clone(),
x,
(FONT_SIZE + PADDING) * i as f32,
i,
Quat::default(),
1.0,
);
}
}
for x in [450.5, 700.0] {
for i in 1..10 {
text(
&mut commands,
font.clone(),
x,
((FONT_SIZE * 2.0) + PADDING) * i as f32,
i,
Quat::default(),
2.0,
);
}
}
for y in [400.0, 600.0] {
for i in 1..10 {
text(
&mut commands,
font.clone(),
(FONT_SIZE + PADDING) * i as f32,
y,
i,
Quat::from_rotation_z(FRAC_PI_2),
1.0,
);
}
}
}
fn text(
commands: &mut Commands,
font: Handle<Font>,
x: f32,
y: f32,
i: usize,
rot: Quat,
scale: f32,
) {
let text = (65..(65 + i)).map(|a| a as u8 as char).collect::<String>();
commands.spawn(TextBundle {
style: Style {
position_type: PositionType::Absolute,
left: Val::Px(x),
top: Val::Px(y),
..default()
},
text: Text::from_section(
text,
TextStyle {
font,
font_size: FONT_SIZE,
..default()
},
),
transform: Transform::from_rotation(rot).with_scale(Vec2::splat(scale).extend(1.)),
..default()
});
}
```
</details>
Open both images in new tabs and swap back and forth. Pay attention to
the "A" and "ABCD" lines.
<details>
<summary>Before</summary>
<img width="640" alt="main3"
src="https://github.com/bevyengine/bevy/assets/200550/248d7a55-d06d-433f-80da-1914803c3551">
</details>
<details>
<summary>After</summary>
<img width="640" alt="pr3"
src="https://github.com/bevyengine/bevy/assets/200550/26a9d292-07ae-4af3-b035-e187b2529ace">
</details>
---------
Co-authored-by: François Mockers <mockersf@gmail.com>
# Objective
`System<f32>` currently does not implement `Eq` even though it should
## Solution
Manually implement `Eq` like other traits are manually implemented
# Objective
To have a user level workaround for #12237.
## Solution
Workaround to the problem is described in:
https://github.com/bevyengine/bevy/issues/12237#issuecomment-1983680632
## Changelog
### Changed
- `CreateWindowParams` type and `create_windows` system from
`bevy_winit` is now public, which allows library authors and game
developers to manually trigger window creation when needed.
# Objective
Fixes#12301. Provide more comprehensive crate level docs for bevy_ptr,
explaining it's methodology and design.
## Solution
Write out said docs.
---------
Co-authored-by: BD103 <59022059+BD103@users.noreply.github.com>
Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
# Objective
- Reduce allocations on the UI hot path.
## Solution
- Cache buffers used by the `ui_stack_system`.
## Follow-Up
- `sort_by_key` is potentially-allocating. It might be worthwhile to
include the child index as part of the sort-key and use unstable sort.
# Objective
- Closes#11954
## Solution
Change the load_meshes field in `GltfLoaderSettings` from a bool to
`RenderAssetUsages` flag, and add a new load_materials flag.
Use these to determine where the gLTF mesh and material assets are
retained in memory (if the provided flags are empty, then the assets are
skipped during load).
---
## Migration Guide
When loading gLTF assets with `asset_server.load_with_settings`, use
`RenderAssetUsages` instead of `bool` when setting load_meshes e.g.
```rust
let _ = asset_server.load_with_settings("...", |s: &mut GltfLoaderSettings| {
s.load_meshes = RenderAssetUsages::RENDER_WORLD;
});
```
Use the new load_materials field for controlling material load &
retention behaviour instead of load_meshes.
gLTF .meta files need similar updates e.g
```
load_meshes: true,
```
to
```
load_meshes: ("MAIN_WORLD | RENDER_WORLD"),
```
---------
Co-authored-by: 66OJ66 <hi0obxud@anonaddy.me>
# Objective
Add a `scale_around_center` method to the `BoundingVolume` trait, as per
#12130.
## Solution
Added `scale_around_center` to the `BoundingVolume` trait, implemented
in `Aabb2d`, `Aabb3d`, `BoundingCircle`, and `BoundingSphere` (with
tests).
# Objective
- Fix GamepadEvent::Connection not being sent for devices connected at
startup.
## Solution
- GamepadConnectionEvent was being sent directly for gamepads connected
at startup, which causes consumers of GamepadEvent to not receive those
events.
- Instead send GamepadEvent. The gamepad_event_system splits
GamepadEvent up, so consumers of GamepadConnectionEvent will still
receive the events.
# Objective
- Part of #12351
- Add fps overlay
## Solution
- Create `FpsOverlayPlugin`
- Allow for configuration through resource `FpsOverlayConfig`
- Allow for configuration during runtime
### Preview on default settings
![20240308_22h23m25s_grim](https://github.com/bevyengine/bevy/assets/62356462/33d3d7a9-435e-4e0b-9814-d3274e779a69)
---------
Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
# Objective
- Adds gizmo line joints, suggestion of #9400
## Solution
- Adds `line_joints: GizmoLineJoint` to `GizmoConfig`. Currently the
following values are supported:
- `GizmoLineJoint::None`: does not draw line joints, same behaviour as
previously
- `GizmoLineJoint::Bevel`: draws a single triangle between the lines
- `GizmoLineJoint::Miter` / 'spiky joints': draws two triangles between
the lines extending them until they meet at a (miter) point.
- NOTE: for very small angles between the lines, which happens
frequently in 3d, the miter point will be very far away from the point
at which the lines meet.
- `GizmoLineJoint::Round(resolution)`: Draw a circle arc between the
lines. The circle is a triangle fan of `resolution` triangles.
---
## Changelog
- Added `GizmoLineJoint`, use that in `GizmoConfig` and added necessary
pipelines and draw commands.
- Added a new `line_joints.wgsl` shader containing three vertex shaders
`vertex_bevel`, `vertex_miter` and `vertex_round` as well as a basic
`fragment` shader.
## Migration Guide
Any manually created `GizmoConfig`s must now set the `.line_joints`
field.
## Known issues
- The way we currently create basic closed shapes like rectangles,
circles, triangles or really any closed 2d shape means that one of the
corners will not be drawn with joints, although that would probably be
expected. (see the triangle in the 2d image)
- This could be somewhat mitigated by introducing line caps or fixed by
adding another segment overlapping the first of the strip. (Maybe in a
followup PR?)
- 3d shapes can look 'off' with line joints (especially bevel) because
wherever 3 or more lines meet one of them may stick out beyond the joint
drawn between the other 2.
- Adding additional lines so that there is a joint between every line at
a corner would fix this but would probably be too computationally
expensive.
- Miter joints are 'unreasonably long' for very small angles between the
lines (the angle is the angle between the lines in screen space). This
is technically correct but distracting and does not feel right,
especially in 3d contexts. I think limiting the length of the miter to
the point at which the lines meet might be a good idea.
- The joints may be drawn with a different gizmo in-between them and
their corresponding lines in 2d. Some sort of z-ordering would probably
be good here, but I believe this may be out of scope for this PR.
## Additional information
Some pretty images :)
<img width="1175" alt="Screenshot 2024-03-02 at 04 53 50"
src="https://github.com/bevyengine/bevy/assets/62256001/58df7e63-9376-4430-8871-32adba0cb53b">
- Note that the top vertex does not have a joint drawn.
<img width="1440" alt="Screenshot 2024-03-02 at 05 03 55"
src="https://github.com/bevyengine/bevy/assets/62256001/137a00cf-cbd4-48c2-a46f-4b47492d4fd9">
Now for a weird video:
https://github.com/bevyengine/bevy/assets/62256001/93026f48-f1d6-46fe-9163-5ab548a3fce4
- The black lines shooting out from the cube are miter joints that get
very long because the lines between which they are drawn are (almost)
collinear in screen space.
---------
Co-authored-by: Pablo Reinhardt <126117294+pablo-lua@users.noreply.github.com>
# Objective
Rotating vectors is a very common task. It is required for a variety of
things both within Bevy itself and in many third party plugins, for
example all over physics and collision detection, and for things like
Bevy's bounding volumes and several gizmo implementations.
For 3D, we can do this using a `Quat`, but for 2D, we do not have a
clear and efficient option. `Mat2` can be used for rotating vectors if
created using `Mat2::from_angle`, but this is not obvious to many users,
it doesn't have many rotation helpers, and the type does not give any
guarantees that it represents a valid rotation.
We should have a proper type for 2D rotations. In addition to allowing
for potential optimization, it would allow us to have a consistent and
explicitly documented representation used throughout the engine, i.e.
counterclockwise and in radians.
## Representation
The mathematical formula for rotating a 2D vector is the following:
```
new_x = x * cos - y * sin
new_y = x * sin + y * cos
```
Here, `sin` and `cos` are the sine and cosine of the rotation angle.
Computing these every time when a vector needs to be rotated can be
expensive, so the rotation shouldn't be just an `f32` angle. Instead, it
is often more efficient to represent the rotation using the sine and
cosine of the angle instead of storing the angle itself. This can be
freely passed around and reused without unnecessary computations.
The two options are either a 2x2 rotation matrix or a unit complex
number where the cosine is the real part and the sine is the imaginary
part. These are equivalent for the most part, but the unit complex
representation is a bit more memory efficient (two `f32`s instead of
four), so I chose that. This is like Nalgebra's
[`UnitComplex`](https://docs.rs/nalgebra/latest/nalgebra/geometry/type.UnitComplex.html)
type, which can be used for the
[`Rotation2`](https://docs.rs/nalgebra/latest/nalgebra/geometry/type.Rotation2.html)
type.
## Implementation
Add a `Rotation2d` type represented as a unit complex number:
```rust
/// A counterclockwise 2D rotation in radians.
///
/// The rotation angle is wrapped to be within the `]-pi, pi]` range.
pub struct Rotation2d {
/// The cosine of the rotation angle in radians.
///
/// This is the real part of the unit complex number representing the rotation.
pub cos: f32,
/// The sine of the rotation angle in radians.
///
/// This is the imaginary part of the unit complex number representing the rotation.
pub sin: f32,
}
```
Using it is similar to using `Quat`, but in 2D:
```rust
let rotation = Rotation2d::radians(PI / 2.0);
// Rotate vector (also works on Direction2d!)
assert_eq!(rotation * Vec2::X, Vec2::Y);
// Get angle as degrees
assert_eq!(rotation.as_degrees(), 90.0);
// Getting sin and cos is free
let (sin, cos) = rotation.sin_cos();
// "Subtract" rotations
let rotation2 = Rotation2d::FRAC_PI_4; // there are constants!
let diff = rotation * rotation2.inverse();
assert_eq!(diff.as_radians(), PI / 4.0);
// This is equivalent to the above
assert_eq!(rotation2.angle_between(rotation), PI / 4.0);
// Lerp
let rotation1 = Rotation2d::IDENTITY;
let rotation2 = Rotation2d::FRAC_PI_2;
let result = rotation1.lerp(rotation2, 0.5);
assert_eq!(result.as_radians(), std::f32::consts::FRAC_PI_4);
// Slerp
let rotation1 = Rotation2d::FRAC_PI_4);
let rotation2 = Rotation2d::degrees(-180.0); // we can use degrees too!
let result = rotation1.slerp(rotation2, 1.0 / 3.0);
assert_eq!(result.as_radians(), std::f32::consts::FRAC_PI_2);
```
There's also a `From<f32>` implementation for `Rotation2d`, which means
that methods can still accept radians as floats if the argument uses
`impl Into<Rotation2d>`. This means that adding `Rotation2d` shouldn't
even be a breaking change.
---
## Changelog
- Added `Rotation2d`
- Bounding volume methods now take an `impl Into<Rotation2d>`
- Gizmo methods with rotation now take an `impl Into<Rotation2d>`
## Future use cases
- Collision detection (a type like this is quite essential considering
how common vector rotations are)
- `Transform` helpers (e.g. return a 2D rotation about the Z axis from a
`Transform`)
- The rotation used for `Transform2d` (#8268)
- More gizmos, maybe meshes... everything in 2D that uses rotation
---------
Co-authored-by: Tristan Guichaoua <33934311+tguichaoua@users.noreply.github.com>
Co-authored-by: Robert Walter <robwalter96@gmail.com>
Co-authored-by: IQuick 143 <IQuick143cz@gmail.com>
# Objective
- Add a way to combine 2 queries together in a similar way to
`Query::transmute_lens`
- Fixes#1658
## Solution
- Use a similar method to query transmute, but take the intersection of
matched archetypes between the 2 queries and the union of the accesses
to create the new underlying QueryState.
---
## Changelog
- Add query joins
---------
Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
# Objective
Fix#10876. Improve `Query` and `QueryState`'s docs.
## Solution
Explicitly denote that Query is always guaranteed to return results from
all matching entities once and only once for each entity, and that
iteration order is not guaranteed in any way.
# Objective
Fixes#12402
## Solution
Use `despawn_recursive` instead of `despawn` for despawning
`PlaybackMode::Despawn` audio.
## Migration Guide
`PlaybackSettings::DESPAWN` (`PlaybackMode::Despawn`) now despawns the
audio entity's children as well. If you were relying on the previous
behavior, you may be able to use `PlaybackMode::Remove`, or you may need
to use `PlaybackMode::Once` and manage your audio component lifecycle
manually.
# Objective
- `toml_edit` released a new patch that deprecates `Document`
- this warns when Bevy builds, and CI deny warns
## Solution
- fix deprecation warnings
Updates the requirements on
[ruzstd](https://github.com/KillingSpark/zstd-rs) to permit the latest
version.
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a
href="https://github.com/KillingSpark/zstd-rs/releases">ruzstd's
releases</a>.</em></p>
<blockquote>
<h2>Send + Sync for FrameDecoder and optional checksum calculation</h2>
<ul>
<li>The FrameDecoder is now Send + Sync (RingBuffer impls these traits
now)</li>
<li>Hashing content and checking the result against the frame header is
now optional</li>
</ul>
</blockquote>
</details>
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a
href="https://github.com/KillingSpark/zstd-rs/blob/master/Changelog.md">ruzstd's
changelog</a>.</em></p>
<blockquote>
<h1>After 0.6.0</h1>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="abc01fa186"><code>abc01fa</code></a>
prepare changelog after version 0.6.0 released</li>
<li><a
href="943f96c97a"><code>943f96c</code></a>
we had a breaking change, bump version to 0.6.0</li>
<li><a
href="e0d32e83b4"><code>e0d32e8</code></a>
bump version to 0.5.1 and update criterion dependency</li>
<li><a
href="a16e38be5c"><code>a16e38b</code></a>
make RingBuffer Send + Sync so that the FrameDecoder is Send + Sync</li>
<li><a
href="4688f442da"><code>4688f44</code></a>
Merge pull request <a
href="https://redirect.github.com/KillingSpark/zstd-rs/issues/54">#54</a>
from a1phyr/add_metadata</li>
<li><a
href="6ab76d53c7"><code>6ab76d5</code></a>
Add crate category and keywords</li>
<li><a
href="f7e99753b9"><code>f7e9975</code></a>
try avoiding node12 github actions</li>
<li><a
href="86f97b84f5"><code>86f97b8</code></a>
fix naming</li>
<li><a
href="ea26ea140a"><code>ea26ea1</code></a>
use cargo-hack to test feature powerset</li>
<li><a
href="1ec35d2a3b"><code>1ec35d2</code></a>
add a changelog</li>
<li>Additional commits viewable in <a
href="https://github.com/KillingSpark/zstd-rs/compare/v0.5.0...v0.6.0">compare
view</a></li>
</ul>
</details>
<br />
Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.
[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)
---
<details>
<summary>Dependabot commands and options</summary>
<br />
You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot merge` will merge this PR after your CI passes on it
- `@dependabot squash and merge` will squash and merge this PR after
your CI passes on it
- `@dependabot cancel merge` will cancel a previously requested merge
and block automerging
- `@dependabot reopen` will reopen this PR if it is closed
- `@dependabot close` will close this PR and stop Dependabot recreating
it. You can achieve the same result by closing it manually
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore this major version` will close this PR and stop
Dependabot creating any more for this major version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop
Dependabot creating any more for this minor version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop
Dependabot creating any more for this dependency (unless you reopen the
PR or upgrade to it yourself)
</details>
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
# Objective
Fixes#10106
Adds a table showing computational complexity, as seen for Query (and
similar to std::collections docs).
## Solution
Add the complexity table
---
## Changelog
- Add complexity table for Input methods
Co-authored-by: James Liu <contact@jamessliu.com>
# Objective
Remove Bevy internals from backtraces
## Solution
Executors insert `__rust_begin_short_backtrace` into the callstack
before running a system.
<details>
<summary>Example current output</summary>
```
thread 'Compute Task Pool (3)' panicked at src/main.rs:7:33:
Foo
stack backtrace:
0: rust_begin_unwind
at /rustc/8ace7ea1f7cbba7b4f031e66c54ca237a0d65de6/library/std/src/panicking.rs:647:5
1: core::panicking::panic_fmt
at /rustc/8ace7ea1f7cbba7b4f031e66c54ca237a0d65de6/library/core/src/panicking.rs:72:14
2: foo::main::{{closure}}
at ./src/main.rs:7:33
3: core::ops::function::impls::<impl core::ops::function::FnMut<A> for &mut F>::call_mut
at /rustc/8ace7ea1f7cbba7b4f031e66c54ca237a0d65de6/library/core/src/ops/function.rs:294:13
4: <Func as bevy_ecs::system::function_system::SystemParamFunction<fn() .> Out>>::run::call_inner
at /home/vj/workspace/rust/bevy/crates/bevy_ecs/src/system/function_system.rs:661:21
5: <Func as bevy_ecs::system::function_system::SystemParamFunction<fn() .> Out>>::run
at /home/vj/workspace/rust/bevy/crates/bevy_ecs/src/system/function_system.rs:664:17
6: <bevy_ecs::system::function_system::FunctionSystem<Marker,F> as bevy_ecs::system::system::System>::run_unsafe
at /home/vj/workspace/rust/bevy/crates/bevy_ecs/src/system/function_system.rs:504:19
7: bevy_ecs::schedule::executor::multi_threaded::ExecutorState::spawn_system_task::{{closure}}::{{closure}}
at /home/vj/workspace/rust/bevy/crates/bevy_ecs/src/schedule/executor/multi_threaded.rs:621:26
8: core::ops::function::FnOnce::call_once
at /rustc/8ace7ea1f7cbba7b4f031e66c54ca237a0d65de6/library/core/src/ops/function.rs:250:5
9: <core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_once
at /rustc/8ace7ea1f7cbba7b4f031e66c54ca237a0d65de6/library/core/src/panic/unwind_safe.rs:272:9
10: std::panicking::try::do_call
at /rustc/8ace7ea1f7cbba7b4f031e66c54ca237a0d65de6/library/std/src/panicking.rs:554:40
11: __rust_try
12: std::panicking::try
at /rustc/8ace7ea1f7cbba7b4f031e66c54ca237a0d65de6/library/std/src/panicking.rs:518:19
13: std::panic::catch_unwind
at /rustc/8ace7ea1f7cbba7b4f031e66c54ca237a0d65de6/library/std/src/panic.rs:142:14
14: bevy_ecs::schedule::executor::multi_threaded::ExecutorState::spawn_system_task::{{closure}}
at /home/vj/workspace/rust/bevy/crates/bevy_ecs/src/schedule/executor/multi_threaded.rs:614:23
15: <core::panic::unwind_safe::AssertUnwindSafe<F> as core::future::future::Future>::poll
at /rustc/8ace7ea1f7cbba7b4f031e66c54ca237a0d65de6/library/core/src/panic/unwind_safe.rs:297:9
16: <futures_lite::future::CatchUnwind<F> as core::future::future::Future>::poll::{{closure}}
at /home/vj/.cargo/registry/src/index.crates.io-6f17d22bba15001f/futures-lite-2.2.0/src/future.rs:588:42
17: <core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_once
at /rustc/8ace7ea1f7cbba7b4f031e66c54ca237a0d65de6/library/core/src/panic/unwind_safe.rs:272:9
18: std::panicking::try::do_call
at /rustc/8ace7ea1f7cbba7b4f031e66c54ca237a0d65de6/library/std/src/panicking.rs:554:40
19: __rust_try
20: std::panicking::try
at /rustc/8ace7ea1f7cbba7b4f031e66c54ca237a0d65de6/library/std/src/panicking.rs:518:19
21: std::panic::catch_unwind
at /rustc/8ace7ea1f7cbba7b4f031e66c54ca237a0d65de6/library/std/src/panic.rs:142:14
22: <futures_lite::future::CatchUnwind<F> as core::future::future::Future>::poll
at /home/vj/.cargo/registry/src/index.crates.io-6f17d22bba15001f/futures-lite-2.2.0/src/future.rs:588:9
23: async_executor::Executor::spawn::{{closure}}
at /home/vj/.cargo/registry/src/index.crates.io-6f17d22bba15001f/async-executor-1.8.0/src/lib.rs:158:20
24: async_task::raw::RawTask<F,T,S,M>::run::{{closure}}
at /home/vj/.cargo/registry/src/index.crates.io-6f17d22bba15001f/async-task-4.7.0/src/raw.rs:550:21
25: core::ops::function::FnOnce::call_once
at /rustc/8ace7ea1f7cbba7b4f031e66c54ca237a0d65de6/library/core/src/ops/function.rs:250:5
26: <core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_once
at /rustc/8ace7ea1f7cbba7b4f031e66c54ca237a0d65de6/library/core/src/panic/unwind_safe.rs:272:9
27: std::panicking::try::do_call
at /rustc/8ace7ea1f7cbba7b4f031e66c54ca237a0d65de6/library/std/src/panicking.rs:554:40
28: __rust_try
29: std::panicking::try
at /rustc/8ace7ea1f7cbba7b4f031e66c54ca237a0d65de6/library/std/src/panicking.rs:518:19
30: std::panic::catch_unwind
at /rustc/8ace7ea1f7cbba7b4f031e66c54ca237a0d65de6/library/std/src/panic.rs:142:14
31: async_task::raw::RawTask<F,T,S,M>::run
at /home/vj/.cargo/registry/src/index.crates.io-6f17d22bba15001f/async-task-4.7.0/src/raw.rs:549:23
32: async_task::runnable::Runnable<M>::run
at /home/vj/.cargo/registry/src/index.crates.io-6f17d22bba15001f/async-task-4.7.0/src/runnable.rs:781:18
33: async_executor::Executor::run::{{closure}}::{{closure}}
at /home/vj/.cargo/registry/src/index.crates.io-6f17d22bba15001f/async-executor-1.8.0/src/lib.rs:254:21
34: <futures_lite::future::Or<F1,F2> as core::future::future::Future>::poll
at /home/vj/.cargo/registry/src/index.crates.io-6f17d22bba15001f/futures-lite-2.2.0/src/future.rs:449:33
35: async_executor::Executor::run::{{closure}}
at /home/vj/.cargo/registry/src/index.crates.io-6f17d22bba15001f/async-executor-1.8.0/src/lib.rs:261:32
36: futures_lite::future::block_on::{{closure}}
at /home/vj/.cargo/registry/src/index.crates.io-6f17d22bba15001f/futures-lite-2.2.0/src/future.rs:99:19
37: std:🧵:local::LocalKey<T>::try_with
at /rustc/8ace7ea1f7cbba7b4f031e66c54ca237a0d65de6/library/std/src/thread/local.rs:286:16
38: std:🧵:local::LocalKey<T>::with
at /rustc/8ace7ea1f7cbba7b4f031e66c54ca237a0d65de6/library/std/src/thread/local.rs:262:9
39: futures_lite::future::block_on
at /home/vj/.cargo/registry/src/index.crates.io-6f17d22bba15001f/futures-lite-2.2.0/src/future.rs:78:5
40: bevy_tasks::task_pool::TaskPool::new_internal::{{closure}}::{{closure}}::{{closure}}::{{closure}}
at /home/vj/workspace/rust/bevy/crates/bevy_tasks/src/task_pool.rs:180:37
41: std::panicking::try::do_call
at /rustc/8ace7ea1f7cbba7b4f031e66c54ca237a0d65de6/library/std/src/panicking.rs:554:40
42: __rust_try
43: std::panicking::try
at /rustc/8ace7ea1f7cbba7b4f031e66c54ca237a0d65de6/library/std/src/panicking.rs:518:19
44: std::panic::catch_unwind
at /rustc/8ace7ea1f7cbba7b4f031e66c54ca237a0d65de6/library/std/src/panic.rs:142:14
45: bevy_tasks::task_pool::TaskPool::new_internal::{{closure}}::{{closure}}::{{closure}}
at /home/vj/workspace/rust/bevy/crates/bevy_tasks/src/task_pool.rs:174:43
46: std:🧵:local::LocalKey<T>::try_with
at /rustc/8ace7ea1f7cbba7b4f031e66c54ca237a0d65de6/library/std/src/thread/local.rs:286:16
47: std:🧵:local::LocalKey<T>::with
at /rustc/8ace7ea1f7cbba7b4f031e66c54ca237a0d65de6/library/std/src/thread/local.rs:262:9
48: bevy_tasks::task_pool::TaskPool::new_internal::{{closure}}::{{closure}}
at /home/vj/workspace/rust/bevy/crates/bevy_tasks/src/task_pool.rs:167:25
note: Some details are omitted, run with `RUST_BACKTRACE=full` for a verbose backtrace.
Encountered a panic in system `foo::main::{{closure}}`!
Encountered a panic in system `bevy_app::main_schedule::Main::run_main`!
get on your knees and beg mommy for forgiveness you pervert~ 💖
```
</details>
<details>
<summary>Example output with this PR</summary>
```
Panic at src/main.rs:7:33:
Foo
stack backtrace:
0: rust_begin_unwind
at /rustc/8ace7ea1f7cbba7b4f031e66c54ca237a0d65de6/library/std/src/panicking.rs:647:5
1: core::panicking::panic_fmt
at /rustc/8ace7ea1f7cbba7b4f031e66c54ca237a0d65de6/library/core/src/panicking.rs:72:14
2: foo::main::{{closure}}
at ./src/main.rs:7:59
3: core::ops::function::impls::<impl core::ops::function::FnMut<A> for &mut F>::call_mut
at /rustc/8ace7ea1f7cbba7b4f031e66c54ca237a0d65de6/library/core/src/ops/function.rs:294:13
4: <Func as bevy_ecs::system::function_system::SystemParamFunction<fn() .> Out>>::run::call_inner
at /home/vj/workspace/rust/bevy/crates/bevy_ecs/src/system/function_system.rs:661:21
5: <Func as bevy_ecs::system::function_system::SystemParamFunction<fn() .> Out>>::run
at /home/vj/workspace/rust/bevy/crates/bevy_ecs/src/system/function_system.rs:664:17
6: <bevy_ecs::system::function_system::FunctionSystem<Marker,F> as bevy_ecs::system::system::System>::run_unsafe
at /home/vj/workspace/rust/bevy/crates/bevy_ecs/src/system/function_system.rs:504:19
note: Some details are omitted, run with `RUST_BACKTRACE=full` for a verbose backtrace.
Encountered a panic in system `foo::main::{{closure}}`!
Encountered a panic in system `bevy_app::main_schedule::Main::run_main`!
```
</details>
Full backtraces (`RUST_BACKTRACE=full`) are unchanged.
## Alternative solutions
Write a custom panic hook. This could potentially let use exclude a few
more callstack frames but requires a dependency on `backtrace` and is
incompatible with user-provided panic hooks.
---
## Changelog
- Backtraces now exclude many Bevy internals (unless
`RUST_BACKTRACE=full` is used)
---------
Co-authored-by: James Liu <contact@jamessliu.com>
# Objective
fix occasional crash from commands.insert when quickly spawning and
despawning skinned/morphed meshes
## Solution
use `try_insert` instead of `insert`. if the entity is deleted we don't
mind failing to add the `NoAutomaticBatching` marker.
# Objective
- Fixes https://github.com/bevyengine/bevy/issues/12380
## Solution
- Before #11986 AssetEvents were scheduled after PostUpdate. That pr
moved these into First. This PR moves them into Last which is closer to
how they were scheduled before.
# Objective
- After #12370, ci testing with minimal plugins doesn't hang but it
crash as the resource `ScreenshotManager` doesn't exist
## Solution
- Check if the resource exists
# Objective
Fix missing `TextBundle` (and many others) which are present in the main
crate as default features but optional in the sub-crate. See:
- https://docs.rs/bevy/0.13.0/bevy/ui/node_bundles/index.html
- https://docs.rs/bevy_ui/0.13.0/bevy_ui/node_bundles/index.html
~~There are probably other instances in other crates that I could track
down, but maybe "all-features = true" should be used by default in all
sub-crates? Not sure.~~ (There were many.) I only noticed this because
rust-analyzer's "open docs" features takes me to the sub-crate, not the
main one.
## Solution
Add "all-features = true" to docs.rs metadata for crates that use
features.
## Changelog
### Changed
- Unified features documented on docs.rs between main crate and
sub-crates
# Objective
Provide guidelines for contributing code to `bevy_audio`, with a focus
on the critical sections of the audio engine.
## Changelog
Added to the crate-level documentation comment with a section
introducing audio programming, real-time safety and why it is important
to audio programming, as well as recommendations for some programming
use-cases. The section concludes with links to more resources about
audio programming.
I might have gone overboard with the writeup, but I didn't want to
assume a lot out of potential `bevy_audio` contributors, and so I spent
a bit of time defining terms as simply as I could.
I didn't want to pressure people to do so, but the first link on the
additional resources should really be "required reading" as it goes more
in depth about the why and how of audio programming.
---------
Co-authored-by: Nathan Graule <nathan.graule@arturia.com>
# Objective
`ButtonInput<KeyCode>` documentation is currently incorrect/incomplete,
see #12273.
## Solution
Fix the documentation.
I think in the future we should also stop triggering
`just_pressed`/`just_released` when focus switches between two Bevy
windows, as those functions are independent of the window. It could also
make sense to add individual `ButtonInput<KeyCode>`s per window.
---------
Co-authored-by: Mateusz Wachowiak <mateusz_wachowiak@outlook.com>
# Objective
- Fix#12356
- better isolation of ci testing tools in dev tools instead of being in
various crates
## Solution
- Move the parts doing the work of ci testing to the dev tools
# Objective
- Fix incorrect link in UIMaterial docs
## Solution
- Updated the link
Co-authored-by: Frank Hampus Weslien <frankhampusweslien@google.com>
This is an implementation of RFC #51:
https://github.com/bevyengine/rfcs/blob/main/rfcs/51-animation-composition.md
Note that the implementation strategy is different from the one outlined
in that RFC, because two-phase animation has now landed.
# Objective
Bevy needs animation blending. The RFC for this is [RFC 51].
## Solution
This is an implementation of the RFC. Note that the implementation
strategy is different from the one outlined there, because two-phase
animation has now landed.
This is just a draft to get the conversation started. Currently we're
missing a few things:
- [x] A fully-fleshed-out mechanism for transitions
- [x] A serialization format for `AnimationGraph`s
- [x] Examples are broken, other than `animated_fox`
- [x] Documentation
---
## Changelog
### Added
* The `AnimationPlayer` has been reworked to support blending multiple
animations together through an `AnimationGraph`, and as such will no
longer function unless a `Handle<AnimationGraph>` has been added to the
entity containing the player. See [RFC 51] for more details.
* Transition functionality has moved from the `AnimationPlayer` to a new
component, `AnimationTransitions`, which works in tandem with the
`AnimationGraph`.
## Migration Guide
* `AnimationPlayer`s can no longer play animations by themselves and
need to be paired with a `Handle<AnimationGraph>`. Code that was using
`AnimationPlayer` to play animations will need to create an
`AnimationGraph` asset first, add a node for the clip (or clips) you
want to play, and then supply the index of that node to the
`AnimationPlayer`'s `play` method.
* The `AnimationPlayer::play_with_transition()` method has been removed
and replaced with the `AnimationTransitions` component. If you were
previously using `AnimationPlayer::play_with_transition()`, add all
animations that you were playing to the `AnimationGraph`, and create an
`AnimationTransitions` component to manage the blending between them.
[RFC 51]:
https://github.com/bevyengine/rfcs/blob/main/rfcs/51-animation-composition.md
---------
Co-authored-by: Rob Parrett <robparrett@gmail.com>
# Objective
- With the recent lighting changes, the default configuration in the
`bloom_3d` example is less clear what bloom actually does
- See [this
screenshot](4fdb1455d5 (r1494648414))
for a comparison.
- `bloom_3d` additionally uses a for-loop to spawn the spheres, which
can be turned into `commands::spawn_batch` call.
- The text is black, which is difficult to see on the gray background.
## Solution
- Increase emmisive values of materials.
- Set text to white.
## Showcase
Before:
<img width="1392" alt="before"
src="https://github.com/bevyengine/bevy/assets/59022059/757057ad-ed9f-4eed-b135-8e2032fcdeb5">
After:
<img width="1392" alt="image"
src="https://github.com/bevyengine/bevy/assets/59022059/3f9dc7a8-94b2-44b9-8ac3-deef1905221b">
---------
Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
# Objective
Make bevy_utils less of a compilation bottleneck. Tackle #11478.
## Solution
* Move all of the directly reexported dependencies and move them to
where they're actually used.
* Remove the UUID utilities that have gone unused since `TypePath` took
over for `TypeUuid`.
* There was also a extraneous bytemuck dependency on `bevy_core` that
has not been used for a long time (since `encase` became the primary way
to prepare GPU buffers).
* Remove the `all_tuples` macro reexport from bevy_ecs since it's
accessible from `bevy_utils`.
---
## Changelog
Removed: Many of the reexports from bevy_utils (petgraph, uuid, nonmax,
smallvec, and thiserror).
Removed: bevy_core's reexports of bytemuck.
## Migration Guide
bevy_utils' reexports of petgraph, uuid, nonmax, smallvec, and thiserror
have been removed.
bevy_core' reexports of bytemuck's types has been removed.
Add them as dependencies in your own crate instead.
# Objective
Fixes#12353
When only `webp` was selected, `ImageLoader` would not be initialized.
That is, users using `default-features = false` would need to add `png`
or `bmp` or something in addition to `webp` in order to use `webp`.
This was also the case for `pnm`.
## Solution
Add `webp` and `pnm` to the list of features that trigger the
initialization of `ImageLoader`.
# Objective
- Resolves#11309
## Solution
- Add `bevy_dev_tools` crate as a default feature.
- Add `DevToolsPlugin` and add it to an app if the `bevy_dev_tools`
feature is enabled.
`bevy_dev_tools` is reserved by @alice-i-cecile, should we wait until it
gets transferred to cart before merging?
---------
Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
Co-authored-by: BD103 <59022059+BD103@users.noreply.github.com>
# Objective
- Fix slightly wrong logic from #11442
- Directional lights should not have a near clip plane
## Solution
- Push near clip out to infinity, so that the frustum normal is still
available if its needed for whatever reason in shader
- also opportunistically nabs a typo
# Objective
Fix#12304. Remove unnecessary type registrations thanks to #4154.
## Solution
Conservatively remove type registrations. Keeping the top level
components, resources, and events, but dropping everything else that is
a type of a member of those types.
# Objective
Following #10756, we're now using raw pointers in BundleInserter and
BundleSpawner. This is primarily to get around the need to split the
borrow on the World, but it leaves a lot to be desired in terms of
safety guarantees. There's no type level guarantee the code can't
dereference a null pointer, and it's restoring them to borrows fairly
liberally within the associated functions.
## Solution
* Replace the pointers with `NonNull` and a new `bevy_ptr::ConstNonNull`
that only allows conversion back to read-only borrows
* Remove the closure to avoid potentially aliasing through the closure
by restructuring the match expression.
* Move all conversions back into borrows as far up as possible to ensure
that the borrow checker is at least locally followed.
# Objective
Fixes#12225
Prior to the `bevy_color` port, `GREEN` used to mean "full green." But
it is now a much darker color matching the css1 spec.
## Solution
Change usages of `basic::GREEN` or `css::GREEN` to `LIME` to restore the
examples to their former colors.
This also removes the duplicate definition of `GREEN` from `css`. (it
was already re-exported from `basic`)
## Note
A lot of these examples could use nicer colors. I'm not trying to do
that here.
"Dark Grey" will be tackled separately and has its own tracking issue.
# Objective
Addresses one of the side-notes in #12225.
Colors in the `basic` palette are inconsistent in a few ways:
- `CYAN` was named `AQUA` in the referenced spec. (an alias was added in
a later spec)
- Colors are defined with e.g. "half green" having a `g` value of `0.5`.
But any spec would have been based on 8-bit color, so `0x80 / 0xFF` or
`128 / 255` or ~`0.502`. This precision is likely meaningful when doing
color math/rounding.
## Solution
Regenerate the colors from
https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=37563bedc8858033bd8b8380328c5230
# Objective
- Avoid version mismatch
- When cpal updates oboe in a patch release, this breaks android support
for Bevy
## Solution
- Use the same version of oboe as cpal by relying on it to re-export the
feature
# Objective
Fixes#12310.
#11681 added transformations for bounding volumes, but I accidentally
only added a note in the docs about repeated rotations for `Aabb2d` and
not `Aabb3d`.
## Solution
Copy the docs over to `Aabb3d`.
# Objective
- Describe the objective or issue this PR addresses.
Improve docs around emissive colors --
I couldn't figure out how to increase the emissive strength of
materials, asking on discord @alice-i-cecile told me that color channel
values can go above `1.0` in the case of the `emissive` field. I would
have never figured this out on my own, because [the docs for
emissive](https://docs.rs/bevy/latest/bevy/prelude/struct.StandardMaterial.html#structfield.emissive)
don't mention this possibility, and indeed if you follow the link in the
`emissive` doc [to the `Color`
type](https://docs.rs/bevy/latest/bevy/render/color/enum.Color.html#variants),
you are told that values should be in `[0.0, 1.0]`.
## Solution
- Describe the solution used to achieve the objective above.
Just added a note on the possibility of large color channel values with
example.
# Objective
`initialize_resource<T>` and it's non-send equivalent is only used in
two locations each. Fix#6285.
## Solution
Remove them, replace their calls with their internals. Cut down on a bit
of generic codegen.
This does mean that `initialize_resource_internal` is now `pub(crate)`,
but that's likely OK given that only one variant will remain once
NonSend resources are removed from the World.
# Objective
Follow up to #11600 and #10588https://github.com/bevyengine/bevy/issues/11944 made clear that some
people want to use slicing with texture atlases
## Changelog
* Added support for `TextureAtlas` slicing and tiling.
`SpriteSheetBundle` and `AtlasImageBundle` can now use `ImageScaleMode`
* Added new `ui_texture_atlas_slice` example using a texture sheet
<img width="798" alt="Screenshot 2024-02-23 at 11 58 35"
src="https://github.com/bevyengine/bevy/assets/26703856/47a8b764-127c-4a06-893f-181703777501">
---------
Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
Co-authored-by: Pablo Reinhardt <126117294+pablo-lua@users.noreply.github.com>
# Objective
When doing a final pass for #3362, it appeared that `ComponentStorage`
as a trait, the two types implementing it, and the associated type on
`Component` aren't really necessary anymore. This likely was due to an
earlier constraint on the use of consts in traits, but that definitely
doesn't seem to be a problem in Rust 1.76.
## Solution
Remove them.
---
## Changelog
Changed: `Component::Storage` has been replaced with
`Component::STORAGE_TYPE` as a const.
Removed: `bevy::ecs::component::ComponentStorage` trait
Removed: `bevy::ecs::component::TableStorage` struct
Removed: `bevy::ecs::component::SparseSetStorage` struct
## Migration Guide
If you were manually implementing `Component` instead of using the
derive macro, replace the associated `Storage` associated type with the
`STORAGE_TYPE` const:
```rust
// in Bevy 0.13
impl Component for MyComponent {
type Storage = TableStorage;
}
// in Bevy 0.14
impl Component for MyComponent {
const STORAGE_TYPE: StorageType = StorageType::Table;
}
```
Component is no longer object safe. If you were relying on `&dyn
Component`, `Box<dyn Component>`, etc. please [file an issue
](https://github.com/bevyengine/bevy/issues) to get [this
change](https://github.com/bevyengine/bevy/pull/12311) reverted.
---------
Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
- Explain it is flushed in the same schedule run (was not obvious to me)
- Point to `apply_deferred` example
- Remove mentions of `System::apply_deferred` and
`Schedule::apply_deferred` which are probably too low level for the most
users
Co-authored-by: James Liu <contact@jamessliu.com>
# Objective
cpal has been updated to [0.15.3](https://crates.io/crates/cpal/0.15.3).
we can remove the skip to avoid check for cpal 0.15.2 dependencies in
deny.toml
cpal now uses ndk 8.0 and Oboe 6.0, so we only have a version for
raw-window-handle, version 0.6
## Solution
- Remove temporal fix that skipped the check for the cpal dependency.
- Update oboe to 0.6
Fixes https://github.com/bevyengine/bevy/issues/11917
# Objective
`bevy_utils::Entry` is only useful when using
`BuildHasherDefault<AHasher>`. It would be great if we didn't have to
write out `bevy_utils::hashbrown::hash_map::Entry` whenever we want to
use a different `BuildHasher`, such as when working with
`bevy_utils::TypeIdMap`.
## Solution
Give `bevy_utils::Entry` a new optional type parameter for defining a
custom `BuildHasher`, such as `NoOpHash`. This parameter defaults to
`BuildHasherDefault<AHasher>`— the `BuildHasher` used by
`bevy_utils::HashMap`.
---
## Changelog
- Added an optional third type parameter to `bevy_utils::Entry` to
specify a custom `BuildHasher`
# Objective
Make it straightforward to translate and rotate bounding volumes.
## Solution
Add `translate_by`/`translated_by`, `rotate_by`/`rotated_by`,
`transform_by`/`transformed_by` methods to the `BoundingVolume` trait.
This follows the naming used for mesh transformations (see #11454 and
#11675).
---
## Changelog
- Added `translate_by`/`translated_by`, `rotate_by`/`rotated_by`,
`transform_by`/`transformed_by` methods to the `BoundingVolume` trait
and implemented them for the bounding volumes
- Renamed `Position` associated type to `Translation`
---------
Co-authored-by: Mateusz Wachowiak <mateusz_wachowiak@outlook.com>
# Objective
- The doc example for `World::run_system_with_input` mistakenly
indicates that systems share state
- Some of the doc example code is unnecessary and/or could be cleaned up
## Solution
Replace the incorrect result value for the correct one in the doc
example. I also went with an explicit `assert_eq` check as it presents
the same information but can be validated by CI via doc tests.
Also removed some unnecessary code, such as the `Resource` derives on
`Counter`. In fact, I just replaced `Counter` with a `u8` in the
`Local`. I think it makes the example a little cleaner.
---
## Changelog
- Update docs for `World::run_system` and `World::run_system_with_input`
# Objective
- Fixes#12255
Still needs confirming what the consequences are from having camera
viewport nodes live on the root of the taffy tree.
## Solution
To fix calculating the layouts for UI nodes we need to cleanup the
children previously set whenever `TargetCamera` is updated. This also
maintains a list of taffy camera nodes and cleans them up when removed.
---
## Changelog
Fixed#12255
## Migration Guide
changes affect private structs/members so shouldn't need actions by
engine users.
# Objective
Fixes#12126
Notably this does not appear to fix the console error spam that appears
to be coming from winit, only the performance bug that occurs when
tabbing out and back into the game.
## Solution
The winit event loop starts out as `ControlFlow::Wait` by default. When
switching to `UpdateMode::Reactive` or `UpdateMode::ReactiveLowPower`,
we repeatedly update this to `ControlFlow::WaitUntil(next)`. When
switching back to `UpdateMode::Continuous`, the event loop is
erroneously stuck at the latest `ControlFlow::WaitUntil(next)` that was
issued.
I also changed how we handle `Event::NewEvents` since the `StartCause`
already tells us enough information to make that decision. This came
about my debugging and I left it in as an improvement.
# Objective
Resolves#4154
Currently, registration must all be done manually:
```rust
#[derive(Reflect)]
struct Foo(Bar);
#[derive(Reflect)]
struct Bar(Baz);
#[derive(Reflect)]
struct Baz(usize);
fn main() {
// ...
app
.register_type::<Foo>()
.register_type::<Bar>()
.register_type::<Baz>()
// .register_type::<usize>() <- This one is handled by Bevy, thankfully
// ...
}
```
This can grow really quickly and become very annoying to add, remove,
and update as types change. It would be great if we could help reduce
the number of types that a user must manually implement themselves.
## Solution
As suggested in #4154, this PR adds automatic recursive registration.
Essentially, when a type is registered, it may now also choose to
register additional types along with it using the new
`GetTypeRegistration::register_type_dependencies` trait method.
The `Reflect` derive macro now automatically does this for all fields in
structs, tuple structs, struct variants, and tuple variants. This is
also done for tuples, arrays, `Vec<T>`, `HashMap<K, V>`, and
`Option<T>`.
This allows us to simplify the code above like:
```rust
#[derive(Reflect)]
struct Foo(Bar);
#[derive(Reflect)]
struct Bar(Baz);
#[derive(Reflect)]
struct Baz(usize);
fn main() {
// ...
app.register_type::<Foo>()
// ...
}
```
This automatic registration only occurs if the type has not yet been
registered. If it has been registered, we simply skip it and move to the
next one. This reduces the cost of registration and prevents overwriting
customized registrations.
## Considerations
While this does improve ergonomics on one front, it's important to look
at some of the arguments against adopting a PR like this.
#### Generic Bounds
~~Since we need to be able to register the fields individually, we need
those fields to implement `GetTypeRegistration`. This forces users to
then add this trait as a bound on their generic arguments. This
annoyance could be relieved with something like #5772.~~
This is no longer a major issue as the `Reflect` derive now adds the
`GetTypeRegistration` bound by default. This should technically be okay,
since we already add the `Reflect` bound.
However, this can also be considered a breaking change for manual
implementations that left out a `GetTypeRegistration` impl ~~or for
items that contain dynamic types (e.g. `DynamicStruct`) since those also
do not implement `GetTypeRegistration`~~.
#### Registration Assumptions
By automatically registering fields, users might inadvertently be
relying on certain types to be automatically registered. If `Foo`
auto-registers `Bar`, but `Foo` is later removed from the code, then
anywhere that previously used or relied on `Bar`'s registration would
now fail.
---
## Changelog
- Added recursive type registration to structs, tuple structs, struct
variants, tuple variants, tuples, arrays, `Vec<T>`, `HashMap<K, V>`, and
`Option<T>`
- Added a new trait in the hidden `bevy_reflect::__macro_exports` module
called `RegisterForReflection`
- Added `GetTypeRegistration` impl for
`bevy_render::render_asset::RenderAssetUsages`
## Migration Guide
All types that derive `Reflect` will now automatically add
`GetTypeRegistration` as a bound on all (unignored) fields. This means
that all reflected fields will need to also implement
`GetTypeRegistration`.
If all fields **derive** `Reflect` or are implemented in `bevy_reflect`,
this should not cause any issues. However, manual implementations of
`Reflect` that excluded a `GetTypeRegistration` impl for their type will
need to add one.
```rust
#[derive(Reflect)]
struct Foo<T: FromReflect> {
data: MyCustomType<T>
}
// OLD
impl<T: FromReflect> Reflect for MyCustomType<T> {/* ... */}
// NEW
impl<T: FromReflect + GetTypeRegistration> Reflect for MyCustomType<T> {/* ... */}
impl<T: FromReflect + GetTypeRegistration> GetTypeRegistration for MyCustomType<T> {/* ... */}
```
---------
Co-authored-by: James Liu <contact@jamessliu.com>
Co-authored-by: radiish <cb.setho@gmail.com>
Co-authored-by: Carter Anderson <mcanders1@gmail.com>
Hi, this is a minimal implementation of #12159. I wasn't sure if the
`EventLoopProxy` should be wrapped somewhat to make it more explicit.
# Objective
Minimal implementation of #12159
When using `UpdateMode::Reactive` it is currently not possible to
request a redraw when a long running task is finished or an external
source has new data.
This makes the following possible which will then run an app update once
``` rust
// EventLoopProxy is Send on most architectures
// The EventLoopProxy can also be saved in a thread local for WASM or a static in other architecturecs
pub fn example(proxy: NonSend<EventLoopProxy<()>>) {
let clone: EventLoopProxy<()> = proxy.clone();
thread::spawn(move || {
// do long work
clone.send_event(());
});
}
```
## Solution
By using the EventLoopProxy one can manually send events from external
threads to the event loop as `UserEvent`s.
This simply sets redraw_requested when a `UserEvent` is received.
## Changelog
- Added the ability to request a redraw from an external source
---------
Co-authored-by: Kellner, Robin <Robin.Kellner@vector.com>
# Objective
Correct references to `Input` into `ButtonInput` in the keyboard input
docs since it was renamed in 0.13.
## Solution
Change the type used in the keyboard input docs from `Input` to
`ButtonInput`.
# Objective
`Dir3` and `Dir3A` can be rotated using `Quat`s. However, if enough
floating point error accumulates or (more commonly) the rotation itself
is degenerate (like not normalized), the resulting direction can also
become denormalized.
Currently, with debug assertions enabled, it panics in these cases with
the message `rotated.is_normalized()`. This error message is unclear,
doesn't give information about *how* it is denormalized (like is the
length too large, NaN, or something else), and is overall not very
helpful. Panicking for small-ish error might also be a bit too strict,
and has lead to unwanted crashes in crates like `bevy_xpbd` (although it
has also helped in finding actual bugs).
The error message should be clearer and give more context, and it
shouldn't cause unwanted crashes.
## Solution
Change the `debug_assert!` to a warning for small error with a (squared
length) threshold of 2e-4 and a panic for clear error with a threshold
of 2e-2. The warnings mention the direction type and the length of the
denormalized vector.
Here's what the error and warning look like:
```
Error: `Dir3` is denormalized after rotation. The length is 1.014242.
```
```
Warning: `Dir3A` is denormalized after rotation. The length is 1.0001414.
```
I gave the same treatment to `new_unchecked`:
```
Error: The vector given to `Dir3::new_unchecked` is not normalized. The length is 1.014242.
```
```
Warning: The vector given to `Dir3A::new_unchecked` is not normalized. The length is 1.0001414.
```
---
## Discussion
### Threshold values
The thresholds are somewhat arbitrary. 2e-4 is what Glam uses for the
squared length in `is_normalized` (after I corrected it in
bitshifter/glam-rs#480), and 2e-2 is just what I thought could be a
clear sign of something being critically wrong. I can definitely tune
them if there are better thresholds though.
### Logging
`bevy_math` doesn't have `bevy_log`, so we can't use `warn!` or
`error!`. This is why I made it use just `eprintln!` and `panic!` for
now. Let me know if there's a better way of logging errors in
`bevy_math`.
# Objective
In my library,
[`bevy_dev_console`](https://github.com/doonv/bevy_dev_console) I need
access to `App` within `LogPlugin::update_subscriber` in order to
communicate with the `App` from my custom `Layer`.
## Solution
Give access to `App`.
---
## Changelog
- Added access to `App` within `LogPlugin::update_subscriber`
## Migration Guide
`LogPlugin::update_subscriber` now has a `&mut App` parameter. If you
don't need access to `App`, you can ignore the parameter with an
underscore (`_`).
```diff,rust
- fn update_subscriber(subscriber: BoxedSubscriber) -> BoxedSubscriber {
+ fn update_subscriber(_: &mut App, subscriber: BoxedSubscriber) -> BoxedSubscriber {
Box::new(subscriber.with(CustomLayer))
}
```
# Objective
- Allow users to read window events in the sequence they appeared. This
is important for precise input handling when there are multiple input
events in a single frame (e.g. click and release vs release and click).
## Solution
- Add a mega-enum `WinitEvent` that collects window events, and send
those alongside the existing more granular window events.
---
## Changelog
- Added `WinitEvent` event that aggregates all window events into a
synchronized event stream.
# Objective
Fixes https://github.com/bevyengine/bevy/issues/11157.
## Solution
Stop using `BackgroundColor` as a color tint for `UiImage`. Add a
`UiImage::color` field for color tint instead. Allow a UI node to
simultaneously include a solid-color background and an image, with the
image rendered on top of the background (this is already how it works
for e.g. text).
![2024-02-29_1709239666_563x520](https://github.com/bevyengine/bevy/assets/12173779/ec50c9ef-4c7f-4ab8-a457-d086ce5b3425)
---
## Changelog
- The `BackgroundColor` component now renders a solid-color background
behind `UiImage` instead of tinting its color.
- Removed `BackgroundColor` from `ImageBundle`, `AtlasImageBundle`, and
`ButtonBundle`.
- Added `UiImage::color`.
- Expanded `RenderUiSystem` variants.
- Renamed `bevy_ui::extract_text_uinodes` to `extract_uinodes_text` for
consistency.
## Migration Guide
- `BackgroundColor` no longer tints the color of UI images. Use
`UiImage::color` for that instead.
- For solid color buttons, replace `ButtonBundle { background_color:
my_color.into(), ... }` with `ButtonBundle { image:
UiImage::default().with_color(my_color), ... }`, and update button
interaction systems to use `UiImage::color` instead of `BackgroundColor`
as well.
- `bevy_ui::RenderUiSystem::ExtractNode` has been split into
`ExtractBackgrounds`, `ExtractImages`, `ExtractBorders`, and
`ExtractText`.
- `bevy_ui::extract_uinodes` has been split into
`bevy_ui::extract_uinode_background_colors` and
`bevy_ui::extract_uinode_images`.
- `bevy_ui::extract_text_uinodes` has been renamed to
`extract_uinode_text`.
# Objective
After the `TextureAtlas` changes that landed in 0.13,
`SpriteSheetBundle` is equivalent to `TextureAtlas` + `SpriteBundle` and
`AtlasImageBundle` is equivalent to `TextureAtlas` + `ImageBundle`. As
such, the atlas bundles aren't particularly useful / necessary additions
to the API anymore.
In addition, atlas bundles are inconsistent with `ImageScaleMode` (also
introduced in 0.13) which doesn't have its own version of each image
bundle.
## Solution
Deprecate `SpriteSheetBundle` and `AtlasImageBundle` in favor of
including `TextureAtlas` as a separate component alongside
`SpriteBundle` and `ImageBundle`, respectively.
---
## Changelog
- Deprecated `SpriteSheetBundle` and `AtlasImageBundle`.
## Migration Guide
- `SpriteSheetBundle` has been deprecated. Use `TextureAtlas` alongside
a `SpriteBundle` instead.
- `AtlasImageBundle` has been deprecated. Use `TextureAtlas` alongside
an `ImageBundle` instead.
# Objective
- Part of #9400.
- Add light gizmos for `SpotLight`, `PointLight` and `DirectionalLight`.
## Solution
- Add a `ShowLightGizmo` and its related gizmo group and plugin, that
shows a gizmo for all lights of an entities when inserted on it. Light
display can also be toggled globally through the gizmo config in the
same way it can already be done for `Aabb`s.
- Add distinct segment setters for height and base one `Cone3dBuilder`.
This allow having a properly rounded base without too much edges along
the height. The doc comments explain how to ensure height and base
connect when setting different values.
Gizmo for the three light types without radius with the depth bias set
to -1:
![without-radius](https://github.com/bevyengine/bevy/assets/18357657/699d0154-f367-4727-9b09-8b458d96a0e2)
With Radius:
![with-radius](https://github.com/bevyengine/bevy/assets/18357657/f3af003e-dbba-427a-a305-c5cc1676e340)
Possible future improvements:
- Add a billboarded sprite with a distinct sprite for each light type.
- Display the intensity of the light somehow (no idea how to represent
that apart from some text).
---
## Changelog
### Added
- The new `ShowLightGizmo`, part of the `LightGizmoPlugin` and
configurable globally with `LightGizmoConfigGroup`, allows drawing gizmo
for `PointLight`, `SpotLight` and `DirectionalLight`. The gizmos color
behavior can be controlled with the `LightGizmoColor` member of
`ShowLightGizmo` and `LightGizmoConfigGroup`.
- The cone gizmo builder (`Cone3dBuilder`) now allows setting a
differing number of segments for the base and height.
---------
Co-authored-by: Gino Valente <49806985+MrGVSV@users.noreply.github.com>
# Objective
Bevy's `Dir3` and `Dir3A` only implement `Mul<f32>` and not vice versa,
and `Dir2` can not be multiplied by `f32` at all. They all should
implement multiplication both ways, just like Glam's vector types.
## Solution
Implement `Mul<Dir2>`, `Mul<Dir3>`, and `Mul<Dir3A>` for `f32`, and
`Mul<f32>` for `Dir2`.
# Objective
Adoption of #2104 and #11843. The `Option<usize>` wastes 3-7 bytes of
memory per potential entry, and represents a scaling memory overhead as
the ID space grows.
The goal of this PR is to reduce memory usage without significantly
impacting common use cases.
Co-Authored By: @NathanSWard
Co-Authored By: @tygyh
## Solution
Replace `usize` in `SparseSet`'s sparse array with
`nonmax::NonMaxUsize`. NonMaxUsize wraps a NonZeroUsize, and applies a
bitwise NOT to the value when accessing it. This allows the compiler to
niche the value and eliminate the extra padding used for the `Option`
inside the sparse array, while moving the niche value from 0 to
usize::MAX instead.
Checking the [diff in x86 generated
assembly](6e4da653cc),
this change actually results in fewer instructions generated. One
potential downside is that it seems to have moved a load before a
branch, which means we may be incurring a cache miss even if the element
is not there.
Note: unlike #2104 and #11843, this PR only targets the metadata stores
for the ECS and not the component storage itself. Due to #9907 targeting
`Entity::generation` instead of `Entity::index`, `ComponentSparseSet`
storing only up to `u32::MAX` elements would become a correctness issue.
This will come with a cost when inserting items into the SparseSet, as
now there is a potential for a panic. These cost are really only
incurred when constructing a new Table, Archetype, or Resource that has
never been seen before by the World. All operations that are fairly cold
and not on any particular hotpath, even for command application.
---
## Changelog
Changed: `SparseSet` now can only store up to `usize::MAX - 1` elements
instead of `usize::MAX`.
Changed: `SparseSet` now uses 33-50% less memory overhead per stored
item.
Follow up to #11057
Implemented suggestions from reviewers from: a simpler
fit_canvas_to_parent leads to an explicit CSS setting to the canvas.
From my understanding, it has do be set after wgpu creation due to wgpu
overriding the canvas width/height:
4400a58470/examples/src/utils.rs (L68-L74)
# Changelog
- Re-enable a `fit_canvas_to_parent`, it's removal from
https://github.com/bevyengine/bevy/pull/11057 was problematic. Still,
its inner working is more simple than before: bevy doesn't handle its
resizing, winit does.
## Migration Guide
- Cancels the migration from
https://github.com/bevyengine/bevy/pull/11057
# Objective
Fixes https://github.com/bevyengine/bevy/issues/11628
## Migration Guide
`Command` and `CommandQueue` have migrated from `bevy_ecs::system` to
`bevy_ecs::world`, so `use bevy_ecs::world::{Command, CommandQueue};`
when necessary.
# Objective
Fixes#11298. Make the use of bevy_log vs bevy_utils::tracing more
consistent.
## Solution
Replace all uses of bevy_log's logging macros with the reexport from
bevy_utils. Remove bevy_log as a dependency where it's no longer needed
anymore.
Ideally we should just be using tracing directly, but given that all of
these crates are already using bevy_utils, this likely isn't that great
of a loss right now.
# Objective
bevy_ecs has been developed with a de facto assumption that `Entity` is
to be treated as an opaque identifier by external users, and that its
internal representation is readable but in no way guaranteed to be
stable between versions of bevy_ecs.
This hasn't been clear to users, and the functions on the type that
expose its guts speak a different story.
## Solution
Explicitly document the lack of stability here and define internal
representation changes as a non-breaking change under SemVer. Give it
the same treatment that the standard lib gives `TypeId`.
# Objective
While mucking around with batch_and_prepare systems, it became apparent
that `GpuArrayBufferIndex::index` doesn't need to be a NonMaxU32.
## Solution
Replace it with a normal u32.
This likely has some potential perf benefit by avoiding panics and the
NOT operations, but I haven't been able to find any substantial gains,
so this is primarily for code quality.
---
## Changelog
Changed: `GpuArrayBufferIndex::index` is now a u32.
## Migration Guide
`GpuArrayBuferIndex::index` is now a u32 instead of a `NonMaxU32`.
Remove any calls to `NonMaxU32::get` on the member.
# Objective
- Fix mismatch between the `Component` trait method and the `World`
method.
## Solution
- Replace init_component_info with register_component_hooks.
# Objective
This PR unpins `web-sys` so that unrelated projects that have
`bevy_render` in their workspace can finally update their `web-sys`.
More details in and fixes#12246.
## Solution
* Update `wgpu` from 0.19.1 to 0.19.3.
* Remove the `web-sys` pin.
* Update docs and wasm helper to remove the now-stale
`--cfg=web_sys_unstable_apis` Rust flag.
---
## Changelog
Updated `wgpu` to v0.19.3 and removed `web-sys` pin.
This is an implementation within `bevy_window::window` that fixes
#12229.
# Objective
Fixes#12229, allow users to retrieve the window's size and physical
size as Vectors without having to manually construct them using
`height()` and `width()` or `physical_height()` and `physical_width()`
## Solution
As suggested in #12229, created two public functions within `window`:
`size() -> Vec` and `physical_size() -> UVec` that return the needed
Vectors ready-to-go.
### Discussion
My first FOSS PRQ ever, so bear with me a bit. I'm new to this.
- I replaced instances of ```Vec2::new(window.width(),
window.height());``` or `UVec2::new(window.physical_width(),
window.physical_height());` within bevy examples be replaced with their
`size()`/`physical_size()` counterparts?
- Discussion within #12229 still holds: should these also be added to
WindowResolution?
Although we cached hashes of `MeshVertexBufferLayout`, we were paying
the cost of `PartialEq` on `InnerMeshVertexBufferLayout` for every
entity, every frame. This patch changes that logic to place
`MeshVertexBufferLayout`s in `Arc`s so that they can be compared and
hashed by pointer. This results in a 28% speedup in the
`queue_material_meshes` phase of `many_cubes`, with frustum culling
disabled.
Additionally, this patch contains two minor changes:
1. This commit flattens the specialized mesh pipeline cache to one level
of hash tables instead of two. This saves a hash lookup.
2. The example `many_cubes` has been given a `--no-frustum-culling`
flag, to aid in benchmarking.
See the Tracy profile:
<img width="1064" alt="Screenshot 2024-02-29 144406"
src="https://github.com/bevyengine/bevy/assets/157897/18632f1d-1fdd-4ac7-90ed-2d10306b2a1e">
## Migration guide
* Duplicate `MeshVertexBufferLayout`s are now combined into a single
object, `MeshVertexBufferLayoutRef`, which contains an
atomically-reference-counted pointer to the layout. Code that was using
`MeshVertexBufferLayout` may need to be updated to use
`MeshVertexBufferLayoutRef` instead.
# Objective
- Provide a reliable and performant mechanism to allows users to keep
components synchronized with external sources: closing/opening sockets,
updating indexes, debugging etc.
- Implement a generic mechanism to provide mutable access to the world
without allowing structural changes; this will not only be used here but
is a foundational piece for observers, which are key for a performant
implementation of relations.
## Solution
- Implement a new type `DeferredWorld` (naming is not important,
`StaticWorld` is also suitable) that wraps a world pointer and prevents
user code from making any structural changes to the ECS; spawning
entities, creating components, initializing resources etc.
- Add component lifecycle hooks `on_add`, `on_insert` and `on_remove`
that can be assigned callbacks in user code.
---
## Changelog
- Add new `DeferredWorld` type.
- Add new world methods: `register_component::<T>` and
`register_component_with_descriptor`. These differ from `init_component`
in that they provide mutable access to the created `ComponentInfo` but
will panic if the component is already in any archetypes. These
restrictions serve two purposes:
1. Prevent users from defining hooks for components that may already
have associated hooks provided in another plugin. (a use case better
served by observers)
2. Ensure that when an `Archetype` is created it gets the appropriate
flags to early-out when triggering hooks.
- Add methods to `ComponentInfo`: `on_add`, `on_insert` and `on_remove`
to be used to register hooks of the form `fn(DeferredWorld, Entity,
ComponentId)`
- Modify `BundleInserter`, `BundleSpawner` and `EntityWorldMut` to
trigger component hooks when appropriate.
- Add bit flags to `Archetype` indicating whether or not any contained
components have each type of hook, this can be expanded for other flags
as needed.
- Add `component_hooks` example to illustrate usage. Try it out! It's
fun to mash keys.
## Safety
The changes to component insertion, removal and deletion involve a large
amount of unsafe code and it's fair for that to raise some concern. I
have attempted to document it as clearly as possible and have confirmed
that all the hooks examples are accepted by `cargo miri` as not causing
any undefined behavior. The largest issue is in ensuring there are no
outstanding references when passing a `DeferredWorld` to the hooks which
requires some use of raw pointers (as was already happening to some
degree in those places) and I have taken some time to ensure that is the
case but feel free to let me know if I've missed anything.
## Performance
These changes come with a small but measurable performance cost of
between 1-5% on `add_remove` benchmarks and between 1-3% on `insert`
benchmarks. One consideration to be made is the existence of the current
`RemovedComponents` which is on average more costly than the addition of
`on_remove` hooks due to the early-out, however hooks doesn't completely
remove the need for `RemovedComponents` as there is a chance you want to
respond to the removal of a component that already has an `on_remove`
hook defined in another plugin, so I have not removed it here. I do
intend to deprecate it with the introduction of observers in a follow up
PR.
## Discussion Questions
- Currently `DeferredWorld` implements `Deref` to `&World` which makes
sense conceptually, however it does cause some issues with rust-analyzer
providing autocomplete for `&mut World` references which is annoying.
There are alternative implementations that may address this but involve
more code churn so I have attempted them here. The other alternative is
to not implement `Deref` at all but that leads to a large amount of API
duplication.
- `DeferredWorld`, `StaticWorld`, something else?
- In adding support for hooks to `EntityWorldMut` I encountered some
unfortunate difficulties with my desired API. If commands are flushed
after each call i.e. `world.spawn() // flush commands .insert(A) //
flush commands` the entity may be despawned while `EntityWorldMut` still
exists which is invalid. An alternative was then to add
`self.world.flush_commands()` to the drop implementation for
`EntityWorldMut` but that runs into other problems for implementing
functions like `into_unsafe_entity_cell`. For now I have implemented a
`.flush()` which will flush the commands and consume `EntityWorldMut` or
users can manually run `world.flush_commands()` after using
`EntityWorldMut`.
- In order to allowing querying on a deferred world we need
implementations of `WorldQuery` to not break our guarantees of no
structural changes through their `UnsafeWorldCell`. All our
implementations do this, but there isn't currently any safety
documentation specifying what is or isn't allowed for an implementation,
just for the caller, (they also shouldn't be aliasing components they
didn't specify access for etc.) is that something we should start doing?
(see 10752)
Please check out the example `component_hooks` or the tests in
`bundle.rs` for usage examples. I will continue to expand this
description as I go.
See #10839 for a more ergonomic API built on top of this one that isn't
subject to the same restrictions and supports `SystemParam` dependency
injection.
# Objective
- We introduce a gizmo that displays coordinate axes relative to a
Transform*, primarily for debugging purposes.
- See #9400
## Solution
A new method, `Gizmos::axes`, takes a `Transform`* as input and displays
the standard coordinate axes, transformed according to it; its signature
looks like this:
````rust
pub fn axes(&mut self, transform: into TransformPoint, base_length: f32) { //... }
````
If my carefully placed asterisks hadn't already tipped you off, the
argument here is not actually a `Transform` but instead anything which
implements `TransformPoint`, which allows it to work also with
`GlobalTransform` (and also `Mat4` and `Affine3A`, if the user happens
to be hand-rolling transformations in some way).
The `base_length` parameter is a scaling factor applied to the
coordinate vectors before the transformation takes place; in other
words, the caller can use this to help size the coordinate axes
appropriately for the entity that they are attached to.
An example invocation of this method looks something like this:
````rust
fn draw_axes_system(
mut gizmos: Gizmos,
query: Query<&Transform, With<MyMarkerComponent>>,
) {
for &transform in &query {
gizmos.axes(transform, 2.);
}
}
````
The result is the three coordinate axes, X, Y, Z (colored red, green,
and blue, respectively), drawn onto the entity:
<img width="206" alt="Screenshot 2024-02-29 at 2 41 45 PM"
src="https://github.com/bevyengine/bevy/assets/2975848/789d1703-29ae-4295-80ab-b87459cf8037">
Note that, if scaling was applied as part of the given transformation,
it shows up in scaling on the axes as well:
<img width="377" alt="Screenshot 2024-02-29 at 2 43 53 PM"
src="https://github.com/bevyengine/bevy/assets/2975848/6dc1caf4-8b3e-47f7-a86a-8906d870fa72">
---
## Changelog
- Added `Gizmos::axes` in bevy_gizmos/src/arrows.rs
- Fixed a minor issue with `ArrowBuilder::with_tip_length` not correctly
implementing builder style (no external impact)
---
## Discussion
### Design considerations
I feel pretty strongly that having no default length scale is for the
best, at least for the time being, since it's very easy for the length
scale to be too small, leading to the axes being hidden inside the body
of the object they are associated with. That is, if the API instead
looked like this:
````rust
gizmos.axes(transform); // or
gizmos.axes(transform).with_length_scale(3.0);
````
then I think it's a reasonable expectation that the first thing would
"just work" for most applications, and it wouldn't, which would be kind
of a footgun.
### Future steps
There are a few directions that this might expand in the future:
1. Introduce additional options via the standard builder pattern; i.e.
introducing `AxesBuilder<T: TransformPoint>` so that people can
configure the axis colors, normalize all axes to a fixed length
independent of scale deformations, etc.
2. Fold this functionality into a plugin (like AabbGizmoPlugin) so that
the functionality becomes more-or-less automatic based on certain fixed
marker components. This wouldn't be very hard to implement, and it has
the benefit of making the axes more frictionless to use. Furthermore, if
we coupled this to the AABB functionality we already have, we could also
ensure that the plugin automatically sizes the axes (by coupling their
size to the dimensions of the AABB, for example).
3. Implement something similar for 2d. Honestly, I have no idea if this
is desired/useful, but I could probably just implement it in this PR if
that's the case.
# Objective
- As part of the migration process we need to a) see the end effect of
the migration on user ergonomics b) check for serious perf regressions
c) actually migrate the code
- To accomplish this, I'm going to attempt to migrate all of the
remaining user-facing usages of `LegacyColor` in one PR, being careful
to keep a clean commit history.
- Fixes#12056.
## Solution
I've chosen to use the polymorphic `Color` type as our standard
user-facing API.
- [x] Migrate `bevy_gizmos`.
- [x] Take `impl Into<Color>` in all `bevy_gizmos` APIs
- [x] Migrate sprites
- [x] Migrate UI
- [x] Migrate `ColorMaterial`
- [x] Migrate `MaterialMesh2D`
- [x] Migrate fog
- [x] Migrate lights
- [x] Migrate StandardMaterial
- [x] Migrate wireframes
- [x] Migrate clear color
- [x] Migrate text
- [x] Migrate gltf loader
- [x] Register color types for reflection
- [x] Remove `LegacyColor`
- [x] Make sure CI passes
Incidental improvements to ease migration:
- added `Color::srgba_u8`, `Color::srgba_from_array` and friends
- added `set_alpha`, `is_fully_transparent` and `is_fully_opaque` to the
`Alpha` trait
- add and immediately deprecate (lol) `Color::rgb` and friends in favor
of more explicit and consistent `Color::srgb`
- standardized on white and black for most example text colors
- added vector field traits to `LinearRgba`: ~~`Add`, `Sub`,
`AddAssign`, `SubAssign`,~~ `Mul<f32>` and `Div<f32>`. Multiplications
and divisions do not scale alpha. `Add` and `Sub` have been cut from
this PR.
- added `LinearRgba` and `Srgba` `RED/GREEN/BLUE`
- added `LinearRgba_to_f32_array` and `LinearRgba::to_u32`
## Migration Guide
Bevy's color types have changed! Wherever you used a
`bevy::render::Color`, a `bevy::color::Color` is used instead.
These are quite similar! Both are enums storing a color in a specific
color space (or to be more precise, using a specific color model).
However, each of the different color models now has its own type.
TODO...
- `Color::rgba`, `Color::rgb`, `Color::rbga_u8`, `Color::rgb_u8`,
`Color::rgb_from_array` are now `Color::srgba`, `Color::srgb`,
`Color::srgba_u8`, `Color::srgb_u8` and `Color::srgb_from_array`.
- `Color::set_a` and `Color::a` is now `Color::set_alpha` and
`Color::alpha`. These are part of the `Alpha` trait in `bevy_color`.
- `Color::is_fully_transparent` is now part of the `Alpha` trait in
`bevy_color`
- `Color::r`, `Color::set_r`, `Color::with_r` and the equivalents for
`g`, `b` `h`, `s` and `l` have been removed due to causing silent
relatively expensive conversions. Convert your `Color` into the desired
color space, perform your operations there, and then convert it back
into a polymorphic `Color` enum.
- `Color::hex` is now `Srgba::hex`. Call `.into` or construct a
`Color::Srgba` variant manually to convert it.
- `WireframeMaterial`, `ExtractedUiNode`, `ExtractedDirectionalLight`,
`ExtractedPointLight`, `ExtractedSpotLight` and `ExtractedSprite` now
store a `LinearRgba`, rather than a polymorphic `Color`
- `Color::rgb_linear` and `Color::rgba_linear` are now
`Color::linear_rgb` and `Color::linear_rgba`
- The various CSS color constants are no longer stored directly on
`Color`. Instead, they're defined in the `Srgba` color space, and
accessed via `bevy::color::palettes::css`. Call `.into()` on them to
convert them into a `Color` for quick debugging use, and consider using
the much prettier `tailwind` palette for prototyping.
- The `LIME_GREEN` color has been renamed to `LIMEGREEN` to comply with
the standard naming.
- Vector field arithmetic operations on `Color` (add, subtract, multiply
and divide by a f32) have been removed. Instead, convert your colors
into `LinearRgba` space, and perform your operations explicitly there.
This is particularly relevant when working with emissive or HDR colors,
whose color channel values are routinely outside of the ordinary 0 to 1
range.
- `Color::as_linear_rgba_f32` has been removed. Call
`LinearRgba::to_f32_array` instead, converting if needed.
- `Color::as_linear_rgba_u32` has been removed. Call
`LinearRgba::to_u32` instead, converting if needed.
- Several other color conversion methods to transform LCH or HSL colors
into float arrays or `Vec` types have been removed. Please reimplement
these externally or open a PR to re-add them if you found them
particularly useful.
- Various methods on `Color` such as `rgb` or `hsl` to convert the color
into a specific color space have been removed. Convert into
`LinearRgba`, then to the color space of your choice.
- Various implicitly-converting color value methods on `Color` such as
`r`, `g`, `b` or `h` have been removed. Please convert it into the color
space of your choice, then check these properties.
- `Color` no longer implements `AsBindGroup`. Store a `LinearRgba`
internally instead to avoid conversion costs.
---------
Co-authored-by: Alice Cecile <alice.i.cecil@gmail.com>
Co-authored-by: Afonso Lage <lage.afonso@gmail.com>
Co-authored-by: Rob Parrett <robparrett@gmail.com>
Co-authored-by: Zachary Harrold <zac@harrold.com.au>
# Objective
Just some mild annoyances:
- The `Color::Oklaba`, `Color::Oklcha` and `oklaba::Oklaba` doc comments
were inconsistent with the others
- The crate-level docs didn't include `Oklch` in the list of
representations and misspelt it in a later paragraph
## Solution
- Fix 'em
# Objective
- Cull 2D text outside the view frustum.
- Part of #11081.
## Solution
- Compute AABBs for entities with a `Text2DBundle` to enable culling
them.
`text2d` example with AABB gizmos on the text entities:
https://github.com/bevyengine/bevy/assets/18357657/52ed3ddc-2274-4480-835b-a7cf23338931
---
## Changelog
### Added
- 2D text outside the view are now culled with the
`calculate_bounds_text2d` system adding the necessary AABBs.
# Objective
`bevy_tasks` provides utilities for parallel mapping over slices. It can
be useful to have a chunk index available in the iteration function to
know which part of the original slice is being processed.
## Solution
Adds an index argument to the parallel map functions in `bevy_tasks`.
---
## Changelog
### Changed
- `par_chunk_map`, `par_splat_map`, `par_chunk_map_mut`, and
`par_splat_map_mut` now provide a chunk index during iteration.
## Migration Guide
Functions passed as arguments to `par_chunk_map`, `par_splat_map`,
`par_chunk_map_mut`, and `par_splat_map_mut` must now take an additional
index argument.
# Objective
Split up from #12017, rename Bevy's direction types.
Currently, Bevy has the `Direction2d`, `Direction3d`, and `Direction3dA`
types, which provide a type-level guarantee that their contained vectors
remain normalized. They can be very useful for a lot of APIs for safety,
explicitness, and in some cases performance, as they can sometimes avoid
unnecessary normalizations.
However, many consider them to be inconvenient to use, and opt for
standard vector types like `Vec3` because of this. One reason is that
the direction type names are a bit long and can be annoying to write (of
course you can use autocomplete, but just typing `Vec3` is still nicer),
and in some intances, the extra characters can make formatting worse.
The naming is also inconsistent with Glam's shorter type names, and
results in names like `Direction3dA`, which (in my opinion) are
difficult to read and even a bit ugly.
This PR proposes renaming the types to `Dir2`, `Dir3`, and `Dir3A`.
These names are nice and easy to write, consistent with Glam, and work
well for variants like the SIMD aligned `Dir3A`. As a bonus, it can also
result in nicer formatting in a lot of cases, which can be seen from the
diff of this PR.
Some examples of what it looks like: (copied from #12017)
```rust
// Before
let ray_cast = RayCast2d::new(Vec2::ZERO, Direction2d::X, 5.0);
// After
let ray_cast = RayCast2d::new(Vec2::ZERO, Dir2::X, 5.0);
```
```rust
// Before (an example using Bevy XPBD)
let hit = spatial_query.cast_ray(
Vec3::ZERO,
Direction3d::X,
f32::MAX,
true,
SpatialQueryFilter::default(),
);
// After
let hit = spatial_query.cast_ray(
Vec3::ZERO,
Dir3::X,
f32::MAX,
true,
SpatialQueryFilter::default(),
);
```
```rust
// Before
self.circle(
Vec3::new(0.0, -2.0, 0.0),
Direction3d::Y,
5.0,
Color::TURQUOISE,
);
// After (formatting is collapsed in this case)
self.circle(Vec3::new(0.0, -2.0, 0.0), Dir3::Y, 5.0, Color::TURQUOISE);
```
## Solution
Rename `Direction2d`, `Direction3d`, and `Direction3dA` to `Dir2`,
`Dir3`, and `Dir3A`.
---
## Migration Guide
The `Direction2d` and `Direction3d` types have been renamed to `Dir2`
and `Dir3`.
## Additional Context
This has been brought up on the Discord a few times, and we had a small
[poll](https://discord.com/channels/691052431525675048/1203087353850364004/1212465038711984158)
on this. `Dir2`/`Dir3`/`Dir3A` was quite unanimously chosen as the best
option, but of course it was a very small poll and inconclusive, so
other opinions are certainly welcome too.
---------
Co-authored-by: IceSentry <c.giguere42@gmail.com>
# Objective
- Fixes#12170
## Solution
- Moved the existing `color_from_entity` internals into
`Hsla::sequence_dispersed` which generates a randomly distributed but
deterministic color sequence based.
- Replicated the method for `Lcha` and `Oklcha` as well.
## Examples
### Getting a few colours for a quick palette
```rust
let palette = Hsla::sequence_dispersed().take(5).collect::<Vec<_>>();
/*[
Hsla::hsl(0.0, 1., 0.5),
Hsla::hsl(222.49225, 1., 0.5),
Hsla::hsl(84.984474, 1., 0.5),
Hsla::hsl(307.4767, 1., 0.5),
Hsla::hsl(169.96895, 1., 0.5),
]*/
```
### Getting a colour from an `Entity`
```rust
let color = Oklcha::sequence_dispersed().nth(entity.index() as u32).unwrap();
```
## Notes
This was previously a private function exclusively for `Entity` types.
I've decided it should instead be public and operate on a `u32`
directly, since this function may have broader uses for debugging
purposes.
---------
Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
# Objective
- Fixes https://github.com/bevyengine/bevy/issues/11929
- make sysinfo plugin optional
## Solution
- added features to allow for conditional compilation
---
## Migration Guide
- For users who disable default features of bevy and wish to enable the
diagnostic plugin, add `sysinfo_plugin` to your bevy features list.
---------
Co-authored-by: ebola <dev@axiomatic>
Co-authored-by: François <mockersf@gmail.com>
# Objective
fix#12182
- extract (or default) target camera for ui material nodes in the same
way as for other material nodes
- render ui material nodes only to their specified target
# Objective
Improve the `bevy::math::cubic_splines` module by making it more
flexible and adding new curve types.
Closes#10220
## Solution
Added new spline types and improved existing
---
## Changelog
### Added
- `CubicNurbs` rational cubic curve generator, allows setting the knot
vector and weights associated with every point
- `LinearSpline` curve generator, allows generating a linearly
interpolated curve segment
- Ability to push additional cubic segments to `CubicCurve`
- `IntoIterator` and `Extend` implementations for `CubicCurve`
### Changed
- `Point` trait has been implemented for more types: `Quat` and `Vec4`.
- `CubicCurve::coefficients` was moved to `CubicSegment::coefficients`
because the function returns `CubicSegment`, so it seems logical to be
associated with `CubicSegment` instead. The method is still not public.
### Fixed
- `CubicBSpline::new` was referencing Cardinal spline instead of
B-Spline
---------
Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
Co-authored-by: IQuick 143 <IQuick143cz@gmail.com>
Co-authored-by: Miles Silberling-Cook <nth.tensor@gmail.com>
Co-authored-by: Joona Aalto <jondolf.dev@gmail.com>
# Objective
- #12165 recently added links to Bevy errors in error messages.
- The links were in the form of `See:
https://bevyengine.org/learn/errors/#b000N`
- B0004 does not have the colon separating `See` and the link, unlike
the rest of the error messages
## Solution
- Add a colon, for consistency :)
# Objective
- More reflection
## Solution
- More. Reflection.
(not sure what bevy's policy on `derive(Debug)` is given that reflection
already lets you accomplish something largely equivalent; maybe
`derive(Reflect)` should generate a `Debug` impl that goes through
`Reflect::debug` unless you opt out?)
# Objective
The `css` contains all of the `basic` colors. Rather than defining them
twice, we can re-export them.
Suggested by @viridia <3
## Solution
- Re-export basic color palette within the css color palette.
- Remove the duplicate colors
- Fix alphabetization of the basic color palette file while I'm here
---------
Co-authored-by: Alice Cecile <alice.i.cecil@gmail.com>
# Objective
- Complete compatibility with CSS Module 4
## Solution
- Added `Oklcha` which implements the Oklch color model.
- Updated `Color` and `LegacyColor` accordingly.
## Migration Guide
- Convert `Oklcha` to `Oklaba` using the provided `From` implementations
and then handle accordingly.
## Notes
This is the _last_ color space missing from the CSS Module 4 standard,
and is also the one I believe we should recommend users actually work
with for hand-crafting colours. It has all the uniformity benefits of
Oklab combined with the intuition chroma and hue provide (when compared
to a-axis and b-axis parameters).
# Objective
- Implement grid gizmos, suggestion of #9400
## Solution
- Added `gizmos.grid(...) ` and `gizmos.grid_2d(...)`
- The grids may be configured using `.outer_edges(...)` to specify
whether to draw the outer border/edges of the grid and `.skew(...)`to
specify the skew of the grid along the x or y directions.
---
## Changelog
- Added a `grid` module to `bevy_gizmos` containing `gizmos.grid(...) `
and `gizmos.grid_2d(...)` as well as assorted items.
- Updated the `2d_gizmos` and `3d_gizmos` examples to use grids.
## Additional
The 2D and 3D examples now look like this:
<img width="1440" alt="Screenshot 2024-02-20 at 15 09 40"
src="https://github.com/bevyengine/bevy/assets/62256001/ce04191e-d839-4faf-a6e3-49b6bb4b922b">
<img width="1440" alt="Screenshot 2024-02-20 at 15 10 07"
src="https://github.com/bevyengine/bevy/assets/62256001/317459ba-d452-42eb-ae95-7c84cdbd569b">
# Objective
As suggested in #12163 by @cart, we should add convenience constructors
to `bevy_color::Color` to match the existing API (easing migration pain)
and generally improve ergonomics.
## Solution
- Add `const fn Color::rgba(red, green, blue, alpha)` and friends, which
directly construct the appropriate variant.
- Add `const fn Color::rgb(red, green, blue)` and friends, which impute
and alpha value of 1.0.
- Add `const BLACK, WHITE, NONE` to `Color`. These are stored in
`LinearRgba` to reduce pointless conversion costs and inaccuracy.
- Changed the default `Color` from `Srgba::WHITE` to the new linear
equivalent for the same reason.
---------
Co-authored-by: Alice Cecile <alice.i.cecil@gmail.com>
# Objective
As we start to migrate to `bevy_color` in earnest (#12056), we should
make it visible to Bevy users, and usable in examples.
## Solution
1. Add a prelude to `bevy_color`: I've only excluded the rarely used
`ColorRange` type and the testing-focused color distance module. I
definitely think that some color spaces are less useful than others to
end users, but at the same time the types used there are very unlikely
to conflict with user-facing types.
2. Add `bevy_color` to `bevy_internal` as an optional crate.
3. Re-export `bevy_color`'s prelude as part of `bevy::prelude`.
---------
Co-authored-by: Alice Cecile <alice.i.cecil@gmail.com>
# Objective
- In #9623 I forgot to change the `FromWorld` requirement for
`ReflectResource`, fix that;
- Fix#12129
## Solution
- Use the same approach as in #9623 to try using `FromReflect` and
falling back to the `ReflectFromWorld` contained in the `TypeRegistry`
provided
- Just reflect `Resource` on `State<S>` since now that's possible
without introducing new bounds.
---
## Changelog
- `ReflectResource`'s `FromType<T>` implementation no longer requires
`T: FromWorld`, but instead now requires `FromReflect`.
- `ReflectResource::insert`, `ReflectResource::apply_or_insert` and
`ReflectResource::copy` now take an extra `&TypeRegistry` parameter.
## Migration Guide
- Users of `#[reflect(Resource)]` will need to also implement/derive
`FromReflect` (should already be the default).
- Users of `#[reflect(Resource)]` may now want to also add `FromWorld`
to the list of reflected traits in case their `FromReflect`
implementation may fail.
- Users of `ReflectResource` will now need to pass a `&TypeRegistry` to
its `insert`, `apply_or_insert` and `copy` methods.
# Objective
`downcast-rs` is not used within bevy_ecs. This is probably a remnant
from before Schedule v3 landed, since stages needed the downcasting.
## Solution
Remove it.
Shows relationships between color spaces and explains what files should
contain which conversions.
# Objective
- Provide documentation for maintainers and users on how color space
conversion is implemented.
## Solution
- Created a mermaid diagram documenting the relationships between
various color spaces. This diagram also includes links to defining
articles, and edges include links to conversion formulae.
- Added a `conversion.md` document which is included in the
documentation of each of the color spaces. This ensures it is readily
visible in all relevant contexts.
## Notes
The diagram is in the Mermaid (`.mmd`) format, and must be converted
into an SVG file (or other image format) prior to use in Rust
documentation. I've included a link to
[mermaid.live](https://mermaid.live) as an option for doing such
conversion in an appropriate README.
Below is a screenshot of the documentation added.
![Capture](https://github.com/bevyengine/bevy/assets/2217286/370a65f2-6dd4-4af7-a99b-3763832d1b8a)
# Objective
`FromWorld` is often used to group loading and creation of assets for
resources.
With this setup, users often end up repetitively calling
`.resource::<AssetServer>` and `.resource_mut::<Assets<T>>`, and may
have difficulties handling lifetimes of the returned references.
## Solution
Add extension methods to `World` to add and load assets, through a new
extension trait defined in `bevy_asset`.
### Other considerations
* This might be a bit too "magic", as it makes implicit the resource
access.
* We could also implement `DirectAssetAccessExt` on `App`, but it didn't
feel necessary, as `FromWorld` is the principal use-case here.
---
## Changelog
* Add the `DirectAssetAccessExt` trait, which adds the `add_asset`,
`load_asset` and `load_asset_with_settings` method to the `World` type.
# Objective
This PR arose as part of the migration process for `bevy_color`: see
#12056.
While examining how `bevy_gizmos` stores color types internally, I found
that rather than storing a `Color` internally, it actually stores a
`[f32;4]` for a linear RGB, type aliased to a `ColorItem`.
While we don't *have* to clean this up to complete the migration, now
that we have explicit strong typing for linear color types we should use
them rather than replicating this idea throughout the codebase.
## Solution
- Added `LinearRgba::NAN`, for when you want to do cursed rendering
things.
- Replaced the internal color representation in `bevy_gizmo`: this was
`ColorItem`, but is now `LinearRgba`.
- `LinearRgba` is now `Pod`, enabling us to use the same fast `bytemuck`
bit twiddling tricks that we were using before. This requires:
1. Forcing `LinearRgba` to be `repr(C)`
2. Implementing `Zeroable`, and unsafe trait which defines what the
struct looks like when all values are zero.
3. Implementing `Pod`, a marker trait with stringent safety requirements
that is required for "plain old data".
---------
Co-authored-by: Alice Cecile <alice.i.cecil@gmail.com>
# Objective
- LinearRgba is the color type intended for shaders but using it for
shaders is currently not easy because it doesn't implement ShaderType
## Solution
- add encase as a dependency and impl the required traits.
---------
Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
Co-authored-by: Zachary Harrold <zac@harrold.com.au>
# Objective
- Improve compatibility with CSS Module 4
- Simplify `Lcha` conversion functions
## Solution
- Added `Laba` which implements the Lab color model.
- Updated `Color` and `LegacyColor` accordingly.
## Migration Guide
- Convert `Laba` to either `Xyza` or `Lcha` using the provided `From`
implementations and then handle accordingly.
## Notes
The Lab color space is a required stepping stone when converting between
XYZ and Lch, therefore we already use the Lab color model, just in an
nameless fashion prone to errors.
This PR also includes a slightly broader refactor of the `From`
implementations between the various colour spaces to better reflect the
graph of definitions. My goal was to keep domain specific knowledge of
each colour space contained to their respective files (e.g., the
`From<Oklaba> for LinearRgba` definition was in `linear_rgba.rs` when it
probably belongs in `oklaba.rs`, since Linear sRGB is a fundamental
space and Oklab is defined in its relation to it)
# Objective
The `AssetIndex` cannot be carried across boundaries that do not allow
explicit rust types.
For context, I ran into this issue while trying to implent an
improvement for bevy_egui which leverages the not-so-new custom loader
API. Passing through a handle directly isn't possible, but instead it
requires stringified URI s. I had to work around the lack of this API s
existance using reflection, which is rather dirty.
## Solution
- Add `to_bits` and `from_bits` functions to `AssetIndex` to allow
moving this type through such boundaries.
---------
Co-authored-by: Rob Parrett <robparrett@gmail.com>
# Objective
- Make these types usable in reflection-based workflows.
## Solution
- The usual. Also reflect `Default` and `Component` behaviors so that
the types can be constructed, inserted, and removed.
# Objective
Added reflect support for `std::HashSet`, `BTreeSet` and `BTreeMap`.
The set support is limited to `reflect_value` since that's the level of
support prior art `bevy_util::HashSet` got.
## Changelog
Dropped `Hash` Requirement on `MapInfo` since it's not needed on
`BTreeMap`s.
# Objective
Memory usage optimisation
## Solution
`HashMap` and `HashSet`'s keys are immutable. So using mutable types
like `String`, `Vec<T>`, or `PathBuf` as a key is a waste of memory:
they have an extra `usize` for their capacity and may have spare
capacity.
This PR replaces these types by their immutable equivalents `Box<str>`,
`Box<[T]>`, and `Box<Path>`.
For more context, I recommend watching the [Use Arc Instead of
Vec](https://www.youtube.com/watch?v=A4cKi7PTJSs) video.
---------
Co-authored-by: James Liu <contact@jamessliu.com>
# Objective
- Avoid misspellings throughout the codebase by using
[`typos`](https://github.com/crate-ci/typos) in CI
Inspired by https://github.com/gfx-rs/wgpu/pull/5191
Typos is a minimal code speller written in rust that finds and corrects
spelling mistakes among source code.
- Fast enough to run on monorepos
- Low false positives so you can run on PRs
## Solution
- Use
[typos-action](https://github.com/marketplace/actions/typos-action) in
CI
- Add how to use typos in the Contribution Guide
---------
Co-authored-by: François <mockersf@gmail.com>
Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
Co-authored-by: Joona Aalto <jondolf.dev@gmail.com>
# Objective
- Fixes#12001.
- Note this PR doesn't change any feature flags, however flaky the issue
revealed they are.
## Solution
- Use `FromReflect` to convert proxy types to concrete ones in
`ReflectSerialize::get_serializable`.
- Use `get_represented_type_info() -> type_id()` to get the correct type
id to interact with the registry in
`bevy_reflect::serde::ser::get_serializable`.
---
## Changelog
- Registering `ReflectSerialize` now imposes additional `FromReflect`
and `TypePath` bounds.
## Migration Guide
- If `ReflectSerialize` is registered on a type, but `TypePath` or
`FromReflect` implementations are omitted (perhaps by
`#[reflect(type_path = false)` or `#[reflect(from_reflect = false)]`),
the traits must now be implemented.
---------
Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
Co-authored-by: Gino Valente <49806985+MrGVSV@users.noreply.github.com>
# Objective
Fix#11845.
## Solution
Remove the `UpdateAssets` and `AssetEvents` schedules. Moved the
`UpdateAssets` systems to `PreUpdate`, and `AssetEvents` systems into
`First`. The former is meant to run before any of the event flushes.
## Future Work
It'd be ideal if we could manually flush the events for assets to avoid
needing two, sort of redundant, systems. This should at least let them
potentially run in parallel with all of the systems in the schedules
they were moved to.
---
## Changelog
Removed: `UpdateAssets` schedule from the main schedule. All systems
have been moved to `PreUpdate`.
Removed: `AssetEvents` schedule from the main schedule. All systems have
been move to `First` with the same system sets.
## Migration Guide
TODO
# Objective
- Partially addresses https://github.com/bevyengine/bevy/issues/11470
(I'd like to add Spatiotemporal Blue Noise in the future, but that's a
bit more controversial).
- Fix cluster_debug_visualization which has not compiled for a while
---
## Changelog
- Added random white noise shader functions to `bevy_pbr::utils`
## Migration Guide
- The `bevy_pbr::utils::random1D` shader function has been replaced by
the similar `bevy_pbr::utils::rand_f`.
# Objective
- During rendering of different gizmo groups, the ordering is random
between executions
## Solution
- Make the ordering stable
- It's using a `TypeIdMap`, its iteration order depends on the insertion
order. so insert when adding a group instead of when adding a gizmo
- Also changed `extract_gizmo_data` to not be group dependent. there
will be only one of those systems, no matter the number of gizmo groups
added
---------
Co-authored-by: pablo-lua <126117294+pablo-lua@users.noreply.github.com>
# Objective
`CameraProjectionPlugin<T>`'s bounds are `T: CameraProjection`. But the
bounds for `CameraProjectionPlugin` implementing `Plugin` are `T:
CameraProjection + Component + GetTypeRegistration`. This means that if
`T` is valid for `CameraProjectionPlugin`'s bounds, but not the plugin
implementation's bounds, then `CameraProjectionPlugin` would not
implement `Plugin`. Which is weird because you'd expect a struct with
`Plugin` in the name to implement `Plugin`.
## Solution
Make `CameraProjectionPlugin<T>`'s bounds `T: CameraProjection +
Component + GetTypeRegistration`. I also rearranged some of the code.
---
## Changelog
- Changed `CameraProjectionPlugin<T>`'s bounds to `T: CameraProjection +
Component + GetTypeRegistration`
## Migration Guide
`CameraProjectionPlugin<T>`'s trait bounds now require `T` to implement
`CameraProjection`, `Component`, and `GetTypeRegistration`. This
shouldn't affect most existing code as `CameraProjectionPlugin<T>` never
implemented `Plugin` unless those bounds were met.
# Objective
Split up from #12017, add an aligned version of `Direction3d` for SIMD,
and move direction types out of `primitives`.
## Solution
Add `Direction3dA` and move direction types into a new `direction`
module.
---
## Migration Guide
The `Direction2d`, `Direction3d`, and `InvalidDirectionError` types have
been moved out of `bevy::math::primitives`.
Before:
```rust
use bevy::math::primitives::Direction3d;
```
After:
```rust
use bevy::math::Direction3d;
```
---------
Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
# Objective
- Improve compatibility with CSS Module 4
- Simplify `Hsla` conversion functions
## Solution
- Added `Hsva` which implements the HSV color model.
- Added `Hwba` which implements the HWB color model.
- Updated `Color` and `LegacyColor` accordingly.
## Migration Guide
- Convert `Hsva` / `Hwba` to either `Hsla` or `Srgba` using the provided
`From` implementations and then handle accordingly.
## Notes
While the HSL color space is older than HWB, the formulation for HWB is
more directly related to RGB. Likewise, HSV is more closely related to
HWB than HSL. This makes the conversion of HSL to/from RGB more
naturally represented as the compound operation HSL <-> HSV <-> HWB <->
RGB. All `From` implementations for HSL, HSV, and HWB have been designed
to take the shortest path between itself and the target space.
---------
Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
# Objective
- We should move towards a consistent use of the new `bevy_color` crate.
- As discussed in #12089, splitting this work up into small pieces makes
it easier to review.
## Solution
- Port all uses of `LegacyColor` in the `bevy_core_pipeline` to
`LinearRgba`
- `LinearRgba` is the correct type to use for internal rendering types
- Added `LinearRgba::BLACK` and `WHITE` (used during migration)
- Add `LinearRgba::grey` to more easily construct balanced grey colors
(used during migration)
- Add a conversion from `LinearRgba` to `wgpu::Color`. The converse was
not done at this time, as this is typically a user error.
I did not change the field type of the clear color on the cameras: as
this is user-facing, this should be done in concert with the other
configurable fields.
## Migration Guide
`ColorAttachment` now stores a `LinearRgba` color, rather than a Bevy
0.13 `Color`.
`set_blend_constant` now takes a `LinearRgba` argument, rather than a
Bevy 0.13 `Color`.
---------
Co-authored-by: Alice Cecile <alice.i.cecil@gmail.com>
# Objective
Right now when using egui, systems are inserted without any identifier
and to the root. I'd like to name those systems and insert them as
children to a root entity. This helps to keep the editor organized.
## Solution
- Although the `SystemId` is documented as an opaque type, examples
depicted above benefit from tear down of the abstraction.
---
## Changelog
### Added
- Implemented `From<SystemId>` for `Entity`
---------
Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
# Objective
- followup to https://github.com/bevyengine/bevy/pull/11671
- I forgot to change the alpha masked phases.
## Solution
- Change the sorting for alpha mask phases to sort by pipeline+mesh
instead of distance, for much better batching for alpha masked
materials.
I also fixed some docs that I missed in the previous PR.
---
## Changelog
- Alpha masked materials are now sorted by pipeline and mesh.
Add Archetype::component_count utility method
# Objective
I wanted a method to count components on an archetype without iterating
over them.
## Solution
Added `Archetype::component_count`
---------
Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
# Objective
The multi-threaded executor currently runs in a dedicated task on a
single thread. When a system finishes running, it needs to notify that
task and wait for the thread to be available and running before the
executor can process the completion.
See #8304
## Solution
Run the multi-threaded executor at the end of each system task. This
allows it to run immediately instead of needing to wait for the main
thread to wake up. Move the mutable executor state into a separate
struct and wrap it in a mutex so it can be shared among the worker
threads.
While this should be faster in theory, I don't actually know how to
measure the performance impact myself.
---------
Co-authored-by: James Liu <contact@jamessliu.com>
Co-authored-by: Mike <mike.hsu@gmail.com>
# Objective
Partially address #888. Gilrs is initialized on a separate thread, and
thus conditionally implements `Send`, and all platforms other than Wasm.
This means the `NonSend` resource constraint is likely too conservative.
## Solution
Relax the requirement, and conditionally derive Resource on a wrapper
around it, using `SyncCell` to satisfy the `Sync` requirement on it.
# Objective
- Fixes#12081
## Solution
Passing the `Affine2` as a neatly packed `mat3x2` breaks WebGL with
`drawElementsInstanced: Buffer for uniform block is smaller than
UNIFORM_BLOCK_DATA_SIZE.`
I fixed this by using a `mat3x3` instead.
Alternative solutions that come to mind:
- Pass in a `mat3x2` on non-webgl targets and a `mat3x3` otherwise. I
guess I could use `#ifdef SIXTEEN_BYTE_ALIGNMENT` for this, but it
doesn't seem quite right? This would be more efficient, but decrease
code quality.
- Do something about `UNIFORM_BLOCK_DATA_SIZE`. I don't know how, so I'd
need some guidance here.
@superdump let me know if you'd like me to implement other variants.
Otherwise, I vote for merging this as a quick fix for `main` and then
improving the packing in subsequent PRs :)
## Additional notes
Ideally we should merge this before @JMS55 rebases #10164 so that they
don't have to rebase everything a second time.
# Objective
- Fixes#12068
## Solution
- Split `bevy_render::color::colorspace` across the various space
implementations in `bevy_color` as appropriate.
- Moved `From` implementations involving
`bevy_render::color::LegacyColor` into `bevy_render::color`
## Migration Guide
###
`bevy_render::color::colorspace::SrgbColorSpace::<f32>::linear_to_nonlinear_srgb`
Use `bevy_color::color::gamma_function_inverse`
###
`bevy_render::color::colorspace::SrgbColorSpace::<f32>::nonlinear_to_linear_srgb`
Use `bevy_color::color::gamma_function`
###
`bevy_render::color::colorspace::SrgbColorSpace::<u8>::linear_to_nonlinear_srgb`
Modify the `u8` value to instead be an `f32` (`|x| x as f32 / 255.`),
use `bevy_color::color::gamma_function_inverse`, and back again.
###
`bevy_render::color::colorspace::SrgbColorSpace::<u8>::nonlinear_to_linear_srgb`
Modify the `u8` value to instead be an `f32` (`|x| x as f32 / 255.`),
use `bevy_color::color::gamma_function`, and back again.
###
`bevy_render::color::colorspace::HslRepresentation::hsl_to_nonlinear_srgb`
Use `Hsla`'s implementation of `Into<Srgba>`
###
`bevy_render::color::colorspace::HslRepresentation::nonlinear_srgb_to_hsl`
Use `Srgba`'s implementation of `Into<Hsla>`
###
`bevy_render::color::colorspace::LchRepresentation::lch_to_nonlinear_srgb`
Use `Lcha`'s implementation of `Into<Srgba>`
###
`bevy_render::color::colorspace::LchRepresentation::nonlinear_srgb_to_lch`
Use `Srgba`'s implementation of `Into<Lcha>`
# Objective
- The bloom effect is currently somewhat costly (in terms of GPU time
used), due to using fragment shaders for down- and upscaling (compute
shaders generally perform better for such tasks).
- Additionally, one might have a `BloomSettings` on a camera whose
`intensity` is only occasionally set to a non-zero value (eg. in outside
areas or areas with bright lighting). Currently, the cost of the bloom
shader is always incurred as long as the `BloomSettings` exists.
## Solution
- Bail out of the bloom render node when `intensity == 0.0`, making the
effect free as long as it is turned all the way down.
# Objective
- Fixes#751
## Solution
- Added `PluginGroupBuilder::add_group`, which accepts an owned `impl
PluginGroup` and adds those plugins to self, following
`PluginGroupBuilder::add`'s replacement rules.
- Split `PluginGroupBuilder::upsert_plugin_state` into two functions,
one of the same name, and
`PluginGroupBuilder::upsert_plugin_entry_state` which takes a
`PluginEntry` and `TypeId` directly. This allows for shared behaviour
between `add` and `add_group`.
- Added 2 unit tests documenting the replacement behaviour in
`PluginGroupBuilder::add_group`.
Co-authored-by: François <mockersf@gmail.com>
# Objective
- A tiny nit I noticed; I think the type of these function is
`EntityCommand`, not `Command`
Co-authored-by: Charles Bournhonesque <cbournhonesque@snapchat.com>
# Objective
#7348 added `bevy_utils::Parallel` and replaced the usage of the
`ThreadLocal<Cell<Vec<...>>>` in `check_visibility`, but we were also
using it in `extract_meshes`.
## Solution
Refactor the system to use `Parallel` instead.
# Objective
The physical width and height (pixels) of an image is always integers,
but for `GpuImage` bevy currently stores them as `Vec2` (`f32`).
Switching to `UVec2` makes this more consistent with the [underlying
texture data](https://docs.rs/wgpu/latest/wgpu/struct.Extent3d.html).
I'm not sure if this is worth the change in the surface level API. If
not, feel free to close this PR.
## Solution
- Replace uses of `Vec2` with `UVec2` when referring to texture
dimensions.
- Use integer types for the texture atlas dimensions and sections.
[`Sprite::rect`](a81a2d1da3/crates/bevy_sprite/src/sprite.rs (L29))
remains unchanged, so manually specifying a sub-pixel region of an image
is still possible.
---
## Changelog
- `GpuImage` now stores its size as `UVec2` instead of `Vec2`.
- Texture atlases store their size and sections as `UVec2` and `URect`
respectively.
- `UiImageSize` stores its size as `UVec2`.
## Migration Guide
- Change floating point types (`Vec2`, `Rect`) to their respective
unsigned integer versions (`UVec2`, `URect`) when using `GpuImage`,
`TextureAtlasLayout`, `TextureAtlasBuilder`,
`DynamicAtlasTextureBuilder` or `FontAtlas`.
# Objective
- I hit an issue using the `file_watcher` feature to hot reload assets
for my game. The change in this PR allows me to now hot reload assets.
- The issue stemmed from my project being a multi crate workspace
project structured like so:
```
└── my_game
├── my_game_core
│ ├── src
│ └── assets
├── my_game_editor
│ └── src/main.rs
└── my_game
└── src/main.rs
```
- `my_game_core` is a crate that holds all my game logic and assets
- `my_game` is the crate that creates the binary for my game (depends on
the game logic and assets in `my_game_core`)
- `my_game_editor` is an editor tool for my game (it also depends on the
game logic and assets in `my_game_core`)
Whilst running `my_game` and `my_game_editor` from cargo during
development I would use `AssetPlugin` like so:
```rust
default_plugins.set(AssetPlugin {
watch_for_changes_override: Some(true),
file_path: "../my_game_core/assets".to_string(),
..Default::default()
})
```
This works fine; bevy picks up the assets. However on saving an asset I
would get the following panic from `file_watcher`. It wouldn't kill the
app, but I wouldn't see the asset hot reload:
```
thread 'notify-rs debouncer loop' panicked at /Users/ian/.cargo/registry/src/index.crates.io-6f17d22bba15001f/bevy_asset-0.12.1/src/io/file/file_watcher.rs:48:58:
called `Result::unwrap()` on an `Err` value: StripPrefixError(())
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
```
## Solution
- The solution is to collapse dot segments in the root asset path
`FileWatcher` is using
- There was already bevy code to do this in `AssetPath`, so I extracted
that code so it could be reused in `FileWatcher`
# Objective
- Simplify `Srgba` hex string parsing using std hex parsing functions
and removing loops in favor of bitwise ops.
This is a follow-up of the `bevy_color` upstream PR review:
https://github.com/bevyengine/bevy/pull/12013#discussion_r1497408114
## Solution
- Reworked `Srgba::hex` to use `from_str_radix` and some bitwise ops;
---------
Co-authored-by: Rob Parrett <robparrett@gmail.com>
# Objective
- Sometimes, it is useful to get a `Handle<T>` from an `AssetId<T>`. For
example, when iterating `Assets` to find a specific asset. So much so
that it's possible to do so with `AssetServer::get_id_handle`
- However, `AssetServer::get_id_handle` doesn't work with assets
directly added to `Assets` using `Assets::add`.
- Fixes#12087
## Solution
- Add `Assets::get_strong_handle` to convert an `AssetId` into an
`Handle`
- Document `AssetServer::get_id_handle` to explain its limitation and
point to `get_strong_handle`.
- Add a test for `get_strong_handle`
- Add a `duplicate_handles` field to `Assets` to avoid dropping assets
with a live handle generated by `get_strong_handle` (more reference
counting yay…)
- Fix typos in `Assets` docs
---
## Changelog
- Add `Assets::get_strong_handle` to convert an `AssetId` into an
`Handle`
# Objective
- Add the new `-Zcheck-cfg` checks to catch more warnings
- Fixes#12091
## Solution
- Create a new `cfg-check` to the CI that runs `cargo check -Zcheck-cfg
--workspace` using cargo nightly (and fails if there are warnings)
- Fix all warnings generated by the new check
---
## Changelog
- Remove all redundant imports
- Fix cfg wasm32 targets
- Add 3 dead code exceptions (should StandardColor be unused?)
- Convert ios_simulator to a feature (I'm not sure if this is the right
way to do it, but the check complained before)
## Migration Guide
No breaking changes
---------
Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
# Objective
- Make `GizmoConfigStore` play well with reflection-based workflows like
editors.
## Solution
- `#[derive(Reflect)]` and call `.register_type()`.
# Objective
The migration process for `bevy_color` (#12013) will be fairly involved:
there will be hundreds of affected files, and a large number of APIs.
## Solution
To allow us to proceed granularly, we're going to keep both
`bevy_color::Color` (new) and `bevy_render::Color` (old) around until
the migration is complete.
However, simply doing this directly is confusing! They're both called
`Color`, making it very hard to tell when a portion of the code has been
ported.
As discussed in #12056, by renaming the old `Color` type, we can make it
easier to gradually migrate over, one API at a time.
## Migration Guide
THIS MIGRATION GUIDE INTENTIONALLY LEFT BLANK.
This change should not be shipped to end users: delete this section in
the final migration guide!
---------
Co-authored-by: Alice Cecile <alice.i.cecil@gmail.com>
# Objective
Add XYZ colour space. This will be most useful as a conversion step when
working with other (more common) colour spaces. See
[Wikipedia](https://en.wikipedia.org/wiki/CIE_1931_color_space) for
details on this space.
## Solution
- Added `Xyza` to `Color` and as its own type.
---
## Changelog
- Added `Xyza` type.
- Added `Color::Xyza` variant.
## Migration Guide
- `Color` enum now has an additional member, `Xyza`. Convert it to any
other type to handle this case in match statements.
# Objective
- Fix a wrongly named type
## Solution
- Rename it properly
---------
Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
Co-authored-by: Nicola Papale <nicopap@users.noreply.github.com>
# Objective
Fixes#11821.
## Solution
* Run `System::apply_deferred` in `System::run` after executing the
system.
* Switch to using `System::run_unsafe` in `SingleThreadedExecutor` to
preserve the current behavior.
* Remove the `System::apply_deferred` in `SimpleExecutor` as it's now
redundant.
* Remove the `System::apply_deferred` when running one-shot systems, as
it's now redundant.
---
## Changelog
Changed: `System::run` will now immediately apply deferred system params
after running the system.
## Migration Guide
`System::run` will now always run `System::apply_deferred` immediately
after running the system now. If you were running systems and then
applying their deferred buffers at a later point in time, you can
eliminate the latter.
```rust
// in 0.13
system.run(world);
// .. sometime later ...
system.apply_deferred(world);
// in 0.14
system.run(world);
```
---------
Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
# Objective
Since #9822, `SimpleExecutor` panics when an automatic sync point is
inserted:
```rust
let mut sched = Schedule::default();
sched.set_executor_kind(ExecutorKind::Simple);
sched.add_systems((|_: Commands| (), || ()).chain());
sched.run(&mut World::new());
```
```
System's param_state was not found. Did you forget to initialize this system before running it?
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
Encountered a panic in system `bevy_ecs::schedule::executor::apply_deferred`!
```
## Solution
Don't try to run the `apply_deferred` system.
# Objective
Fixes Skyboxes on WebGL, which broke in Bevy 0.13 due to the addition of
the `brightness` uniform, when previously the skybox pipeline only had
view and global uniforms.
```ignore
panicked at ~/.cargo/registry/src/index.crates.io-6f17d22bba15001f/wgpu-0.19.1/src/backend/wgpu_core.rs:3009:5:
wgpu error: Validation Error
Caused by:
In Device::create_render_pipeline
note: label = `skybox_pipeline`
In the provided shader, the type given for group 0 binding 3 has a size of 4. As the device does not support `DownlevelFlags::BUFFER_BINDINGS_NOT_16_BYTE_ALIGNED`, the type must have a size that is a multiple of 16 bytes.
```
It would be nice if this could be backported to a 0.13.1 patch as well
if possible. I'm needing to rely on my own fork for now.
## Solution
Similar to the Globals uniform solution here:
d31de3f139/crates/bevy_render/src/globals.rs (L59-L60)
I've added 3 conditional fields to `SkyboxUniforms`.
# Objective
`Scope::spawn`, `Scope::spawn_on_external`, and `Scope::spawn_on_scope`
have different signatures depending on whether the `multi-threaded`
feature is enabled. The single-threaded version has a stricter signature
that prevents sending the `Scope` itself to spawned tasks.
## Solution
Changed the lifetime constraints in the single-threaded signatures from
`'env` to `'scope` to match the multi-threaded version.
This was split off from #11906.
# Objective
- Assist Bevy contributors in the creation of `bevy_color` spaces by
ensuring consistent API implementation.
## Solution
Created a `pub(crate)` trait `StandardColor` which has all the
requirements for a typical color space (e.g, `Srgba`, `Color`, etc.).
---
## Changelog
- Implemented traits missing from certain color spaces.
## Migration Guide
_No migration required_
# Objective
Improve code quality and prevent bugs.
## Solution
I removed the unnecessary wildcards from `<LogPlugin as Plugin>::build`.
I also changed the warnings that would occur if the subscriber/logger
was already set into errors.
# Objective
This provides a new set of color types and operations for Bevy.
Fixes: #10986#1402
## Solution
The new crate provides a set of distinct types for various useful color
spaces, along with utilities for manipulating and converting colors.
This is not a breaking change, as no Bevy APIs are modified (yet).
---------
Co-authored-by: François <mockersf@gmail.com>
# Objective
When dealing with custom asset sources it can be a bit tricky to get
asset roots combined with relative paths correct.
It's even harder when it isn't mentioned which path was problematic.
## Solution
Mention which path failed for the file watcher.
Signed-off-by: Torstein Grindvik <torstein.grindvik@muybridge.com>
Co-authored-by: Torstein Grindvik <torstein.grindvik@muybridge.com>
# Objective
- Fixes#11977 - user defined shaders don't work in wasm
- After investigation, it won't work if the shader is not yet available
when compiling the pipeline on all platforms, for example if you load
many assets
## Solution
- Set the pipeline state to queued when it errs waiting for the shader
so that it's retried
# Objective
- Some properties of public types are private but sometimes it's useful
to be able to set those
## Solution
- Make more stuff pub
---
## Changelog
- `MaterialBindGroupId` internal id is now pub and added a new()
constructor
- `ExtractedPointLight` and `ExtractedDirectionalLight` properties are
now all pub
---------
Co-authored-by: James Liu <contact@jamessliu.com>
This PR closes#11978
# Objective
Fix rendering on iOS Simulators.
iOS Simulator doesn't support the capability CUBE_ARRAY_TEXTURES, since
0.13 this started to make iOS Simulator not render anything with the
following message being outputted:
```
2024-02-19T14:59:34.896266Z ERROR bevy_render::render_resource::pipeline_cache: failed to create shader module: Validation Error
Caused by:
In Device::create_shader_module
Shader validation error:
Type [40] '' is invalid
Capability Capabilities(CUBE_ARRAY_TEXTURES) is required
```
## Solution
- Split up NO_ARRAY_TEXTURES_SUPPORT into both NO_ARRAY_TEXTURES_SUPPORT
and NO_CUBE_ARRAY_TEXTURES_SUPPORT and correctly apply
NO_ARRAY_TEXTURES_SUPPORT for iOS Simulator using the cfg flag
introduced in #10178.
---
## Changelog
### Fixed
- Rendering on iOS Simulator due to missing CUBE_ARRAY_TEXTURES support.
---------
Co-authored-by: Sam Pettersson <sam.pettersson@geoguessr.com>
# Objective
- Taplo in CI is not running. The link used to download taplo doesn't
work anymore.
## Solution
- Compile taplo directly with cargo
- Improve docs a little
- Run taplo
---------
Co-authored-by: François <mockersf@gmail.com>
# Objective
- The `touch_screen_input_system` system runs on every tick.
- It unconditionally calls `update(&mut self)`, on the `Touches`
resource.
- This blocks the usage of a `resource_changed::<Touches>` run
condition.
## Solution
- Remove `update(&mut self)` as it's only used in this one system, and
in-lining the method implementation removes an indirection to an
ambiguously named method.
- Add conditional checks around the calls to clearing the internal maps.
---------
Signed-off-by: Jean Mertz <git@jeanmertz.com>
# Objective
- Some members of `bevy_dynamic_plugin` are not documented.
- Part of #3492.
## Solution
- Add documentation to members missing it in `bevy_dynamic_plugin`.
- Update existing documentation for clarity and formatting.
---
## Changelog
- Completely document `bevy_dynamic_plugin`.
---------
Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
Co-authored-by: James Liu <contact@jamessliu.com>
# Objective
- Part of #11590
- Fix `unsafe_op_in_unsafe_fn` for trivial cases in bevy_ecs
## Solution
Fix `unsafe_op_in_unsafe_fn` in bevy_ecs for trivial cases, i.e., add an
`unsafe` block when the safety comment already exists or add a comment
like "The invariants are uphold by the caller".
---------
Co-authored-by: James Liu <contact@jamessliu.com>
## Objective
Always have `some_system.into_system().type_id() ==
some_system.into_system_set().system_type().unwrap()`.
System sets have a `fn system_type() -> Option<TypeId>` that is
implemented by `SystemTypeSet` to returning the TypeId of the system's
function type. This was implemented in
https://github.com/bevyengine/bevy/pull/7715 and is used in
`bevy_mod_debugdump` to handle `.after(function)` constraints.
Back then, `System::type_id` always also returned the type id of the
function item, not of `FunctionSystem<M, F>`.
https://github.com/bevyengine/bevy/pull/11728 changes the behaviour of
`System::type_id` so that it returns the id of the
`FunctionSystem`/`ExclusiveFunctionSystem` wrapper, but it did not
change `SystemTypeSet::system_type`, so doing the lookup breaks in
`bevy_mod_debugdump`.
## Solution
Change `IntoSystemSet` for functions to return a
`SystemTypeSet<FunctionSystem>` /
`SystemTypeSet<ExclusiveFunctionSystem>` instead of `SystemTypeSet<F>`.
# Objective
- Globals are supposed to be available in vertex shader but that was
mistakenly removed in 0.13
## Solution
- Configure the visibility of the globals correctly
Fixes https://github.com/bevyengine/bevy/issues/12015
# Objective
- The file asset source currently creates the `imported_assets/Default`
directory with relative path, which leads to wrongly created directories
when the executable is run with a working directory different from the
project root.
## Solution
- Use the full path instead.
# Objective
This PR adds some missing mime types to the
`ImageFormat::from_mime_type` method. As discussed [in this comment on
the Discord Bevy
community](https://discord.com/channels/691052431525675048/691052431974465548/1209904290227949729):
> It's strange that Bevy supports parsing `ImageFormat::WebP` from a
.webp str extension in the method below, but not from the mime type.
>
> In comparison, the image crate does parse it:
https://github.com/image-rs/image/blob/master/src/image.rs#L170
# Solution
For each of the missing mime types, I added them based on the
`ImageFormat::from_mime_type` of the image crate:
https://github.com/image-rs/image/blob/master/src/image.rs#L209, except
for `ImageFormat::Basis` and `ImageFormat::Ktx2` which are not present
in the image crate, and I ignore if they have a mime type or not*
\* apparently nowadays there is an official mime type: `image/ktx2`
https://www.iana.org/assignments/media-types/image/ktx2
Any feedback is welcome! I thought of refactoring a bit more and
delegating the mime type parsing to the image crate (and possibly the
same for extensions), let me know if that's desired 🙂
Fixes#12016.
Bump version after release
This PR has been auto-generated
Co-authored-by: Bevy Auto Releaser <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: François <mockersf@gmail.com>
# Objective
- Closes#11985
## Solution
- alpha.rs has been moved from bevy_pbr into bevy_render; bevy_pbr and
bevy_gltf now access `AlphaMode` through bevy_render.
---
## Migration Guide
In the present implementation, external consumers of `AlphaMode` will
have to access it through bevy_render rather than through bevy_pbr,
changing their import from `bevy_pbr::AlphaMode` to
`bevy_render::alpha::AlphaMode` (or the corresponding glob import from
`bevy_pbr::prelude::*` to `bevy_render::prelude::*`).
## Uncertainties
Some remaining things from this that I am uncertain about:
- Here, the `app.register_type<AlphaMode>()` call has been moved from
`PbrPlugin` to `RenderPlugin`; I'm not sure if this is quite right, and
I was unable to find any direct relationship between `PbrPlugin` and
`RenderPlugin`.
- `AlphaMode` was placed in the prelude of bevy_render. I'm not certain
that this is actually appropriate.
- bevy_pbr does not re-export `AlphaMode`, which makes this a breaking
change for external consumers.
Any of these things could be easily changed; I'm just not confident that
I necessarily adopted the right approach in these (known) ways since
this codebase and ecosystem is quite new to me.
Adopted #8266, so copy-pasting the description from there:
# Objective
Support the KHR_texture_transform extension for the glTF loader.
- Fixes#6335
- Fixes#11869
- Implements part of #11350
- Implements the GLTF part of #399
## Solution
As is, this only supports a single transform. Looking at Godot's source,
they support one transform with an optional second one for detail, AO,
and emission. glTF specifies one per texture. The public domain
materials I looked at seem to share the same transform. So maybe having
just one is acceptable for now. I tried to include a warning if multiple
different transforms exist for the same material.
Note the gltf crate doesn't expose the texture transform for the normal
and occlusion textures, which it should, so I just ignored those for
now. (note by @janhohenheim: this is still the case)
Via `cargo run --release --example scene_viewer
~/src/clone/glTF-Sample-Models/2.0/TextureTransformTest/glTF/TextureTransformTest.gltf`:
![texture_transform](https://user-images.githubusercontent.com/283864/228938298-aa2ef524-555b-411d-9637-fd0dac226fb0.png)
## Changelog
Support for the
[KHR_texture_transform](https://github.com/KhronosGroup/glTF/tree/main/extensions/2.0/Khronos/KHR_texture_transform)
extension added. Texture UVs that were scaled, rotated, or offset in a
GLTF are now properly handled.
---------
Co-authored-by: Al McElrath <hello@yrns.org>
Co-authored-by: Kanabenki <lucien.menassol@gmail.com>
# Objective
If multiple cameras render to the same target with MSAA enabled, only
the first and the last camera output will appear in the final output*.
This is because each camera maintains a separate flag to track the
active main texture. The first camera renders to texture A and all
subsequent cameras first write-back from A and then render into texture
B. Hence, camera 3 onwards will overwrite the work of the previous
camera.
\* This would manifest slightly differently if there were other calls to
post_process_write() in a more complex setup.
The is a functional regression from Bevy 0.12.
## Solution
The flag which tracks the active main texture should be shared between
cameras with the same `NormalizedRenderTarget`. Add the
`Arc<AtomicUsize>` to the existing per-target cache.
# Objective
- Save 16 bytes per MeshUniform in uniform/storage buffers.
## Solution
- Reorder members of MeshUniform to capitalise on alignment and size
rules for tighter data packing. Before the size of a MeshUniform was 160
bytes, and after it is 144 bytes, saving 16 bytes of unused padding for
alignment.
---
## Changelog
- Reduced the size of MeshUniform by 16 bytes.
# Objective
The derive macro wasn't doc-commented, so it showed up in the generated
doc as follow:
```rust
#[derive(Asset, TypePath)]
let shader = asset_server.load::<Shader>("embedded://bevy_rock/render/rock.wgsl");
```
Which is very confusing
## Solution
Comment the `derive` attribute as well
# Objective
We deprecated quite a few APIs in 0.13. 0.13 has shipped already. It
should be OK to remove them in 0.14's release. Fixes#4059. Fixes#9011.
## Solution
Remove them.
# Objective
- Some workspace members do not inherit the global lints.
## Solution
- Add a `[lints]` entry for all files returned by `rg
--files-without-match -F "[lints]" **/Cargo.toml`, except the compile
failure tests since these aren't part of the workspace.
- Add some docstrings where needed.
---------
Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
# Objective
* Fixes#11932 (performance impact when stepping is disabled)
## Solution
The `Option<FixedBitSet>` argument added to `ScheduleExecutor::run()` in
#8453 caused a measurable performance impact even when stepping is
disabled. This can be seen by the benchmark of running `Schedule:run()`
on an empty schedule in a tight loop
(https://github.com/bevyengine/bevy/issues/11932#issuecomment-1950970236).
I was able to get the same performance results as on 0.12.1 by changing
the argument
`ScheduleExecutor::run()` from `Option<FixedBitSet>` to
`Option<&FixedBitSet>`. The down-side of this change is that
`Schedule::run()` now takes about 6% longer (3.7319 ms vs 3.9855ns) when
stepping is enabled
---
## Changelog
* Change `ScheduleExecutor::run()` `_skipped_systems` from
`Option<FixedBitSet>` to `Option<&FixedBitSet>`
* Added a few benchmarks to measure `Schedule::run()` performance with
various executors
# Objective
- Gltf loader now shows which file is missing pre baked tangents
- Fixes#11831
## Solution
- The file name is shown in the error message
- What changed as a result of this PR?
### Changed:
- Gltf loader now shows which file is missing pre baked tangents
- If this PR is a breaking change (relative to the last release of
Bevy), describe how a user might need to migrate their code to support
these changes
- Simply adding new functionality is not a breaking change.
- Fixing behavior that was definitely a bug, rather than a questionable
design choice is not a breaking change.
# Objective
Currently, the `ambiguous_names` hash set in `TypeRegistry` is used to
keep track of short type names that are ambiguous, and to require the
use of long type names for these types.
However, there's no way for the consumer of `TypeRegistry` to known
whether a given call to `get_with_short_type_path()` or
`get_with_short_type_path_mut()` failed because a type was not
registered at all, or because the short name is ambiguous.
This can be used, for example, for better error reporting to the user by
an editor tool. Here's some code that uses this, from my remote protocol
exploration branch:
```rust
let type_registration = type_registry
.get_with_type_path(component_name)
.or_else(|| registry.get_with_short_type_path(component_name))
.ok_or_else(|| {
if type_registry.is_ambiguous(component_name) {
BrpError::ComponentAmbiguous(component_name.clone())
} else {
BrpError::MissingTypeRegistration(component_name.clone())
}
})?
```
## Solution
- Introduces a `is_ambiguous()` method.
- Also drive-by fixes two documentation comments that had broken links.
---
## Changelog
- Added a `TypeRegistry::is_ambiguous()` method, for checking whether a
given short type path is ambiguous (e.g. `MyType` potentially matching
either `some_crate::MyType` or `another_crate::MyType`)
---------
Co-authored-by: François <mockersf@gmail.com>
# Objective
- On some devices, UI buttons are not responsive
## Solution
- On device with a slower frame rate, touch event can start and end in
the frame rate
- When looking for a touch position, also look into the `just_pressed`
touches that are not cleared by the end event but only at the end of the
frame
Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
# Objective
Implement Debug trait for SpriteBundle and SpriteSheetBundle
It's helpful and other basic bundles like TransformBundle and
VisibilityBundle already implement this trait
# Objective
There's a repeating pattern of `ThreadLocal<Cell<Vec<T>>>` which is very
useful for low overhead, low contention multithreaded queues that have
cropped up in a few places in the engine. This pattern is surprisingly
useful when building deferred mutation across multiple threads, as noted
by it's use in `ParallelCommands`.
However, `ThreadLocal<Cell<Vec<T>>>` is not only a mouthful, it's also
hard to ensure the thread-local queue is replaced after it's been
temporarily removed from the `Cell`.
## Solution
Wrap the pattern into `bevy_utils::Parallel<T>` which codifies the
entire pattern and ensures the user follows the contract. Instead of
fetching indivdual cells, removing the value, mutating it, and replacing
it, `Parallel::get` returns a `ParRef<'a, T>` which contains the
temporarily removed value and a reference back to the cell, and will
write the mutated value back to the cell upon being dropped.
I would like to use this to simplify the remaining part of #4899 that
has not been adopted/merged.
---
## Changelog
TODO
---------
Co-authored-by: Joseph <21144246+JoJoJet@users.noreply.github.com>
# Objective
Bevy's animation system currently does tree traversals based on `Name`
that aren't necessary. Not only do they require in unsafe code because
tree traversals are awkward with parallelism, but they are also somewhat
slow, brittle, and complex, which manifested itself as way too many
queries in #11670.
# Solution
Divide animation into two phases: animation *advancement* and animation
*evaluation*, which run after one another. *Advancement* operates on the
`AnimationPlayer` and sets the current animation time to match the game
time. *Evaluation* operates on all animation bones in the scene in
parallel and sets the transforms and/or morph weights based on the time
and the clip.
To do this, we introduce a new component, `AnimationTarget`, which the
asset loader places on every bone. It contains the ID of the entity
containing the `AnimationPlayer`, as well as a UUID that identifies
which bone in the animation the target corresponds to. In the case of
glTF, the UUID is derived from the full path name to the bone. The rule
that `AnimationTarget`s are descendants of the entity containing
`AnimationPlayer` is now just a convention, not a requirement; this
allows us to eliminate the unsafe code.
# Migration guide
* `AnimationClip` now uses UUIDs instead of hierarchical paths based on
the `Name` component to refer to bones. This has several consequences:
- A new component, `AnimationTarget`, should be placed on each bone that
you wish to animate, in order to specify its UUID and the associated
`AnimationPlayer`. The glTF loader automatically creates these
components as necessary, so most uses of glTF rigs shouldn't need to
change.
- Moving a bone around the tree, or renaming it, no longer prevents an
`AnimationPlayer` from affecting it.
- Dynamically changing the `AnimationPlayer` component will likely
require manual updating of the `AnimationTarget` components.
* Entities with `AnimationPlayer` components may now possess descendants
that also have `AnimationPlayer` components. They may not, however,
animate the same bones.
* As they aren't specific to `TypeId`s,
`bevy_reflect::utility::NoOpTypeIdHash` and
`bevy_reflect::utility::NoOpTypeIdHasher` have been renamed to
`bevy_reflect::utility::NoOpHash` and
`bevy_reflect::utility::NoOpHasher` respectively.
# Objective
- having different field names for `Camera2dBundle` and `Camera3dBundle`
implies that there is something different between these fields when
there is not
## Solution
- rename the field in `Camera3dBundle` to align with `Camera2dBundle`
## Migration Guide
- use the new `deband_dither` field name with `Camera3dBundle`, rather
than the old field name, `dither`
# Objective
Do #11829, but without breaking CI.
## Solution
Update to `toml_edit` v0.22, replace the deprecated function with the
the newer equivalent.
# Objective
Fixes#11964.
## Solution
Adds the `serde` feature to `bitflags` for `bevy_render`. This makes
`bevy_render` compile correctly when used alone.
---
## Changelog
- Fixed an issue where depending on `bevy_render` alone would fail to
compile.
# Objective
Improve code quality and performance
## Solution
Instead of using `plugin.downcast_ref::<T>().is_some()` in
`App::is_plugin_added`, use `plugin.is::<T>()`. Which is more performant
and cleaner.
# Objective
- Fixes#11960
- The compilation of `bevy_core_pipeline` failed with the `dds` feature
enabled
## Solution
- Enable the `dds` feature of `bevy_render` when enabling it for
`bevy_core_pipeline`
# Objective
`update_archetype_component_access` was removed from queries in #9774,
but some documentation still refers to it.
## Solution
Update the documentation. Since a bunch of these were in SAFETY comments
it would be nice if someone who knows the details better could check
that the rest of those comments are still valid.
# Objective
Right now, if you call `embedded_asset` with 2 arguments as a qualified
path it doesn't work (`bevy::asset::embedded_asset!(app, "foo.wgsl")` ->
"cannot find macro `embedded_asset` in this scope")
## Solution
Use `$crate::` in expansion for 2-arg case.
# Objective
- I hated having to do `Cuboid::new(1.0, 1.0, 1.0)` or
`Cuboid::from_size(Vec3::splat(1.0))` when there should be a much easier
way to do this.
## Solution
- Implemented a `from_length()` method that only takes in a single
float, and constructs a primitive of equal size in all directions.
- Ex:
```rs
// These:
Cuboid::new(1.0, 1.0, 1.0);
Cuboid::from_size(Vec3::splat(1.0));
// Are equivalent to this:
Cuboid::from_length(1.0);
```
- For the rest of the changed primitives:
```rs
Rectangle::from_length(1.0);
Plane3d::default().mesh().from_length(1.0);
```
# Objective
Another PR failed CI due to duplicate deps, and I noticed this one in
particular while scanning through the error messages.
I think this was missed in #11082.
## Solution
Bump `encase_derive_impl` dep in `bevy_encase_derive` to same version as
`encase` dep for `bevy_render`.
I spot-checked a few examples, and glanced at the
[changelog](<https://github.com/teoxoy/encase/blob/main/CHANGELOG.md#v070-2024-01-02>)
and I don't think there's anything to be concerned about, but I barely
know what this thing does.
# Objective
Fixes#11908
## Solution
- Remove the `naga_oil` dependency from `bevy_pbr`.
- We were doing a little dance to disable `glsl` support on not-wasm, so
incorporate that dance into `bevy_render`'s `Cargo.toml`.
They cause the number of texture bindings to overflow on those
platforms. Ultimately, we shouldn't unconditionally disable them, but
this fixes a crash blocking 0.13.
Closes#11885.
I did this during the prepass, but I neglected to do it during the
shadow map pass, causing a panic when directional lights with shadows
were enabled with lightmapped meshes present. This patch fixes the
issue.
Closes#11898.
# Objective
- Being able to build for WebGPU
```
error[E0061]: this function takes 1 argument but 3 arguments were supplied
--> .cargo/registry/src/index.crates.io-6f17d22bba15001f/wgpu-0.19.1/src/backend/webgpu.rs:375:22
|
375 | let mut mapped = web_sys::GpuDepthStencilState::new(
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
376 | map_compare_function(desc.depth_compare),
| ---------------------------------------- unexpected argument of type `GpuCompareFunction`
377 | desc.depth_write_enabled,
| ------------------------ unexpected argument of type `bool`
|
note: associated function defined here
--> .cargo/registry/src/index.crates.io-6f17d22bba15001f/web-sys-0.3.68/src/features/gen_GpuDepthStencilState.rs:27:12
|
27 | pub fn new(format: GpuTextureFormat) -> Self {
| ^^^
help: remove the extra arguments
|
376 - map_compare_function(desc.depth_compare),
376 + map_texture_format(desc.format),
|
error[E0061]: this function takes 1 argument but 2 arguments were supplied
--> .cargo/registry/src/index.crates.io-6f17d22bba15001f/wgpu-0.19.1/src/backend/webgpu.rs:1693:13
|
1693 | web_sys::GpuVertexState::new(desc.vertex.entry_point, &module.0);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -------------------------
| |
| unexpected argument of type `&str`
| help: remove the extra argument
|
note: associated function defined here
--> .cargo/registry/src/index.crates.io-6f17d22bba15001f/web-sys-0.3.68/src/features/gen_GpuVertexState.rs:27:12
|
27 | pub fn new(module: &GpuShaderModule) -> Self {
| ^^^
error[E0061]: this function takes 2 arguments but 3 arguments were supplied
--> .cargo/registry/src/index.crates.io-6f17d22bba15001f/wgpu-0.19.1/src/backend/webgpu.rs:1768:17
|
1768 | web_sys::GpuFragmentState::new(frag.entry_point, &module.0, &targets);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ---------------- -------- unexpected argument of type `&js_sys::Array`
| |
| expected `&GpuShaderModule`, found `&str`
|
= note: expected reference `&GpuShaderModule`
found reference `&str`
note: associated function defined here
--> .cargo/registry/src/index.crates.io-6f17d22bba15001f/web-sys-0.3.68/src/features/gen_GpuFragmentState.rs:27:12
|
27 | pub fn new(module: &GpuShaderModule, targets: &::wasm_bindgen::JsValue) -> Self {
| ^^^
help: remove the extra argument
|
1768 - web_sys::GpuFragmentState::new(frag.entry_point, &module.0, &targets);
1768 + web_sys::GpuFragmentState::new(/* &GpuShaderModule */, &module.0);
|
error[E0061]: this function takes 1 argument but 2 arguments were supplied
--> .cargo/registry/src/index.crates.io-6f17d22bba15001f/wgpu-0.19.1/src/backend/webgpu.rs:1793:13
|
1793 | web_sys::GpuProgrammableStage::new(desc.entry_point, &shader_module.0);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ------------------
| |
| unexpected argument of type `&str`
| help: remove the extra argument
|
note: associated function defined here
--> .cargo/registry/src/index.crates.io-6f17d22bba15001f/web-sys-0.3.68/src/features/gen_GpuProgrammableStage.rs:27:12
|
27 | pub fn new(module: &GpuShaderModule) -> Self {
| ^^^
error[E0599]: no method named `write_timestamp` found for struct `GpuCommandEncoder` in the current scope
--> .cargo/registry/src/index.crates.io-6f17d22bba15001f/wgpu-0.19.1/src/backend/webgpu.rs:2505:14
|
2503 | / encoder_data
2504 | | .0
2505 | | .write_timestamp(&query_set_data.0, query_index);
| | -^^^^^^^^^^^^^^^ method not found in `GpuCommandEncoder`
| |_____________|
|
Some errors have detailed explanations: E0061, E0599.
For more information about an error, try `rustc --explain E0061`.
```
## Solution
- `web-sys` doesn't follow semver for the WebGPU APIs as they are
unstable. Force using a compatible version
---------
Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
# Objective
When registering and preregistering asset loaders, there would be a
`warn!` if multiple asset loaders use a given extension, and an `info!`
if multiple asset loaders load the same asset type. Since both of these
situations are individually fine, it was decided that these messages
should be removed.
## Solution
Replace both of these messages with a new `warn!` that notes that if
multiple asset loaders share the same asset type _and_ share extensions,
that the loader must be specified in the `.meta` file for those assets
in order to solve the ambiguity. This is a more useful message, since it
notes when a user must take special action / consideration.
# Objective
Fixes#11846
## Solution
Add a `synchronous_pipeline_compilation ` field to `RenderPlugin`,
defaulting to `false`.
Most of the diff is whitespace.
## Changelog
Added `synchronous_pipeline_compilation ` to `RenderPlugin` for
disabling async pipeline creation.
## Migration Guide
TODO: consider combining this with the guide for #11846
`RenderPlugin` has a new `synchronous_pipeline_compilation ` property.
The default value is `false`. Set this to `true` if you want to retain
the previous synchronous behavior.
---------
Co-authored-by: JMS55 <47158642+JMS55@users.noreply.github.com>
Co-authored-by: François <mockersf@gmail.com>
This represents when the user has configured `ClearColorConfig::None` in
their application. If the clear color is `None`, we will always `Load`
instead of attempting to clear the attachment on the first call.
Fixes#11883.