Commit graph

6166 commits

Author SHA1 Message Date
re0312
0f27500e46
Improve par_iter and Parallel (#12904)
# Objective

- bevy usually use `Parallel::scope` to collect items from `par_iter`,
but `scope` will be called with every satifified items. it will cause a
lot of unnecessary lookup.

## Solution

- similar to Rayon ,we introduce `for_each_init` for `par_iter` which
only be invoked when spawn a task for a group of items.

---

## Changelog

- added  `for_each_init`

## Performance
`check_visibility `  in  `many_foxes ` 

![image](https://github.com/bevyengine/bevy/assets/45868716/030c41cf-0d2f-4a36-a071-35097d93e494)
 
~40% performance gain in `check_visibility`.

---------

Co-authored-by: James Liu <contact@jamessliu.com>
2024-04-23 12:05:34 +00:00
Aceeri
b1ab036329
Contextually clearing gizmos (#10973)
# Objective
Allow `Gizmos` to work in `FixedUpdate` without any changes needed. This
changes `Gizmos` from being a purely immediate mode api, but allows the
user to use it as if it were an immediate mode API regardless of
schedule context.

Also allows for extending by other custom schedules by adding their own
`GizmoStorage<Clear>` and the requisite systems:
- `propagate_gizmos::<Clear>` before `update_gizmo_meshes`
- `stash_default_gizmos` when starting a clear context
- `pop_default_gizmos` when ending a clear context
- `collect_default_gizmos` when grabbing the requested gizmos 
- `clear_gizmos` for clearing the context's gizmos

## Solution
Adds a generic to `Gizmos` that defaults to `Update` (the current way
gizmos works). When entering a new clear context the default `Gizmos`
gets swapped out for that context's duration so the context can collect
the gizmos requested.

Prior work: https://github.com/bevyengine/bevy/pull/9153

## To do
- [x] `FixedUpdate` should probably get its own First, Pre, Update,
Post, Last system sets for this. Otherwise users will need to make sure
to order their systems before `clear_gizmos`. This could alternatively
be fixed by moving the setup of this to `bevy_time::fixed`?
   PR to fix this issue: https://github.com/bevyengine/bevy/pull/10977
- [x] use mem::take internally for the swaps?
- [x] Better name for the `Context` generic on gizmos? `Clear`?

---

## Changelog
- Gizmos drawn in `FixedMain` now last until the next `FixedMain`
iteration runs.
2024-04-23 00:16:12 +00:00
BD103
fcd87b2528
Small CI improvements (#13060)
# Objective

- Some CI jobs specifically use `macos-14`, as compared to the default
`macos-latest`.
- `macos-latest` is equivalent to `macos-12`, but may be updated in the
future.
- The CI job that tests on the minimum supported Rust version (MSRV)
uses environmental variables to save the toolchain version.
  - This specific usage is what step outputs were designed for.
- Both do the same thing, but step outputs can be checked by the [Github
Actions VSCode
Extension](https://marketplace.visualstudio.com/items?itemName=GitHub.vscode-github-actions).
- Some workflows have a `NIGHTLY_TOOLCHAIN` variable that let us pin the
nightly version, in case a new release breaks CI.

## Solution

- Document why certain actions required `macos-14`.
- Switch MSRV step to use step outputs.
- Add a small comment documenting the purpose of the `NIGHTLY_TOOLCHAIN`
environmental variable.
2024-04-22 22:41:45 +00:00
Daniel Skates
279e89b858
Bump async-task (#13062)
Bumps `async-task` to 4.7.0 , note this is what Cargo.lock has as well.
Building as a dependency gives the following:

```
   Compiling async-channel v1.8.0
   Compiling futures-lite v1.12.0
error[E0432]: unresolved import `async_task::Builder`
  --> /Users/daniel/.cargo/registry/src/index.crates.io-6f17d22bba15001f/async-executor-1.8.0/src/lib.rs:46:18
   |
46 | use async_task::{Builder, Runnable};
   |                  ^^^^^^^ no `Builder` in the root
   |
   = help: consider importing this struct instead:
           std:🧵:Builder

For more information about this error, try `rustc --explain E0432`.
error: could not compile `async-executor` (lib) due to 1 previous error
warning: build failed, waiting for other jobs to finish...
```

With this change, builds correctly
2024-04-22 22:40:17 +00:00
nullicorn
f496d2a3c3
Additional doc aliases for WindingOrder in bevy_math (#13065)
# Objective

Adds a few extra `#[doc(alias)]` entries to the
`bevy_math::primitives::WindingOrder` enum and its variants to improve
searchability.

## Solution

- Add "Orientation" for `WindingOrder` itself
- Add "AntiClockwise" for `CounterClockwise` variant
- Add "Collinear" for `Invalid` variant

These alternate terms seem to be quite common, especially in the
contexts of rendering and collision-detection.

Signed-off-by: Nullicorn <git@nullicorn.me>
2024-04-22 21:50:27 +00:00
Rob Parrett
e1ee6af275
Improve output of example showcase patches CI workflow (#12609)
# Objective

Fixes #12539

Improve [this CI
output](https://github.com/bevyengine/bevy/actions/runs/8367408952/job/22909715870#step:7:11).

## Solution

- Don't stop after the first failure.
- Print the filename of the patch(es) that failed.
- Clean up an unused package install while we're at it.

Tested over here: https://github.com/rparrett/bevy/pull/20

---------

Co-authored-by: BD103 <59022059+BD103@users.noreply.github.com>
2024-04-22 21:47:56 +00:00
Daniel Miller
5c452c6c00
Added ButtonInput docs usage example (#13046)
# Objective

Fixes #12470

This adds a examples for `ButtonInput` with `KeyCode`, `MouseButton`,
and `GamepadButton`.

It also includes an example of checking a multi-key combination, and
checking multiple keys to mean roughly the same thing.
2024-04-22 17:48:46 +00:00
Brezak
de875fdc4c
Make AppExit more specific about exit reason. (#13022)
# Objective

Closes #13017.

## Solution

- Make `AppExit` a enum with a `Success` and `Error` variant.
- Make `App::run()` return a `AppExit` if it ever returns.
- Make app runners return a `AppExit` to signal if they encountered a
error.

---

## Changelog

### Added

- [`App::should_exit`](https://example.org/)
- [`AppExit`](https://docs.rs/bevy/latest/bevy/app/struct.AppExit.html)
to the `bevy` and `bevy_app` preludes,

### Changed

- [`AppExit`](https://docs.rs/bevy/latest/bevy/app/struct.AppExit.html)
is now a enum with 2 variants (`Success` and `Error`).
- The app's [runner
function](https://docs.rs/bevy/latest/bevy/app/struct.App.html#method.set_runner)
now has to return a `AppExit`.
-
[`App::run()`](https://docs.rs/bevy/latest/bevy/app/struct.App.html#method.run)
now also returns the `AppExit` produced by the runner function.


## Migration Guide

- Replace all usages of
[`AppExit`](https://docs.rs/bevy/latest/bevy/app/struct.AppExit.html)
with `AppExit::Success` or `AppExit::Failure`.
- Any custom app runners now need to return a `AppExit`. We suggest you
return a `AppExit::Error` if any `AppExit` raised was a Error. You can
use the new [`App::should_exit`](https://example.org/) method.
- If not exiting from `main` any other way. You should return the
`AppExit` from `App::run()` so the app correctly returns a error code if
anything fails e.g.
```rust
fn main() -> AppExit {
    App::new()
        //Your setup here...
        .run()
}
```

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
2024-04-22 16:48:18 +00:00
BD103
a50223622f
Remove unecessary lint #[allow(...)] (#12983)
# Objective

- https://github.com/rust-lang/rust/pull/123905 has been merged, so the
workaround introduced in #12913 is no longer necessary.
- Closes #12968

## Solution

- Remove unecessary `allow` attribute
  - This is currently blocked until Rust beta updates.
  - Last tested with `rustc 1.78.0-beta.7 (6fd191292 2024-04-12)`.
2024-04-22 16:45:29 +00:00
Salvador Carvalhinho
16ff354f1c
Correctly handle UI hierarchy without a camera (#12816)
# Objective
Add support so bevy_ui can correctly handle an UI hierarchy without a
camera present.

- Fixes #12184

## Solution

As there was no default behavior for what should happen when a camera is
not present in a UI hierarchy, the solution
was based in defining that default behavior and improving the overall
handling of this "exception".


## Changelog

- Create default values to be used in upsert_node
- Add flag to control warnings about no camera present
- Create unit test no_camera_ui (to test if ui handles no camera
present)
2024-04-22 16:42:13 +00:00
Jonathan
e9be54b0ea
Parallel event reader (#12554)
# Objective

Allow parallel iteration over events, resolve #10766

## Solution

- Add `EventParIter` which works similarly to `QueryParIter`,
implementing a `for_each{_with_id}` operator.
I chose to not mirror `EventIteratorWithId` and instead implement both
operations on a single struct.
- Reuse `BatchingStrategy` from `QueryParIter`

## Changelog

- `EventReader` now supports parallel event iteration using
`par_read().for_each(|event| ...)`.

---------

Co-authored-by: James Liu <contact@jamessliu.com>
Co-authored-by: Pablo Reinhardt <126117294+pablo-lua@users.noreply.github.com>
2024-04-22 16:37:42 +00:00
dependabot[bot]
473577621d
Bump crate-ci/typos from 1.20.8 to 1.20.9 (#13061)
Bumps [crate-ci/typos](https://github.com/crate-ci/typos) from 1.20.8 to
1.20.9.
<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.20.9</h2>
<h2>[1.20.9] - 2024-04-16</h2>
<h3>Fixes</h3>
<ul>
<li>Don't correct the unit <code>dBA</code> (as an identifier to limit
to that case)</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.20.9] - 2024-04-16</h2>
<h3>Fixes</h3>
<ul>
<li>Don't correct the unit <code>dBA</code> (as an identifier to limit
to that case)</li>
</ul>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="44548ad17a"><code>44548ad</code></a>
chore: Release</li>
<li><a
href="73fb2cad75"><code>73fb2ca</code></a>
docs: Update changelog</li>
<li><a
href="21838b0e7d"><code>21838b0</code></a>
Merge pull request <a
href="https://redirect.github.com/crate-ci/typos/issues/1000">#1000</a>
from epage/dba</li>
<li><a
href="ee32d77aba"><code>ee32d77</code></a>
fix(dict): Don't correct dBA</li>
<li><a
href="56df0bd8d6"><code>56df0bd</code></a>
test(dict): Show dBA behavior</li>
<li>See full diff in <a
href="https://github.com/crate-ci/typos/compare/v1.20.8...v1.20.9">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.20.8&new-version=1.20.9)](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>
2024-04-22 06:16:09 +00:00
Miles Silberling-Cook
6b95b0137a
Switch monolithic lib to module re-exports (#13059)
# Objective

Makes crate module docs render correctly in the docs for the monolithic
library. Fixes https://github.com/bevyengine/bevy/issues/13055.

## Solution

Swap from
```rust
pub mod foo {
    pub use bevy_foo::*;
}
```
to
```rust
pub use bevy_foo as foo;
```
2024-04-22 01:32:51 +00:00
Daniel Miller
570c43fdd5
ButtonInput docs - performance cost adjustment (#13047)
Adjusted the documentation to better describe the performance cost of
`ButtonInput::any_just_pressed|any_just_released|any_pressed`.

Each function iterates the full input, but each check is expected
constant cost. It was described previously as a full input check, and a
full internal list iteration, which I believe is incorrect.
2024-04-22 00:42:04 +00:00
François Mockers
c40b485095
use a u64 for MeshPipelineKey (#13015)
# Objective

- `MeshPipelineKey` use some bits for two things
- First commit in this PR adds an assertion that doesn't work currently
on main
- This leads to some mesh topology not working anymore, for example
`LineStrip`
- With examples `lines`, there should be two groups of lines, the blue
one doesn't display currently

## Solution

- Change the `MeshPipelineKey` to be backed by a `u64` instead, to have
enough bits
2024-04-21 20:01:45 +00:00
Charles Bournhonesque
13cac2eeff
Fix doc when state is missing (#13049)
# Objective

The warning mentions the function `add_state` which doesn't exist;
replaced with `init_state`
2024-04-21 13:19:26 +00:00
James Liu
54456b7ea6
Make SystemParam::new_archetype and QueryState::new_archetype unsafe functions (#13044)
# Objective
Fix #2128. Both `Query::new_archetype` and `SystemParam::new_archetype`
do not check if the `Archetype` comes from the same World the state is
initialized from. This could result in unsoundness via invalid accesses
if called incorrectly.

## Solution
Make them `unsafe` functions and lift the invariant to the caller. This
also caught one instance of us not validating the World in
`SystemState::update_archetypes_unsafe_world_cell`'s implementation.

---

## Changelog
Changed: `QueryState::new_archetype` is now an unsafe function.
Changed: `SystemParam::new_archetype` is now an unsafe function.

## Migration Guide
`QueryState::new_archetype` and `SystemParam::new_archetype` are now an
unsafe functions that must be sure that the provided `Archetype` is from
the same `World` that the state was initialized from. Callers may need
to add additional assertions or propagate the safety invariant upwards
through the callstack to ensure safety.
2024-04-21 02:49:42 +00:00
IceSentry
8403c41c67
Use WireframeColor to override global color (#13034)
# Objective

- The docs says the WireframeColor is supposed to override the default
global color but it doesn't.

## Solution

- Use WireframeColor to override global color like docs said it was
supposed to do.
- Updated the example to document this feature
- I also took the opportunity to clean up the code a bit

Fixes #13032
2024-04-20 13:59:12 +00:00
BD103
b3d3daad5a
Fix Clippy lints on WASM (#13030)
# Objective

- Fixes #13024.

## Solution

- Run `cargo clippy --target wasm32-unknown-unknown` until there are no
more errors.
  - I recommend reviewing one commit at a time :)

---

## Changelog

- Fixed Clippy lints for `wasm32-unknown-unknown` target.
- Updated `bevy_transform`'s `README.md`.
2024-04-20 09:15:42 +00:00
andristarr
70d9dfdc48
Adding explanation for loading additonal audio formats to example (#12998)
# Objective

Fixes #12900

## Solution

Added comment to example indicating that additional audio formats are
supported when the feature is added.

---------

Co-authored-by: James Liu <contact@jamessliu.com>
2024-04-20 02:15:06 +00:00
Kanabenki
1df41b79dd
Expose desired_maximum_frame_latency through window creation (#12954)
# Objective

- Closes #12930.

## Solution

- Add a corresponding optional field on `Window` and `ExtractedWindow`

---

## Changelog

### Added

- `wgpu`'s `desired_maximum_frame_latency` is exposed through window
creation. This can be used to override the default maximum number of
queued frames on the GPU (currently 2).

## Migration Guide

- The `desired_maximum_frame_latency` field must be added to instances
of `Window` and `ExtractedWindow` where all fields are explicitly
specified.
2024-04-19 23:09:30 +00:00
BD103
e9fb82ae7f
Remove unused nightly toolchain environmental variable (#13037)
# Objective

- Many of our CI workflows contain a `NIGHTLY_TOOLCHAIN` environmental
variable.
- This specifies which nightly to use. If there is a bug in one of the
nightlies, we can pin the toolchain to be an earlier version.
- Both the daily and weekly workflows do not use the nightly compiler,
but still have a `NIGHTLY_TOOLCHAIN` variable.

## Solution

- Delete the unused variable.
2024-04-19 21:17:38 +00:00
targrub
8316166622
Fix uses of "it's" vs "its". (#13033)
Grammar changes only.
2024-04-19 18:17:31 +00:00
Marco Meijer
2ad27ee4ee
fix: use try_insert instead of insert in bevy_ui to prevent panics when despawning ui nodes (#13000)
# Objective

Sometimes when despawning a ui node in the PostUpdate schedule it
panics. This is because both a despawn command and insert command are
being run on the same entity.

See this example code:

```rs
use bevy::{prelude::*, ui::UiSystem};

#[derive(Resource)]
struct SliceSquare(Handle<Image>);

fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        .add_systems(Startup, setup)
        .add_systems(Update, create_ui)
        .add_systems(PostUpdate, despawn_nine_slice.after(UiSystem::Layout))
        .run();
}

fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
    commands.spawn(Camera2dBundle::default());
    commands.insert_resource(SliceSquare(asset_server.load("textures/slice_square.png")));
}

fn create_ui(mut commands: Commands, slice_square: Res<SliceSquare>) {
    commands.spawn((
        NodeBundle {
            style: Style {
                width: Val::Px(200.),
                height: Val::Px(200.),
                ..default()
            },
            background_color: Color::WHITE.into(),
            ..default()
        },
        UiImage::new(slice_square.0.clone()),
        ImageScaleMode::Sliced(TextureSlicer {
            border: BorderRect::square(220.),
            center_scale_mode: SliceScaleMode::Stretch,
            sides_scale_mode: SliceScaleMode::Stretch,
            max_corner_scale: 1.,
        }),
    ));
}

fn despawn_nine_slice(mut commands: Commands, mut slices: Query<Entity, With<ImageScaleMode>>) {
    for entity in slices.iter_mut() {
        commands.entity(entity).despawn_recursive();
    }
}
```

This code spawns a UiNode with a sliced image scale mode, and despawns
it in the same frame. The
bevy_ui::texture_slice::compute_slices_on_image_change system tries to
insert the ComputedTextureSlices component on that node, but that entity
is already despawned causing this error:

```md
error[B0003]: Could not insert a bundle (of type `bevy_ui::texture_slice::ComputedTextureSlices`) for entity Entity { index: 2, generation: 3 } because it doesn't 
exist in this World. See: https://bevyengine.org/learn/errors/#b0003
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
Encountered a panic when applying buffers for system `bevy_ui::texture_slice::compute_slices_on_image_change`!
Encountered a panic in system `bevy_ecs::schedule::executor::apply_deferred`!
Encountered a panic in system `bevy_app::main_schedule::Main::run_main`!
```

Note that you might have to run the code a few times before this error
appears.

## Solution

Use try_insert instead of insert for non critical inserts in the bevy_ui
crate.

## Some notes

In a lot of cases it does not makes much sense to despawn ui nodes after
the layout system has finished. Except maybe if you delete the root ui
node of a tree. I personally encountered this issue in bevy `0.13.2`
with a system that was running before the layout system. And in `0.13.2`
the `compute_slices_on_image_change` system was also running before the
layout system. But now it runs after the layout system. So the only way
that this bug appears now is if you despawn ui nodes after the layout
system. So I am not 100% sure if using try_insert in this system is the
best option. But personally I still think it is better then the program
panicking.

However the `update_children_target_camera` system does still run before
the layout system. So I do think it might still be able to panic when ui
nodes are despawned before the layout system. Though I haven't been able
to verify that.
2024-04-19 18:12:08 +00:00
Lynn
cd80b10d43
Math primitives cleanup (#13020)
# Objective

- General clenup of the primitives in `bevy_math`
- Add `eccentricity()` to `Ellipse`

## Solution

- Moved `Bounded3d` implementation for `Triangle3d` to the `bounded`
module
- Added `eccentricity()` to `Ellipse`
- `Ellipse::semi_major()` and `::semi_minor()` now accept `&self`
instead of `self`
- `Triangle3d::is_degenerate()` actually uses `f32::EPSILON` as
documented
- Added tests for `Triangle3d`-maths

---------

Co-authored-by: Joona Aalto <jondolf.dev@gmail.com>
Co-authored-by: Miles Silberling-Cook <nth.tensor@gmail.com>
2024-04-18 23:45:51 +00:00
Brezak
f68bc01544
Run CheckVisibility after all the other visibility system sets have… (#12962)
# Objective

Make visibility system ordering explicit. Fixes #12953.

## Solution

Specify `CheckVisibility` happens after all other `VisibilitySystems`
sets have happened.

---------

Co-authored-by: Elabajaba <Elabajaba@users.noreply.github.com>
2024-04-18 20:33:29 +00:00
andristarr
2b3e3341d6
separating finite and infinite 3d planes (#12426)
# Objective

Fixes #12388

## Solution

- Removing the plane3d and adding rect3d primitive mesh
2024-04-18 14:13:22 +00:00
vero
158defd67b
Document Camera coordinate space (#13012)
# Objective

Missing docs

## Solution

Add docs paraphrased from the Cart's mouth:
https://discord.com/channels/691052431525675048/691052431974465548/1172305792154738759
> It follows the natural "results" of right handed y-up. The default
camera will face "forward" in -Z, with +X being "right". The RH y-up
setup is reasonably common. Thats why I asked for existing examples.I
think we should appeal to the masses here / see how other RH Y-up 3D
packages / engines handle this

---------

Co-authored-by: Robert Swain <robert.swain@gmail.com>
2024-04-18 13:02:15 +00:00
zuiyu
3fea726db3
Added deref trait for Mesh2dHandle (#13002)
# Added deref trait for Mesh2dHandle

- Fixes #13001 ".

## Solution

- Added Derive Deref for Mesh2dHandle.
2024-04-18 12:59:29 +00:00
charlotte
ef7bafa68e
Add missing Default impl to ExtendedMaterial. (#13008)
# Objective

When trying to be generic over `Material + Default`, the lack of a
`Default` impl for `ExtendedMaterial`, even when both of its components
implement `Default`, is problematic. I think was probably just
overlooked.

## Solution

Impl `Default` if the material and extension both impl `Default`.

---

## Changelog

## Migration Guide
2024-04-18 12:57:14 +00:00
Victor
11afe16079
Fix extensionless image loading panic (#13005)
Remake of #12938 targeting main
2024-04-17 15:13:33 +00:00
vero
cab1c5702a
Fix a copy-paste typo doc (#13004)
trivial, new doc copied from
https://github.com/bevyengine/bevy/blob/main/crates/bevy_asset/src/io/mod.rs#L138
2024-04-17 03:11:56 +00:00
Luke Van Der Male
cae07ef56a
grammar fix (#12999)
Changed incorrect "it's" to "its" in a code comment.

---------

Co-authored-by: François Mockers <francois.mockers@vleue.com>
2024-04-16 20:49:58 +00:00
Brezak
368c5cef1a
Implement clone for most bundles. (#12993)
# Objective

Closes #12985.

## Solution

- Derive clone for most types with bundle in their name.
- Bundle types missing clone:
-
[`TextBundle`](https://docs.rs/bevy/latest/bevy/prelude/struct.TextBundle.html)
(Contains
[`ContentSize`](https://docs.rs/bevy/latest/bevy/ui/struct.ContentSize.html)
which can't be cloned because it itself contains a `Option<MeasureFunc>`
where
[`MeasureFunc`](https://docs.rs/taffy/0.3.18/taffy/node/enum.MeasureFunc.html)
isn't clone)
-
[`ImageBundle`](https://docs.rs/bevy/latest/bevy/prelude/struct.ImageBundle.html)
(Same as `TextBundle`)
-
[`AtlasImageBundle`](https://docs.rs/bevy/latest/bevy/prelude/struct.AtlasImageBundle.html)
(Will be deprecated in 0.14 there's no point)
2024-04-16 16:37:09 +00:00
Marco Meijer
7e9f6328da
fix: incorrect sprite size for aabb when sprite has rect and no custom_size (#12738)
# Objective

Fixes #12736 

## Solution

Use sprite rect to calculate sprite size for aabb when custom_size is
None
2024-04-16 16:36:16 +00:00
Matty
221d925e90
Make Transform::rotate_axis and Transform::rotate_local_axis use Dir3 (#12986)
# Objective

Related to #12981

Presently, there is a footgun where we allow non-normalized vectors to
be passed in the `axis` parameters of `Transform::rotate_axis` and
`Transform::rotate_local_axis`. These methods invoke
`Quat::from_axis_angle` which expects the vector to be normalized. This
PR aims to address this.

## Solution

Require `Dir3`-valued `axis` parameters for these functions so that the
vector's normalization can be enforced at type-level.

---

## Migration Guide

All calls to `Transform::rotate_axis` and `Transform::rotate_local_axis`
will need to be updated to use a `Dir3` for the `axis` parameter rather
than a `Vec3`. For a general input, this means calling `Dir3::new` and
handling the `Result`, but if the previous vector is already known to be
normalized, `Dir3::new_unchecked` can be called instead. Note that
literals like `Vec3::X` also have corresponding `Dir3` literals; e.g.
`Dir3::X`, `Dir3::NEG_Y` and so on.

---

## Discussion

This axis input is unambigiously a direction instead of a vector, and
that should probably be reflected and enforced by the function
signature. In previous cases where we used, e.g., `impl TryInto<Dir3>`,
the associated methods already implemented (and required!) additional
fall-back logic, since the input is conceptually more complicated than
merely specifying an axis. In this case, I think it's fairly
cut-and-dry, and I'm pretty sure these methods just predate our
direction types.
2024-04-16 13:07:03 +00:00
Chris Russell
e3f55d6dfc
Instrument asset loading and processing. (#12988)
# Objective

As described in #12467, Bevy does not have any spans for any of the
tasks scheduled onto the IO and async compute task pools.

## Solution

Instrument all asset loads and asset processing. Since this change is
restricted to asset tasks, it does not completely solve #12467, but it
does mean we can record the asset path in the trace.


![image](https://github.com/bevyengine/bevy/assets/8494645/59faee63-1f69-40af-bf47-312c4d67d1e2)

---

## Changelog

Tracing will now include spans for asset loading and asset processing.
2024-04-16 12:02:11 +00:00
Emily Selwood
da2ba8a43c
Add comment to example about coordinate system (#12991)
# Objective

When learning about creating meshes in bevy using this example I
couldn't tell which coordinate system bevy uses, which caused confusion
and having to look it up else where.

## Solution

Add a comment that says what coordinate system bevy uses.
2024-04-16 12:01:48 +00:00
Patrick Walton
6003a317b8
Add Cascades to the type registry, fixing lights in glTF. (#12989)
glTF files that contain lights currently panic when loaded into Bevy,
because Bevy tries to reflect on `Cascades`, which accidentally wasn't
registered.
2024-04-16 05:16:45 +00:00
Robert Walter
2532447dcb
impl Reflect for EntityHashSet (#12971)
`EntityHashSet` doesn't seem to implement `Reflect` which seems weird!
Especially since `EntityHashMap` implements `Reflect`.

This PR just added an extra `impl_reflect_value!` for `EntityHashSet`
and this seems to do the trick.

I left out doing the same for `StableHashSet` since it's marked as
deprecated.

---

I'm really wondering what was the issue here. If anyone can explain why
`EntityHashSet` can't use the `Reflect` impl of `bevy_utils::HashSet`
similar to how it's the case with the `...HashMap`s I'd be interested!
2024-04-16 02:48:03 +00:00
BD103
7b8d502083
Fix beta lints (#12980)
# Objective

- Fixes #12976

## Solution

This one is a doozy.

- Run `cargo +beta clippy --workspace --all-targets --all-features` and
fix all issues
- This includes:
- Moving inner attributes to be outer attributes, when the item in
question has both inner and outer attributes
  - Use `ptr::from_ref` in more scenarios
- Extend the valid idents list used by `clippy:doc_markdown` with more
names
  - Use `Clone::clone_from` when possible
  - Remove redundant `ron` import
  - Add backticks to **so many** identifiers and items
    - I'm sorry whoever has to review this

---

## Changelog

- Added links to more identifiers in documentation.
2024-04-16 02:46:46 +00:00
James Liu
9dde99fb96
Cleanup the multithreaded executor (#12969)
# Objective
Improve the code quality of the multithreaded executor.

## Solution
 * Remove some unused variables.
 * Use `Mutex::get_mut` where applicable instead of locking.
* Use a `startup_systems` FixedBitset to pre-compute the starting
systems instead of building it bit-by-bit on startup.
* Instead of using `FixedBitset::clear` and `FixedBitset::union_with`,
use `FixedBitset::clone_from` instead, which does only a single copy and
will not allocate if the target bitset has a large enough allocation.
* Replace the `Mutex` around `Conditions` with `SyncUnsafeCell`, and add
a `Context::try_lock` that forces it to be synchronized fetched
alongside the executor lock.

This might produce minimal performance gains, but the focus here is on
the code quality improvements.
2024-04-16 02:37:19 +00:00
Vitaliy Sapronenko
a5fa32e1e7
Normalization anchor for sprite slice in dimensions of this slice (#12769)
# Objective

Fixes #12408 .
Fixes #12680.

## Solution

- Recaclulated anchor from dimensions of sprite to dimension of each
part of it (each part contains its own anchor)
2024-04-16 01:36:47 +00:00
Pablo Reinhardt
6b0e3fa572
Add double end arrow to gizmos (#11890)
# Objective

- Implement double ended arrows, suggestion of #9400

## Solution

- Creation of new field and method to the `ArrowBuilder`

---

## Changelog

### Added
- New field `ArrowBuilder::double_ended`
- New method `ArrowBuilder::with_double_end` to redefine the
double_ended field

## Additional

I added this in the 3d_gizmos example, that's the result:


![image](https://github.com/bevyengine/bevy/assets/126117294/2f8a93eb-4952-401a-b600-b1454cf898a9)

I added this arrow in the 2d_gizmos example too:


![image](https://github.com/bevyengine/bevy/assets/126117294/c46b4871-8acf-4711-9ca8-c2df36c0464b)

---------

Co-authored-by: Afonso Lage <lage.afonso@gmail.com>
Co-authored-by: Pablo Reinhardt <pabloreinhardt@gmail.com>
2024-04-16 01:34:22 +00:00
Patrick Walton
1141e731ff
Implement alpha to coverage (A2C) support. (#12970)
[Alpha to coverage] (A2C) replaces alpha blending with a
hardware-specific multisample coverage mask when multisample
antialiasing is in use. It's a simple form of [order-independent
transparency] that relies on MSAA. ["Anti-aliased Alpha Test: The
Esoteric Alpha To Coverage"] is a good summary of the motivation for and
best practices relating to A2C.

This commit implements alpha to coverage support as a new variant for
`AlphaMode`. You can supply `AlphaMode::AlphaToCoverage` as the
`alpha_mode` field in `StandardMaterial` to use it. When in use, the
standard material shader automatically applies the texture filtering
method from ["Anti-aliased Alpha Test: The Esoteric Alpha To Coverage"].
Objects with alpha-to-coverage materials are binned in the opaque pass,
as they're fully order-independent.

The `transparency_3d` example has been updated to feature an object with
alpha to coverage. Happily, the example was already using MSAA.

This is part of #2223, as far as I can tell.

[Alpha to coverage]: https://en.wikipedia.org/wiki/Alpha_to_coverage

[order-independent transparency]:
https://en.wikipedia.org/wiki/Order-independent_transparency

["Anti-aliased Alpha Test: The Esoteric Alpha To Coverage"]:
https://bgolus.medium.com/anti-aliased-alpha-test-the-esoteric-alpha-to-coverage-8b177335ae4f

---

## Changelog

### Added

* The `AlphaMode` enum now supports `AlphaToCoverage`, to provide
limited order-independent transparency when multisample antialiasing is
in use.
2024-04-15 20:37:52 +00:00
re0312
09a1f94d14
fix shadow pass trace (#12977)
# Objective

- shadow pass trace does not work correctly

## Solution

- enable it.
2024-04-15 15:55:39 +00:00
Robert Walter
e7ab65675d
Update docs of set_if_neq and replace_if_neq (#12919)
# Objective

- ~~This PR adds more flexible versions of `set_if_neq` and
`replace_if_neq` to only compare and update certain fields of a
components which is not just a newtype~~
- https://github.com/bevyengine/bevy/pull/12919#issuecomment-2048049786
gave a good solution to the original problem, so let's update the docs
so that this is easier to find

## Solution

- ~~Add `set_if_neq_with` and `replace_if_neq_with` which take an
accessor closure to access the relevant field~~

---

In a recent project, a scenario emerged that required careful
consideration regarding change detection without compromising
performance. The context involves a component that maintains a
collection of `Vec<Vec2>` representing a horizontal surface, alongside a
height field. When the height is updated, there are a few approaches to
consider:

1. Clone the collection of points to utilize the existing `set_if_neq`
method.
2. Inline and adjust the `set_if_neq` code specifically for this
scenario.
3. (Consider splitting the component into more granular components.)

It's worth noting that the third option might be the most suitable in
most cases.

A similar situation arises with the Bevy internal Transform component,
which includes fields for translation, rotation, and scale. These fields
are relatively small (`Vec3` or `Quat` with 3 or 4 `f32` values), but
the creation of a single pointer (`usize`) might be more efficient than
copying the data of the other fields. This is speculative, and insights
from others could be valuable.

Questions remain:

- Is it feasible to develop a more flexible API, and what might that
entail?
- Is there general interest in this change?

There's no hard feelings if this idea or the PR is ultimately rejected.
I just wanted to put this idea out there and hope that this might be
beneficial to others and that feedback could be valuable before
abandoning the idea.
2024-04-15 12:38:38 +00:00
dependabot[bot]
409e409ee6
Bump crate-ci/typos from 1.20.4 to 1.20.8 (#12972)
Bumps [crate-ci/typos](https://github.com/crate-ci/typos) from 1.20.4 to
1.20.8.
<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.20.8</h2>
<h2>[1.20.8] - 2024-04-12</h2>
<h3>Fixes</h3>
<ul>
<li>Don't correct <code>kms</code></li>
<li>Don't correct <code>inout</code></li>
</ul>
<h2>v1.20.7</h2>
<h2>[1.20.7] - 2024-04-09</h2>
<h3>Fixes</h3>
<ul>
<li>Treat <code>.pyi</code> files as Python</li>
</ul>
<h2>v1.20.6</h2>
<h2>[1.20.6] - 2024-04-09</h2>
<h3>Fixes</h3>
<ul>
<li>Don't correct <code>automations</code></li>
</ul>
<h2>v1.20.5</h2>
<h2>[1.20.5] - 2024-04-09</h2>
<h3>Fixes</h3>
<ul>
<li>Don't correct <code>hd</code></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.20.8] - 2024-04-12</h2>
<h3>Fixes</h3>
<ul>
<li>Don't correct <code>kms</code></li>
<li>Don't correct <code>inout</code></li>
</ul>
<h2>[1.20.7] - 2024-04-09</h2>
<h3>Fixes</h3>
<ul>
<li>Treat <code>.pyi</code> files as Python</li>
</ul>
<h2>[1.20.6] - 2024-04-09</h2>
<h3>Fixes</h3>
<ul>
<li>Don't correct <code>automations</code></li>
</ul>
<h2>[1.20.5] - 2024-04-09</h2>
<h3>Fixes</h3>
<ul>
<li>Don't correct <code>hd</code></li>
</ul>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="efad85b292"><code>efad85b</code></a>
chore: Release</li>
<li><a
href="bd72069e0a"><code>bd72069</code></a>
chore: Release</li>
<li><a
href="19c217a99c"><code>19c217a</code></a>
docs: Update changelog</li>
<li><a
href="4fff810a21"><code>4fff810</code></a>
Merge pull request <a
href="https://redirect.github.com/crate-ci/typos/issues/995">#995</a>
from epage/kms</li>
<li><a
href="13d8f4b349"><code>13d8f4b</code></a>
fix(dict): Don't correct kms</li>
<li><a
href="45d4d0297f"><code>45d4d02</code></a>
Merge pull request <a
href="https://redirect.github.com/crate-ci/typos/issues/994">#994</a>
from epage/inout</li>
<li><a
href="4d4e19f143"><code>4d4e19f</code></a>
fix(dict): Always allow inout</li>
<li><a
href="e1591a6852"><code>e1591a6</code></a>
chore: Release</li>
<li><a
href="3ccad73642"><code>3ccad73</code></a>
docs: Update changelog</li>
<li><a
href="859859ac4e"><code>859859a</code></a>
Merge pull request <a
href="https://redirect.github.com/crate-ci/typos/issues/985">#985</a>
from augustelalande/add-more-python-extensions</li>
<li>Additional commits viewable in <a
href="https://github.com/crate-ci/typos/compare/v1.20.4...v1.20.8">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.20.4&new-version=1.20.8)](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>
2024-04-15 06:30:58 +00:00
Robert Swain
5f05e75a70
Fix 2D BatchedInstanceBuffer clear (#12922)
# Objective

- `cargo run --release --example bevymark -- --benchmark --waves 160
--per-wave 1000 --mode mesh2d` runs slower and slower over time due to
`no_gpu_preprocessing::write_batched_instance_buffer<bevy_sprite::mesh2d::mesh::Mesh2dPipeline>`
taking longer and longer because the `BatchedInstanceBuffer` is not
cleared

## Solution

- Split the `clear_batched_instance_buffers` system into CPU and GPU
versions
- Use the CPU version for 2D meshes
2024-04-15 05:00:43 +00:00
François Mockers
62f2a73cac
fail when an example doesn't set doc-scrape-examples (#12964)
# Objective

- Ensure that all examples are scrapped for doc

## Solution

- Panic in the example tool when an example doesn't specify
`doc-scrape-examples`
- If an example must not be scrapped, it can set the value to false
2024-04-14 20:07:55 +00:00