Commit Graph

8411 Commits

Author SHA1 Message Date
Chris Russell
6f39e44c48
Introduce methods on QueryState to obtain a Query (#15858)
# Objective

Simplify and expand the API for `QueryState`.  

`QueryState` has a lot of methods that mirror those on `Query`. These
are then multiplied by variants that take `&World`, `&mut World`, and
`UnsafeWorldCell`. In addition, many of them have `_manual` variants
that take `&QueryState` and avoid calling `update_archetypes()`. Not all
of the combinations exist, however, so some operations are not possible.

## Solution

Introduce methods to get a `Query` from a `QueryState`. That will reduce
duplication between the types, and ensure that the full `Query` API is
always available for `QueryState`.

Introduce methods on `Query` that consume the query to return types with
the full `'w` lifetime. This avoids issues with borrowing where things
like `query_state.query(&world).get(entity)` don't work because they
borrow from the temporary `Query`.

Finally, implement `Copy` for read-only `Query`s. `get_inner` and
`iter_inner` currently take `&self`, so changing them to consume `self`
would be a breaking change. By making `Query: Copy`, they can consume a
copy of `self` and continue to work.

The consuming methods also let us simplify the implementation of methods
on `Query`, by doing `fn foo(&self) { self.as_readonly().foo_inner() }`
and `fn foo_mut(&mut self) { self.reborrow().foo_inner() }`. That
structure makes it more difficult to accidentally extend lifetimes,
since the safe `as_readonly()` and `reborrow()` methods shrink them
appropriately. The optimizer is able to see that they are both identity
functions and inline them, so there should be no performance cost.

Note that this change would conflict with #15848. If `QueryState` is
stored as a `Cow`, then the consuming methods cannot be implemented, and
`Copy` cannot be implemented.

## Future Work

The next step is to mark the methods on `QueryState` as `#[deprecated]`,
and move the implementations into `Query`.

## Migration Guide

`Query::to_readonly` has been renamed to `Query::as_readonly`.
2025-02-05 18:33:15 +00:00
charlotte
2ea5e9b846
Cold Specialization (#17567)
# Cold Specialization

## Objective

An ongoing part of our quest to retain everything in the render world,
cold-specialization aims to cache pipeline specialization so that
pipeline IDs can be recomputed only when necessary, rather than every
frame. This approach reduces redundant work in stable scenes, while
still accommodating scenarios in which materials, views, or visibility
might change, as well as unlocking future optimization work like
retaining render bins.

## Solution

Queue systems are split into a specialization system and queue system,
the former of which only runs when necessary to compute a new pipeline
id. Pipelines are invalidated using a combination of change detection
and ECS ticks.

### The difficulty with change detection

Detecting “what changed” can be tricky because pipeline specialization
depends not only on the entity’s components (e.g., mesh, material, etc.)
but also on which view (camera) it is rendering in. In other words, the
cache key for a given pipeline id is a view entity/render entity pair.
As such, it's not sufficient simply to react to change detection in
order to specialize -- an entity could currently be out of view or could
be rendered in the future in camera that is currently disabled or hasn't
spawned yet.

### Why ticks?

Ticks allow us to ensure correctness by allowing us to compare the last
time a view or entity was updated compared to the cached pipeline id.
This ensures that even if an entity was out of view or has never been
seen in a given camera before we can still correctly determine whether
it needs to be re-specialized or not.

## Testing

TODO: Tested a bunch of different examples, need to test more.

## Migration Guide

TODO

- `AssetEvents` has been moved into the `PostUpdate` schedule.

---------

Co-authored-by: Patrick Walton <pcwalton@mimiga.net>
2025-02-05 18:31:20 +00:00
Vic
be9b38e372
implement UniqueEntitySlice (#17589)
# Objective

Follow-up to #17549 and #16547.

A large part of `Vec`s usefulness is behind its ability to be sliced,
like sorting f.e., so we want the same to be possible for
`UniqueEntityVec`.

## Solution

Add a `UniqueEntitySlice` type. It is a wrapper around `[T]`, and itself
a DST.

Because `mem::swap` has a `Sized` bound, DSTs cannot be swapped, and we
can freely hand out mutable subslices without worrying about the
uniqueness invariant of the backing collection!
`UniqueEntityVec` and the relevant `UniqueEntityIter`s now have methods
and trait impls that return `UniqueEntitySlice`s.
`UniqueEntitySlice` itself can deref into normal slices, which means we
can avoid implementing the vast majority of immutable slice methods.

Most of the remaining methods:
- split a slice/collection in further unique subsections/slices
- reorder the slice: `sort`, `rotate_*`, `swap`
- construct/deconstruct/convert pointer-like types: `Box`, `Arc`, `Rc`,
`Cow`
- are comparison trait impls

As this PR is already larger than I'd like, we leave several things to
follow-ups:
- `UniqueEntityArray` and the related slice methods that would return it
    - denoted by "chunk", "array_*" for iterators
- Methods that return iterators with `UniqueEntitySlice` as their item 
    - `windows`, `chunks` and `split` families
- All methods that are capable of actively mutating individual elements.
While they could be offered unsafely, subslicing makes their safety
contract weird enough to warrant its own discussion.
- `fill_with`, `swap_with_slice`, `iter_mut`, `split_first/last_mut`,
`select_nth_unstable_*`

Note that `Arc`, `Rc` and `Cow` are not fundamental types, so even if
they contain `UniqueEntitySlice`, we cannot write direct trait impls for
them.
On top of that, `Cow` is not a receiver (like `self: Arc<Self>` is) so
we cannot write inherent methods for it either.
2025-02-05 18:10:56 +00:00
Patrick Walton
69b2ae871c
Don't reallocate work item buffers every frame. (#17684)
We were calling `clear()` on the work item buffer table, which caused us
to deallocate all the CPU side buffers. This patch changes the logic to
instead just clear the buffers individually, but leave their backing
stores. This has two consequences:

1. To effectively retain work item buffers from frame to frame, we need
to key them off `RetainedViewEntity` values and not the render world
`Entity`, which is transient. This PR changes those buffers accordingly.

2. We need to clean up work item buffers that belong to views that went
away. Amusingly enough, we actually have a system,
`delete_old_work_item_buffers`, that tries to do this already, but it
wasn't doing anything because the `clear_batched_gpu_instance_buffers`
system already handled that. This patch actually makes the
`delete_old_work_item_buffers` system useful, by removing the clearing
behavior from `clear_batched_gpu_instance_buffers` and instead making
`delete_old_work_item_buffers` delete buffers corresponding to
nonexistent views.

On Bistro, this PR improves the performance of
`batch_and_prepare_binned_render_phase` from 61.2 us to 47.8 us, a 28%
speedup.

![Screenshot 2025-02-04
135542](https://github.com/user-attachments/assets/b0ecb551-f6c8-4677-8e4e-e39aa28115a3)
2025-02-05 17:37:24 +00:00
Patrick Walton
48049f7256
Don't mark a previous mesh transform as changed if it didn't actually change. (#17688)
This patch fixes a bug whereby we're re-extracting every mesh every
frame. It's a regression from PR #17413. The code in question has
actually been in the tree with this bug for quite a while; it's that
just the code didn't actually run unless the renderer considered the
previous view transforms necessary. Occlusion culling expanded the set
of circumstances under which Bevy computes the previous view transforms,
causing this bug to appear more often.

This patch fixes the issue by checking to see if the previous transform
of a mesh actually differs from the current transform before copying the
current transform to the previous transform.
2025-02-05 17:35:19 +00:00
Zachary Harrold
642e016aef
Bump to uuid 1.13.1 and enable js on wasm targets (#17689)
# Objective

- Fixes CI failure due to `uuid` 1.13 using the new version of
`getrandom` which requires using a new API to work on Wasm.

## Solution

- Based on [`uuid` 1.13 release
notes](https://github.com/uuid-rs/uuid/releases/tag/1.13.0) I've enabled
the `js` feature on `wasm32`. This will need to be revisited once #17499
is up for review
- Updated minimum `uuid` version to 1.13.1, which fixes a separate issue
with `target_feature = atomics` on `wasm`.

## Testing

- `cargo check --target wasm32-unknown-unknown`
2025-02-05 06:05:32 +00:00
charlotte
8c7f1b34d3
Fix text-2d. (#17674)
# Objective

Fix text 2d. Fixes https://github.com/bevyengine/bevy/issues/17670

## Solution

Evidently there's a 1:N extraction going on here that requires using the
render entity rather than main entity.

## Testing

Text 2d example
2025-02-04 21:32:14 +00:00
Patrick Walton
18c4050dd2
Make batch_and_prepare_binned_render_phase only record information about the first batch in each batch set. (#17680)
Data for the other batches is only accessed by the GPU, not the CPU, so
it's a waste of time and memory to store information relating to those
other batches.

On Bistro, this reduces time spent in
`batch_and_prepare_binned_render_phase` from 85.9 us to 61.2 us, a 40%
speedup.

![Screenshot 2025-02-04
093315](https://github.com/user-attachments/assets/eb00db93-a260-44f9-9ae0-4e90b0697138)
2025-02-04 19:26:36 +00:00
Alice Cecile
0ca9d6968a
Improve docs for WorldQuery (#17654)
# Objective

While working on #17649, I found the docs for `WorldQuery` and the
related traits frustratingly vague.

## Solution

Clarify them and add some more tangible advice.

Also fix a copy-pasted typo in related comments.

---------

Co-authored-by: James O'Brien <james.obrien@drafly.net>
2025-02-03 22:13:42 +00:00
Mincong Lu
29d0ef6f3a
Added try_map_unchanged. (#17653)
# Objective

Allow mapping `Mut` to another value while returning a custom error on
failure.

## Solution

Added `try_map_unchanged` to `Mut` which returns a `Result` instead of
`Option` .
2025-02-03 22:03:39 +00:00
Johannes Ringler
bdf60d6933
Warnings and docs for exponential denormalization in rotate functions (alternative to #17604) (#17646)
# Objective

- When obtaining an axis from the transform and putting that into
`Transform::rotate_axis` or `Transform::rotate_axis_local`, floating
point errors could accumulate exponentially, resulting in denormalized
rotation.
- This is an alternative to and closes #17604, due to lack of consent
around this in the [discord
discussion](https://discord.com/channels/691052431525675048/1203087353850364004/1334232710658392227)
- Closes #16480 

## Solution

- Add a warning of this issue and a recommendation to normalize to the
API docs.
- Add a runtime warning that checks for denormalized axis in debug mode,
with a reference to the API docs.
2025-02-03 22:02:12 +00:00
Chris Russell
2d66099f3d
Fix access checks for DeferredWorld as SystemParam. (#17616)
# Objective

Prevent unsound uses of `DeferredWorld` as a `SystemParam`. It is
currently unsound because it does not check for existing access, and
because it incorrectly registers filtered access.

## Solution

Have `DeferredWorld` panic if a previous parameter has conflicting
access.

Have `DeferredWorld` update `archetype_component_access` so that the
multi-threaded executor sees the access.

Fix `FilteredAccessSet::read_all()` and `write_all()` to correctly add a
`FilteredAccess` with no filter so that `Query` is able to detect the
conflicts.

Remove redundant `read_all()` call, since `write_all()` already declares
read access.

Remove unnecessary `set_has_deferred()` call, since `<DeferredWorld as
SystemParam>::apply_deferred()` does nothing. Previously we were
inserting unnecessary `apply_deferred` systems in the schedule.

## Testing

Added unit tests for systems where `DeferredWorld` conflicts with a
`Query` in the same system.
2025-02-03 21:58:07 +00:00
Erick Z
b978b13a7b
Implementing Reflect on *MeshBuilder types (#17600)
# Objective

- Most of the `*MeshBuilder` classes are not implementing `Reflect`

## Solution

- Implementing `Reflect` for all `*MeshBuilder` were is possible.
- Make sure all `*MeshBuilder` implements `Default`.
- Adding new `MeshBuildersPlugin` that registers all `*MeshBuilder`
types.

## Testing

- `cargo run -p ci`
- Tested some examples like `3d_scene` just in case something was
broken.
2025-02-03 21:53:51 +00:00
Máté Homolya
f22ea72db0
Atmosphere LUT parameterization improvements (#17555)
# Objective

- Fix the atmosphere LUT parameterization in the aerial -view and
sky-view LUTs
- Correct the light accumulation according to a ray-marched reference
- Avoid negative values of the sun disk illuminance when the sun disk is
below the horizon

## Solution

- Adding a Newton's method iteration to `fast_sqrt` function
- Switched to using `fast_acos_4` for better precision of the sun angle
towards the horizon (view mu angle = 0)
- Simplified the function for mapping to and from the Sky View UV
coordinates by removing an if statement and correctly apply the method
proposed by the [Hillarie
paper](https://sebh.github.io/publications/egsr2020.pdf) detailed in
section 5.3 and 5.4.
- Replaced the `ray_dir_ws.y` term with a shadow factor in the
`sample_sun_illuminance` function that correctly approximates the sun
disk occluded by the earth from any view point

## Testing

- Ran the atmosphere and SSAO examples to make sure the shaders still
compile and run as expected.

---

## Showcase

<img width="1151" alt="showcase-img"
src="https://github.com/user-attachments/assets/de875533-42bd-41f9-9fd0-d7cc57d6e51c"
/>

---------

Co-authored-by: Emerson Coskey <emerson@coskey.dev>
2025-02-03 21:52:11 +00:00
Joseph
721bb91987
Add basic debug checks for read-only UnsafeWorldCell (#17393)
# Objective

The method `World::as_unsafe_world_cell_readonly` is used to create an
`UnsafeWorldCell` which is only allowed to access world data immutably.
This can be tricky to use, as the data that an `UnsafeWorldCell` is
allowed to access exists only in documentation (you could think of it as
a "doc-time abstraction" rather than a "compile-time" abstraction). It's
quite easy to forget where a particular instance came from and attempt
to use it for mutable access, leading to instant, silent undefined
behavior.

## Solution

Add a debug-mode only flag to `UnsafeWorldCell` which tracks whether or
not the instance can be used to access world data mutably. This should
catch basic improper usages of `as_unsafe_world_cell_readonly`.

## Future work

There are a few ways that you can bypass the runtime checks introduced
by this PR:

* Any world accesses done via `UnsafeWorldCell::storages` are completely
invisible to these runtime checks. Unfortunately, `storages` constitutes
most of the world accesses used in the engine itself, so this PR will
mostly benefit downstream users of bevy.
* It's possible to call `get_resource_by_id`, and then convert the
returned `Ptr` to a `PtrMut` by calling `assert_unique`. In the future
we'll probably want to add a debug-mode only flag to `Ptr` which tracks
whether or not it can be upgraded to a `PtrMut`. I didn't include this
change in this PR as those types are currently defined using macros
which makes it a bit tricky to modify their definitions.
* Any data accesses done through a mutable `UnsafeWorldCell` are
completely unchecked, meaning it's possible to unsoundly create multiple
mutable references to a single component, for example. In the future we
may want to store an `Access<>` set inside of the world's `Storages` to
add granular debug-mode runtime checks.

That said, I'd consider this PR to be a good first step towards adding
full runtime checks to `UnsafeWorldCell`.

## Testing

Added a few tests that basic invalid mutable world access result in a
panic.

---------

Co-authored-by: Joseph <21144246+JoJoJet@users.noreply.github.com>
Co-authored-by: Alice I Cecile <alice.i.cecile@gmail.com>
2025-02-03 21:46:39 +00:00
Rob Parrett
adcc80c43d
Improve TextSpan docs (#17415)
# Objective

Our
[`TextSpan`](https://docs.rs/bevy/latest/bevy/prelude/struct.TextSpan.html)
docs include a code example that does not actually "work." The code
silently does not render anything, and the `Text*Writer` helpers fail.

This seems to be by design, because we can't use `Text` or `Text2d` from
`bevy_ui` or `bevy_sprite` within docs in `bevy_text`. (Correct me if I
am wrong)

I have seen multiple users confused by these docs.

Also fixes #16794

## Solution

Remove the code example from `TextSpan`, and instead encourage users to
seek docs on `Text` or `Text2d`.

Add examples with nested `TextSpan`s in those areas.
2025-02-03 21:36:52 +00:00
ickshonpe
f62775235d
Revert #17631 (#17660)
# Objective

Revert #17631

After some more experimentation, realised it's not the right approach.
2025-02-03 19:01:15 +00:00
dependabot[bot]
d9df371ef2
Bump crate-ci/typos from 1.29.4 to 1.29.5 (#17655)
Bumps [crate-ci/typos](https://github.com/crate-ci/typos) from 1.29.4 to
1.29.5.
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a
href="https://github.com/crate-ci/typos/releases">crate-ci/typos's
releases</a>.</em></p>
<blockquote>
<h2>v1.29.5</h2>
<h2>[1.29.5] - 2025-01-30</h2>
<h3>Internal</h3>
<ul>
<li>Update a dependency</li>
</ul>
</blockquote>
</details>
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a
href="https://github.com/crate-ci/typos/blob/master/CHANGELOG.md">crate-ci/typos's
changelog</a>.</em></p>
<blockquote>
<h2>[1.29.5] - 2025-01-30</h2>
<h3>Internal</h3>
<ul>
<li>Update a dependency</li>
</ul>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="11ca4583f2"><code>11ca458</code></a>
chore: Release</li>
<li><a
href="99fd37f157"><code>99fd37f</code></a>
docs: Update changelog</li>
<li><a
href="4f604f6eff"><code>4f604f6</code></a>
Merge pull request <a
href="https://redirect.github.com/crate-ci/typos/issues/1220">#1220</a>
from epage/w7</li>
<li><a
href="ba04a1a0fd"><code>ba04a1a</code></a>
perf: Remove ErrMode overhead</li>
<li><a
href="60452b5a81"><code>60452b5</code></a>
chore: Update to Winnow 0.7</li>
<li><a
href="4c22f194b5"><code>4c22f19</code></a>
refactor: Migrate from Parser to ModalParser</li>
<li><a
href="7830eb8730"><code>7830eb8</code></a>
refactor: Resolve deprecations</li>
<li><a
href="07f1292e29"><code>07f1292</code></a>
chore: Upgrade to Winnow 0.6.26</li>
<li><a
href="3683264986"><code>3683264</code></a>
chore(deps): Update Rust Stable to v1.84 (<a
href="https://redirect.github.com/crate-ci/typos/issues/1216">#1216</a>)</li>
<li><a
href="2ed38e07fc"><code>2ed38e0</code></a>
chore(deps): Update Rust crate bstr to v1.11.3 (<a
href="https://redirect.github.com/crate-ci/typos/issues/1202">#1202</a>)</li>
<li>See full diff in <a
href="https://github.com/crate-ci/typos/compare/v1.29.4...v1.29.5">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=crate-ci/typos&package-manager=github_actions&previous-version=1.29.4&new-version=1.29.5)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)

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>
2025-02-03 07:36:25 +00:00
Alice Cecile
da5064889a
Add required serde_derive feature flag to bevy_ecs (#17651)
# Objective

```
cargo test --package bevy_ecs --lib --all-features
```

fails to compile, with output like

> error[E0433]: failed to resolve: could not find `Serialize` in `serde`
>    --> crates/bevy_ecs/src/entity/index_set.rs:14:69
>     |
> 14 | #[cfg_attr(feature = "serialize", derive(serde::Deserialize,
serde::Serialize))]
> | ^^^^^^^^^ could not find `Serialize` in `serde`
>     |
> note: found an item that was configured out
> -->
/home/alice/.cargo/registry/src/index.crates.io-6f17d22bba15001f/serde-1.0.217/src/lib.rs:343:37
>     |
> 343 | pub use serde_derive::{Deserialize, Serialize};
>     |                                     ^^^^^^^^^
> note: the item is gated behind the `serde_derive` feature
> -->
/home/alice/.cargo/registry/src/index.crates.io-6f17d22bba15001f/serde-1.0.217/src/lib.rs:341:7
>     |
> 341 | #[cfg(feature = "serde_derive")]
>     |       ^^^^^^^^^^^^^^^^^^^^^^^^


## Solution

Add the required feature flags and get bevy_ecs compiling standalone
corrctly.

## Testing

The command above now compiles succesfully. Note that several system
stepping tests are failing, and were not being tested in CI. That's a
different PR's problem though.
2025-02-03 03:19:57 +00:00
charlotte
aab39d5693
Move sprite batches to resource (#17636)
# Objective

Currently, `prepare_sprite_image_bind_group` spawns sprite batches onto
an individual representative entity of the batch. This poses significant
problems for multi-camera setups, since an entity may appear in multiple
phase instances.

## Solution

Instead, move batches into a resource that is keyed off the view and the
representative entity. Long term we should switch to mesh2d and use the
existing BinnedRenderPhase functionality rather than naively queueing
into transparent and doing our own ad-hoc batching logic.

Fixes #16867, #17351

## Testing

Tested repros in above issues.
2025-02-02 22:08:57 +00:00
NiseVoid
62285a47ba
Add simple Disabled marker (#17514)
# Objective

We have default query filters now, but there is no first-party marker
for entity disabling yet
Fixes #17458

## Solution

Add the marker, cool recursive features and/or potential hook changes
should be follow up work

## Testing

Added a unit test to check that the new marker is enabled by default
2025-02-02 21:42:25 +00:00
Periwink
75e8e8c0f6
Expose ObserverDescriptor fields (#17623)
# Objective

Expose accessor functions to the `ObserverDescriptor`, so that users can
use the `Observer` component to inspect what the observer is watching.
This would be useful for me, I don't think there's any reason to hide
these.
2025-02-02 20:10:37 +00:00
Lucas Franca
55283bb115
Revert "Fix rounding bug in camera projection (#16828)" (#17592)
This reverts commit ae522225cd.

# Objective

Fixes #16856

## Solution

Remove rounding from `OrthographicProjection::update`, which was causing
the center of the orthographic projection to be off center.

## Testing

Ran the examples mentioned on #16856 and code from #16773

## Showcase
`orthographic` example

![image](https://github.com/user-attachments/assets/d3bb1480-5908-4427-b1f2-af8a5c411745)

`projection_zoom` example

![image](https://github.com/user-attachments/assets/e560c81b-db8f-44f0-91f4-d6bae3ae7f32)

`camera_sub_view` example

![image](https://github.com/user-attachments/assets/615e9eb8-f4e5-406a-b98a-501f7d652145)

`custom_primitives` example

![image](https://github.com/user-attachments/assets/8fd7702e-07e7-47e3-9510-e247d268a3e7)

#16773 code

![image](https://github.com/user-attachments/assets/1b759e90-6c53-4279-987e-284518db034b)
2025-02-02 19:16:13 +00:00
mgi388
756948e311
Fix cursor hotspot out of bounds when flipping (#17571)
# Objective

- Fix off by one error introduced in
https://github.com/bevyengine/bevy/pull/17540 causing:

```
Cursor image StrongHandle<Image>{ id: Index(AssetIndex { generation: 0, index: 3 }), path: Some(cursors/kenney_crosshairPack/Tilesheet/crosshairs_tilesheet_white.png) } is invalid: The specified hotspot (64, 64) is outside the image bounds (64x64).
```

- First PR commit and run shows the bug:
https://github.com/bevyengine/bevy/actions/runs/13009405866/job/36283507530?pr=17571
- Second PR commit fixes it.

## Solution

- Hotspot coordinates are 0-indexed, so we need to subtract 1 from the
width and height.

## Testing

- Fix the tests which included the off-by-one error in their expected
values.
- Consolidate the tests into a single test for brevity.
- Test round trip transform to ensure we can "undo" to get back to the
original value.
- Add a specific bounds test.
- Ran the example again and observed there are no more error logs:
`cargo run --example custom_cursor_image --features=custom_cursor`.
2025-02-02 18:22:34 +00:00
Mathspy
469b218f20
Improve ergonomics of platform_support's Instant (#17577)
# Objective

- Make working with `bevy_time` more ergonomic in `no_std` environments.

Currently `bevy_time` expects the getter in environments where time
can't be obtained automatically via the instruction set or the standard
library to be of type `*mut fn() -> Duration`.
[`fn()`](https://doc.rust-lang.org/beta/std/primitive.fn.html) is
already a function pointer, so `*mut fn()` is a _pointer to a function
pointer_. This is harder to use and error prone since creating a pointer
out of something like `&mut fn() -> Duration` when the lifetime of the
reference isn't static will lead to an undefined behavior once the
reference is freed

## Solution

- Accept a `fn() -> Duration` instead

## Testing

- I made a whole game on the Playdate that relies on `bevy_time`
heavily, see:
[bevydate_time](1b4f02adcd/src/lib.rs (L510-L546))
for usage of the Instant's getter.

---

## Showcase

<details>
  <summary>Click to view showcase</summary>


https://github.com/user-attachments/assets/f687847f-6b62-4322-95f3-c908ada3db30

</details>

## Migration Guide

This is a breaking change but it's not for people coming from Bevy v0.15

### Small thank you note
Thanks to my friend https://github.com/repnop for helping me understand
how to deal with function pointers in `unsafe` environments

Co-authored-by: Wesley Norris <repnop@repnop.dev>
2025-02-02 15:50:48 +00:00
Joona Aalto
9165fb020a
Implement Serialize/Deserialize for entity collections (#17620)
# Objective

Follow-up to #17615.

Bevy's entity collection types like `EntityHashSet` no longer implement
serde's `Serialize` and `Deserialize` after becoming newtypes instead of
type aliases in #16912. This broke some types that support serde for me
in Avian.

I also missed creating const constructors for `EntityIndexMap` and
`EntityIndexSet` in #17615. Oops!

## Solution

Implement `Serialize` and `Deserialize` for Bevy's entity collection
types, and add const constructors for `EntityIndexMap` and
`EntityIndexSet`.

I didn't implement `ReflectSerialize` or `ReflectDeserialize` here,
because I had some trouble fixing the resulting errors, and they were
not implemented previously either.
2025-02-02 15:42:36 +00:00
IceSentry
9c5ce33e1d
Use more headers in AsBindGroup docs (#17586)
# Objective

- Linking to a specific AsBindGroup attribute is hard because it doesn't
use any headers and all the docs is in a giant block

## Solution

- Make each attribute it's own sub-header so they can be easily linked

---

## Showcase

Here's what the rustdoc output looks like with this change


![image](https://github.com/user-attachments/assets/4987b03c-c75d-4a5f-89b7-0c356b61706a)

## Notes

I kept the bullet point so the text is still indented like before. Not
sure if we should keep that or not
2025-02-02 15:18:39 +00:00
Erick Z
416100a253
Fixing ValArithmeticError typo and unused variant (#17597)
# Objective

- `ValArithmeticError` contains a typo, and one of it's variants is not
used

## Solution

- Rename `NonEvaluateable::NonEvaluateable ` variant to
`NonEvaluateable::NonEvaluable`.
- Remove variant `ValArithmeticError:: NonIdenticalVariants`.

## Testing

- `cargo run -p ci`

---

## Migration Guide


- `ValArithmeticError::NonEvaluateable` has been renamed to
`NonEvaluateable::NonEvaluable`
- `ValArithmeticError::NonIdenticalVariants ` has been removed
2025-02-02 15:10:14 +00:00
RobWalt
a893c5d572
feat: impl Ease for Isometry[2/3]d (#17545)
# Objective

- We kind of missed out on implementing the `Ease` trait for some
objects like `Isometry2D` and `Isometry3D` even though it makes sense
and isn't that hard
- Fixes #17539

## Testing

- wrote some minimal tests
- ~~noticed that quat easing isn't working as expected yet~~ I just
confused degrees and radians once again 🙈
2025-02-02 15:07:35 +00:00
ickshonpe
89a1c49377
Fix Taffy viewport node leaks (#17596)
# Objective

For most UI node entities there's a 1-to-1 mapping from the entity to
its associated Taffy node. Root UI nodes are an exception though, their
corresponding Taffy node in the Taffy tree is also given a parent that
represents the viewport. These viewport Taffy nodes are not removed when
a root UI node is despawned.

Parenting of an existing root UI node with an associated viewport Taffy
node also results in the leak of the viewport node.

These tests fail if added to the `layout` module's tests on the main
branch:

```rust
    #[test]
    fn no_viewport_node_leak_on_root_despawned() {
        let (mut world, mut ui_schedule) = setup_ui_test_world();

        let ui_root_entity = world.spawn(Node::default()).id();

        // The UI schedule synchronizes Bevy UI's internal `TaffyTree` with the
        // main world's tree of `Node` entities.
        ui_schedule.run(&mut world);

        // Two taffy nodes are added to the internal `TaffyTree` for each root UI entity.
        // An implicit taffy node representing the viewport and a taffy node corresponding to the
        // root UI entity which is parented to the viewport taffy node.
        assert_eq!(
            world.resource_mut::<UiSurface>().taffy.total_node_count(),
            2
        );

        world.despawn(ui_root_entity);

        // The UI schedule removes both the taffy node corresponding to `ui_root_entity` and its
        // parent viewport node.
        ui_schedule.run(&mut world);

        // Both taffy nodes should now be removed from the internal `TaffyTree`
        assert_eq!(
            world.resource_mut::<UiSurface>().taffy.total_node_count(),
            0
        );
    }

    #[test]
    fn no_viewport_node_leak_on_parented_root() {
        let (mut world, mut ui_schedule) = setup_ui_test_world();

        let ui_root_entity_1 = world.spawn(Node::default()).id();
        let ui_root_entity_2 = world.spawn(Node::default()).id();

        ui_schedule.run(&mut world);

        // There are two UI root entities. Each root taffy node is given it's own viewport node parent,
        // so a total of four taffy nodes are added to the `TaffyTree` by the UI schedule.
        assert_eq!(
            world.resource_mut::<UiSurface>().taffy.total_node_count(),
            4
        );

        // Parent `ui_root_entity_2` onto `ui_root_entity_1` so now only `ui_root_entity_1` is a
        // UI root entity.
        world
            .entity_mut(ui_root_entity_1)
            .add_child(ui_root_entity_2);

        // Now there is only one root node so the second viewport node is removed by
        // the UI schedule.
        ui_schedule.run(&mut world);

        // There is only one viewport node now, so the `TaffyTree` contains 3 nodes in total.
        assert_eq!(
            world.resource_mut::<UiSurface>().taffy.total_node_count(),
            3
        );
    }
```

Fixes #17594

## Solution

Change the `UiSurface::entity_to_taffy` to map to `LayoutNode`s. A
`LayoutNode` has a `viewport_id: Option<taffy::NodeId>` field which is
the id of the corresponding implicit "viewport" node if the node is a
root UI node, otherwise it is `None`. When removing or parenting nodes
this field is checked and the implicit viewport node is removed if
present.

## Testing

There are two new tests in `bevy_ui::layout::tests` included with this
PR:
* `no_viewport_node_leak_on_root_despawned`
* `no_viewport_node_leak_on_parented_root`
2025-02-02 15:03:10 +00:00
ickshonpe
afef7d5797
queue_sprites comment fix (#17621)
# Objective

Fix this comment in `queue_sprites`:
```
// batch_range and dynamic_offset will be calculated in prepare_sprites.
```
`Transparent2d` no longer has a `dynamic_offset` field and the
`batch_range` is calculated in `prepare_sprite_image_bind_groups` now.
2025-02-02 14:49:12 +00:00
ickshonpe
74acb95ed3
anti-alias outside the edges of UI nodes, not across them (#17631)
# Objective

Fixes #17561

## Solution

The anti-aliasing function used by the UI fragment shader is this:
```wgsl
fn antialias(distance: f32) -> f32 {
    return saturate(0.5 - distance);      // saturate clamps between 0 and 1
}
```
The returned value is multiplied with the alpha channel value to get the
anti-aliasing effect.

The `distance` is a signed distance value. A positive `distance` means
we are outside the shape we're drawing and a negative `distance` means
we are on the inside.

So with `distance` at `0` (on the edge of the shape):
```
antialias(0) = saturate(0.5 - 0) = saturate(0.5) = 0.5
```
but we want it to be `1` at this point, so the entire interior of the
shape is given a solid colour, and then decrease as the signed distance
increases.

So in this PR we change it to:
```wgsl
fn antialias(distance: f32) -> f32 {
    return saturate(1. - distance);
}
```
Then:
```
antialias(-0.5) = saturate(1 - (-1)) = saturate(2) = 1
antialias(1) = saturate(1 - 0) = 1
antialias(0.5) = saturate(1 - 0.5) = 0.5
antialias(1) = saturate(1 - 1) = 0
```
as desired.

## Testing

```cargo run --example button```

On main:
<img width="400" alt="bleg" src="https://github.com/user-attachments/assets/314994cb-4529-479d-b179-18e5c25f75bc" />

With this PR:
<img width="400" alt="bbwhite" src="https://github.com/user-attachments/assets/072f481d-8b67-4fae-9a5f-765090d1713f" />

Modified the `button` example to draw a white background to make the bleeding more obvious.
2025-02-02 14:44:31 +00:00
Patrick Walton
7774a624c2
Fix Maya-exported rigs by not trying to topologically sort glTF nodes. (#17641)
The code added in #14343 seems to be trying to ensure that a `Handle`
for each glTF node exists by topologically sorting the directed graph of
glTF nodes containing edges from parent to child and from skin to joint.
Unfortunately, such a graph can contain cycles, as there's no guarantee
that joints are descendants of nodes with the skin. In particular, glTF
exported from Maya using the popular babylon.js export plugin create
skins attached to nodes that animate their parent nodes. This was
causing the topological sort code to enter an infinite loop.

Assuming that the intent of the topological sort is indeed to ensure
that `Handle`s exist for each glTF node before populating them, there's
a better mechanism for this: `LoadContext::get_label_handle`. This is
the documented way to obtain a handle for a node before populating it,
obviating the need for a topological sort. This patch replaces the
topological sort with a pre-pass that uses
`LoadContext::get_label_handle` to get handles for each `Node` before
populating them. This fixes the problem with Maya rigs, in addition to
making the code simpler and faster.
2025-02-02 13:53:55 +00:00
ElliottjPierce
361397fcac
Add a test for direct recursion in required components. (#17626)
I realized there wasn't a test for this yet and figured it would be
trivial to add. Why not? Unless there was a test for this, and I just
missed it?

I appreciate the unique error message it gives and wanted to make sure
it doesn't get broken at some point. Or worse, endlessly recurse.

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
2025-02-02 06:47:10 +00:00
François Mockers
33c5e0bc96
Tiny ci improvements (#17627)
# Objective

- make CI a bit faster without losing anything

## Solution

- Always disable incremental compilation. This was done in a few jobs,
just do it everywhere
- Also disable debug info. This should reduce target folder a bit,
reducing cache size and upload duration
2025-02-02 06:32:07 +00:00
Predko Silvestr
082d87141f
Run handle_lifetime only when AudioSink is added to the world (#17637)
# Objective

Fixes:
https://discord.com/channels/691052431525675048/756998293665349712/1335019849516056586

## Solution

Let's wait till `AudioSInk` will be added to the world.

## Testing

Run ios example
2025-02-02 00:07:02 +00:00
François Mockers
e57f73207e
Smarter testbeds (#17573)
# Objective

- Improve CI when testing rendering by having smarter testbeds

## Solution

- CI testing no longer need a config file and will run with a default
config if not found
- It is now possible to give a name to a screenshot instead of just a
frame number
- 2d and 3d testbeds are now driven from code
  - a new system in testbed will watch for state changed
- on state changed, trigger a screenshot 100 frames after (so that the
scene has time to render) with the name of the scene
- when the screenshot is taken (`Captured` component has been removed),
switch scene
- this means less setup to run a testbed (no need for a config file),
screenshots have better names, and it's faster as we don't wait 100
frames for the screenshot to be taken

## Testing

- `cargo run --example testbed_2d --features bevy_ci_testing`
2025-01-31 22:38:39 +00:00
Sven Niederberger
fcd1847a48
Image::get_color_at and Image::set_color_at: Support 16-bit float values (#17550)
# Objective

- Also support `f16` values when getting and setting colors.

## Solution

- Use the `half` crate to work with `f16` until it's in stable Rust.
2025-01-31 00:36:11 +00:00
ickshonpe
ba1b0092e5
Extract UI nodes into a Vec (#17618)
# Objective

Extract UI nodes into a `Vec` instead of an `EntityHashMap`.

## Solution

Extract UI nodes into a `Vec` instead of an `EntityHashMap`.
Store an index into the `Vec` in each transparent UI item.
Compare both the index and render entity in prepare so there aren't any
collisions.

## Showcase

Yellow this PR, Red main

```
cargo run --example many_buttons --release --features trace_tracy
```

`extract_uinode_background_colors`
<img width="448" alt="extract_uinode_background_colors"
src="https://github.com/user-attachments/assets/09c0f434-ab4f-4c0f-956a-cf31e9060061"
/>

`extract_uinode_images`
<img width="587" alt="extract_uinode_images"
src="https://github.com/user-attachments/assets/43246d7f-d22c-46d0-9a07-7e13d5379f56"
/>

`prepare_uinodes`
<img width="441" alt="prepare_uinodes_vec"
src="https://github.com/user-attachments/assets/cc9a7eac-60e9-42fa-8093-bce833a1c153"
/>
2025-01-30 23:25:07 +00:00
Joona Aalto
59697f9ccc
Make EntityHashMap::new and EntityHashSet::new const (#17615)
# Objective

#16912 turned `EntityHashMap` and `EntityHashSet` into proper newtypes
instead of type aliases. However, this removed the ability to create
these collections in const contexts; previously, you could use
`EntityHashSet::with_hasher(EntityHash)`, but it doesn't exist anymore.

## Solution

Make `EntityHashMap::new` and `EntityHashSet::new` const methods.
2025-01-30 17:40:06 +00:00
Chris Russell
7d68ac029e
Use the provided caller instead of Location::caller() in despawn_with_caller() (#17598)
# Objective

Pass the correct location to triggers when despawning entities.
`EntityWorldMut::despawn_with_caller()` currently passes
`Location::caller()` to some triggers instead of the `caller` parameter
it was passed. As `despawn_with_caller()` is not `#[track_caller]`, this
means the location will always be reported as `despawn_with_caller()`
itself.

## Solution

Pass `caller` instead of `Location::caller()`.
2025-01-30 04:50:17 +00:00
SpecificProtagonist
2c9950fcf8
Remove IDE gitignores (#17603)
Remove gitignores for IDE files, recommend how to set up local
gitignore.
2025-01-30 04:49:15 +00:00
Jean Mertz
6bda03cc08
chore: impl PartialEq for bevy_ui::Text and bevy_text::TextColor (#17606)
Adding these allows using `DetectChangesMut::set_if_neq` to only update
the values when needed. Currently you need to get the inner values first
(`String` and `Color`), to do any equality checks.

---------

Signed-off-by: Jean Mertz <git@jeanmertz.com>
2025-01-30 04:47:29 +00:00
Alexandru Scvorțov
909b02e9de
Fix link to states example (#17595)
Fixes the link to the states example.

Co-authored-by: Rob Parrett <robparrett@gmail.com>
2025-01-29 21:44:55 +00:00
janis-bhm
f7c27b534a
Fixes #17508: bevy_color::Color constructor docs get docs matching underlying constructor (#17601)
# Objective

Fixes #17508

`bevy_color::Color` constructors don't have docs explaining the valid
range for the values passed.

## Solution

I've mostly copied the docs from the respective underlying type's docs,
because that seemed most consistent and accurate.
2025-01-29 18:21:23 +00:00
aecsocket
f232674291
Remove unnecessary PartialReflect bound on DeserializeWithRegistry (#17560)
# Objective

The new `DeserializeWithRegistry` trait in 0.15 was designed to be used
with reflection, and so has a `trait DeserializeWithRegistry:
PartialReflect` bound. However, this bound is not actually necessary for
the trait to function properly. And this `PartialReflect` bound already
exists on:
```rs
impl<T: PartialReflect + for<'de> DeserializeWithRegistry<'de>> FromType<T>
    for ReflectDeserializeWithRegistry
```
So there is no point in constraining the trait itself with this bound as
well.

This lets me use `DeserializeWithRegistry` with non-`Reflect` types,
which I want to do to avoid making a bunch of `FooDeserializer` structs
and `impl DeserializeSeed` on them.

## Solution

Removes this unnecessary bound.

## Testing

Trivial change, does not break compilation or `bevy_reflect` tests.

## Migration Guide

`DeserializeWithRegistry` types are no longer guaranteed to be
`PartialReflect` as well. If you were relying on this type bound, you
should add it to your own bounds manually.
```diff
- impl<T: DeserializeWithRegistry> Foo for T { .. }
+ impl<T: DeserializeWithRegistry + PartialReflect> Foo for T { .. }
```
2025-01-29 17:36:39 +00:00
Jean Mertz
b58eda01e2
feat(ecs): add EntityEntryCommands::entity() method chaining (#17580)
This allows you to continue chaining method calls after calling
`EntityCommands::entry`:

```rust
commands
    .entity(player.entity)
    .entry::<Level>()
    // Modify the component if it exists
    .and_modify(|mut lvl| lvl.0 += 1)
    // Otherwise insert a default value
    .or_insert(Level(0))
    // Return the EntityCommands for the entity
    .entity()
    // And continue chaining method calls
    .insert(Name::new("Player"));
```

---------

Signed-off-by: Jean Mertz <git@jeanmertz.com>
2025-01-29 17:36:02 +00:00
ickshonpe
d4356062bf
UiSurface::upsert_node refactor (#8831)
# Objective

Simplify the `UiSurface::upsert_node` method by directly matching on
HashMap entry states.
2025-01-28 18:05:59 +00:00
ickshonpe
5bbcf646a7
Improved UI camera mapping (#17244)
# Objective

Two more optimisations for UI extraction:
* We only need to query for the camera's render entity when the target
camera changes. If the target camera is the same as for the previous UI
node we can use the previous render entity.
* The cheap checks for visibility and zero size should be performed
first before the camera queries.

## Solution
Add a new system param `UiCameraMap` that resolves the correct render
camera entity and only queries when necessary.

<img width="506" alt="tracee"
src="https://github.com/user-attachments/assets/f57d1e0d-f3a7-49ee-8287-4f01ffc8ba24"
/>

I don't like the `UiCameraMap` + `UiCameraMapper` implementation very
much, maybe someone else can suggest a better construction.

This is partly motivated by #16942 which adds further indirection and
these changes would ameliorate that performance regression.
2025-01-28 18:05:00 +00:00
ickshonpe
a80263a5bf
no-camera many_buttons argument, only emit UI camera warnings once (#17557)
# Objective

* Add a `no-camera` argument to the `many_buttons` stress test example.
* Only emit the UI "no camera found" warnings once.
2025-01-28 18:04:52 +00:00