Commit Graph

228 Commits

Author SHA1 Message Date
Bevy Auto Releaser a74009b22e chore: Release 2026-06-21 16:55:28 +00:00
DavidCrossman 7c77ecd576 Fix documentation typos (#24446)
# Objective

Fix typos and other small issues in the documentation. I can drop the
changes to `bevy_reflect`'s and `bevy_anti_alias`'s crate descriptions
if it's a problem.
2026-06-02 00:52:42 +00:00
DavidCrossman 9dfc7a6d33 Use absolute paths in declarative macros (#24261)
# Objective

- Improve declarative macro hygiene.
- Fix declarative macros using non-imported items.
  - `AnimatedField` is unqualified in the `animated_field` macro.
  - `offset_of` is unqualified in the `impl_atomic_pod` macro.
- `format` is unqualified in `hash_error` macro (requires import in
`no_std`).

## Solution

- Qualify unqualified items and use absolute paths in every public
(`#[macro_export]`) `macro_rules`.
- Re-export `format` in `bevy_reflect::__macro_exports::alloc_utils`.

## Testing

- Ran `cargo run -p ci -- compile`
2026-05-21 09:47:16 +00:00
François Mockers 7a42034ffa make TypeIdMap iteration order respect its comment (#23864)
# Objective

- Fixes #23840
- Make `TypeIdMap` iteration order depends only on insertion/removals

## Solution

- Replace the backing `HashMap` by an `IndexMap`

## Testing

- CI
2026-04-18 04:35:29 +00:00
Arne Berner 03709a7638 make bevy_utils::DebugName public outside of prelude (#23641) (#23725)
# Objective

Fixes #23641 

## Solution

To stay consistent to the provided API by bevy_utils I only made
DebugName public instead of debug_info.

## Testing

I was able to call DebugName from outside like this:
```rust
use bevy_utils::DebugName;

struct Foo();

fn main() {
    let name = DebugName::type_name::<Foo>();
    println!("{name}");
}
```
This is a simple change that should be platform independent.
2026-04-12 20:47:15 +00:00
Aevyrie 9797fb24ea Parallelize mark_dirty_trees (#23185)
# Objective

- Make `mark_dirty_trees` faster

## Solution

- Use `BufferedChannel`s to make a parallel concurrent worker queue to
propagate dirty bits from leaves to the root.
- Use atomics to coordinate cross-thread early-exiting when hitting
visited entities in the hierarchy.

## Testing

- `transform_hierarchy` `humanoids_inactive`
<img width="1440" height="778" alt="image"
src="https://github.com/user-attachments/assets/d9bb5f60-dd6d-4d2c-8c37-7adb3218c97e"
/>
- `bevy_city` while simulating cars 
<img width="1086" height="798" alt="image"
src="https://github.com/user-attachments/assets/4c372332-5e37-4079-80c4-acc1444efb15"
/>
- `bevy_city` while static 
<img width="1096" height="742" alt="image"
src="https://github.com/user-attachments/assets/6a7f6e7b-c97c-4969-9058-9991d59e9d32"
/>

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
2026-03-10 04:44:09 +00:00
Aevyrie 7b65256780 Fix buffered channel memory leak (#23086)
# Objective

- Fix a possible memory leak when a producer and consumer are on
different threads and never switch.

## Solution

- Set a maximum size for the object pool to avoid unbounded growth.

## Testing

- Reproduced leak in `bevy_city` with moving cars.
- Verified leak is no longer present with this patch.

Closes #23038 
Introduced in #22297
2026-02-21 10:40:26 +00:00
François Mockers d13ef9d8ef remove circular dependency (#23081)
# Objective

- #22297 introduced circular dependencies that would make it impossible
to release Bevy

## Solution

- Remove it
2026-02-21 00:27:23 +00:00
Guillaume Gomez 28fd2cb3c0 Enable the rustdoc "--generate-macro-expansion" feature (#23075)
You can see this feature in action in the compiler docs like
[here](https://doc.rust-lang.org/nightly/nightly-rustc/src/rustc_ast_lowering/errors.rs.html#323)
or
[here](https://doc.rust-lang.org/nightly/nightly-rustc/src/rustc_ast_lowering/format.rs.html#89).
2026-02-21 00:24:25 +00:00
atlv 1789b76d09 doc and clean up bevy_shader (#22774)
# Objective

- murder mwriting monday's mortal menemy `#![expect(missing_docs, reason
= "Not all docs are written yet, see #3492.")]`
- clean up bevy_shader

## Solution

- move RenderDevice param from `get` to `new`, because we will soon be
in a Render Recovery world and need to ensure different render devices
do not end up in the same shader cache.
- delete an unused enum
- delete some boilerplate getters
- document everything
- also document define_atomic_id macro

## Testing

- ci
2026-02-02 23:32:58 +00:00
Yash Kumar 41f3ee7e47 Improve time complexity of get_component_mut (#22572)
# Objective

- Addresses #22483.

## Solution

Add a bloom filter to `has_conflicts` as a pre-check to see if we need
to check a given access against every other access or not. If the access
doesn't hit any component or resource a previous access does, we know we
don't need to check it element-by-element. Well-formed calls to
get_components_mut should then be linear in time taken to check for
conflicts, as they would always pass the pre-check.

The filter used is exported in the `bevy_utils` API as it is not
specific to components or resources.

## Testing

Tested via `cargo test`, where the get_component_mut tests pass or panic
as expected.

The get_component_mut benchmarks show >=20% improvements at as little as
5 components compared to the existing fallback for smaller sets. The
larger, 32 component benchmark added shows massive improvements. In
general, the new pre-check filter means we're only about 4-5x slower
than not checking at all.

```
ecs::world::world_get::world_query_get_components_mut/10_components_50000_entities
                        time:   [6.5252 ms 6.5314 ms 6.5388 ms]
                        change: [−34.225% −33.954% −33.747%] (p = 0.00 < 0.05)
                        Performance has improved.
[...]
ecs::world::world_get::world_query_get_components_mut/32_components
                        time:   [21.608 ms 21.696 ms 21.828 ms]
                        change: [−92.284% −92.236% −92.186%] (p = 0.00 < 0.05)
                        Performance has improved.
```
| bench | mean (prev, with fallback threshold) | mean (post, always
complex) | delta |
|-|-|-|-|
| 2_components | 770.73 us | 925.90 us | +19.62% |
| unchecked_2_components | 288.66 us | 288.71 us | -0.84% |
| 5_components | 2.960 ms | 2.286 ms | -22.77% |
| unchecked_5_components | 505.45 us | 521.56 us | +2.14% |
| 10_components | 9.889 ms | 6.531 ms | -33.95% |
| unchecked_10_components | 1.452 ms | 1.538 ms | +5.48% |
| 32_components | 279.44 ms | 21.696 ms | -92.24% |
| unchecked_32_components | 4.460 ms | 4.458 ms | -0.05%
2026-01-22 19:18:17 +00:00
Aevyrie 3ffa26b021 Parallel Mesh Collection (#22297)
# Objective

- Speed up `collect_meshes_for_gpu_building`, a bottleneck for scenes
with many moving meshes.

## Solution

- Parallelize the gather step for mesh collection.
- Immediately start up a task for serial collection of meshes, which
cannot be parallelized.
- Spawn many tasks for gathering meshes, and send batches of these to
the collection task
- This allows the serial collection step to start immediately, instead
of being delayed until after all collection is finished.

## Testing

- Built a new `bevymark_3d` stress test for benchmarking dynamic 3d mesh
scenes. This is not currently covered by our stress tests.
https://github.com/bevyengine/bevy/pull/22298
- With 200k meshes, this drops total frame times from 16.4ms to 12.3ms
(-4.1ms)

<img width="631" height="377" alt="image"
src="https://github.com/user-attachments/assets/ff9de860-e1f2-4f98-8075-0b3720a82913"
/>

- Mesh collection itself drops from 7.9ms to 3.6ms (-4.3ms)

<img width="623" height="372" alt="image"
src="https://github.com/user-attachments/assets/cf52687a-503b-4f70-8e99-0ad2e63f4da0"
/>
2026-01-17 21:10:05 +00:00
ickshonpe 637948b904 Add delimiters around the "Enable the debug feature to see the name" message (#22532)
# Objective

A user on Discord was confused by this warning, assuming that the
message must be corrupted in some way:

`
warning[B0004]: Entity 290v0 with the Enable the debug feature to see
the name component has a parent (289v0 entity) without Enable the debug
feature to see the name.
This will cause inconsistent behaviors! See:
https://bevy.org/learn/errors/b0004
`

## Solution

Add some delimiters to the `FEATURE_DISABLED` string. This makes the
warning much more legible:

`
warning[B0004]: Entity 290v0 with the <Enable the debug feature to see
the name> component has a parent (289v0 entity) without <Enable the
debug feature to see the name>.
This will cause inconsistent behaviors! See:
https://bevy.org/learn/errors/b0004
`
2026-01-16 00:22:42 +00:00
github-actions[bot] d772c32071 Bump Version after Release (#22498)
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 Mockers <francois.mockers@vleue.com>
2026-01-14 18:21:56 +00:00
atlv 7a436e3aa1 move define_atomic_id to bevy_utils (#22417)
# Objective

- when i made bevy_shader, i inlined the define_atomic_id macro because
i wasnt sure if one usage was enough justification for kicking it into
utils
- ~~bevy_material needs this in several places too, so let's kick it out
in preparation. 3 usages outside bevy_render is enough justification~~
its not actually needed for bevy_material

## Solution

- move file

## Testing

- examples, clippy etc.
2026-01-08 05:08:01 +00:00
Chris Russell e2b2f4aea8 Simplify Debug display of DebugName (#21870)
# Objective

As noted in #21856, the `Debug` output of `DebugName` is too verbose. It
is supposed to be a thin wrapper around a string, but it renders as a
`struct`.

## Solution

Manually `impl Debug for DebugName` and write the string directly.  

## Showcase

The following code

```rust
#[derive(Debug)]
struct TestStruct {
    debug_name: DebugName,
}
let test_struct = TestStruct {
    debug_name: DebugName::type_name::<TestStruct>(),
};
println!("{test_struct:#?}");
```

Prints the following before this change

```
TestStruct {
    debug_name: DebugName {
        name: "crate_name::TestStruct",
    },
}
```

And the following after it

```
TestStruct {
    debug_name: "crate_name::TestStruct",
}
```

When the `debug` feature is disabled, it prints the following both
before and after the change

```
TestStruct {
    debug_name: DebugName,
}
```

---------

Co-authored-by: François Mockers <francois.mockers@vleue.com>
2025-11-26 08:52:25 +00:00
Kevin Reid c179b27a83 Replace feature(doc_auto_cfg) with feature(doc_cfg). (#21304)
## Objective

Fixes #21303 (but does not add any testing that similar issues will not
recur).

## Solution

Globally replace `feature(doc_auto_cfg)` with `feature(doc_cfg)`.

## Testing

Tested that `RUSTDOCFLAGS=--cfg=docsrs cargo +nightly doc -p
bevy_platform` succeeds. This is not a test of all documentation builds,
but I do not know of a way to do that until bevy’s dependencies catch
up.
2025-09-30 21:20:23 +00:00
Periwink f484b78537 Add conversion from DebugName to Cow<'static, str> (#21257)
# Objective

There seems to be no way to get the underlying `Cow<'static, str>` from
the `DebugName`.

This is useful for me to be able to use `DebugName` and have it interop
seamlessly with the `metrics` crate:
https://docs.rs/metrics/latest/metrics/type.SharedString.html

which is the standard why to register/record metrics in rust.

Is it possible to include this in 0.17?

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
Co-authored-by: Jan Hohenheim <jan@hohenheim.ch>
2025-09-28 18:35:18 +00:00
Periwink 1e6e6cfb41 Re-export disqualified::ShortName from bevy_utils (#21255)
To migrate to 0.17, I tried switching to using
`DebugName::type_name::<C>()` from bevy_utils.

In some cases I wanted to use the `ShortName` type that I saw in
bevy_utils, but to my surprise it was not exported.

Is it possible to include this in 0.17?
2025-09-28 17:14:43 +00:00
James Liu ca506d73ce Bump crate versions to 0.18.0-dev (#21001)
# Objective
The 0.17 release candidate process has been started. We should be able
to start merging PRs scheduled for 0.18 now.

## Solution
Update the crate versions all to `0.18.0-dev`
2025-09-22 16:53:58 +00:00
François Mockers 3d608e76b1 Fix some lints and feature gates (#20606)
# Objective

- Some more lints
- Also fixes #20542

## Solution

- Fix them
2025-08-16 19:53:06 +00:00
Christian Hughes 0e97d8cc02 impl Deref for DebugName (#20566)
# Objective

Remove the need for allocation by allowing `DebugName` -> `&str`
conversion.

## Solution

Implemented `Deref<Target=str>` for `DebugName`.
2025-08-14 01:16:13 +00:00
James Liu 8e52194d70 CI fixes for Rust 1.89 (#20462)
Adopted from #20456

Notes:

* The origin of the `dead_code` lints were coming from the `ShaderType `
derive macro. This has been reported as
https://github.com/teoxoy/encase/issues/102, and a temporary
workspace-wide `allow` added to the top level Cargo.toml.
* One of the lints pointed out that `PartialEq` and `Eq` may not work as
expected for function pointers, so `CloneBehavior` no longer implements
either trait, and pattern matching is used in instead.

Original PR Description:
># Objective
>
>Unbreak CI.
>
> ## Solution
>
> Fix the lints.
>
>I've opted for anonymous lifetimes in every revealed case so far;
please let me know if you think I should used named lifetimes in
specific cases and why.
>
>## Testing
>
>Is CI green?
>
>## Context
>
> This lint originally had a much larger splash damage, with fairly
negative effects on Bevy. See
https://github.com/rust-lang/rust/issues/131725.
>
> The more restricted former is much more helpful, despite the large
diff in this PR. Bevy is a large code base!
>
>## TODO
>
>- [x] discuss proposed lifetime lint fixes
>,- [x] use cargo clippy --fix to fix newly uncovered docs misformatting
>- [x] fix newly revealed dead code issues
>- [x] ensure CI is green

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
Co-authored-by: Mike <mike.hsu@gmail.com>
2025-08-08 21:14:36 +00:00
atlv 1e07b21571 revert #19303, moving WgpuWrapper out of bevy_utils (#20220)
# Objective

- the changes done in #19303 did not end up being necessary for
bevy_camera, because i found a better split. it was still a good
refactor, but lets leave it in bevy_render

## Solution

- partially revert by moving the extracted file to bevy_render

## Testing

- it compiles
2025-07-21 23:20:38 +00:00
Christian Hughes fb5d8fd867 Make Parallel<T> more T: !Default accessible (#17943)
# Objective

`ThreadLocal::<T>::default()` doesn't require `T: Default`, so
`Parallel<T>` shouldn't require it either.

## Solution

- Replaced the `Default` derive with a manually specified impl.
- Added `Parallel::borrow_local_mut_or` as a non-`T: Default`-requiring
alternative to `borrow_local_mut`.
- Added `Parallel::scope_or` as a non-`T: Default`-requiring alternative
to `scope`.
2025-07-07 20:22:20 +00:00
Rob Parrett 2342e993ec Bump typos to 1.34.0 (#20013)
# Objective

Closes #20006

## Solution

Bump `typos` and also fix the new typos detected

## Testing

CI
2025-07-07 20:15:06 +00:00
Chris Russell 6e918f56d8 Have System::run_unsafe return Result. (#19145)
# Objective

Allow combinator and pipe systems to delay validation of the second
system, while still allowing the second system to be skipped.

Fixes #18796

Allow fallible systems to be used as one-shot systems, reporting errors
to the error handler when used through commands.

Fixes #19722

Allow fallible systems to be used as run conditions, including when used
with combinators. Alternative to #19580.

Always validate parameters when calling the safe
`run_without_applying_deferred`, `run`, and `run_readonly` methods on a
`System`.

## Solution

Have `System::run_unsafe` return a `Result`.  

We want pipe systems to run the first system before validating the
second, since the first system may affect whether the second system has
valid parameters. But if the second system skips then we have no output
value to return! So, pipe systems must return a `Result` that indicates
whether the second system ran.

But if we just make pipe systems have `Out = Result<B::Out>`, then
chaining `a.pipe(b).pipe(c)` becomes difficult. `c` would need to accept
the `Result` from `a.pipe(b)`, which means it would likely need to
return `Result` itself, giving `Result<Result<Out>>`!

Instead, we make *all* systems return a `Result`! We move the handling
of fallible systems from `IntoScheduleConfigs` and `IntoObserverSystem`
to `SystemParamFunction` and `ExclusiveSystemParamFunction`, so that an
infallible system can be wrapped before being passed to a combinator.

As a side effect, this enables fallible systems to be used as run
conditions and one-shot systems.

Now that the safe `run_without_applying_deferred`, `run`, and
`run_readonly` methods return a `Result`, we can have them perform
parameter validation themselves instead of requiring each caller to
remember to call them. `run_unsafe` will continue to not validate
parameters, since it is used in the multi-threaded executor when we want
to validate and run in separate tasks.

Note that this makes type inference a little more brittle. A function
that returns `Result<T>` can be considered either a fallible system
returning `T` or an infallible system returning `Result<T>` (and this is
important to continue supporting `pipe`-based error handling)! So there
are some cases where the output type of a system can no longer be
inferred. It will work fine when directly adding to a schedule, since
then the output type is fixed to `()` (or `bool` for run conditions).
And it will work fine when `pipe`ing to a system with a typed input
parameter.

I used a dedicated `RunSystemError` for the error type instead of plain
`BevyError` so that skipping a system does not box an error or capture a
backtrace.
2025-07-03 21:48:09 +00:00
François Mockers c077c65ddd bevy_utils: clippy without debug feature enabled (#19861)
# Objective

- bevy_utils has warnings with clippy

## Solution

- Fix them

## Testing

`cargo clippy -p bevy_utils  --no-deps -- -D warnings`
2025-06-29 17:13:27 +00:00
Chris Russell 85448b767e Make DebugName work when building with no default features (#19824)
# Objective

Let `bevy_utils` build with no default features.  

`cargo build -p bevy_utils --no-default-features` currently fails with 

```
error[E0433]: failed to resolve: use of unresolved module or unlinked crate `alloc`
 --> crates\bevy_utils\src\debug_info.rs:1:5
  |
1 | use alloc::{borrow::Cow, fmt, string::String};
  |     ^^^^^ use of unresolved module or unlinked crate `alloc`
  |
  = help: add `extern crate alloc` to use the `alloc` crate

error[E0432]: unresolved import `alloc`
 --> crates\bevy_utils\src\debug_info.rs:1:5
  |
1 | use alloc::{borrow::Cow, fmt, string::String};
  |     ^^^^^ help: a similar path exists: `core::alloc`
```

I would have expected CI to catch this earlier, but I have not
investigated why it did not.

## Solution

Wrap the parts of `DebugName` that use `Cow` and `String` in
`cfg::alloc!`.

If the `debug` feature is enabled, then `DebugName` itself stores a
`Cow`, so make the `debug` feature require `bevy_platform/alloc`.

That is, you can use `DebugName` in no-std contexts when it's just a
ZST! (I bet it's even possible to support no-std `debug` by storing
`&'static str` instead of `Cow<'static, str>`, but that seemed like too
much complexity for now.)
2025-06-29 02:45:41 +00:00
github-actions[bot] a466084167 Bump Version after Release (#19774)
Bump version after release
This PR has been auto-generated

Fixes #19766

---------

Co-authored-by: Bevy Auto Releaser <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: François Mockers <francois.mockers@vleue.com>
Co-authored-by: François Mockers <mockersf@gmail.com>
2025-06-22 23:06:43 +00:00
François Mockers 4e694aea53 ECS: put strings only used for debug behind a feature (#19558)
# Objective

- Many strings in bevy_ecs are created but only used for debug: system
name, component name, ...
- Those strings make a significant part of the final binary and are no
use in a released game

## Solution

- Use [`strings`](https://linux.die.net/man/1/strings) to find ...
strings in a binary
- Try to find where they come from
- Many are made from `type_name::<T>()` and only used in error / debug
messages
- Add a new structure `DebugName` that holds no value if `debug` feature
is disabled
- Replace `core::any::type_name::<T>()` by `DebugName::type_name::<T>()`

## Testing

Measurements were taken without the new feature being enabled by
default, to help with commands

### File Size

I tried building the `breakout` example with `cargo run --release
--example breakout`

|`debug` enabled|`debug` disabled|
|-|-|
|81621776 B|77735728B|
|77.84MB|74.13MB|

### Compilation time

`hyperfine --min-runs 15 --prepare "cargo clean && sleep 5"
'RUSTC_WRAPPER="" cargo build --release --example breakout'
'RUSTC_WRAPPER="" cargo build --release --example breakout --features
debug'`

```
breakout' 'RUSTC_WRAPPER="" cargo build --release --example breakout --features debug'
Benchmark 1: RUSTC_WRAPPER="" cargo build --release --example breakout
  Time (mean ± σ):     84.856 s ±  3.565 s    [User: 1093.817 s, System: 32.547 s]
  Range (min … max):   78.038 s … 89.214 s    15 runs

Benchmark 2: RUSTC_WRAPPER="" cargo build --release --example breakout --features debug
  Time (mean ± σ):     92.303 s ±  2.466 s    [User: 1193.443 s, System: 33.803 s]
  Range (min … max):   90.619 s … 99.684 s    15 runs

Summary
  RUSTC_WRAPPER="" cargo build --release --example breakout ran
    1.09 ± 0.05 times faster than RUSTC_WRAPPER="" cargo build --release --example breakout --features debug
```
2025-06-18 20:15:25 +00:00
theotherphil 66086a2616 Add TypeIdMapExt trait to make TypeIdMap operations more ergonomic (#19683)
# Objective
 
Fix https://github.com/bevyengine/bevy/issues/19642 by enabling e.g.

```
map.get_type::<MyType>();
```

in place of

```
map.get(&TypeId::of::<MyType>());
```

## Solution

Add an extension trait `TypeIdMapExt` with `insert_type`, `get_type`,
`get_type_mut` and `remove_type` counterparts for `insert`, `get`,
`get_mut` and `remove`.

## Testing

Doc test.
2025-06-17 21:06:27 +00:00
Carter Anderson 7e9d6d852b bevyengine.org -> bevy.org (#19503)
We have acquired [bevy.org](https://bevy.org) and the migration has
finished! Meaning we can now update all of the references in this repo.
2025-06-05 23:09:28 +00:00
Coty 439c0fb973 fix reference in example usage comments (#19434)
# Objective

- Fix a reference in the example usage comments of bevy_utils
Default::default

## Solution

- Just a word change in the comments
 
## Testing

- No actual code changes to test
2025-05-29 19:12:55 +00:00
atlv d4985af7cb refactor(utils): move SyncCell and SyncUnsafeCell to bevy_platform (#19305)
# Objective

- move SyncCell and SyncUnsafeCell to bevy_platform

## Solution

- move SyncCell and SyncUnsafeCell to bevy_platform

## Testing

- cargo clippy works
2025-05-27 04:57:26 +00:00
atlv 1732c2253b refactor(render): move WgpuWrapper into bevy_utils (#19303)
# Objective

- A step towards splitting out bevy_camera from bevy_render

## Solution

- Move a shim type into bevy_utils to avoid a dependency cycle
- Manually expand Deref/DerefMut to avoid having a bevy_derive
dependency so early in the dep tree

## Testing

- It compiles
2025-05-27 03:43:49 +00:00
theotherphil 3690ad5b0b Remove apostrophes in possessive its (#19244)
# Objective

Fix some grammatical errors: it's -> its

Not the most useful commit in the world, but I saw a couple of these and
decided to fix the lot.

## Solution
-

## Testing
-
2025-05-26 19:53:14 +00:00
Zachary Harrold 3d3746e5d0 Simplify bevy_utils Features (#19090)
# Objective

Now that `bevy_platform::cfg` is merged, we can start tidying up
features. This PR starts with `bevy_utils`.

## Solution

- Removed `serde` and `critical-section` features (they were just
re-exports of `bevy_platform` anyway)
- Removed `std`, `alloc` features, relying on `bevy_platform::cfg` to
check for availability.
- Added `parallel` feature to provide access to the `Parallel` type.
- Moved the `HashMap` type aliases into `map.rs` for better
organisation.

## Testing

- CI
2025-05-24 01:46:11 +00:00
Carter Anderson e9a0ef49f9 Rename bevy_platform_support to bevy_platform (#18813)
# Objective

The goal of `bevy_platform_support` is to provide a set of platform
agnostic APIs, alongside platform-specific functionality. This is a high
traffic crate (providing things like HashMap and Instant). Especially in
light of https://github.com/bevyengine/bevy/discussions/18799, it
deserves a friendlier / shorter name.

Given that it hasn't had a full release yet, getting this change in
before Bevy 0.16 makes sense.

## Solution

- Rename `bevy_platform_support` to `bevy_platform`.
2025-04-11 23:13:28 +00:00
Zachary Harrold 72b4ed05c7 Address clippy::let_and_return in bevy_utils (#18480)
# Objective

`clippy::let_and_return` fails on Windows.

## Solution

Fixed it!

## Testing

- CI
2025-03-22 11:44:49 +00:00
Zachary Harrold 76e9bf9c99 Automatically enable portable-atomic when required (#17570)
# Objective

- Contributes to #15460
- Reduce quantity and complexity of feature gates across Bevy

## Solution

- Used `target_has_atomic` configuration variable to automatically
detect impartial atomic support and automatically switch to
`portable-atomic` over the standard library on an as-required basis.

## Testing

- CI

## Notes

To explain the technique employed here, consider getting `Arc` either
from `alloc::sync` _or_ `portable-atomic-util`. First, we can inspect
the `alloc` crate to see that you only have access to `Arc` _if_
`target_has_atomic = "ptr"`. We add a target dependency for this
particular configuration _inverted_:

```toml
[target.'cfg(not(target_has_atomic = "ptr"))'.dependencies]
portable-atomic-util = { version = "0.2.4", default-features = false }
```

This ensures we only have the dependency when it is needed, and it is
entirely excluded from the dependency graph when it is not. Next, we
adjust our configuration flags to instead of checking for `feature =
"portable-atomic"` to instead check for `target_has_atomic = "ptr"`:

```rust
// `alloc` feature flag hidden for brevity

#[cfg(not(target_has_atomic = "ptr"))]
use portable_atomic_util as arc;

#[cfg(target_has_atomic = "ptr")]
use alloc::sync as arc;

pub use arc::{Arc, Weak};
```

The benefits of this technique are three-fold:

1. For platforms without full atomic support, the functionality is
enabled automatically.
2. For platforms with atomic support, the dependency is never included,
even if a feature was enabled using `--all-features` (for example)
3. The `portable-atomic` feature no longer needs to virally spread to
all user-facing crates, it's instead something handled within
`bevy_platform_support` (with some extras where other dependencies also
need their features enabled).
2025-02-24 20:52:46 +00:00
Zachary Harrold 5241e09671 Upgrade to Rust Edition 2024 (#17967)
# Objective

- Fixes #17960

## Solution

- Followed the [edition upgrade
guide](https://doc.rust-lang.org/edition-guide/editions/transitioning-an-existing-project-to-a-new-edition.html)

## Testing

- CI

---

## Summary of Changes

### Documentation Indentation

When using lists in documentation, proper indentation is now linted for.
This means subsequent lines within the same list item must start at the
same indentation level as the item.

```rust
/* Valid */
/// - Item 1
///   Run-on sentence.
/// - Item 2
struct Foo;

/* Invalid */
/// - Item 1
///     Run-on sentence.
/// - Item 2
struct Foo;
```

### Implicit `!` to `()` Conversion

`!` (the never return type, returned by `panic!`, etc.) no longer
implicitly converts to `()`. This is particularly painful for systems
with `todo!` or `panic!` statements, as they will no longer be functions
returning `()` (or `Result<()>`), making them invalid systems for
functions like `add_systems`. The ideal fix would be to accept functions
returning `!` (or rather, _not_ returning), but this is blocked on the
[stabilisation of the `!` type
itself](https://doc.rust-lang.org/std/primitive.never.html), which is
not done.

The "simple" fix would be to add an explicit `-> ()` to system
signatures (e.g., `|| { todo!() }` becomes `|| -> () { todo!() }`).
However, this is _also_ banned, as there is an existing lint which (IMO,
incorrectly) marks this as an unnecessary annotation.

So, the "fix" (read: workaround) is to put these kinds of `|| -> ! { ...
}` closuers into variables and give the variable an explicit type (e.g.,
`fn()`).

```rust
// Valid
let system: fn() = || todo!("Not implemented yet!");
app.add_systems(..., system);

// Invalid
app.add_systems(..., || todo!("Not implemented yet!"));
```

### Temporary Variable Lifetimes

The order in which temporary variables are dropped has changed. The
simple fix here is _usually_ to just assign temporaries to a named
variable before use.

### `gen` is a keyword

We can no longer use the name `gen` as it is reserved for a future
generator syntax. This involved replacing uses of the name `gen` with
`r#gen` (the raw-identifier syntax).

### Formatting has changed

Use statements have had the order of imports changed, causing a
substantial +/-3,000 diff when applied. For now, I have opted-out of
this change by amending `rustfmt.toml`

```toml
style_edition = "2021"
```

This preserves the original formatting for now, reducing the size of
this PR. It would be a simple followup to update this to 2024 and run
`cargo fmt`.

### New `use<>` Opt-Out Syntax

Lifetimes are now implicitly included in RPIT types. There was a handful
of instances where it needed to be added to satisfy the borrow checker,
but there may be more cases where it _should_ be added to avoid
breakages in user code.

### `MyUnitStruct { .. }` is an invalid pattern

Previously, you could match against unit structs (and unit enum
variants) with a `{ .. }` destructuring. This is no longer valid.

### Pretty much every use of `ref` and `mut` are gone

Pattern binding has changed to the point where these terms are largely
unused now. They still serve a purpose, but it is far more niche now.

### `iter::repeat(...).take(...)` is bad

New lint recommends using the more explicit `iter::repeat_n(..., ...)`
instead.

## Migration Guide

The lifetimes of functions using return-position impl-trait (RPIT) are
likely _more_ conservative than they had been previously. If you
encounter lifetime issues with such a function, please create an issue
to investigate the addition of `+ use<...>`.

## Notes

- Check the individual commits for a clearer breakdown for what
_actually_ changed.

---------

Co-authored-by: François Mockers <francois.mockers@vleue.com>
2025-02-24 03:54:47 +00:00
François Mockers 7400e7adfd Cleanup publish process (#17728)
# Objective

- publish script copy the license files to all subcrates, meaning that
all publish are dirty. this breaks git verification of crates
- the order and list of crates to publish is manually maintained,
leading to error. cargo 1.84 is more strict and the list is currently
wrong

## Solution

- duplicate all the licenses to all crates and remove the
`--allow-dirty` flag
- instead of a manual list of crates, get it from `cargo package
--workspace`
- remove the `--no-verify` flag to... verify more things?
2025-02-09 17:46:19 +00:00
Zachary Harrold 9bc0ae33c3 Move hashbrown and foldhash out of bevy_utils (#17460)
# Objective

- Contributes to #16877

## Solution

- Moved `hashbrown`, `foldhash`, and related types out of `bevy_utils`
and into `bevy_platform_support`
- Refactored the above to match the layout of these types in `std`.
- Updated crates as required.

## Testing

- CI

---

## Migration Guide

- The following items were moved out of `bevy_utils` and into
`bevy_platform_support::hash`:
  - `FixedState`
  - `DefaultHasher`
  - `RandomState`
  - `FixedHasher`
  - `Hashed`
  - `PassHash`
  - `PassHasher`
  - `NoOpHash`
- The following items were moved out of `bevy_utils` and into
`bevy_platform_support::collections`:
  - `HashMap`
  - `HashSet`
- `bevy_utils::hashbrown` has been removed. Instead, import from
`bevy_platform_support::collections` _or_ take a dependency on
`hashbrown` directly.
- `bevy_utils::Entry` has been removed. Instead, import from
`bevy_platform_support::collections::hash_map` or
`bevy_platform_support::collections::hash_set` as appropriate.
- All of the above equally apply to `bevy::utils` and
`bevy::platform_support`.

## Notes

- I left `PreHashMap`, `PreHashMapExt`, and `TypeIdMap` in `bevy_utils`
as they might be candidates for micro-crating. They can always be moved
into `bevy_platform_support` at a later date if desired.
2025-01-23 16:46:08 +00:00
Zachary Harrold a64446b77e Create bevy_platform_support Crate (#17250)
# Objective

- Contributes to #16877

## Solution

- Initial creation of `bevy_platform_support` crate.
- Moved `bevy_utils::Instant` into new `bevy_platform_support` crate.
- Moved `portable-atomic`, `portable-atomic-util`, and
`critical-section` into new `bevy_platform_support` crate.

## Testing

- CI

---

## Showcase

Instead of needing code like this to import an `Arc`:

```rust
#[cfg(feature = "portable-atomic")]
use portable_atomic_util::Arc;

#[cfg(not(feature = "portable-atomic"))]
use alloc::sync::Arc;
```

We can now use:

```rust
use bevy_platform_support::sync::Arc;
```

This applies to many other types, but the goal is overall the same:
allowing crates to use `std`-like types without the boilerplate of
conditional compilation and platform-dependencies.

## Migration Guide

- Replace imports of `bevy_utils::Instant` with
`bevy_platform_support::time::Instant`
- Replace imports of `bevy::utils::Instant` with
`bevy::platform_support::time::Instant`

## Notes

- `bevy_platform_support` hasn't been reserved on `crates.io`
- ~~`bevy_platform_support` is not re-exported from `bevy` at this time.
It may be worthwhile exporting this crate, but I am unsure of a
reasonable name to export it under (`platform_support` may be a bit
wordy for user-facing).~~
- I've included an implementation of `Instant` which is suitable for
`no_std` platforms that are not Wasm for the sake of eliminating feature
gates around its use. It may be a controversial inclusion, so I'm happy
to remove it if required.
- There are many other items (`spin`, `bevy_utils::Sync(Unsafe)Cell`,
etc.) which should be added to this crate. I have kept the initial scope
small to demonstrate utility without making this too unwieldy.

---------

Co-authored-by: TimJentzsch <TimJentzsch@users.noreply.github.com>
Co-authored-by: Chris Russell <8494645+chescock@users.noreply.github.com>
Co-authored-by: François Mockers <francois.mockers@vleue.com>
2025-01-20 20:45:30 +00:00
MichiRecRoom 26bb0b40d2 Move #![warn(clippy::allow_attributes, clippy::allow_attributes_without_reason)] to the workspace Cargo.toml (#17374)
# Objective
Fixes https://github.com/bevyengine/bevy/issues/17111

## Solution
Move `#![warn(clippy::allow_attributes,
clippy::allow_attributes_without_reason)]` to the workspace `Cargo.toml`

## Testing
Lots of CI testing, and local testing too.

---------

Co-authored-by: Benjamin Brienen <benjamin.brienen@outlook.com>
2025-01-15 01:14:58 +00:00
MichiRecRoom 447108b2a4 Downgrade clippy::allow_attributes and clippy::allow_attributes_without_reason to warn (#17320)
# Objective
I realized that setting these to `deny` may have been a little
aggressive - especially since we upgrade warnings to denies in CI.

## Solution
Downgrades these lints to `warn`, so that compiles can work locally. CI
will still treat these as denies.
2025-01-12 05:28:26 +00:00
MichiRecRoom 900509bec0 bevy_utils: Apply #![deny(clippy::allow_attributes, clippy::allow_attributes_without_reason)] (#17305)
# Objective
- https://github.com/bevyengine/bevy/issues/17111

## Solution
Set the `clippy::allow_attributes` and
`clippy::allow_attributes_without_reason` lints to `deny`, and bring
`bevy_utils` in line with the new restrictions.

## Testing
`cargo clippy --tests --all-features --package bevy_utils` was run, and
no errors were encountered.
2025-01-12 01:26:44 +00:00
Rob Parrett b77e3ef33a Fix a few typos (#17292)
# Objective

Stumbled upon a `from <-> form` transposition while reviewing a PR,
thought it was interesting, and went down a bit of a rabbit hole.

## Solution

Fix em
2025-01-10 22:48:30 +00:00
mgi388 b20e23dd41 Add compile-time dyn compatible checks for DynEq, DynHash (#17254)
# Objective

- Shrink `bevy_utils` more.
- Refs #11478

## Solution

- Removes `assert_object_safe` from `bevy_utils` by using a compile time
check instead.

## Testing

- CI.

---

## Migration Guide

`assert_object_safe` is no longer exported by `bevy_utils`. Instead, you
can write a compile time check that your trait is "dyn compatible":

```rust
/// Assert MyTrait is dyn compatible
const _: Option<Box<dyn MyTrait>> = None;
```

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
2025-01-09 07:30:54 +00:00