Commit graph

5726 commits

Author SHA1 Message Date
charlotte
da211ee314
Fix broken mesh2d (#15838)
Forgot to clean this up when I was still trying to figure out what was
broken.

Closes #15835.
2024-10-10 21:28:45 +00:00
Matty
a06802a66e
Make AnimatableCurve::curve public (#15831)
# Objective

The other `Curve -> AnimationCurve` wrappers allow public access to the
inner curve, so this one should as well.

## Solution

Made the field public. Instances will still need to be constructed using
the (more ergonomic) `from_curve` method, which infers the phantom type
for the user.
2024-10-10 18:51:17 +00:00
akimakinai
922a25d295
Picking: Filter out invisible sprites early (#15819)
# Objective

- We don't have to `collect` and `sort` invisible sprites in
`sprite_picking` system.

## Solution

- Filter by `ViewVisibility::get()` earlier

## Testing

- `sprite_picking` example still works.
2024-10-10 18:49:23 +00:00
charlotte
dd812b3e49
Type safe retained render world (#15756)
# Objective

In the Render World, there are a number of collections that are derived
from Main World entities and are used to drive rendering. The most
notable are:
- `VisibleEntities`, which is generated in the `check_visibility` system
and contains visible entities for a view.
- `ExtractedInstances`, which maps entity ids to asset ids.

In the old model, these collections were trivially kept in sync -- any
extracted phase item could look itself up because the render entity id
was guaranteed to always match the corresponding main world id.

After #15320, this became much more complicated, and was leading to a
number of subtle bugs in the Render World. The main rendering systems,
i.e. `queue_material_meshes` and `queue_material2d_meshes`, follow a
similar pattern:

```rust
for visible_entity in visible_entities.iter::<With<Mesh2d>>() {
    let Some(mesh_instance) = render_mesh_instances.get_mut(visible_entity) else {
        continue;
    };
            
    // Look some more stuff up and specialize the pipeline...
            
    let bin_key = Opaque2dBinKey {
        pipeline: pipeline_id,
        draw_function: draw_opaque_2d,
        asset_id: mesh_instance.mesh_asset_id.into(),
        material_bind_group_id: material_2d.get_bind_group_id().0,
    };
    opaque_phase.add(
        bin_key,
        *visible_entity,
        BinnedRenderPhaseType::mesh(mesh_instance.automatic_batching),
    );
}
```

In this case, `visible_entities` and `render_mesh_instances` are both
collections that are created and keyed by Main World entity ids, and so
this lookup happens to work by coincidence. However, there is a major
unintentional bug here: namely, because `visible_entities` is a
collection of Main World ids, the phase item being queued is created
with a Main World id rather than its correct Render World id.

This happens to not break mesh rendering because the render commands
used for drawing meshes do not access the `ItemQuery` parameter, but
demonstrates the confusion that is now possible: our UI phase items are
correctly being queued with Render World ids while our meshes aren't.

Additionally, this makes it very easy and error prone to use the wrong
entity id to look up things like assets. For example, if instead we
ignored visibility checks and queued our meshes via a query, we'd have
to be extra careful to use `&MainEntity` instead of the natural
`Entity`.

## Solution

Make all collections that are derived from Main World data use
`MainEntity` as their key, to ensure type safety and avoid accidentally
looking up data with the wrong entity id:

```rust
pub type MainEntityHashMap<V> = hashbrown::HashMap<MainEntity, V, EntityHash>;
```

Additionally, we make all `PhaseItem` be able to provide both their Main
and Render World ids, to allow render phase implementors maximum
flexibility as to what id should be used to look up data.

You can think of this like tracking at the type level whether something
in the Render World should use it's "primary key", i.e. entity id, or
needs to use a foreign key, i.e. `MainEntity`.

## Testing

##### TODO:

This will require extensive testing to make sure things didn't break!
Additionally, some extraction logic has become more complicated and
needs to be checked for regressions.

## Migration Guide

With the advent of the retained render world, collections that contain
references to `Entity` that are extracted into the render world have
been changed to contain `MainEntity` in order to prevent errors where a
render world entity id is used to look up an item by accident. Custom
rendering code may need to be changed to query for `&MainEntity` in
order to look up the correct item from such a collection. Additionally,
users who implement their own extraction logic for collections of main
world entity should strongly consider extracting into a different
collection that uses `MainEntity` as a key.

Additionally, render phases now require specifying both the `Entity` and
`MainEntity` for a given `PhaseItem`. Custom render phases should ensure
`MainEntity` is available when queuing a phase item.
2024-10-10 18:47:04 +00:00
akimakinai
11d1ebeed3
Fix OIT shaders error with DX12 backend (#15782)
# Objective

- Fixes #15781

## Solution

- DX12 backend seems to require functions with return types to return
value. [WebGPU spec also requires
this](https://gpuweb.github.io/gpuweb/wgsl/#behaviors-rules).

Upstream issue: https://github.com/gfx-rs/wgpu/issues/4458
https://github.com/gpuweb/gpuweb/issues/2523

## Testing

- Tested `order_independent_transparency` example with both dx12 and
vulkan backend on Windows
2024-10-10 14:17:09 +00:00
Emerson Coskey
f18be66a0c
Fix mesh flags (#15804)
Fixed incorrect mesh flags offsets

## Testing

Ran OIT example since that was the affected flag
2024-10-09 23:50:48 +00:00
ickshonpe
15072d7937
Dark text colors fix (#15794)
# Objective

Fix the text colors.

fixes #15788

## Solution

Add the missing corner flags.
2024-10-09 22:14:36 +00:00
Tim
3da0ef048e
Remove the Component trait implementation from Handle (#15796)
# Objective

- Closes #15716
- Closes #15718

## Solution

- Replace `Handle<MeshletMesh>` with a new `MeshletMesh3d` component
- As expected there were some random things that needed fixing:
- A couple tests were storing handles just to prevent them from being
dropped I believe, which seems to have been unnecessary in some.
- The `SpriteBundle` still had a `Handle<Image>` field. I've removed
this.
- Tests in `bevy_sprite` incorrectly added a `Handle<Image>` field
outside of the `Sprite` component.
- A few examples were still inserting `Handle`s, switched those to their
corresponding wrappers.
- 2 examples that were still querying for `Handle<Image>` were changed
to query `Sprite`

## Testing

- I've verified that the changed example work now

## Migration Guide

`Handle` can no longer be used as a `Component`. All existing Bevy types
using this pattern have been wrapped in their own semantically
meaningful type. You should do the same for any custom `Handle`
components your project needs.

The `Handle<MeshletMesh>` component is now `MeshletMesh3d`.

The `WithMeshletMesh` type alias has been removed. Use
`With<MeshletMesh3d>` instead.
2024-10-09 21:10:01 +00:00
UkoeHB
a6be9b4ccd
Rename TextBlock to TextLayout (#15797)
# Objective

- Improve clarity when spawning a text block. See [this
discussion](https://github.com/bevyengine/bevy/pull/15591/#discussion_r1787083571).

## Solution

- Rename `TextBlock` to `TextLayout`.
2024-10-09 20:58:27 +00:00
Christian Hughes
b4071ca370
Add World::get_resource_or_init as an alternative to World::get_resource_or_insert_with (#15758)
# Objective

If a `Resource` implements `FromWorld` or `Default`, it's nicer to be
able to write:

```rust
let foo = world.get_resource_or_init::<Foo>();
```

Rather than:

```rust
let foo = world.get_resource_or_insert_with(Foo::default);
```

The latter is also not possible if a type implements `FromWorld` only,
and not `Default`.

## Solution

Added:

```rust
impl World {
    pub fn get_resource_or_init<R: Resource + FromWorld>(&mut self) -> Mut<'_, R>;
}
```

Turns out all current in-engine uses of `get_resource_or_insert_with`
are exactly the above, so they've also been replaced.

## Testing

- Added a doc-test.
- Also added a doc-test for `World::get_resource_or_insert_with`.
2024-10-09 20:56:26 +00:00
Brandon Reinhart
88d9ead7f8
promote atlas sources texture_ids to pub visibility (#15795)
In order to create texture atlases from other systems (custom game
solutions) that are compatible with the ones generated by the bevy
builders, it would be nice to have the interface be fully public. This
field is pub(crate). Unless there's a good reason, can we promote this
to pub?

Alternatives:
- Don't do it.
2024-10-09 18:37:26 +00:00
UkoeHB
c2c19e5ae4
Text rework (#15591)
**Ready for review. Examples migration progress: 100%.**

# Objective

- Implement https://github.com/bevyengine/bevy/discussions/15014

## Solution

This implements [cart's
proposal](https://github.com/bevyengine/bevy/discussions/15014#discussioncomment-10574459)
faithfully except for one change. I separated `TextSpan` from
`TextSpan2d` because `TextSpan` needs to require the `GhostNode`
component, which is a `bevy_ui` component only usable by UI.

Extra changes:
- Added `EntityCommands::commands_mut` that returns a mutable reference.
This is a blocker for extension methods that return something other than
`self`. Note that `sickle_ui`'s `UiBuilder::commands` returns a mutable
reference for this reason.

## Testing

- [x] Text examples all work.

---

## Showcase

TODO: showcase-worthy

## Migration Guide

TODO: very breaking

### Accessing text spans by index

Text sections are now text sections on different entities in a
hierarchy, Use the new `TextReader` and `TextWriter` system parameters
to access spans by index.

Before:
```rust
fn refresh_text(mut query: Query<&mut Text, With<TimeText>>, time: Res<Time>) {
    let text = query.single_mut();
    text.sections[1].value = format_time(time.elapsed());
}
```

After:
```rust
fn refresh_text(
    query: Query<Entity, With<TimeText>>,
    mut writer: UiTextWriter,
    time: Res<Time>
) {
    let entity = query.single();
    *writer.text(entity, 1) = format_time(time.elapsed());
}
```

### Iterating text spans

Text spans are now entities in a hierarchy, so the new `UiTextReader`
and `UiTextWriter` system parameters provide ways to iterate that
hierarchy. The `UiTextReader::iter` method will give you a normal
iterator over spans, and `UiTextWriter::for_each` lets you visit each of
the spans.

---------

Co-authored-by: ickshonpe <david.curthoys@googlemail.com>
Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2024-10-09 18:35:36 +00:00
Nathan Lilienthal
0b2e0cfaca
bevy_reflect: Add crate level functions feature docs (#15086)
Adds the missing section for the `functions` cargo feature of the
`bevy_reflect` crate.
2024-10-09 18:06:56 +00:00
Tim
e19c53ebbd
Remove Handle<T> trait implementations that are dependent on Component (#15749)
# Objective

- Another step towards #15716
- Remove trait implementations that are dependent on `Handle<T>` being a
`Component`

## Solution

- Remove unused `ExtractComponent` trait implementation for `Handle<T>`
- Remove unused `ExtractInstance` trait implementation for `AssetId`
- Although the `ExtractInstance` trait wasn't used, the `AssetId`s were
being stored inside of `ExtractedInstances` which has an
`ExtractInstance` trait bound on its contents.
I've upgraded the `RenderMaterialInstances` type alias to be its own
resource, identical to `ExtractedInstances<AssetId<M>>` to get around
that with minimal breakage.
## Testing

Tested `many_cubes`, rendering did not explode
2024-10-09 17:12:27 +00:00
Matty
123a19afa9
Put curve-related stuff behind a feature (#15790)
# Objective

A bunch of code is used only if you care about the `Curve` trait. Put it
behind a feature so it can be ignored if wanted.

## Solution

Added a default feature `curve` to `bevy_math` which feature-gates the
`curve` module and internal integrations.

## Testing

Tested compiling with the feature enabled and disabled.
2024-10-09 16:38:23 +00:00
Emerson Coskey
7d40e3ec87
Migrate bevy_sprite to required components (#15489)
# Objective

Continue migration of bevy APIs to required components, following
guidance of https://hackmd.io/@bevy/required_components/

## Solution

- Make `Sprite` require `Transform` and `Visibility` and
`SyncToRenderWorld`
- move image and texture atlas handles into `Sprite`
- deprecate `SpriteBundle`
- remove engine uses of `SpriteBundle`

## Testing

ran cargo tests on bevy_sprite and tested several sprite examples.

---

## Migration Guide

Replace all uses of `SpriteBundle` with `Sprite`. There are several new
convenience constructors: `Sprite::from_image`,
`Sprite::from_atlas_image`, `Sprite::from_color`.

WARNING: use of `Handle<Image>` and `TextureAtlas` as components on
sprite entities will NO LONGER WORK. Use the fields on `Sprite` instead.
I would have removed the `Component` impls from `TextureAtlas` and
`Handle<Image>` except it is still used within ui. We should fix this
moving forward with the migration.
2024-10-09 16:17:26 +00:00
Christian Hughes
219b5930f1
Rename App/World::observe to add_observer, EntityWorldMut::observe_entity to observe. (#15754)
# Objective

- Closes #15752

Calling the functions `App::observe` and `World::observe` doesn't make
sense because you're not "observing" the `App` or `World`, you're adding
an observer that listens for an event that occurs *within* the `World`.
We should rename them to better fit this.

## Solution

Renames:
- `App::observe` -> `App::add_observer`
- `World::observe` -> `World::add_observer`
- `Commands::observe` -> `Commands::add_observer`
- `EntityWorldMut::observe_entity` -> `EntityWorldMut::observe`

(Note this isn't a breaking change as the original rename was introduced
earlier this cycle.)

## Testing

Reusing current tests.
2024-10-09 15:39:29 +00:00
Joona Aalto
a2b53d46e7
Fix meshlet materials (#15755)
# Objective

After #15524, there are these bunny-shaped holes in rendering in the
meshlet example!


![broken](https://github.com/user-attachments/assets/9e9f20ec-b820-44df-b961-68a1dee44002)

This is because (1) they're using a raw asset handle instead of
`MeshMaterial3d`, and (2) the system that extracts mesh materials into
the render world has an unnecessary `With<Mesh3d>` filter, which makes
it not account for meshlets.

## Solution

Remove the redundant filter and use `MeshMaterial3d`. The bunnies got
some paint!


![fixed](https://github.com/user-attachments/assets/adb42556-fd4b-4000-8ca8-1356250dd532)
2024-10-09 15:39:10 +00:00
Zachary Harrold
35edb256ab
Remove thiserror from bevy_asset (#15778)
# Objective

- Contributes to #15460

## Solution

- Removed `thiserror` from `bevy_asset`
2024-10-09 14:30:46 +00:00
Zachary Harrold
ecd04c1b72
Remove thiserror from bevy_sprite (#15763)
# Objective

- Contributes to #15460

## Solution

- Removed `thiserror` from `bevy_sprite`
2024-10-09 14:29:26 +00:00
Zachary Harrold
b50f2ec334
Remove thiserror from bevy_scene (#15764)
# Objective

- Contributes to #15460

## Solution

- Removed `thiserror` from `bevy_scene`
2024-10-09 14:29:10 +00:00
Zachary Harrold
c9e41ef552
Remove thiserror from bevy_ui (#15760)
# Objective

- Contributes to #15460

## Solution

- Removed `thiserror` from `bevy_ui`
2024-10-09 14:27:53 +00:00
Zachary Harrold
bdc649a2d1
Remove thiserror from bevy_transform (#15761)
# Objective

- Contributes to #15460

## Solution

- Removed `thiserror` from `bevy_transform`
2024-10-09 14:27:30 +00:00
Zachary Harrold
8fd3d54e48
Remove thiserror from bevy_text (#15762)
# Objective

- Contributes to #15460

## Solution

- Removed `thiserror` from `bevy_text`
2024-10-09 14:27:09 +00:00
Zachary Harrold
8718adc74f
Remove thiserror from bevy_render (#15765)
# Objective

- Contributes to #15460

## Solution

- Removed `thiserror` from `bevy_render`
2024-10-09 14:26:28 +00:00
Zachary Harrold
3cc1527e9e
Remove thiserror from bevy_reflect (#15766)
# Objective

- Contributes to #15460

## Solution

- Removed `thiserror` from `bevy_reflect`
2024-10-09 14:25:41 +00:00
Zachary Harrold
46ad0b7513
Remove thiserror from bevy_pbr (#15767)
# Objective

- Contributes to #15460

## Solution

- Removed `thiserror` from `bevy_pbr`
2024-10-09 14:25:16 +00:00
Zachary Harrold
80fe269349
Remove thiserror from bevy_mesh (#15768)
# Objective

- Contributes to #15460

## Solution

- Removed `thiserror` from `bevy_mesh`
2024-10-09 14:24:54 +00:00
Zachary Harrold
1f4adec7df
Remove thiserror from bevy_image (#15771)
# Objective

- Contributes to #15460

## Solution

- Removed `thiserror` from `bevy_image`
2024-10-09 14:23:53 +00:00
Zachary Harrold
9366b95006
Remove thiserror from bevy_math (#15769)
# Objective

- Contributes to #15460

## Solution

- Removed `thiserror` from `bevy_math`
2024-10-09 14:23:23 +00:00
Zachary Harrold
5e89acacb4
Remove thiserror from bevy_input (#15770)
# Objective

- Contributes to #15460

## Solution

- Removed `thiserror` from `bevy_input`
2024-10-09 14:23:01 +00:00
Zachary Harrold
f88c6820f0
Remove thiserror from bevy_gltf (#15772)
# Objective

- Contributes to #15460

## Solution

- Removed `thiserror` from `bevy_gltf`
2024-10-09 14:22:00 +00:00
Zachary Harrold
c6a2411e90
Remove thiserror from bevy_gilrs (#15773)
# Objective

- Contributes to #15460

## Solution

- Removed `thiserror` from `bevy_gilrs`
2024-10-09 14:21:25 +00:00
Zachary Harrold
0a61f04d9b
Remove thiserror from bevy_ecs (#15774)
# Objective

- Contributes to #15460

## Solution

- Removed `thiserror` from `bevy_ecs`
2024-10-09 14:20:58 +00:00
Zachary Harrold
4c76ea7a5a
Remove thiserror from bevy_core_pipeline (#15775)
# Objective

- Contributes to #15460

## Solution

- Removed `thiserror` from `bevy_core_pipeline`
2024-10-09 14:20:16 +00:00
Zachary Harrold
284e36af5e
Remove thiserror from bevy_color (#15777)
# Objective

- Contributes to #15460

## Solution

- Removed `thiserror` from `bevy_color`
2024-10-09 14:18:41 +00:00
Zachary Harrold
1be0ed33fc
Remove thiserror from bevy_app (#15779)
# Objective

- Contributes to #15460

## Solution

- Removed `thiserror` from `bevy_app`
2024-10-09 14:17:52 +00:00
Zachary Harrold
814f8ec039
Remove thiserror from bevy_animation (#15780)
# Objective

- Contributes to #15460

## Solution

- Removed `thiserror` from `bevy_animation`
2024-10-09 14:16:21 +00:00
Zachary Harrold
6cc2322fa3
Remove thiserror from bevy_time (#15759)
# Objective

- Contributes to #15460

## Solution

- Removed `thiserror` from `bevy_time`

## Notes

`thiserror` actually wasn't even used in this crate.
2024-10-09 14:13:28 +00:00
ickshonpe
a7ed13ad17
Add register_type for UiAntiAlias (#15783)
# Objective

Add `register_type` for `UiAntiAlias`
2024-10-09 14:04:26 +00:00
Tim
57c297becc
Add register_type for UiMaterialHandle and AnimationGraphHandle (#15784) 2024-10-09 14:04:06 +00:00
Gino Valente
05b0f28ebf
bevy_scene: Use FromReflect on extracted resources (#15753)
# Objective

Fixes #15726

The extraction logic for components makes use of `FromReflect` to try
and ensure we have a concrete type for serialization. However, we did
not do the same for resources.

The reason we're seeing this for the glam types is that #15174 also made
a change to rely on the glam type's `Serialize` and `Deserialize` impls,
which I don't think should have been merged (I'll put up a PR addressing
this specifically soon).

## Solution

Use `FromReflect` on extracted resources.

## Testing

You can test locally by running:

```
cargo test --package bevy_scene
```
2024-10-09 02:56:35 +00:00
Joona Aalto
bc352561c9
Migrate reflection probes to required components (#15737)
# Objective

Getting closer to the end! Another part of the required components
migration: reflection probes.

## Solution

As per the [proposal added by
Cart](https://hackmd.io/@bevy/required_components/%2FNmpIh0tGSiayGlswbfcEzw)
(Proposal 2), make `LightProbe` require `Transform` and `Visibility`,
and deprecate `ReflectionProbeBundle`.

Note that this proposal wasn't officially blessed yet, but it is the
only existing one that really works, so I implemented it here for
consideration.

## Testing

I ran the reflection probe example, and it appears to work.

---

## Migration Guide

`ReflectionProbeBundle` has been deprecated in favor of inserting the
`LightProbe` and `EnvironmentMapLight` components directly. Inserting
them will now automatically insert `Transform` and `Visibility`
components.

---------

Co-authored-by: Tim Blackbird <justthecooldude@gmail.com>
Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
2024-10-08 23:59:27 +00:00
Shoyu Vanilla (Flint)
a89ae8e9d9
fix: Skip some rendering logics when the viewport width or height is zero (#15654)
# Objective

- Fixes #15285

## Solution

`winit` sends resized to zero events when the window is minimized only
on Windows OS(rust-windowing/winit#2015).
This makes updating window viewport size to `(0, 0)` and panicking when
calculating aspect ratio.

~~So, just skip these kinds of events - resizing to (0, 0) when the
window is minimized - on Windows OS~~

Idially, the camera extraction excludes the cameras whose target size
width or height is zero here;


25bfa80e60/crates/bevy_render/src/camera/camera.rs (L1060-L1074)

but it seems that winit event loop sends resize events after extraction
and before post update schedule, so they might panics before the
extraction filters them out.

Alternatively, it might be possible to change event loop evaluating
order or defer them to the right schedule but I'm afraid that it might
cause some breaking changes, so just skip rendering logics for such
windows and they will be all filtered out by the extractions on the next
frame and thereafter.

## Testing

Running the example in the original issue and minimizing causes panic,
or just running `tests/window/minimising.rs` with `cargo run --example
minimising` panics without this PR and doesn't panics with this PR.

I think that we should run it in CI on Windows OS btw
2024-10-08 22:52:19 +00:00
Antony
0837ade0fc
Ensure Bevy's rendering byte usage is little-endian (#15750)
# Objective

- Fixes (partially) #15701.

## Solution

- Use little-endian bytes over native-endian bytes where applicable.

## Testing

- Ran CI.

## Open Questions

- Should we config-gate these for big-endian targets? It looks like
there are [very few
targets](https://doc.rust-lang.org/nightly/rustc/platform-support.html)
that use big-endian.
2024-10-08 22:43:35 +00:00
Tim
700123ec64
Replace Handle<AnimationGraph> component with a wrapper (#15742)
# Objective

- Closes #15717 

## Solution

- Wrap the handle in a new wrapper component: `AnimationGraphHandle`.

## Testing

Searched for all instances of `AnimationGraph` in the examples and
updated and tested those

## Migration Guide

`Handle<AnimationGraph>` is no longer a component. Instead, use the
`AnimationGraphHandle` component which contains a
`Handle<AnimationGraph>`.
2024-10-08 22:41:24 +00:00
papow65
01b37d67fc
Fix failing cargo check with only the bevy_dev_tools feature (#15743)
# Objective
Fixes #15741

## Solution

- Copied the feature gates of a type to where the type is used.

## Testing

- `cargo check` works now using only the bevy_dev_tools feature
2024-10-08 22:41:04 +00:00
IceSentry
dec52a0c8f
Use shader_def for oit resolve layer count (#15747)
# Objective

- Size is currently hardcoded in the shader which means it will break if
a user uses anything higher than that.

## Solution

- Use a shader_def to define the size

## Testing

Tested with the OIT example
2024-10-08 22:40:17 +00:00
ickshonpe
675f8ad403
Improved text batching (#14848)
# Objective

The UI text rendering is really slow because it extracts each glyph as a
separate ui node even though all the glyphs in a text section have the
same texture, color and clipping rects.

## Solution

Store the glyphs in a seperate contiguous array, queue one transparent
ui item per text section which has indices into the glyph array.

## Testing

```cargo run --example many_glyphs --release```

Runs at about 22fps on main and 95fps with this PR on my computer.

I'll do some proper comparisons once I work out why tracy 11 is refusing to run.

---------

Co-authored-by: Kristoffer Søholm <k.soeholm@gmail.com>
2024-10-08 22:24:27 +00:00
Kristoffer Søholm
2d1b4939d2
Synchronize removed components with the render world (#15582)
# Objective

Fixes #15560
Fixes (most of) #15570

Currently a lot of examples (and presumably some user code) depend on
toggling certain render features by adding/removing a single component
to an entity, e.g. `SpotLight` to toggle a light. Because of the
retained render world this no longer works: Extract will add any new
components, but when it is removed the entity persists unchanged in the
render world.

## Solution

Add `SyncComponentPlugin<C: Component>` that registers
`SyncToRenderWorld` as a required component for `C`, and adds a
component hook that will clear all components from the render world
entity when `C` is removed. We add this plugin to
`ExtractComponentPlugin` which fixes most instances of the problem. For
custom extraction logic we can manually add `SyncComponentPlugin` for
that component.

We also rename `WorldSyncPlugin` to `SyncWorldPlugin` so we start a
naming convention like all the `Extract` plugins.

In this PR I also fixed a bunch of breakage related to the retained
render world, stemming from old code that assumed that `Entity` would be
the same in both worlds.

I found that using the `RenderEntity` wrapper instead of `Entity` in
data structures when referring to render world entities makes intent
much clearer, so I propose we make this an official pattern.

## Testing

Run examples like

```
cargo run --features pbr_multi_layer_material_textures --example clearcoat
cargo run --example volumetric_fog
```

and see that they work, and that toggles work correctly. But really we
should test every single example, as we might not even have caught all
the breakage yet.

---

## Migration Guide

The retained render world notes should be updated to explain this edge
case and `SyncComponentPlugin`

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
Co-authored-by: Trashtalk217 <trashtalk217@gmail.com>
2024-10-08 22:23:17 +00:00
François Mockers
45eff09213
remove the interpolation dependency from bevy_math (#15748)
# Objective

- `interpolation` crates provides all the curves functions, but some of
them were wrong
- We have a partial solution where some functions comes from the
external crate, some from bevy_math

## Solution

- Move them all to bevy_math
- Remove the dependency on `interpolation`

## Testing

Playing the `easing_functions` example

![easing-functions](https://github.com/user-attachments/assets/88832f34-4bb3-4dc2-85af-7b9e4fa23e52)
2024-10-08 22:18:25 +00:00
Alice Cecile
2f63ebc9c9
Remove warning for children in UI hierarchies without Style (#15736)
# Objective

As discussed in #15591, this warning prevents us from storing leaf nodes
without a `Style` component. Because text sections (as distinct
entities) should not be laid out using `taffy`, this warning is
incorrect.

Users may also have other uses for doing this, and this should generally
increase flexibility without posing particularly serious correctness
concerns.

## Solution

- removed warning about non-UI children with UI parents
- improved the warning about UI parents with non-UI parents
- this warning should stay, for now, as it results in a genuine failure
to perform `taffy` layout
- that said, we should be clearer about the cause and potentially
harmful results of this!
   
## Testing

I inserted an empty entity into the hierarchy in the `button` example as
a leaf node, and it ran with no warnings.
2024-10-08 19:51:47 +00:00
Matty
e563f86a1d
Simplified easing curves (#15711)
# Objective

Simplify the API surrounding easing curves. Broaden the base of types
that support easing.

## Solution

There is now a single library function, `easing_curve`, which constructs
a unit-parametrized easing curve between two values based on an
`EaseFunction`:
```rust
/// Given a `start` and `end` value, create a curve parametrized over [the unit interval]
/// that connects them, using the given [ease function] to determine the form of the
/// curve in between.
///
/// [the unit interval]: Interval::UNIT
/// [ease function]: EaseFunction
pub fn easing_curve<T: Ease>(start: T, end: T, ease_fn: EaseFunction) -> EasingCurve<T> { //... }
```

As this shows, the type of the output curve is generic only in `T`. In
particular, as long as `T` is `Reflect` (and `FromReflect` etc. — i.e.,
a standard "well-behaved" reflectable type), `EasingCurve<T>` is also
`Reflect`, and there is no special field handling nonsense. Therefore,
`EasingCurve` is the kind of thing that would be able to be easily
changed in an editor. This is made possible by storing the actual
`EaseFunction` on `EasingCurve<T>` instead of indirecting through some
kind of function type (which generally leads to issues with reflection).

The types that can be eased are those that implement a trait `Ease`:
```rust
/// A type whose values can be eased between.
///
/// This requires the construction of an interpolation curve that actually extends
/// beyond the curve segment that connects two values, because an easing curve may
/// extrapolate before the starting value and after the ending value. This is
/// especially common in easing functions that mimic elastic or springlike behavior.
pub trait Ease: Sized {
    /// Given `start` and `end` values, produce a curve with [unlimited domain]
    /// that:
    /// - takes a value equivalent to `start` at `t = 0`
    /// - takes a value equivalent to `end` at `t = 1`
    /// - has constant speed everywhere, including outside of `[0, 1]`
    ///
    /// [unlimited domain]: Interval::EVERYWHERE
    fn interpolating_curve_unbounded(start: &Self, end: &Self) -> impl Curve<Self>;
}
```

(I know, I know, yet *another* interpolation trait. See 'Future
direction'.)

The other existing easing functions from the previous version of this
module have also become new members of `EaseFunction`: `Linear`,
`Steps`, and `Elastic` (which maybe needs a different name). The latter
two are parametrized.

## Testing

Tested using the `easing_functions` example. I also axed the
`cubic_curve` example which was of questionable value and replaced it
with `eased_motion`, which uses this API in the context of animation:


https://github.com/user-attachments/assets/3c802992-6b9b-4b56-aeb1-a47501c29ce2


---

## Future direction

Morally speaking, `Ease` is incredibly similar to `StableInterpolate`.
Probably, we should just merge `StableInterpolate` into `Ease`, and then
make `SmoothNudge` an automatic extension trait of `Ease`. The reason I
didn't do that is that `StableInterpolate` is not implemented for
`VectorSpace` because of concerns about the `Color` types, and I wanted
to avoid controversy. I think that may be a good idea though.

As Alice mentioned before, we should also probably get rid of the
`interpolation` dependency.

The parametrized `Elastic` variant probably also needs some additional
work (e.g. renaming, in/out/in-out variants, etc.) if we want to keep
it.
2024-10-08 19:45:13 +00:00
Tim
9aef71bd9b
Replace Handle<M: UiMaterial> component with UiMaterialHandle wrapper (#15740)
# Objective

- Closes #15720

## Solution

Wrap the handle in a new wrapper component: `UiMaterialHandle`
It's not possible to match the naming convention of `MeshMaterial3d/2d`
here with the trait already being called `UiMaterial`

Should we consider renaming to `Material3d/2dHandle` and `Mesh3d/2d` to
`Mesh3d/2dHandle`?

- This shouldn't have any merge conflicts with #15591

## Testing

Tested the `ui_material` example

## Migration Guide

Let's defer the migration guide to the required component port. I just
want to yeet the `Component` impl on `Handle` in the meantime :)
2024-10-08 19:07:58 +00:00
JMS55
aa626e4f0b
Per-meshlet compressed vertex data (#15643)
# Objective
- Prepare for streaming by storing vertex data per-meshlet, rather than
per-mesh (this means duplicating vertices per-meshlet)
- Compress vertex data to reduce the cost of this

## Solution
The important parts are in from_mesh.rs, the changes to the Meshlet type
in asset.rs, and the changes in meshlet_bindings.wgsl. Everything else
is pretty secondary/boilerplate/straightforward changes.

- Positions are quantized in centimeters with a user-provided power of 2
factor (ideally auto-determined, but that's a TODO for the future),
encoded as an offset relative to the minimum value within the meshlet,
and then stored as a packed list of bits using the minimum number of
bits needed for each vertex position channel for that meshlet
- E.g. quantize positions (lossly, throws away precision that's not
needed leading to using less bits in the bitstream encoding)
- Get the min/max quantized value of each X/Y/Z channel of the quantized
positions within a meshlet
- Encode values relative to the min value of the meshlet. E.g. convert
from [min, max] to [0, max - min]
- The new max value in the meshlet is (max - min), which only takes N
bits, so we only need N bits to store each channel within the meshlet
(lossless)
- We can store the min value and that it takes N bits per channel in the
meshlet metadata, and reconstruct the position from the bitstream
- Normals are octahedral encoded and than snorm2x16 packed and stored as
a single u32.
- Would be better to implement the precise variant of octhedral encoding
for extra precision (no extra decode cost), but decided to keep it
simple for now and leave that as a followup
- Tried doing a quantizing and bitstream encoding scheme like I did for
positions, but struggled to get it smaller. Decided to go with this for
simplicity for now
- UVs are uncompressed and take a full 64bits per vertex which is
expensive
  - In the future this should be improved
- Tangents, as of the previous PR, are not explicitly stored and are
instead derived from screen space gradients
- While I'm here, split up MeshletMeshSaverLoader into two separate
types

Other future changes include implementing a smaller encoding of triangle
data (3 u8 indices = 24 bits per triangle currently), and more
disk-oriented compression schemes.

References:
* "A Deep Dive into UE5's Nanite Virtualized Geometry"
https://advances.realtimerendering.com/s2021/Karis_Nanite_SIGGRAPH_Advances_2021_final.pdf#page=128
(also available on youtube)
* "Towards Practical Meshlet Compression"
https://arxiv.org/pdf/2404.06359
* "Vertex quantization in Omniforce Game Engine"
https://daniilvinn.github.io/2024/05/04/omniforce-vertex-quantization.html

## Testing

- Did you test these changes? If so, how?
- Converted the stanford bunny, and rendered it with a debug material
showing normals, and confirmed that it's identical to what's on main.
EDIT: See additional testing in the comments below.
- Are there any parts that need more testing?
- Could use some more size comparisons on various meshes, and testing
different quantization factors. Not sure if 4 is a good default. EDIT:
See additional testing in the comments below.
- Also did not test runtime performance of the shaders. EDIT: See
additional testing in the comments below.
- How can other people (reviewers) test your changes? Is there anything
specific they need to know?
- Use my unholy script, replacing the meshlet example
https://paste.rs/7xQHk.rs (must make MeshletMesh fields pub instead of
pub crate, must add lz4_flex as a dev-dependency) (must compile with
meshlet and meshlet_processor features, mesh must have only positions,
normals, and UVs, no vertex colors or tangents)

---

## Migration Guide
- TBD by JMS55 at the end of the release
2024-10-08 18:42:55 +00:00
Joona Aalto
f6cd6a4874
Use Dir2/Dir3 instead of Vec2/Vec3 for Ray2d::new/Ray3d::new (#15735)
# Objective

The `new` constructors for our ray types currently take a `Vec2`/`Vec3`
instead of a `Dir2`/`Dir3`. This is confusing and footgunny for several
reasons.

- Which one of these is the direction? You can't see it from the type.

```rust
let ray = Ray2d::new(Vec2::X, Vec2::X);
```

- Many engines allow unnormalized rays, and this can affect ray cast
results by scaling the time of impact. However, in Bevy, rays are
*always* normalized despite what the input argument in this case
implies, and ray cast results are *not* scaled.

```rust
// The true ray direction is still normalized, unlike what you'd expect.
let ray = Ray2d::new(Vec2::X, Vec2::new(5.0, 0.0, 0.0)));
```

These cases are what the direction types are intended for, and we should
use them as such.

## Solution

Use `Dir2`/`Dir3` in the constructors.

```rust
let ray = Ray2d::new(Vec2::X, Dir2::X);
```

We *could* also use `impl TryInto<DirN>`, which would allow both vectors
and direction types, and then panic if the input is not normalized. This
could be fine for ergonomics in some cases, but especially for rays, I
think it's better to take an explicit direction type here.

---

## Migration Guide

`Ray2d::new` and `Ray3d::new` now take a `Dir2` and `Dir3` instead of
`Vec2` and `Vec3` respectively for the ray direction.
2024-10-08 16:45:03 +00:00
Isse
82aa2e3161
Add the functions start_drag_move and start_drag_resize to Window (#15674)
# Objective
Expose the `winit` functions
[drag_window](https://docs.rs/winit/latest/winit/window/struct.Window.html#method.drag_window)
and
[resize_window](https://docs.rs/winit/latest/winit/window/struct.Window.html#method.drag_resize_window).

Which allows implementing move & resize for windows without decorations.

## Solution

Add the functions `start_drag_move` and `start_drag_resize` to
`bevy_window::Window`, which are then assigned to fields in
`InternalWindowState`, and propagated to `winit` in the
`changed_windows` system.

## Testing

I've tested that both functions works on x11 and wayland. Not sure if
someone needs to test on windows/mac?

---

## Showcase

[Screencast from 2024-10-06 11-49-58
(trimmed).webm](https://github.com/user-attachments/assets/1cdee7b1-22bd-41d3-8a0a-6872a6ebf62c)

(The flickering in the video is some issue with resizing without
decorations on x11)

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

Not the same code used in the video, but simple way to test moving a
window without decorations.
```rust
use bevy::prelude::*;

fn main() {
    App::new()
        .add_plugins(DefaultPlugins.set(WindowPlugin {
            primary_window: Some(Window {
                decorations: false,
                ..default()
            }),
            ..default()
        }))
        .add_systems(Update, move_windows)
        .run();
}

fn move_windows(mut windows: Query<&mut Window>, input: Res<ButtonInput<MouseButton>>) {
    if input.pressed(MouseButton::Left) {
        for mut window in windows.iter_mut() {
            window.start_drag_move();
        }
    }
}
```

</details>

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
2024-10-08 16:32:07 +00:00
ickshonpe
99b9a2fcd7
box shadow (#15204)
# Objective

UI box shadow support

Adds a new component `BoxShadow`:

```rust
pub struct BoxShadow {
    /// The shadow's color
    pub color: Color,
    /// Horizontal offset
    pub x_offset: Val,
    /// Vertical offset
    pub y_offset: Val,
    /// Horizontal difference in size from the occluding uninode
    pub spread_radius: Val,
    /// Blurriness of the shadow
    pub blur_radius: Val,
}
```

To use `BoxShadow`, add the component to any Bevy UI node and a shadow
will be drawn beneath that node.
Also adds a resource `BoxShadowSamples` that can be used to adjust the
shadow quality.

#### Notes
* I'm not super happy with the field names. Maybe we need a `struct Size
{ width: Val, height: Val }` type or something.
* The shader isn't very optimised but I don't see that it's too
important for now as the number of shadows being rendered is not going
to be massive most of the time. I think it's more important to get the
API and geometry correct with this PR.
* I didn't implement an inset property, it's not essential and can
easily be added in a follow up.
* Shadows are only rendered for uinodes, not for images or text.
* Batching isn't supported, it would need out-of-the-scope-of-this-pr
changes to the way the UI handles z-ordering for it to be effective.

# Showcase

```cargo run --example box_shadow -- --samples 4```

<img width="391" alt="br" src="https://github.com/user-attachments/assets/4e8add96-dc93-46e0-9e35-d995eb0943ad">

```cargo run --example box_shadow -- --samples 10```

<img width="391" alt="s10"
src="https://github.com/user-attachments/assets/ecb384c9-4012-4cd6-9dea-5180904bf28e">
2024-10-08 16:26:17 +00:00
Liam Gallagher
f1fbb668f9
Watching versions of bevy/get and bevy/list with HTTP SSE (#15608)
## Objective

Add a way to stream BRP requests when the data changes.

## Solution

#### BRP Side (reusable for other transports)

Add a new method handler type that returns a optional value. This
handler is run in update and if a value is returned it will be sent on
the message channel. Custom watching handlers can be added with
`RemotePlugin::with_watching_method`.

#### HTTP Side

If a request comes in with `+watch` in the method, it will respond with
`text/event-stream` rather than a single response.

## Testing

I tested with the podman HTTP client. This client has good support for
SSE's if you want to test it too.

## Parts I want some opinions on

- For separating watching methods I chose to add a `+watch` suffix to
the end kind of like `content-type` headers. A get would be
`bevy/get+watch`.
- Should watching methods send an initial response with everything or
only respond when a change happens? Currently the later is what happens.

## Future work

- The `bevy/query` method would also benefit from this but that
condition will be quite complex so I will leave that to later.

---------

Co-authored-by: Zachary Harrold <zac@harrold.com.au>
2024-10-08 16:21:46 +00:00
Joona Aalto
21b78b5990
Implement From translation and rotation for isometries (#15733)
# Objective

Several of our APIs (namely gizmos and bounding) use isometries on
current Bevy main. This is nicer than separate properties in a lot of
cases, but users have still expressed usability concerns.

One problem is that in a lot of cases, you only care about e.g.
translation, so you end up with this:

```rust
gizmos.cross_2d(
    Isometry2d::from_translation(Vec2::new(-160.0, 120.0)),
    12.0,
    FUCHSIA,
);
```

The isometry adds quite a lot of length and verbosity, and isn't really
that relevant since only the translation is important here.

It would be nice if you could use the translation directly, and only
supply an isometry if both translation and rotation are needed. This
would make the following possible:

```rust
gizmos.cross_2d(Vec2::new(-160.0, 120.0), 12.0, FUCHSIA);
```

removing a lot of verbosity.

## Solution

Implement `From<Vec2>` and `From<Rot2>` for `Isometry2d`, and
`From<Vec3>`, `From<Vec3A>`, and `From<Quat>` for `Isometry3d`. These
are lossless conversions that fit the semantics of `From`.

This makes the proposed API possible! The methods must now simply take
an `impl Into<IsometryNd>`, and this works:

```rust
gizmos.cross_2d(Vec2::new(-160.0, 120.0), 12.0, FUCHSIA);
```
2024-10-08 16:09:28 +00:00
Peter Hayman
1c3dee4a6c
fix: register_type::<ScrollPosition> (#15721)
# Objective

- register types that derive reflect.
2024-10-08 16:07:09 +00:00
Tomi Fontanilles
3d8e56f766
introduction of ConvexPolygon and ConvexPolygonMeshBuilder (#15544)
# Objective

- As discussed on
[Discord](https://discord.com/channels/691052431525675048/1203087353850364004/1285300659746246849),
implement a `ConvexPolygon` 2D math primitive and associated mesh
builder.
- The original goal was to have a mesh builder for the simplest (i.e.
convex) polygons.

## Solution

- The `ConvexPolygon` is created from its vertices.
- The convexity of the polygon is checked when created via `new()` by
verifying that the winding order of all the triangles formed with
adjacent vertices is the same.
- The `ConvexPolygonMeshBuilder` uses an anchor vertex and goes through
every adjacent pair of vertices in the polygon to form triangles that
fill up the polygon.

## Testing

- Tested locally with my own simple `ConvexPolygonMeshBuilder` usage.
2024-10-08 15:02:38 +00:00
charlotte
b48f9e2a4b
Fix oit webgl (#15728)
The previous fixes were breaking pretty much everything on main due to
naga-oil complaining about the OIT shader not being loaded, since
apparently webgl is a default feature. This fix is a bit messier, but
properly warns the user and is probably what we should have gone for in
the first place.
2024-10-08 14:50:35 +00:00
Patrick Walton
48e2027827
Add some missing features from the gamepads-as-entities change that were needed to update leafwing-input-manager. (#15685)
The gamepads-as-entities change caused several regressions. This patch
fixes each of them:

1. This PR introduces two new fields on `GamepadInfo`: `vendor_id`, and
`product_id`, as well as associated methods. These fields are simply
mirrored from the `gilrs` library.

2. That PR removed the methods that allowed iterating over all pressed
and released buttons, as well as the method that allowed iterating over
the axis values. (It was still technically possible to do so by using
reflection to access the private fields of `Gamepad`.)

3. The `Gamepad` component wasn't marked reflectable. This PR fixes that
problem.

These changes allowed me to forward port `leafwing-input-manager`.
2024-10-08 12:19:38 +00:00
IceSentry
4bf647ff3b
Add Order Independent Transparency (#14876)
# Objective

- Alpha blending can easily fail in many situations and requires sorting
on the cpu

## Solution

- Implement order independent transparency (OIT) as an alternative to
alpha blending
- The implementation uses 2 passes
- The first pass records all the fragments colors and position to a
buffer that is the size of N layers * the render target resolution.
- The second pass sorts the fragments, blends them and draws them to the
screen. It also currently does manual depth testing because early-z
fails in too many cases in the first pass.

## Testing

- We've been using this implementation at foresight in production for
many months now and we haven't had any issues related to OIT.

---

## Showcase


![image](https://github.com/user-attachments/assets/157f3e32-adaf-4782-b25b-c10313b9bc43)

![image](https://github.com/user-attachments/assets/bef23258-0c22-4b67-a0b8-48a9f571c44f)

## Future work

- Add an example showing how to use OIT for a custom material
- Next step would be to implement a per-pixel linked list to reduce
memory use
- I'd also like to investigate using a BinnedRenderPhase instead of a
SortedRenderPhase. If it works, it would make the transparent pass
significantly faster.

---------

Co-authored-by: Kristoffer Søholm <k.soeholm@gmail.com>
Co-authored-by: JMS55 <47158642+JMS55@users.noreply.github.com>
Co-authored-by: Charlotte McElwain <charlotte.c.mcelwain@gmail.com>
2024-10-07 23:50:28 +00:00
notmd
cab00766d9
Serialize and deserialize tuple struct with one field as newtype struct (#15628)
# Objective

- fix https://github.com/bevyengine/bevy/issues/15623
## Solution

- Checking field length of tuple struct before ser/der

## Testing

- CI should pass

## Migration Guide

- Reflection now will serialize and deserialize tuple struct with single
field as newtype struct. Consider this code.
```rs
#[derive(Reflect, Serialize)]
struct Test(usize);
let reflect = Test(3);
let serializer = TypedReflectSerializer::new(reflect.as_partial_reflect(), &registry);
return serde_json::to_string(&serializer)
```
Old behavior will return `["3"]`. New behavior will return `"3"`. If you
were relying on old behavior you need to update your logic. Especially
with `serde_json`. `ron` doesn't affect from this.
2024-10-07 23:40:03 +00:00
Matty
9b863be2fb
Curves: FromReflect boogaloo part 2 (#15714)
# Objective

Allow curve adaptors to be reliably `Reflect` even if the curves they
hold are not `FromReflect`. This allows them, for example, to be used in
`bevy_animation`. I previously addressed this with the functional
adaptors, but I forgot to address this in the case of fields that hold
other curves and not arbitrary functions.

## Solution

Do the following on every curve adaptor that holds another curve:
```rust
// old:
#[derive(Reflect)]
```

```rust
// new:
#[derive(Reflect, FromReflect)]
#[reflect(from_reflect = false)]
```

This looks inane, but it's necessary because the default
`#[derive(Reflect)]` macro places `FromReflect` bounds on everything. To
avoid this, we opt out of deriving `FromReflect` with that macro by
adding `#[reflect(from_reflect = false)]`, then separately derive
`FromReflect`. (Of course, the latter still has the `FromReflect`
bounds, which is fine.)
2024-10-07 22:59:17 +00:00
Tim
bef44d7ac2
Stop using Handle<T> as a component in bevy_gizmos (#15713)
# Objective

- Another step towards removing the `Component` impl on `Handle<T>`

## Solution

- Yeet
2024-10-07 22:57:26 +00:00
François Mockers
1869e45c49
fix some of the ease functions from interpolation (#15706)
# Objective

- Followup to #15675
- Some of the functions are wrong, noticed in #15703: `Sine`, `Elastic`
and `Back`

## Solution

- Fix them and make them deterministic


![ease-fixed-functions](https://github.com/user-attachments/assets/8a4d5c0c-36fa-4a49-a189-5b832dc24721)
2024-10-07 19:08:32 +00:00
Tim
d454db8e58
Rename the Pickable component and fix incorrect documentation (#15707)
# Objective

- Rename `Pickable` to `PickingBehavior` to counter the easily-made
assumption that the component is required. It is optional
- Fix and clarify documentation
- The docs in `crates/bevy_ui/src/picking_backend.rs` were incorrect
about the necessity of `Pickable`
- Plus two minor code quality changes in this commit
(7c2e75f48d)

Closes #15632
2024-10-07 17:09:57 +00:00
Clar Fon
8adc9e9d6e
Feature-gate all image formats (#15586)
# Objective

Bevy supports feature gates for each format it supports, but several
formats that it loads via the `image` crate do not have feature gates.
Additionally, the QOI format is supported by the `image` crate and
wasn't available at all. This fixes that.

## Solution

The following feature gates are added:

* `avif`
* `ff` (Farbfeld)
* `gif`
* `ico`
* `qoi`
* `tiff`

None of these formats are enabled by default, despite the fact that all
these formats appeared to be enabled by default before. Since
`default-features` was disabled for the `image` crate, it's likely that
using any of these formats would have errored by default before this
change, although this probably needs additional testing.

## Testing

The changes seemed minimal enough that a compile test would be
sufficient.

## Migration guide

Image formats that previously weren't feature-gated are now
feature-gated, meaning they will have to be enabled if you use them:

* `avif`
* `ff` (Farbfeld)
* `gif`
* `ico`
* `tiff`

Additionally, the `qoi` feature has been added to support loading QOI
format images.

Previously, these formats appeared in the enum by default, but weren't
actually enabled via the `image` crate, potentially resulting in weird
bugs. Now, you should be able to add these features to your projects to
support them properly.
2024-10-07 16:37:45 +00:00
Patrick Walton
0a1d60f3b0
Fix a system ordering issue with motion blur for skinned meshes. (#15693)
Currently, it's possible for the `collect_meshes_for_gpu_building`
system to run after `set_mesh_motion_vector_flags`. This will cause
those motion vector flags to be overwritten, which will cause the shader
to ignore the motion vectors for skinned meshes, which will cause
graphical artifacts.

This patch corrects the issue by forcing `set_mesh_motion_vector_flags`
to run after `collect_meshes_for_gpu_building`.
2024-10-07 16:33:15 +00:00
Gino Valente
8039f34b0d
bevy_ecs: Replace panics in QueryData derive compile errors (#15691)
# Objective

The current `QueryData` derive panics when it encounters an error.
Additionally, it doesn't provide the clearest error message:

```rust
#[derive(QueryData)]
#[query_data(mut)]
struct Foo {
    // ...
}
```

```
error: proc-macro derive panicked
  --> src/foo.rs:16:10
   |
16 | #[derive(QueryData)]
   |          ^^^^^^^^^
   |
   = help: message: Invalid `query_data` attribute format
```

## Solution

Updated the derive logic to not panic and gave a bit more detail in the
error message.

This is makes the error message just a bit clearer and maintains the
correct span:

```
error: invalid attribute, expected `mutable` or `derive`
  --> src/foo.rs:17:14
   |
17 | #[query_data(mut)]
   |              ^^^
```

## Testing

You can test locally by running the following in
`crates/bevy_ecs/compile_fail`:

```
cargo test --target-dir ../../../target
```
2024-10-07 16:30:34 +00:00
Emerson Coskey
d1927736de
Migrate bevy picking (#15690)
# Objective

Migrate `bevy_picking` to the required components API

## Solution
- Made `PointerId` require `PointerLocation`, `PointerPress`, and
`PointerInteraction`
- Removed `PointerBundle`
- Removed all engine uses of `PointerBundle`

- Added convenience constructor `PointerLocation::new(location:
Location)`

## Testing

- ran unit tests
- ran `sprite_picking` example, everything seemed fine.

## Migration Guide

This API hasn't shipped yet, so I didn't bother with a deprecation.
However, for any crates tracking main the changes are as follows:

Previous api:
```rs
commands.insert(PointerBundle::new(PointerId::Mouse));
commands.insert(PointerBundle::new(PointerId::Mouse).with_location(location));
```

New api:
```rs
commands.insert(PointerId::Mouse);
commands.insert((PointerId::Mouse, PointerLocation::new(location)));
```
2024-10-07 16:26:37 +00:00
Trashtalk217
d1bd46d45e
Deprecate get_or_spawn (#15652)
# Objective

After merging retained rendering world #15320, we now have a good way of
creating a link between worlds (*HIYAA intensifies*). This means that
`get_or_spawn` is no longer necessary for that function. Entity should
be opaque as the warning above `get_or_spawn` says. This is also part of
#15459.

I'm deprecating `get_or_spawn_batch` in a different PR in order to keep
the PR small in size.

## Solution

Deprecate `get_or_spawn` and replace it with `get_entity` in most
contexts. If it's possible to query `&RenderEntity`, then the entity is
synced and `render_entity.id()` is initialized in the render world.

## Migration Guide

If you are given an `Entity` and you want to do something with it, use
`Commands.entity(...)` or `World.entity(...)`. If instead you want to
spawn something use `Commands.spawn(...)` or `World.spawn(...)`. If you
are not sure if an entity exists, you can always use `get_entity` and
match on the `Option<...>` that is returned.

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
2024-10-07 16:08:22 +00:00
charlotte
037464800e
Use global clear color for camera driver node. (#15688)
When no cameras are configured, the `ClearColor` resource has no effect
on the default window.

Fixes
https://discord.com/channels/691052431525675048/866787577687310356/1292601838075379796


![image](https://github.com/user-attachments/assets/f42479c0-b239-4660-acd0-daa859b1f815)

![image](https://github.com/user-attachments/assets/4d625960-f105-4a29-91a3-44f4baadac30)
2024-10-07 15:59:51 +00:00
François Mockers
4357539e06
Add most common interpolations (#15675)
# Objective

- Followup for #14788 
- Support most usual ease function

## Solution

- Use the crate
[`interpolation`](https://docs.rs/interpolation/0.3.0/interpolation/trait.Ease.html)
which has them all
- it's already used by bevy_easings, bevy_tweening, be_tween,
bevy_tweening_captured, bevy_enoki, kayak_ui in the Bevy ecosystem for
various easing/tweening/interpolation
2024-10-07 15:56:06 +00:00
Alice Cecile
0a150b0d22
Add more tools for traversing hierarchies (#15627)
# Objective

- Working with hierarchies in Bevy is far too tedious due to a lack of
helper functions.
- This is the first half of #15609. 

## Solution

Extend
[`HierarchyQueryExt`](https://docs.rs/bevy/latest/bevy/hierarchy/trait.HierarchyQueryExt)
with the following methods:

- `parent`
- `children`
- `root_parent`
- `iter_leaves`
- `iter_siblings`
- `iter_descendants_depth_first`

I've opted to make both `iter_leaves` and `iter_siblings` collect the
list of matching Entities for now, rather that operate by reference like
the existing `iter_descendants`. This was simpler, and in the case of
`iter_siblings` especially, the number of matching entities is likely to
be much smaller.

I've kept the generics in the type signature however, so we can go back
and optimize that freely without a breaking change whenever we want.

## Testing

I've added some basic testing, but they're currently failing. If you'd
like to help, I'd welcome suggestions or a PR to my PR over the weekend
<3

---------

Co-authored-by: Viktor Gustavsson <villor94@gmail.com>
Co-authored-by: poopy <gonesbird@gmail.com>
Co-authored-by: Christian Hughes <9044780+ItsDoot@users.noreply.github.com>
2024-10-07 15:24:57 +00:00
Christian Hughes
584d14808a
Allow World::entity family of functions to take multiple entities and get multiple references back (#15614)
# Objective

Following the pattern established in #15593, we can reduce the API
surface of `World` by providing a single function to grab both a
singular entity reference, or multiple entity references.

## Solution

The following functions can now also take multiple entity IDs and will
return multiple entity references back:
- `World::entity`
- `World::get_entity`
- `World::entity_mut`
- `World::get_entity_mut`
- `DeferredWorld::entity_mut`
- `DeferredWorld::get_entity_mut`

If you pass in X, you receive Y:
- give a single `Entity`, receive a single `EntityRef`/`EntityWorldMut`
(matches current behavior)
- give a `[Entity; N]`/`&[Entity; N]` (array), receive an equally-sized
`[EntityRef; N]`/`[EntityMut; N]`
- give a `&[Entity]` (slice), receive a
`Vec<EntityRef>`/`Vec<EntityMut>`
- give a `&EntityHashSet`, receive a
`EntityHashMap<EntityRef>`/`EntityHashMap<EntityMut>`

Note that `EntityWorldMut` is only returned in the single-entity case,
because having multiple at the same time would lead to UB. Also,
`DeferredWorld` receives an `EntityMut` in the single-entity case
because it does not allow structural access.

## Testing

- Added doc-tests on `World::entity`, `World::entity_mut`, and
`DeferredWorld::entity_mut`
- Added tests for aliased mutability and entity existence

---

## Showcase

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

The APIs for fetching `EntityRef`s and `EntityMut`s from the `World`
have been unified.

```rust
// This code will be referred to by subsequent code blocks.
let world = World::new();
let e1 = world.spawn_empty().id();
let e2 = world.spawn_empty().id();
let e3 = world.spawn_empty().id();
```

Querying for a single entity remains mostly the same:

```rust
// 0.14
let eref: EntityRef = world.entity(e1);
let emut: EntityWorldMut = world.entity_mut(e1);
let eref: Option<EntityRef> = world.get_entity(e1);
let emut: Option<EntityWorldMut> = world.get_entity_mut(e1);

// 0.15
let eref: EntityRef = world.entity(e1);
let emut: EntityWorldMut = world.entity_mut(e1);
let eref: Result<EntityRef, Entity> = world.get_entity(e1);
let emut: Result<EntityWorldMut, Entity> = world.get_entity_mut(e1);
```

Querying for multiple entities with an array has changed:

```rust
// 0.14
let erefs: [EntityRef; 2] = world.many_entities([e1, e2]);
let emuts: [EntityMut; 2] = world.many_entities_mut([e1, e2]);
let erefs: Result<[EntityRef; 2], Entity> = world.get_many_entities([e1, e2]);
let emuts: Result<[EntityMut; 2], QueryEntityError> = world.get_many_entities_mut([e1, e2]);

// 0.15
let erefs: [EntityRef; 2] = world.entity([e1, e2]);
let emuts: [EntityMut; 2] = world.entity_mut([e1, e2]);
let erefs: Result<[EntityRef; 2], Entity> = world.get_entity([e1, e2]);
let emuts: Result<[EntityMut; 2], EntityFetchError> = world.get_entity_mut([e1, e2]);
```

Querying for multiple entities with a slice has changed:

```rust
let ids = vec![e1, e2, e3]);

// 0.14
let erefs: Result<Vec<EntityRef>, Entity> = world.get_many_entities_dynamic(&ids[..]);
let emuts: Result<Vec<EntityMut>, QueryEntityError> = world.get_many_entities_dynamic_mut(&ids[..]);

// 0.15
let erefs: Result<Vec<EntityRef>, Entity> = world.get_entity(&ids[..]);
let emuts: Result<Vec<EntityMut>, EntityFetchError> = world.get_entity_mut(&ids[..]);
let erefs: Vec<EntityRef> = world.entity(&ids[..]); // Newly possible!
let emuts: Vec<EntityMut> = world.entity_mut(&ids[..]); // Newly possible!
```

Querying for multiple entities with an `EntityHashSet` has changed:

```rust
let set = EntityHashSet::from_iter([e1, e2, e3]);

// 0.14
let emuts: Result<Vec<EntityMut>, QueryEntityError> = world.get_many_entities_from_set_mut(&set);

// 0.15
let emuts: Result<EntityHashMap<EntityMut>, EntityFetchError> = world.get_entity_mut(&set);
let erefs: Result<EntityHashMap<EntityRef>, EntityFetchError> = world.get_entity(&set); // Newly possible!
let emuts: EntityHashMap<EntityMut> = world.entity_mut(&set); // Newly possible!
let erefs: EntityHashMap<EntityRef> = world.entity(&set); // Newly possible!
```

</details>

## Migration Guide

- `World::get_entity` now returns `Result<_, Entity>` instead of
`Option<_>`.
- Use `world.get_entity(..).ok()` to return to the previous behavior.
- `World::get_entity_mut` and `DeferredWorld::get_entity_mut` now return
`Result<_, EntityFetchError>` instead of `Option<_>`.
- Use `world.get_entity_mut(..).ok()` to return to the previous
behavior.
- Type inference for `World::entity`, `World::entity_mut`,
`World::get_entity`, `World::get_entity_mut`,
`DeferredWorld::entity_mut`, and `DeferredWorld::get_entity_mut` has
changed, and might now require the input argument's type to be
explicitly written when inside closures.
- The following functions have been deprecated, and should be replaced
as such:
    - `World::many_entities` -> `World::entity::<[Entity; N]>`
    - `World::many_entities_mut` -> `World::entity_mut::<[Entity; N]>`
    - `World::get_many_entities` -> `World::get_entity::<[Entity; N]>`
- `World::get_many_entities_dynamic` -> `World::get_entity::<&[Entity]>`
- `World::get_many_entities_mut` -> `World::get_entity_mut::<[Entity;
N]>`
- The equivalent return type has changed from `Result<_,
QueryEntityError>` to `Result<_, EntityFetchError>`
- `World::get_many_entities_dynamic_mut` ->
`World::get_entity_mut::<&[Entity]>1
- The equivalent return type has changed from `Result<_,
QueryEntityError>` to `Result<_, EntityFetchError>`
- `World::get_many_entities_from_set_mut` ->
`World::get_entity_mut::<&EntityHashSet>`
- The equivalent return type has changed from `Result<Vec<EntityMut>,
QueryEntityError>` to `Result<EntityHashMap<EntityMut>,
EntityFetchError>`. If necessary, you can still convert the
`EntityHashMap` into a `Vec`.
2024-10-07 15:21:40 +00:00
Ida "Iyes
31409ebc61
Add Image methods for easy access to a pixel's color (#10392)
# Objective

If you want to draw / generate images from the CPU, such as:
 - to create procedurally-generated assets
- for games whose artstyle is best implemented by poking pixels directly
from the CPU, instead of using shaders

It is currently very unergonomic to do in Bevy, because you have to deal
with the raw bytes inside `image.data`, take care of the pixel format,
etc.

## Solution

This PR adds some helper methods to `Image` for pixel manipulation.
These methods allow you to use Bevy's user-friendly `Color` struct to
read and write the colors of pixels, at arbitrary coordinates (specified
as `UVec3` to support any texture dimension). They handle
encoding/decoding to the `Image`s `TextureFormat`, incl. any sRGB
conversion.

While we are at it, also add methods to help with direct access to the
raw bytes. It is now easy to compute the offset where the bytes of a
specific pixel coordinate are found, or to just get a Rust slice to
access them.

Caveat: `Color` roundtrips are obviously going to be lossy for non-float
`TextureFormat`s. Using `set_color_at` followed by `get_color_at` will
return a different value, due to the data conversions involved (such as
`f32` -> `u8` -> `f32` for the common `Rgba8UnormSrgb` texture format).
Be careful when comparing colors (such as checking for a color you wrote
before)!

Also adding a new example: `cpu_draw` (under `2d`), to showcase these
new APIs.

---

## Changelog

### Added

 - `Image` APIs for easy access to the colors of specific pixels.

---------

Co-authored-by: Pascal Hertleif <killercup@gmail.com>
Co-authored-by: François <mockersf@gmail.com>
Co-authored-by: ltdk <usr@ltdk.xyz>
2024-10-07 14:38:41 +00:00
dependabot[bot]
aa56d4831a
Update sysinfo requirement from 0.31.0 to 0.32.0 (#15697)
Updates the requirements on
[sysinfo](https://github.com/GuillaumeGomez/sysinfo) to permit the
latest version.
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a
href="https://github.com/GuillaumeGomez/sysinfo/blob/master/CHANGELOG.md">sysinfo's
changelog</a>.</em></p>
<blockquote>
<h1>0.32.0</h1>
<ul>
<li>Add new <code>Disk::is_read_only</code> API.</li>
<li>Add new <code>remove_dead_processes</code> argument to
<code>System::refresh_processes</code> and
<code>System::refresh_processes_specifics</code>.</li>
<li>macOS: Fix memory leak in disk refresh.</li>
</ul>
<h1>0.31.4</h1>
<ul>
<li>macOS: Force memory cleanup in disk list retrieval.</li>
</ul>
<h1>0.31.3</h1>
<ul>
<li>Raspberry Pi: Fix temperature retrieval.</li>
</ul>
<h1>0.31.2</h1>
<ul>
<li>Remove <code>bstr</code> dependency (needed for rustc
development).</li>
</ul>
<h1>0.31.1</h1>
<ul>
<li>Downgrade version of <code>memchr</code> (needed for rustc
development).</li>
</ul>
<h1>0.31.0</h1>
<ul>
<li>Split crate in features to only enable what you need.</li>
<li>Remove <code>System::refresh_process</code>,
<code>System::refresh_process_specifics</code> and
<code>System::refresh_pids</code>
methods.</li>
<li>Add new argument of type <code>ProcessesToUpdate</code> to
<code>System::refresh_processes</code> and
<code>System::refresh_processes_specifics</code> methods.</li>
<li>Add new <code>NetworkData::ip_networks</code> method.</li>
<li>Add new <code>System::refresh_cpu_list</code> method.</li>
<li>Global CPU now only contains CPU usage.</li>
<li>Rename <code>TermalSensorType</code> to
<code>ThermalSensorType</code>.</li>
<li>Process names is now an <code>OsString</code>.</li>
<li>Remove <code>System::global_cpu_info</code>.</li>
<li>Add <code>System::global_cpu_usage</code>.</li>
<li>macOS: Fix invalid CPU computation when single processes are
refreshed one after the other.</li>
<li>Windows: Fix virtual memory computation.</li>
<li>Windows: Fix WoW64 parent process refresh.</li>
<li>Linux: Retrieve RSS (Resident Set Size) memory for cgroups.</li>
</ul>
<h1>0.30.13</h1>
<ul>
<li>macOS: Fix segfault when calling
<code>Components::refresh_list</code> multiple times.</li>
<li>Windows: Fix CPU arch retrieval.</li>
</ul>
<h1>0.30.12</h1>
<ul>
<li>FreeBSD: Fix network interfaces retrieval (one was always
missing).</li>
</ul>
<h1>0.30.11</h1>
<!-- raw HTML omitted -->
</blockquote>
<p>... (truncated)</p>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="e022ae4fd1"><code>e022ae4</code></a>
Merge pull request <a
href="https://redirect.github.com/GuillaumeGomez/sysinfo/issues/1354">#1354</a>
from GuillaumeGomez/update</li>
<li><a
href="0c5ca6af60"><code>0c5ca6a</code></a>
Update migration guide for 0.32</li>
<li><a
href="9f14cba660"><code>9f14cba</code></a>
Update crate version to 0.32.0</li>
<li><a
href="eb7f147b27"><code>eb7f147</code></a>
Update CHANGELOG for 0.32.0</li>
<li><a
href="9c86e253dd"><code>9c86e25</code></a>
Fix new clippy lints</li>
<li><a
href="2fb2903272"><code>2fb2903</code></a>
Merge pull request <a
href="https://redirect.github.com/GuillaumeGomez/sysinfo/issues/1353">#1353</a>
from GuillaumeGomez/rm-dead-processes</li>
<li><a
href="7452b8d828"><code>7452b8d</code></a>
Update <code>System::refresh_processes</code> API to give control over
when to remove de...</li>
<li><a
href="6f1d382276"><code>6f1d382</code></a>
Merge pull request <a
href="https://redirect.github.com/GuillaumeGomez/sysinfo/issues/1348">#1348</a>
from kevinbaker/master</li>
<li><a
href="6d5ea97ade"><code>6d5ea97</code></a>
add dependency on windows SystemServices for disk</li>
<li><a
href="1c87f50f1c"><code>1c87f50</code></a>
win: add correct location of FILE_READ_ONLY_VOLUME, correct call</li>
<li>Additional commits viewable in <a
href="https://github.com/GuillaumeGomez/sysinfo/compare/v0.31.0...v0.32.0">compare
view</a></li>
</ul>
</details>
<br />


Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot merge` will merge this PR after your CI passes on it
- `@dependabot squash and merge` will squash and merge this PR after
your CI passes on it
- `@dependabot cancel merge` will cancel a previously requested merge
and block automerging
- `@dependabot reopen` will reopen this PR if it is closed
- `@dependabot close` will close this PR and stop Dependabot recreating
it. You can achieve the same result by closing it manually
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore this major version` will close this PR and stop
Dependabot creating any more for this major version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop
Dependabot creating any more for this minor version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop
Dependabot creating any more for this dependency (unless you reopen the
PR or upgrade to it yourself)


</details>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-10-07 07:31:17 +00:00
Matty
d3657a04cd
Fixes to animation graph evaluation (#15689)
# Objective

Fix a couple of substantial errors found during the development of
#15665:
- `AnimationCurveEvaluator::add` was secretly unreachable. In other
words, additive blending never actually occurred.
- Weights from the animation graph nodes were ignored, and only
`ActiveAnimation`'s weights were used.

## Solution

Made additive blending reachable and included the graph node weight in
the weight of the stack elements appended in the curve application loop
of `animate_targets`.

## Testing

Tested on existing examples and on the new example added in #15665.
2024-10-07 07:30:00 +00:00
Liam Gallagher
d016e52843
Spelling (#15686)
Fix two spelling mistakes
2024-10-07 00:10:04 +00:00
poopy
b4ffb7ab7d
Don't trigger animation events when paused 2 (#15682)
# Objective

I completely forgot that animation events are triggered in two separate
systems (sorry). The issue ~~fixed~~ by #15677, can still happen if the
animation event is not targeting a specific bone.

## Solution

_Realy_ don't trigger animation events for paused animations.
2024-10-06 20:16:39 +00:00
Chang Guo
e7c1c997ac
simplify adding headers and improve consistency for RemoteHttpPlugin (#15680)
# Objective

- a follow up pr for #15651 

## Solution

- rename add to insert cuz insert make more sense when using a HashMap
and new value overrides previous value based on key (quote:
https://github.com/bevyengine/bevy/pull/15651#discussion_r1788851778)
- use `TryInto<>` for add(insert) as well when constructing `Headers`.
Doing so user won't need to interact with hyper APIs, and `with_headers`
will align better with `with_header` (quote:
https://github.com/bevyengine/bevy/pull/15651#discussion_r1788687251)
- move example usage of Headers to `with_headers` method (quote:
https://github.com/bevyengine/bevy/pull/15651#discussion_r1788989500)

## Testing

- the same as I tested my previous pr
2024-10-06 19:06:19 +00:00
Willem
5a0bd23106
Add scene summary (#15679)
# Objective

-- Fixes #14361
2024-10-06 19:03:56 +00:00
poopy
70269ef758
Don't trigger animation events when paused (#15677)
# Objective

Pausing the `animated_fox` example perfectly as one of the feet hits the
ground causes the event to be triggered every frame.

Context: #15538

## Solution

Don't trigger animation events if the animation is paused.

## Testing

Ran the example, I no longer see the issue.
2024-10-06 18:57:07 +00:00
Bude
6edb78a8c3
Inverse bevy_render bevy_winit dependency and move cursor to bevy_winit (#15649)
# Objective

- `bevy_render` should not depend on `bevy_winit`
- Fixes #15565

## Solution

- `bevy_render` no longer depends on `bevy_winit`
- The following is behind the `custom_cursor` feature
- Move custom cursor code from `bevy_render` to `bevy_winit` behind the
`custom_cursor` feature
- `bevy_winit` now depends on `bevy_render` (for `Image` and
`TextureFormat`)
- `bevy_winit` now depends on `bevy_asset` (for `Assets`, `Handle` and
`AssetId`)
  - `bevy_winit` now depends on `bytemuck` (already in tree)
- Custom cursor code in `bevy_winit` reworked to use `AssetId` (other
than that it is taken over 1:1)
- Rework `bevy_winit` custom cursor interface visibility now that the
logic is all contained in `bevy_winit`

## Testing

- I ran the screenshot and window_settings examples
- Tested on linux wayland so far

---

## Migration Guide

`CursorIcon` and `CustomCursor` previously provided by
`bevy::render::view::cursor` is now available from `bevy::winit`.
A new feature `custom_cursor` enables this functionality (default
feature).
2024-10-06 18:25:50 +00:00
vero
4a23dc4216
Split out bevy_mesh from bevy_render (#15666)
# Objective

- bevy_render is gargantuan

## Solution

- Split out bevy_mesh

## Testing

- Ran some examples, everything looks fine

## Migration Guide

`bevy_render::mesh::morph::inherit_weights` is now
`bevy_render::mesh::inherit_weights`

if you were using `Mesh::compute_aabb`, you will need to `use
bevy_render::mesh::MeshAabb;` now

---------

Co-authored-by: Joona Aalto <jondolf.dev@gmail.com>
2024-10-06 14:18:11 +00:00
Chang Guo
7c4a0683c7
Add with_headers() method to RemoteHttpPlugin (#15651)
# Objective

- fulfill the needs presented in this issue, which requires the ability
to set custom HTTP headers for responses in the Bevy Remote Protocol
server. #15551

## Solution

- Created a `Headers` struct to store custom HTTP headers as key-value
pairs.
- Added a `headers` field to the `RemoteHttpPlugin` struct.
- Implemented a `with_headers` method in `RemoteHttpPlugin` to allow
users to set custom headers.
- Passed the headers into the processing chain.

## Testing

- I added cors_headers in example/remote/server.rs and tested it with a
static html
[file](https://github.com/spacemen0/bevy/blob/test_file/test.html)

---
2024-10-06 13:21:21 +00:00
poopy
d9190e4ff6
Add Support for Triggering Events via AnimationEvents (#15538)
# Objective

Add support for events that can be triggered from animation clips. This
is useful when you need something to happen at a specific time in an
animation. For example, playing a sound every time a characters feet
hits the ground when walking.

Closes #15494 

## Solution

Added a new field to `AnimationClip`: `events`, which contains a list of
`AnimationEvent`s. These are automatically triggered in
`animate_targets` and `trigger_untargeted_animation_events`.

## Testing

Added a couple of tests and example (`animation_events.rs`) to make sure
events are triggered when expected.

---

## Showcase

`Events` need to also implement `AnimationEvent` and `Reflect` to be
used with animations.

```rust
#[derive(Event, AnimationEvent, Reflect)]
struct SomeEvent;
```

Events can be added to an `AnimationClip` by specifying a time and
event.

```rust
// trigger an event after 1.0 second
animation_clip.add_event(1.0, SomeEvent);
```

And optionally, providing a target id.

```rust
let id = AnimationTargetId::from_iter(["shoulder", "arm", "hand"]);
animation_clip.add_event_to_target(id, 1.0, HandEvent);
```

I modified the `animated_fox` example to show off the feature.

![CleanShot 2024-10-05 at 02 41
57](https://github.com/user-attachments/assets/0bb47db7-24f9-4504-88f1-40e375b89b1b)

---------

Co-authored-by: Matty <weatherleymatthew@gmail.com>
Co-authored-by: Chris Biscardi <chris@christopherbiscardi.com>
Co-authored-by: François Mockers <francois.mockers@vleue.com>
2024-10-06 10:03:05 +00:00
Vlady Veselinov
856cab56f9
Fix wrong link in error (#15672)
Hi y'all, I got an error that leads to a wrong link:
https://bevyengine.org/learn/errors/#b0002

It should be: https://bevyengine.org/learn/errors/b0002


![image](https://github.com/user-attachments/assets/863ae8cd-6a3b-4830-b125-2944a211a737)
2024-10-06 08:14:50 +00:00
Tom Frantz
0305f2edc0
Fix doc comment (#15673)
# Objective

I noticed a weird break in a doc comment, I assume it must be a typo.

## Solution

Put the missing doc comment in there.

## Testing

It looks better in my IDE now
2024-10-06 08:12:58 +00:00
UkoeHB
0b5a360585
Fix text measurement when multiple font sizes are present (#15669)
# Objective

- Fixes https://github.com/bevyengine/bevy/issues/15659

## Solution

- Add up line heights to get text block height instead of using
`Metrics`, which only records the largest line height.

## Testing

- [x] Fixed issue shown in https://github.com/bevyengine/bevy/pull/15622
2024-10-05 22:46:37 +00:00
Matty
42e0771633
Fix additive blending of quaternions (#15662)
# Objective

Fixes #13832

## Solution

Additively blend quaternions like this:
```rust
rotation = Quat::slerp(Quat::IDENTITY, incoming_rotation, weight) * rotation;
```

## Testing

Ran `animation_masks`, which behaves the same as before. (In the context
of an animation being blended only onto the base pose, there is no
difference.)

We should create some examples that actually exercise more of the
capabilities of the `AnimationGraph` so that issues like this can become
more visible in general. (On the other hand, I'm quite certain this was
wrong before.)

## Migration Guide

This PR changes the implementation of `Quat: Animatable`, which was not
used internally by Bevy prior to this release version. If you relied on
the old behavior of additive quaternion blending in manual applications,
that code will have to be updated, as the old behavior was incorrect.
2024-10-05 20:03:10 +00:00
Joona Aalto
25bfa80e60
Migrate cameras to required components (#15641)
# Objective

Yet another PR for migrating stuff to required components. This time,
cameras!

## Solution

As per the [selected
proposal](https://hackmd.io/tsYID4CGRiWxzsgawzxG_g#Combined-Proposal-1-Selected),
deprecate `Camera2dBundle` and `Camera3dBundle` in favor of `Camera2d`
and `Camera3d`.

Adding a `Camera` without `Camera2d` or `Camera3d` now logs a warning,
as suggested by Cart [on
Discord](https://discord.com/channels/691052431525675048/1264881140007702558/1291506402832945273).
I would personally like cameras to work a bit differently and be split
into a few more components, to avoid some footguns and confusing
semantics, but that is more controversial, and shouldn't block this core
migration.

## Testing

I ran a few 2D and 3D examples, and tried cameras with and without
render graphs.

---

## Migration Guide

`Camera2dBundle` and `Camera3dBundle` have been deprecated in favor of
`Camera2d` and `Camera3d`. Inserting them will now also insert the other
components required by them automatically.
2024-10-05 01:59:52 +00:00
m-edlund
ac9b0c848c
fix: corrected projection calculation of camera sub view (#15646)
# Objective

- Fixes #15600

## Solution

- The projection calculations did not use the aspect ratio of
`full_size`, this was amended

## Testing

- I created a test example on [this
fork](https://github.com/m-edlund/bevy/tree/bug/main/subViewProjectionBroken)
to allow testing with different aspect ratios and offsets
- The sub view is bound to a view port that can move across the screen.
The image in the moving sub view should "match" the full image exactly

## Showcase

Current version:


https://github.com/user-attachments/assets/17ad1213-d5ae-4181-89c1-81146edede7d

Fixed version:


https://github.com/user-attachments/assets/398e0927-e1dd-4880-897d-8157aa4398e6
2024-10-05 01:36:47 +00:00
urben1680
2e89e98931
Deprecate Events::oldest_id (#15658)
# Objective

Fixes #15617 

## Solution

The original author confirmed it was not intentional that both these
methods exist.

They do the same, one has the better implementation and the other the
better name.

## Testing

I just ran the unit tests of the module.

---

## Migration Guide

- Change usages of `Events::oldest_id` to `Events::oldest_event_count`
- If `Events::oldest_id` was used to get the actual oldest
`EventId::id`, note that the deprecated method never reliably did that
in the first place as the buffers may contain no id currently.
2024-10-05 01:35:44 +00:00
Kristoffer Søholm
ddd4b4daf8
Fix deferred rendering (#15656)
# Objective

Fixes #15525

The deferred and mesh pipelines tonemapping LUT bindings were
accidentally out of sync, breaking deferred rendering.

As noted in the issue it's still broken on wasm due to hitting a texture
limit.

## Solution

Add constants for these instead of hardcoding them.

## Testing

Test with `cargo run --example deferred_rendering` and see it works, run
the same on main and see it crash.
2024-10-04 22:51:23 +00:00
Patrick Walton
0094bcbc07
Implement additive blending for animation graphs. (#15631)
*Additive blending* is an ubiquitous feature in game engines that allows
animations to be concatenated instead of blended. The canonical use case
is to allow a character to hold a weapon while performing arbitrary
poses. For example, if you had a character that needed to be able to
walk or run while attacking with a weapon, the typical workflow is to
have an additive blend node that combines walking and running animation
clips with an animation clip of one of the limbs performing a weapon
attack animation.

This commit adds support for additive blending to Bevy. It builds on top
of the flexible infrastructure in #15589 and introduces a new type of
node, the *add node*. Like blend nodes, add nodes combine the animations
of their children according to their weights. Unlike blend nodes,
however, add nodes don't normalize the weights to 1.0.

The `animation_masks` example has been overhauled to demonstrate the use
of additive blending in combination with masks. There are now controls
to choose an animation clip for every limb of the fox individually.

This patch also fixes a bug whereby masks were incorrectly accumulated
with `insert()` during the graph threading phase, which could cause
corruption of computed masks in some cases.

Note that the `clip` field has been replaced with an `AnimationNodeType`
enum, which breaks `animgraph.ron` files. The `Fox.animgraph.ron` asset
has been updated to the new format.

Closes #14395.

## Showcase


https://github.com/user-attachments/assets/52dfe05f-fdb3-477a-9462-ec150f93df33

## Migration Guide

* The `animgraph.ron` format has changed to accommodate the new
*additive blending* feature. You'll need to change `clip` fields to
instances of the new `AnimationNodeType` enum.
2024-10-04 22:13:22 +00:00