Commit Graph

8712 Commits

Author SHA1 Message Date
person93
f3323f8b14 Add accessors to DynamicEnum for the DynamicVariant (#18693)
# Objective

- Closes https://github.com/bevyengine/bevy/issues/18692

## Solution

Add the methods as described
```rust
impl DynamicEnum {
    fn variant(&self) -> &DynamicVariant;
    fn variant_mut(&mut self) -> &mut DynamicVariant;
}
```
2025-04-09 00:21:40 +02:00
Greeble
76318d99d7 Fix motion blur on skinned meshes (#18712)
## Objective

Fix motion blur not working on skinned meshes.

## Solution

`set_mesh_motion_vector_flags` can set
`RenderMeshInstanceFlags::HAS_PREVIOUS_SKIN` after specialization has
already cached the material. This can lead to
`MeshPipelineKey::HAS_PREVIOUS_SKIN` never getting set, disabling motion
blur.

The fix is to make sure `set_mesh_motion_vector_flags` happens before
specialization.

Note that the bug is fixed in a different way by #18074, which includes
other fixes but is a much larger change.

## Testing

Open the `animated_mesh` example and add these components to the
`Camera3d` entity:

```rust
MotionBlur {
    shutter_angle: 5.0,
    samples: 2,
    #[cfg(all(feature = "webgl2", target_arch = "wasm32", not(feature = "webgpu")))]
    _webgl2_padding: Default::default(),
},
#[cfg(all(feature = "webgl2", target_arch = "wasm32", not(feature = "webgpu")))]
Msaa::Off,
```

Tested on `animated_mesh`, `many_foxes`, `custom_skinned_mesh`,
Win10/Nvidia with Vulkan, WebGL/Chrome, WebGPU/Chrome. Note that testing
`many_foxes` WebGL requires #18715.
2025-04-05 01:08:55 +02:00
Lucas Franca
ded663b9b9 Add PartialEq and Hash reflections for AnimationNodeIndex (#18718)
# Objective

Fixes #18701

## Solution

Add reflection of `PartialEq` and `Hash` to `AnimationNodeIndex`

## Testing

Added a new `#[test]` with the minimal reproduction posted on #18701.
2025-04-04 23:16:49 +02:00
BD103
0b3a51bd7e Add #[deprecated(since = "0.16.0", ...)] to items missing it (#18702)
- The `#[deprecated]` attributes supports a `since` field, which
documents in which version an item was deprecated. This field is visible
in `rustdoc`.
- We inconsistently use `since` throughout the project.

For an example of what `since` renders as, take a look at
`ChildOf::get()`:

```rust
/// The parent entity of this child entity.
pub fn get(&self) -> Entity {
    self.0
}
```

![image](https://github.com/user-attachments/assets/2ea5d8c9-2eab-430a-9a1c-421f315ff123)

- Add `since = "0.16.0"` to all `#[deprecated]` attributes that do not
already use it.
- Add an example of deprecating a struct with the `since` field in the
migration guide document.

I would appreciate if this could be included in 0.16's release, as its a
low-risk documentation improvement that is valuable for the release, but
I'd understand if this was cut.

You can use `cargo doc` to inspect the rendered form of
`#[deprecated(since = "0.16.0", ...)]`.
2025-04-03 21:46:46 +02:00
Vic
c9fb956058 use entity set collections type aliases instead of defaults (#18695)
# Objective

Newest installment of the #16547 series.

In #18319 we introduced `Entity` defaults to accomodate the most common
use case for these types, however that resulted in the switch of the `T`
and `N` generics of `UniqueEntityArray`.
Swapping generics might be somewhat acceptable for `UniqueEntityArray`,
it is not at all acceptable for map and set types, which we would make
generic over `T: EntityEquivalent` in #18408.

Leaving these defaults in place would result in a glaring inconsistency
between these set collections and the others.

Additionally, the current standard in the engine is for "entity" to mean
`Entity`. APIs could be changed to accept `EntityEquivalent`, however
that is a separate and contentious discussion.

## Solution

Name these set collections `UniqueEntityEquivalent*`, and retain the
`UniqueEntity*` name for an alias of the `Entity` case.
While more verbose, this allows for all generics to be in proper order,
full consistency between all set types*, and the "entity" name to be
restricted to `Entity`.
On top of that, `UniqueEntity*` now always have 1 generic less, when
previously this was not enforced for the default case.

*`UniqueEntityIter<I: Iterator<T: EntityEquivalent>>` is the sole
exception to this. Aliases are unable to enforce bounds
(`lazy_type_alias` is needed for this), so for this type, doing this
split would be a mere suggestion, and in no way enforced.
Iterator types are rarely ever named, and this specific one is intended
to be aliased when it sees more use, like we do for the corresponding
set collection iterators.
Furthermore, the `EntityEquivalent` precursor `Borrow<Entity>` was used
exactly because of such iterator bounds!
Because of that, we leave it as is.

While no migration guide for 0.15 users, for those that upgrade from
main:
`UniqueEntityVec<T>` -> `UniqueEntityEquivalentVec<T>`
`UniqueEntitySlice<T>` -> `UniqueEntityEquivalentSlice<T>`
`UniqueEntityArray<N, T>` -> `UniqueEntityEquivalentArray<T, N>`
2025-04-03 21:45:44 +02:00
Periwink
2771803cbd add reflect for SocketAddr (#18676) 2025-04-03 21:45:43 +02:00
Chris Russell
ed28b5ccf7 Improve error message for missing events (#18683)
# Objective

Improve the parameter validation error message for
`Event(Reader|Writer|Mutator)`.

System parameters defined using `#[derive(SystemParam)]`, including the
parameters for events, currently propagate the validation errors from
their subparameters. The error includes the type of the failing
parameter, so the resulting error includes the type of the failing
subparameter instead of the derived parameter.

In particular, `EventReader<T>` will report an error from a
`Res<Events<T>>`, even though the user has no parameter of that type!

This is a follow-up to #18593.

## Solution

Have `#[derive]`d system parameters map errors during propagation so
that they report the outer parameter type.

To continue to provide context, add a field to
`SystemParamValidationError` that identifies the subparameter by name,
and is empty for non-`#[derive]`d parameters.

Allow them to override the failure message for individual parameters.
Use this to convert "Resource does not exist" to "Event not initialized"
for `Event(Reader|Writer|Mutator)`.

## Showcase

The validation error for a `EventReader<SomeEvent>` parameter when
`add_event` has not been called changes from:

Before: 
```
Parameter `Res<Events<SomeEvent>>` failed validation: Resource does not exist
```

After
```
Parameter `EventReader<SomeEvent>::events` failed validation: Event not initialized
```
2025-04-03 21:45:43 +02:00
BD103
4b5df0f1ab Fix indentation of bevy/query strict parameter in docs (#18681)
# Objective

- The `strict` field of
[`BrpQueryParams`](https://dev-docs.bevyengine.org/bevy/remote/builtin_methods/struct.BrpQueryParams.html)
was newly added as part of 0.16.
- Its documentation in `lib.rs` improperly indents `strict`, making look
like its part of
[`BrpQueryFilter`](https://dev-docs.bevyengine.org/bevy/remote/builtin_methods/struct.BrpQueryFilter.html):


![image](https://github.com/user-attachments/assets/f49521da-36d3-4d5d-a7ea-f7a44ddaf195)

## Solution

- Fix `strict`'s indentation so its clear that it is a field of
`BrpQueryParams`, not `BrpQueryFilter`.

I would like this to be included in 0.16, since it's a trivial
documentation change that fixes an error, but if it needs to be removed
from the milestone that's fine.

## Testing

Run `cargo doc -p bevy_remote --no-deps` and verify the indentation is
fixed. :)
2025-04-03 21:45:43 +02:00
JaySpruce
deba691fff Implement insert_children for EntityCommands (#18675)
Extension of #18409.

I was updating a migration guide for hierarchy commands and realized
`insert_children` wasn't added to `EntityCommands`, only
`EntityWorldMut`.

This adds that and `insert_related` (basically just some
copy-and-pasting).
2025-04-03 21:45:43 +02:00
Kristoffer Søholm
d5d799cbb6 Fix issues in log_diagnostics example (#18652)
# Objective

Adopts / builds on top of #18435.

The `log_diagnostics` example has bit-rotted and accumulated multiple
issues:
- It didn't explain the ordering constraint on DefaultPlugins, as noted
by the original PR
- Apparently `AssetCountDiagnosticsPlugin` no longer exists (?!). I
couldn't figure out when or why it was removed, maybe it got missed in
Assets v2?
- The comments didn't explain what kind of info you get by the various
plugins, making you do work to figure it out
- ~As far as I can tell `RenderDiagnosticsPlugin` currently doesn't
register any diagnostics in the traditional sense, but is only focused
on rendering spans? At least it doesn't print anything extra when added
for me, so having it here is misleading.~ It didn't print anything
because there was nothing to render in this example

## Solution

- Make all plugins be commented in to prevent further bit-rot
- Remove reference to the missing plugin
- Add extra comments describing the diagnostics in more detail
- Add something to render so we get render diagnostics

## Testing

Run the example, see relevant diagnostics printed out
2025-04-03 21:45:43 +02:00
Carter Anderson
1553ee98ff Switch ChildOf back to tuple struct (#18672)
# Objective

In #17905 we swapped to a named field on `ChildOf` to help resolve
variable naming ambiguity of child vs parent (ex: `child_of.parent`
clearly reads as "I am accessing the parent of the child_of
relationship", whereas `child_of.0` is less clear).

Unfortunately this has the side effect of making initialization less
ideal. `ChildOf { parent }` reads just as well as `ChildOf(parent)`, but
`ChildOf { parent: root }` doesn't read nearly as well as
`ChildOf(root)`.

## Solution

Move back to `ChildOf(pub Entity)` but add a `child_of.parent()`
function and use it for all accesses. The downside here is that users
are no longer "forced" to access the parent field with `parent`
nomenclature, but I think this strikes the right balance.

Take a look at the diff. I think the results provide strong evidence for
this change. Initialization has the benefit of reading much better _and_
of taking up significantly less space, as many lines go from 3 to 1, and
we're cutting out a bunch of syntax in some cases.

Sadly I do think this should land in 0.16 as the cost of doing this
_after_ the relationships migration is high.
2025-04-03 21:45:43 +02:00
JaySpruce
5cbc20f787 Update relationship commands to use EntityCommands instead of Commands (#18667)
These should use `EntityCommands` so that the entity existence check is
hooked up to the default error handler, rather than only panicking.
2025-04-03 21:45:43 +02:00
ickshonpe
8be04958c1 Remove the visited local system param from update_ui_context_system. (#18664)
# Objective

The `visited: Local<HashSet<Entity>>` system param is meant to track
which entities `update_contexts_recursively` has visited and updated but
when the reparent_nodes_query isn't ordered descending from parent to
child nodes can get marked as visited even though their camera target is
unset and if the camera target is unset then the node won't be rendered.

Fixes #18616

## Solution

Remove the `visited` system param from `update_ui_context_system` and
the associated visited check from `update_contexts_recursively`. It was
redundant anyway since the set_if_neq check is sufficient to track
already updated nodes.

## Testing

The example from #18616 can be used for testing.
2025-04-03 21:45:42 +02:00
Chris Russell
9d4d110704 Include SystemParamValidationError in RunSystemError and RegisteredSystemError (#18666)
# Objective

Provide more useful errors when `World::run_system` and related methods
fail parameter validation.

Let callers determine whether the validation failure would have skipped
or failed the system.

Follow-up to #18541.

## Solution

Add a `SystemParamValidationError` value to the
`RunSystemError::InvalidParams` and
`RegisteredSystemError::InvalidParams` variants. That includes the
complete context of the parameter validation error, including the
`skipped` flag.
2025-04-03 21:45:42 +02:00
JaySpruce
4ad5f464ea Add notes to fallible commands (#18649)
Follow-up to #18639.

Fallible commands should have notes explaining how they can fail, what
error they return, and how it's handled.
2025-04-03 21:45:42 +02:00
Eagster
11ad3b6dde Finish #17558, re-adding insert_children (#18409)
fixes #17478

# Objective

- Complete #17558.
- the `insert_children` method was previously removed, and as #17478
points out, needs to be added back.

## Solution

- Add a `OrderedRelationshipSourceCollection`, which allows sorting,
ordering, rearranging, etc of a `RelationshipSourceCollection`.
- Implement `insert_related`
- Implement `insert_children`
- Tidy up some docs while I'm here.

## Testing

@bjoernp116 set up a unit test, and I added a doc test to
`OrderedRelationshipSourceCollection`.

---------

Co-authored-by: bjoernp116 <bjoernpollen@gmail.com>
Co-authored-by: Dmytro Banin <banind@cs.washington.edu>
Co-authored-by: Talin <viridia@gmail.com>
2025-04-03 21:45:42 +02:00
Eagster
202faf6a1c Get names of queued components (#18451)
# Objective

#18173 allows components to be queued without being fully registered.
But much of bevy's debug logging contained
`components.get_name(id).unwrap()`. However, this panics when the id is
queued. This PR fixes this, allowing names to be retrieved for debugging
purposes, etc, even while they're still queued.

## Solution

We change `ComponentInfo::descriptor` to be `Arc<ComponentDescriptor>`
instead of not arc'd. This lets us pass the descriptor around (as a name
or otherwise) as needed. The alternative would require some form of
`MappedRwLockReadGuard`, which is unstable, and would be terribly
blocking. Putting it in an arc also signifies that it doesn't change,
which is a nice signal to users. This does mean there's an extra pointer
dereference, but I don't think that's an issue here, as almost all paths
that use this are for debugging purposes or one-time set ups.

## Testing

Existing tests.

## Migration Guide

`Components::get_name` now returns `Option<Cow<'_, str>` instead of
`Option<&str>`. This is because it now returns results for queued
components. If that behavior is not desired, or you know the component
is not queued, you can use
`components.get_info().map(ComponentInfo::name)` instead.

Similarly, `ScheduleGraph::conflicts_to_string` now returns `impl
Iterator<Item = (String, String, Vec<Cow<str>>)>` instead of `impl
Iterator<Item = (String, String, Vec<&str>)>`. Because `Cow<str>` derefs
to `&str`, most use cases can remain unchanged.

---------

Co-authored-by: Chris Russell <8494645+chescock@users.noreply.github.com>
2025-04-03 21:45:42 +02:00
Zachary Harrold
7925e03f7f Add sleep based on spin to bevy_platform_support (#18633)
# Objective

- Fixes #18617

## Solution

- Added `thread::sleep` to `bevy_platform_support` using a spin-based
fallback.
- Fixed bug in `bevy_platform_support::time::Instant::elapsed`
(comparison was backwards)
- Switched `ScheduleRunnerPlugin` to use
`bevy_platform_support:🧵:sleep` on `std` and `no_std` platforms
(WASM + Browser excluded)

## Testing

- Ran reproduction code from @mockersf in linked issue and confirmed a
consistent 60 counts per `println!`.

---

## Notes

- I chose to add `bevy_platform_support:🧵:sleep` instead of
putting the fix in-line within `ScheduleRunnerPlugin` to keep the
separation of concerns clean. `sleep` is only used in one other location
in Bevy, `bevy_asset`, but I have decided to leave that as-is since
`bevy_asset` isn't `no_std` compatible anyway.
- The bug in `bevy_platform_support::time::Instant::elapsed` wasn't the
cause of this issue, but it did prevent this fix from working so I have
included the it in this PR.
2025-04-03 21:45:42 +02:00
François Mockers
bdfd7a3443 Release 0.16.0-rc.3 2025-03-31 23:07:43 +02:00
JaySpruce
735c43390c bevy_ecs/system/commands/ folder docs pass (#18639)
- Lots of nits, formatting, and rephrasing, with the goal of making
things more consistent.
- Fix outdated error handler explanation in `Commands` and
`EntityCommands` docs.
- Expand docs for system-related commands.
- Remove panic notes if the command only panics with the default error
handler.
- Update error handling notes for `try_` variants.
- Hide `prelude` import in most doctest examples, unless the example
uses something that people might not realize is in the prelude (like
`Name`).
- Remove a couple doctest examples that (in my opinion) didn't make
sense.

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
Co-authored-by: Chris Russell <8494645+chescock@users.noreply.github.com>
2025-03-31 22:36:30 +02:00
charlotte
831c57d8b1 Fix no indirect drawing (#18628)
# Objective

The `NoIndirectDrawing` wasn't working and was causing the scene not to
be rendered.

## Solution

Check the configured preprocessing mode when adding new batch sets and
mark them as batchable instead of muli-drawable if indirect rendering
has been disabled.

## Testing

`cargo run --example many_cubes -- --no-indirect-drawing`
2025-03-31 22:36:30 +02:00
Zachary Harrold
a2b14983f4 Upgrade to Glam 0.29.3 and Simplify Feature Gating (#18638)
- Fixes #18397
- Supersedes #18474
- Simplifies 0.16 migration

- Upgrade to Glam 0.29.3, which has backported the `nostd-libm` feature.
- Expose a similar feature in `bevy_math` and enable it in
`bevy_internal`, allowing `bevy_math`, `bevy_input`, and
`bevy_transform` to be unconditional dependencies again.

- CI

---

- This includes `libm` as a dependency, but this was already the case in
the common scenario where `rand` or many other features were enabled.
Considering `libm` is an official Rust crate, it's a very low-risk
dependency to unconditionally include.
- For users who do not want `libm` included, simply import Bevy's
subcrates directly, since `bevy_math/nostd-libm` will not be enabled.
- I know we are _very_ late in the RC cycle for 0.16, but this has a
substantial impact on the usability of `bevy` that I consider worth
including.
2025-03-31 22:36:16 +02:00
Beni Bachmann
10daca0947 Return triangle index instead of vertex index (Fixes #18081) (#18647)
# Objective

- Fixes #18081
- Enable use-cases like getting UVs or texture colors for the hit point
(which are currently not possible due to this bug).

## Solution

- Return the triangle index instead of the first vertex index of the
triangle.

## Testing

Tested successfully with my project which does a raycast to get the UV
coordinates of the hit. My code:
```rust
fn get_uv(
    mesh: &Mesh,
    attribute: &MeshVertexAttribute,
    hit: &RayMeshHit,
    _gizmos: &mut Gizmos,
) -> Result<Vec2> {
    let (a, b, c) = get_indices(mesh, hit)?;

    let attrs = mesh
        .attribute(*attribute)
        .ok_or_eyre(format!("Attribute {:?} not found", &attribute))?;
    let all_uvs: &Vec<[f32; 2]> = match &attrs {
        VertexAttributeValues::Float32x2(positions) => positions,
        _ => bail!("Unexpected types in {:?}", Mesh::ATTRIBUTE_UV_0),
    };

    let bary = hit.barycentric_coords;

    Ok(Vec2::from_array(all_uvs[a]) * bary.x
        + Vec2::from_array(all_uvs[b]) * bary.y
        + Vec2::from_array(all_uvs[c]) * bary.z)
}

fn get_indices(mesh: &Mesh, hit: &RayMeshHit) -> Result<(usize, usize, usize)> {
    let i = hit
        .triangle_index
        .ok_or_eyre("Intersection Index not found")?;

    Ok(mesh.indices().map_or_else(
        || (i, i + 1, i + 2),
        |indices| match indices {
            Indices::U16(indices) => (
                indices[i * 3] as usize,
                indices[i * 3 + 1] as usize,
                indices[i * 3 + 2] as usize,
            ),
            Indices::U32(indices) => (
                indices[i * 3] as usize,
                indices[i * 3 + 1] as usize,
                indices[i * 3 + 2] as usize,
            ),
        },
    ))
}
```

PS: created a new PR because the old one was coming from and targeting
the wrong branches
2025-03-31 22:33:28 +02:00
Lucas Franca
eb37e86a1f Make bindings behind pbr_specular_textures flag consistent with other gated fields (#18645)
# Objective

Make all feature gated bindings consistent with each other

## Solution

Make the bindings of fields gated by `pbr_specular_textures` feature
consistent with the other gated bindings
2025-03-31 22:33:28 +02:00
HugoPeters1024
3e7c6a6e9e 0.16 Regression fix: re-expose the display handle via a wrapper resource (#18644)
# Objective

- In the latest released version (15.3) I am able to obtain this
information by getting the actual `EventLoop` via `non_send_resource`.
Now that this object has (probably rightfully so) been replaced by the
`EventLoopProxy`, I can no longer maintain my custom render backend:
https://github.com/HugoPeters1024/bevy_vulkan. I also need the display
handle for a custom winit integration, for which I've made patches to
bevy before: XREF: https://github.com/bevyengine/bevy/pull/15884


## Solution

- Luckily, all that is required is exposing the `OwnedDisplayHandle` in
its own wrapper resource.

## Testing

- Aforementioned custom rendering backend works on this commit.

---------

Co-authored-by: HugoPeters1024 <hugopeters1024@gmail.com>
2025-03-31 22:33:28 +02:00
andriyDev
4fc4fa4559 Delete unused weak handle and remove duplicate loads. (#18635)
# Objective

- Cleanup

## Solution

- Remove completely unused weak_handle
(`MESH_PREPROCESS_TYPES_SHADER_HANDLE`). This value is not used
directly, and is never populated.
- Delete multiple loads of `BUILD_INDIRECT_PARAMS_SHADER_HANDLE`. We
load it three times right after one another. This looks to be a
copy-paste error.

## Testing

- None.
2025-03-31 22:33:28 +02:00
Aevyrie
cba6698033 Parallelize bevy 0.16-rc bottlenecks (#18632)
# Objective

- Found stuttering and performance degradation while updating big_space
stress tests.

## Solution

- Identify and fix slow spots using tracy. Patch to verify fixes.

## Testing

- Tracy
- Before: 

![image](https://github.com/user-attachments/assets/ab7f440d-88c1-4ad9-9ad9-dca127c9421f)
- prev_gt parallelization and mutating instead of component insertion: 

![image](https://github.com/user-attachments/assets/9279a663-c0ba-4529-b709-d0f81f2a1d8b)
- parallelize visibility ranges and mesh specialization

![image](https://github.com/user-attachments/assets/25b70e7c-5d30-48ab-9bb2-79211d4d672f)

---------

Co-authored-by: Zachary Harrold <zac@harrold.com.au>
2025-03-31 22:33:28 +02:00
Chris Russell
d5c5de20b1 Use Display instead of Debug in the default error handler (#18629)
# Objective

Improve error messages for missing resources.  

The default error handler currently prints the `Debug` representation of
the error type instead of `Display`. Most error types use
`#[derive(Debug)]`, resulting in a dump of the structure, but will have
a user-friendly message for `Display`.

Follow-up to #18593

## Solution

Change the default error handler to use `Display` instead of `Debug`.  

Change `BevyError` to include the backtrace in the `Display` format in
addition to `Debug` so that it is still included.

## Showcase

Before: 

```
Encountered an error in system `system_name`: SystemParamValidationError { skipped: false, message: "Resource does not exist", param: "bevy_ecs::change_detection::Res<app_name::ResourceType>" }

Encountered an error in system `other_system_name`: "String message with\nmultiple lines."
```

After

```
Encountered an error in system `system_name`: Parameter `Res<ResourceType>` failed validation: Resource does not exist

Encountered an error in system `other_system_name`: String message with
multiple lines.
```
2025-03-31 22:33:28 +02:00
Robin KAY
d5d57bbd26 Expose symbols needed to replicate SetMeshBindGroup in ecosystem crates. (#18613)
# Objective

My ecosystem crate, bevy_mod_outline, currently uses `SetMeshBindGroup`
as part of its custom rendering pipeline. I would like to allow for
possibility that, due to changes in 0.16, I need to customise the
behaviour of `SetMeshBindGroup` in order to make it work. However, not
all of the symbol needed to implement this render command are public
outside of Bevy.

## Solution

- Include `MorphIndices` in re-export list. I feel this is morally
equivalent to `SkinUniforms` already being exported.
- Change `MorphIndex::index` field to be public. I feel this is morally
equivalent to the `SkinByteOffset::byte_offset` field already being
public.
- Change `RenderMeshIntances::mesh_asset_id()` to be public (although
since all the fields of `RenderMeshInstances` are public it's possible
to work around this one by reimplementing).

These changes exclude:
- Making any change to the `RenderLightmaps` type as I don't need to
bind the light-maps for my use-case and I wanted to keep these changes
minimal. It has a private field which would need to be public or have
access methods.
- The changes already included in #18612.

## Testing

Confirmed that a copy of `SetMeshBindGroup` can be compiled outside of
Bevy with these changes, provided that the light-map code is removed.

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
2025-03-31 22:33:28 +02:00
charlotte
754d1fa7ca Remove entities from specialization caches when despawned. (#18627)
# Objective

Fixes #17872 

## Solution

This should have basically no impact on static scenes. We can optimize
more later if anything comes up. Needing to iterate the two level bin is
a bit unfortunate but shouldn't matter for apps that use a single
camera.
2025-03-31 22:33:27 +02:00
BD103
4dcee649eb Improve Query's top-level documentation (#18622)
# Objective

- There's been several changes to `Query` for this release cycle, and
`Query`'s top-level documentation has gotten slightly out-of-date.
- Alternative to #18615.

## Solution

- Edit `Query`'s docs for consistency, clarity, and correctness.
- Make sure to group `get()` and `get_many()` together instead of
`single()` and `get_many()`, to enforce the distinction from
https://github.com/bevyengine/bevy/pull/18615#issuecomment-2764355672.
- Reformat doc tests so they would be readable if extracted into their
own file. (Which mainly involves adding more spacing.)
- Move link definitions to be nearer where they are used.
- Fix the tables so they are up-to-date and correctly escape square
brackets `\[ \]`.

## Testing

I ran `cargo doc -p bevy_ecs --no-deps` to view the docs and `cargo test
-p bevy_ecs --doc` to test the doc comments.

## Reviewing

The diff is difficult to read, so I don't recommend _just_ looking at
that. Instead, run `cargo doc -p bevy_ecs --no-deps` locally and read
through the new version. It should theoretically read smoother with less
super-technical jargon. :)

## Follow-up

I want to go through some of `Query`'s methods, such as `single()`,
`get()`, and `get_many()`, but I'll leave that for another PR.

---------

Co-authored-by: Chris Russell <8494645+chescock@users.noreply.github.com>
2025-03-31 22:33:27 +02:00
charlotte
3d1335aeed Use GpuPreprocessingMode::None if features not supported. (#18630)
# Objective

Fixes #18463 

## Solution

The features didn't seem to be getting checked for selecting
`GpuPreprocessingMode::None`.
2025-03-31 22:33:27 +02:00
charlotte
8edeb85f01 Fix mesh extraction for meshes without associated material. (#18631)
# Objective

Fixes #17986
Fixes #18608

## Solution

Guard against situations where an extracted mesh does not have an
associated material. The way that mesh is dependent on the material api
(although decoupled) here is a bit unfortunate and we might consider
ways in the future to support these material features without this
indirect dependency.
2025-03-31 22:33:27 +02:00
charlotte
4ddab0af39 Add required shader defs for environment map binding arrays in deferred (#18634)
# Objective

Fixes #18468

## Solution

Missing shader defs caused shader compilation failure.
2025-03-31 22:33:27 +02:00
charlotte
d9c62c043e Fix mesh tag feature for 2d. (#18636)
# Objective

Fixes #18564
2025-03-31 22:33:27 +02:00
charlotte
52e314c68d Fix AsBindGroup hygenic issues with storage texture. (#18640)
# Objective

Fixes #18573
2025-03-31 22:33:27 +02:00
charlotte
b9ee68a5bb Only send unused event when final handle is dropped. (#18641)
# Objective

Fixes #18457

## Solution

Move the Unused even after the check for existing strong handles.
2025-03-31 22:33:27 +02:00
François Mockers
3bc61a54be remove bevy_log as a dev-dependency from bevy_asset (#18619)
- the bevy workspace fails to publish
```
   Packaging bevy_asset v0.16.0-dev (/home/runner/work/bevy-releasability/bevy-releasability/crates/bevy_asset)
    Updating crates.io index
    Updating `kellnr` index
error: failed to prepare local package for uploading

Caused by:
  no matching package named `bevy_log` found
  location searched: `kellnr` index
  required by package `bevy_asset v0.16.0-dev (/home/runner/work/bevy-releasability/bevy-releasability/crates/bevy_asset)`
```
-
https://github.com/TheBevyFlock/bevy-releasability/actions/runs/14153238476/job/39649160443

- Remove bevy_log dev-dependency from bevy_asset
- Not sure of why this is a problem, but the dev-dependency is not
really needed so... 🤷
2025-03-31 22:33:24 +02:00
Vic
10da4dc9ae Rename EntityBorrow/TrustedEntityBorrow to ContainsEntity/EntityEquivalent (#18470)
# Objective

Fixes #9367.

Yet another follow-up to #16547.

These traits were initially based on `Borrow<Entity>` because that trait
was what they were replacing, and it felt close enough in meaning.
However, they ultimately don't quite match: `borrow` always returns
references, whereas `EntityBorrow` always returns a plain `Entity`.
Additionally, `EntityBorrow` can imply that we are borrowing an `Entity`
from the ECS, which is not what it does.

Due to its safety contract, `TrustedEntityBorrow` is important an
important and widely used trait for `EntitySet` functionality.
In contrast, the safe `EntityBorrow` does not see much use, because even
outside of `EntitySet`-related functionality, it is a better idea to
accept `TrustedEntityBorrow` over `EntityBorrow`.

Furthermore, as #9367 points out, abstracting over returning `Entity`
from pointers/structs that contain it can skip some ergonomic friction.

On top of that, there are aspects of #18319 and #18408 that are relevant
to naming:
We've run into the issue that relying on a type default can switch
generic order. This is livable in some contexts, but unacceptable in
others.

To remedy that, we'd need to switch to a type alias approach: 
The "defaulted" `Entity` case becomes a
`UniqueEntity*`/`Entity*Map`/`Entity*Set` alias, and the base type
receives a more general name. `TrustedEntityBorrow` does not mesh
clearly with sensible base type names.

## Solution
Replace any `EntityBorrow` bounds with `TrustedEntityBorrow`.
+
Rename them as such:
`EntityBorrow` -> `ContainsEntity`
`TrustedEntityBorrow` -> `EntityEquivalent`

For `EntityBorrow` we produce a change in meaning; We designate it for
types that aren't necessarily strict wrappers around `Entity` or some
pointer to `Entity`, but rather any of the myriad of types that contain
a single associated `Entity`.
This pattern can already be seen in the common `entity`/`id` methods
across the engine.
We do not mean for `ContainsEntity` to be a trait that abstracts input
API (like how `AsRef<T>` is often used, f.e.), because eliding
`entity()` would be too implicit in the general case.

We prefix "Contains" to match the intuition of a struct with an `Entity`
field, like some contain a `length` or `capacity`.
It gives the impression of structure, which avoids the implication of a
relationship to the `ECS`.
`HasEntity` f.e. could be interpreted as "a currently live entity", 

As an input trait for APIs like #9367 envisioned, `TrustedEntityBorrow`
is a better fit, because it *does* restrict itself to strict wrappers
and pointers. Which is why we replace any
`EntityBorrow`/`ContainsEntity` bounds with
`TrustedEntityBorrow`/`EntityEquivalent`.

Here, the name `EntityEquivalent` is a lot closer to its actual meaning,
which is "A type that is both equivalent to an `Entity`, and forms the
same total order when compared".
Prior art for this is the
[`Equivalent`](https://docs.rs/hashbrown/latest/hashbrown/trait.Equivalent.html)
trait in `hashbrown`, which utilizes both `Borrow` and `Eq` for its one
blanket impl!

Given that we lose the `Borrow` moniker, and `Equivalent` can carry
various meanings, we expand on the safety comment of `EntityEquivalent`
somewhat. That should help prevent the confusion we saw in
[#18408](https://github.com/bevyengine/bevy/pull/18408#issuecomment-2742094176).

The new name meshes a lot better with the type aliasing approach in
#18408, by aligning with the base name `EntityEquivalentHashMap`.
For a consistent scheme among all set types, we can use this scheme for
the `UniqueEntity*` wrapper types as well!
This allows us to undo the switched generic order that was introduced to
`UniqueEntityArray` by its `Entity` default.

Even without the type aliases, I think these renames are worth doing!

## Migration Guide

Any use of `EntityBorrow` becomes `ContainsEntity`.
Any use of `TrustedEntityBorrow` becomes `EntityEquivalent`.
2025-03-30 10:24:00 +02:00
Vic
8723096d57 reexport entity set collections in entity module (#18413)
# Objective

Unlike for their helper typers, the import paths for
`unique_array::UniqueEntityArray`, `unique_slice::UniqueEntitySlice`,
`unique_vec::UniqueEntityVec`, `hash_set::EntityHashSet`,
`hash_map::EntityHashMap`, `index_set::EntityIndexSet`,
`index_map::EntityIndexMap` are quite redundant.

When looking at the structure of `hashbrown`, we can also see that while
both `HashSet` and `HashMap` have their own modules, the main types
themselves are re-exported to the crate level.

## Solution

Re-export the types in their shared `entity` parent module, and simplify
the imports where they're used.
2025-03-30 10:24:00 +02:00
François Mockers
c946b9d827 bevy_image: derive TypePath when Reflect is not available (#18501)
- bevy_image fails to build without default features:
```
error[E0277]: `image::Image` does not implement `TypePath` so cannot provide static type path information
   --> crates/bevy_image/src/image.rs:341:12
    |
341 | pub struct Image {
    |            ^^^^^ the trait `bevy_reflect::type_path::TypePath` is not implemented for `image::Image`
    |
    = note: consider annotating `image::Image` with `#[derive(Reflect)]` or `#[derive(TypePath)]`
    = help: the following other types implement trait `bevy_reflect::type_path::TypePath`:
              &'static Location<'static>
              &'static T
              &'static mut T
              ()
              (P,)
              (P1, P0)
              (P1, P2, P0)
              (P1, P2, P3, P0)
            and 146 others
note: required by a bound in `Asset`
   --> /home/runner/work/bevy-releasability/bevy-releasability/crates/bevy_asset/src/lib.rs:415:43
    |
415 | pub trait Asset: VisitAssetDependencies + TypePath + Send + Sync + 'static {}
    |                                           ^^^^^^^^ required by this bound in `Asset`
    = note: `Asset` is a "sealed trait", because to implement it you also need to implement `bevy_reflect::type_path::TypePath`, which is not accessible; this is usually done to force you to use one of the provided types that already implement it
    = help: the following types implement the trait:
              bevy_asset::AssetIndex
              bevy_asset::LoadedUntypedAsset
              bevy_asset::AssetEvent<A>
              bevy_asset::LoadedFolder
              bevy_asset::StrongHandle
              bevy_asset::Handle<A>
              bevy_asset::AssetId<A>
              bevy_asset::AssetPath<'a>
            and 148 others

error[E0277]: `image::Image` does not implement `TypePath` so cannot provide static type path information
   --> crates/bevy_image/src/image_loader.rs:121:18
    |
121 |     type Asset = Image;
    |                  ^^^^^ the trait `bevy_reflect::type_path::TypePath` is not implemented for `image::Image`
    |
    = note: consider annotating `image::Image` with `#[derive(Reflect)]` or `#[derive(TypePath)]`
    = help: the following other types implement trait `bevy_reflect::type_path::TypePath`:
              &'static Location<'static>
              &'static T
              &'static mut T
              ()
              (P,)
              (P1, P0)
              (P1, P2, P0)
              (P1, P2, P3, P0)
            and 146 others
    = note: required for `<ImageLoader as AssetLoader>::Asset` to implement `Asset`
note: required by a bound in `bevy_asset::AssetLoader::Asset`
   --> /home/runner/work/bevy-releasability/bevy-releasability/crates/bevy_asset/src/loader.rs:33:17
    |
33  |     type Asset: Asset;
    |                 ^^^^^ required by this bound in `AssetLoader::Asset`

error[E0277]: `texture_atlas::TextureAtlasLayout` does not implement `TypePath` so cannot provide static type path information
   --> crates/bevy_image/src/texture_atlas.rs💯12
    |
100 | pub struct TextureAtlasLayout {
    |            ^^^^^^^^^^^^^^^^^^ the trait `bevy_reflect::type_path::TypePath` is not implemented for `texture_atlas::TextureAtlasLayout`
    |
    = note: consider annotating `texture_atlas::TextureAtlasLayout` with `#[derive(Reflect)]` or `#[derive(TypePath)]`
    = help: the following other types implement trait `bevy_reflect::type_path::TypePath`:
              &'static Location<'static>
              &'static T
              &'static mut T
              ()
              (P,)
              (P1, P0)
              (P1, P2, P0)
              (P1, P2, P3, P0)
            and 146 others
note: required by a bound in `Asset`
   --> /home/runner/work/bevy-releasability/bevy-releasability/crates/bevy_asset/src/lib.rs:415:43
    |
415 | pub trait Asset: VisitAssetDependencies + TypePath + Send + Sync + 'static {}
    |                                           ^^^^^^^^ required by this bound in `Asset`
    = note: `Asset` is a "sealed trait", because to implement it you also need to implement `bevy_reflect::type_path::TypePath`, which is not accessible; this is usually done to force you to use one of the provided types that already implement it
    = help: the following types implement the trait:
              bevy_asset::AssetIndex
              bevy_asset::LoadedUntypedAsset
              bevy_asset::AssetEvent<A>
              bevy_asset::LoadedFolder
              bevy_asset::StrongHandle
              bevy_asset::Handle<A>
              bevy_asset::AssetId<A>
              bevy_asset::AssetPath<'a>
            and 148 others
```
- `Asset` trait depends on `TypePath` which is in bevy_reflect. it's
usually implemented by the `Reflect` derive

- make bevy_reflect not an optional dependency
- when feature `bevy_reflect` is not enabled, derive `TypePath` directly
2025-03-30 10:23:55 +02:00
Aevyrie
c4139fe296 Transform Propagation Optimization: Static Subtree Marking (#18589)
# Objective

- Optimize static scene performance by marking unchanged subtrees.
-
[bef0209](bef0209de1)
fixes #18255 and #18363.
- Closes #18365 
- Includes change from #18321

## Solution

- Mark hierarchy subtrees with dirty bits to avoid transform propagation
where not needed
- This causes a performance regression when spawning many entities, or
when the scene is entirely dynamic.
- This results in massive speedups for largely static scenes.
- In the future we could allow the user to change this behavior, or add
some threshold based on how dynamic the scene is?

## Testing

- Caldera Hotel scene
2025-03-30 10:21:20 +02:00
JMS55
f8f7dfe792 Fix diffuse transmission for anisotropic materials (#18610)
Expand the diff, this was obviously just a copy paste bug at some point.
2025-03-30 10:21:20 +02:00
Chris Russell
ac04ec0075 Improve error message for missing resources (#18593)
# Objective

Fixes #18515 

After the recent changes to system param validation, the panic message
for a missing resource is currently:

```
Encountered an error in system `missing_resource_error::res_system`: SystemParamValidationError { skipped: false }
```

Add the parameter type name and a descriptive message, improving the
panic message to:

```
Encountered an error in system `missing_resource_error::res_system`: SystemParamValidationError { skipped: false, message: "Resource does not exist", param: "bevy_ecs::change_detection::Res<missing_resource_error::MissingResource>" }
```

## Solution

Add fields to `SystemParamValidationError` for error context. Include
the `type_name` of the param and a message.

Store them as `Cow<'static, str>` and only format them into a friendly
string in the `Display` impl. This lets us create errors using a
`&'static str` with no allocation or formatting, while still supporting
runtime `String` values if necessary.

Add a unit test that verifies the panic message.

## Future Work

If we change the default error handling to use `Display` instead of
`Debug`, and to use `ShortName` for the system name, the panic message
could be further improved to:

```
Encountered an error in system `res_system`: Parameter `Res<MissingResource>` failed validation: Resource does not exist
```

However, `BevyError` currently includes the backtrace in `Debug` but not
`Display`, and I didn't want to try to change that in this PR.
2025-03-30 10:21:20 +02:00
Brian Reavis
03e299b455 Fix NonMesh draw command item queries (#17893)
# Objective

This fixes `NonMesh` draw commands not receiving render-world entities
since
- https://github.com/bevyengine/bevy/pull/17698

This unbreaks item queries for queued non-mesh entities:

```rust
struct MyDrawCommand {
    type ItemQuery = Read<DynamicUniformIndex<SomeUniform>>;
    // ...
}
```

### Solution

Pass render entity to `NonMesh` draw commands instead of
`Entity::PLACEHOLDER`. This PR also introduces sorting of the `NonMesh`
bin keys like other types, which I assume is the intended behavior.
@pcwalton

## Testing

- Tested on a local project that extensively uses `NonMesh` items.
2025-03-30 10:21:20 +02:00
Kristoffer Søholm
94eeebb189 Fix compilation of compile_fail_utils when not using rustup (#18394)
# Objective

Currently the `compile_fail_utils` crate fails to compile (ironic) when
the `RUSTUP_HOME` env var isn't set. This has been the case for a long
time, but I only noticed it recently due to rust-analyzer starting to
show the error.

## Solution

Only filter the logs for the `RUSTUP_HOME` variable if it's set.
2025-03-30 10:21:20 +02:00
Robin KAY
d0c92de937 Expose skins_use_uniform_buffers() necessary to use pre-existing setup_morph_and_skinning_defs() API. (#18612)
# Objective

As of bevy 0.16-dev, the pre-existing public function
`bevy::pbr::setup_morph_and_skinning_defs()` is now passed a boolean
flag called `skins_use_uniform_buffers`. The value of this boolean is
computed by the function
`bevy_pbr::render::skin::skins_use_uniform_buffers()`, but it is not
exported publicly.

Found while porting
[bevy_mod_outline](https://github.com/komadori/bevy_mod_outline) to
0.16.

## Solution

Add `skin::skins_use_uniform_buffers` to the re-export list of
`bevy_pbr::render`.

## Testing

Confirmed test program can access public API.
2025-03-30 10:21:20 +02:00
aloucks
002cb73e38 Fix shader pre-pass compile failure when using AlphaMode::Blend and a Mesh without UVs (0.16.0-rc.2) (#18602)
# Objective

The flags are referenced later outside of the VERTEX_UVS ifdef/endif
block. The current behavior causes the pre-pass shader to fail to
compile when UVs are not present in the mesh, such as when using a
`LineStrip` to render a grid.

Fixes #18600

## Solution

Move the definition of the `flags` outside of the ifdef/endif block.

## Testing

Ran a modified `3d_example` that used a mesh and material with
alpha_mode blend, `LineStrip` topology, and no UVs.
2025-03-30 10:21:20 +02:00
Gino Valente
39745eb069 bevy_reflect: Fix TypePath string concatenation (#18609)
# Objective

Fixes #18606

When a type implements `Add` for `String`, the compiler can get confused
when attempting to add a `&String` to a `String`.

Unfortunately, this seems to be [expected
behavior](https://github.com/rust-lang/rust/issues/77143#issuecomment-698369286)
which causes problems for generic types since the current `TypePath`
derive generates code that appends strings in this manner.

## Solution

Explicitly use the `Add<&str>` implementation in the `TypePath` derive
macro.

## Testing

You can test locally by running:

```
cargo check -p bevy_reflect --tests
```
2025-03-30 10:21:19 +02:00
Satellile
c5aca5bca3 Fix LogDiagnosticsPlugin log target typo (#18534)
# Objective

For the LogDiagnosticsPlugin, the log target is "bevy diagnostic" with a
space; I think it may (?) be a typo intended to be "bevy_diagnostic"
with an underline.

I couldn't get filtering INFO level logs with work with this plugin,
changing this seems to produce the expected behavior.
2025-03-30 10:21:19 +02:00