Commit graph

5345 commits

Author SHA1 Message Date
BD103
593d41ce58
Fix typo in comment (#11486)
# Objective

- `World::get_resource`'s comment on it's `unsafe` usage meant to say
"mutably" but instead said "immutably."
- Fixes #11430.

## Solution

- Replace "immutably" with "mutably."
2024-01-23 02:50:06 +00:00
Alice Cecile
1d17453697
Unpin nightly for miri (#11462)
# Objective

- Using the latest nightly for `miri` is generally desirable as we want
to catch regressions upstream or new problems quickly
- https://github.com/rust-lang/rust/pull/120123 should be merged now, so
it should work.

## Solution

- Revert #11421.

---------

Co-authored-by: François <mockersf@gmail.com>
Co-authored-by: Alice Cecile <alice.i.cecil@gmail.com>
2024-01-22 19:32:44 +00:00
Joona Aalto
6a3b059db9
Implement bounding volume intersections (#11439)
# Objective

#10946 added bounding volume types and an `IntersectsVolume` trait, but
didn't actually implement intersections between bounding volumes.

This PR implements AABB-AABB, circle-circle / sphere-sphere, and
AABB-circle / AABB-sphere intersections.

## Solution

Implement `IntersectsVolume` for bounding volume pairs. I also added
`closest_point` methods to return the closest point on the surface /
inside of bounding volumes. This is used for AABB-circle / AABB-sphere
intersections.

---------

Co-authored-by: IQuick 143 <IQuick143cz@gmail.com>
2024-01-22 17:55:59 +00:00
Pixelstorm
df063ab1ef
Implement Debug for CommandQueue (#11444)
# Objective

Allow users to impl Debug on types containing `CommandQueue`s

## Solution

Derive Debug on `CommandQueue`

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
2024-01-22 15:45:17 +00:00
Bude
b2e2f8d9e3
TextureAtlasBuilder now respects insertion order (#11474)
# Objective

TextureAtlases are commonly used to drive animations described as a
consecutive range of indices. The current TextureAtlasBuilder uses the
AssetId of the image to determine the index of the texture in the
TextureAtlas. The AssetId of an Image Asset can change between runs.
The TextureAtlas exposes
[`get_texture_index`](https://docs.rs/bevy/latest/bevy/sprite/struct.TextureAtlas.html#method.get_texture_index)
to get the index from a given AssetId, but this needlessly complicates
the process of creating a simple TextureAtlas animation.
Fixes #2459

## Solution

- Use the (ordered) image_ids of the 'texture to place' vector to
retrieve the packed locations and compose the textures of the
TextureAtlas.
2024-01-22 15:44:56 +00:00
James O'Brien
f8191bebfb
Fix memory leak in dynamic ECS example (#11461)
# Objective

- Fix a memory leak in the dynamic ECS example mentioned in #11459

## Solution

- Rather than allocate the memory manually instead store a collection of
`Vec` that will be dropped after it is used.

---

I must have misinterpreted `OwningPtr`s semantics when initially writing
this example. I believe we should be able to provide better APIs here
for inserting dynamic components that don't require the user to wrangle
so much unsafety. We have no other examples using `insert_by_ids` and
our only tests show it being used for 1 or 2 values with nested calls to
`OwningPtr::make` despite the function taking an iterator. Rust's type
system is quite restrictive here but we could at least let
`OwningPtr::new` take non u8 `NonNull`.

I also agree with #11459 that we should generally be trying to simplify
and clarify this example.
2024-01-22 15:41:32 +00:00
Joseph
7d69d3195f
refactor: Simplify lifetimes for Commands and related types (#11445)
# Objective

It would be convenient to be able to call functions with `Commands` as a
parameter without having to move your own instance of `Commands`. Since
this struct is composed entirely of references, we can easily get an
owned instance of `Commands` by shortening the lifetime.

## Solution

Add `Commands::reborrow`, `EntiyCommands::reborrow`, and
`Deferred::reborrow`, which returns an owned version of themselves with
a shorter lifetime.

Remove unnecessary lifetimes from `EntityCommands`. The `'w` and `'s`
lifetimes only have to be separate for `Commands` because it's used as a
`SystemParam` -- this is not the case for `EntityCommands`.

---

## Changelog

Added `Commands::reborrow`. This is useful if you have `&mut Commands`
but need `Commands`. Also added `EntityCommands::reborrow` and
`Deferred:reborrow` which serve the same purpose.

## Migration Guide

The lifetimes for `EntityCommands` have been simplified.

```rust
// Before (Bevy 0.12)
struct MyStruct<'w, 's, 'a> {
     commands: EntityCommands<'w, 's, 'a>,
}

// After (Bevy 0.13)
struct MyStruct<'a> {
    commands: EntityCommands<'a>,
}
```

The method `EntityCommands::commands` now returns `Commands` rather than
`&mut Commands`.

```rust
// Before (Bevy 0.12)
let commands = entity_commands.commands();
commands.spawn(...);

// After (Bevy 0.13)
let mut commands = entity_commands.commands();
commands.spawn(...);
```
2024-01-22 15:35:42 +00:00
laund
e2e4e8eb9a
document which lifetime is needed for systemparam derive (#11321)
# Objective

Document a few common cases of which lifetime is required when using
SystemParam Derive

## Solution

Added a table in the doc comment

---------

Co-authored-by: laund <me@laund.moe>
Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
2024-01-22 15:32:42 +00:00
JMS55
a796d53a05
Meshlet prep (#11442)
# Objective

- Prep for https://github.com/bevyengine/bevy/pull/10164
- Make deferred_lighting_pass_id a ColorAttachment
- Correctly extract shadow view frusta so that the view uniforms get
populated
- Make some needed things public
- Misc formatting
2024-01-22 15:28:33 +00:00
Thierry Berger
2165793ff0
Add logical key data to KeyboardInput (#11400)
Add logical key data to KeyboardInput

Addresses an item of https://github.com/bevyengine/bevy/issues/11052

---------

Co-authored-by: Mateusz Wachowiak <mateusz_wachowiak@outlook.com>
2024-01-22 15:25:17 +00:00
John Lewis
cfe4034d25
Add Reflection for Wrapping/Saturating types (#11397)
# Objective

- Extend reflection to the standard library's `Wrapping` and
`Saturating` generic types.

This wasn't my use-case but someone in the discord was surprised that
this wasn't already done. I decided to make a PR because the other
`std::num` items were reflected and if there's a reason to exclude
`Wrapping` and `Saturating`, I am unaware of it.

## Solution

Trivial fix

---

## Changelog

Implemented `Reflect` for `Wrapping<T>` and `Saturating<T>` from
`std::num`.
2024-01-22 15:21:20 +00:00
irate
1e7e6c93e6
Fix scene example (#11289)
Since #9907 the generation starts at `1` instead of `0` so
`Entity::to_bits` now returns `4294967296` (ie. `u32::MAX + 1`) as the
lowest number instead of `0`.

Without this change scene loading fails with this error message:
`ERROR bevy_asset::server: Failed to load asset
'scenes/load_scene_example.scn.ron' with asset loader
'bevy_scene::scene_loader::SceneLoader': Could not parse RON: 8:6:
Invalid generation bits`
2024-01-22 15:14:41 +00:00
Chia-Hsiang Cheng
8ad1b93e63
Double the capacity when BlobVec is full (#11167)
# Objective

- Fixes #10797

## Solution

- Double the capacity of a full `BlobVec` before pushing a new element.
2024-01-22 15:05:34 +00:00
Alice Cecile
eb07d16871
Revert rendering-related associated type name changes (#11027)
# Objective

> Can anyone explain to me the reasoning of renaming all the types named
Query to Data. I'm talking about this PR
https://github.com/bevyengine/bevy/pull/10779 It doesn't make sense to
me that a bunch of types that are used to run queries aren't named Query
anymore. Like ViewQuery on the ViewNode is the type of the Query. I
don't really understand the point of the rename, it just seems like it
hides the fact that a query will run based on those types.


[@IceSentry](https://discord.com/channels/691052431525675048/692572690833473578/1184946251431694387)

## Solution

Revert several renames in #10779.

## Changelog

- `ViewNode::ViewData` is now `ViewNode::ViewQuery` again.

## Migration Guide

- This PR amends the migration guide in
https://github.com/bevyengine/bevy/pull/10779

---------

Co-authored-by: atlas dostal <rodol@rivalrebels.com>
2024-01-22 15:01:55 +00:00
HugoPeters1024
8afb3ceb89
add storage_texture option to as_bind_group macro (#9943)
# Objective

- Add the ability to describe storage texture bindings when deriving
`AsBindGroup`.
- This is especially valuable for the compute story of bevy which
deserves some extra love imo.

## Solution

- This add the ability to annotate struct fields with a
`#[storage_texture(0)]` annotation.
- Instead of adding specific option parsing for all the image formats
and access modes, I simply accept a token stream and defer checking to
see if the option is valid to the compiler. This still results in useful
and friendly errors and is free to maintain and always compatible with
wgpu changes.

---

## Changelog

- The `#[storage_texture(..)]` annotation is now accepted for fields of
`Handle<Image>` in structs that derive `AsBindGroup`.
- The game_of_life compute shader example has been updated to use
`AsBindGroup` together with `[storage_texture(..)]` to obtain the
`BindGroupLayout`.

## Migration Guide
2024-01-21 18:47:13 +00:00
Giacomo Stevanato
0fa14c86de
Fix wrong transmuted type in TaskPool::scope_with_executor_inner (#11455)
# Objective

#8219 changed the target type of a `transmute` without changing the one
transmuting from ([see the relevant
diff](55e9ab7c92 (diff-11413fb2eeba97978379d325353d32aa76eefd0af0c8e9b50b7f394ddfda7a26R351-R355))),
making them incompatible. This PR fixes this by changing the initial
type to match the target one (modulo lifetimes).

## Solution

Change the type to be transmuted from to match the one transmuting into
(modulo lifetimes)
2024-01-21 18:08:45 +00:00
Marco Buono
18833fa67c
Fix reflected serialization/deserialization on Name component (#11447)
# Objective

- This PR makes it so that `ReflectSerialize` and `ReflectDeserialize`
traits are properly derived on `Name`. This avoids having the internal
hash “leak” into the serialization when using reflection.

## Solution

- Added a conditional derive for `ReflectDeserialize` and
`ReflectSerialize` via `#[cfg_attr()]`

---

## Changelog

- `Name` now implements `ReflectDeserialize` and `ReflectSerialize`
whenever the `serialize` feature is enabled.
2024-01-21 18:04:13 +00:00
Arthur Brussee
ffb6faafc2
Use Direction3d for gizmos.circle normal (#11422)
# Objective

Fix weird visuals when drawing a gizmo with a non-normed normal.

Fixes #11401

## Solution
Just normalize right before we draw. Could do it when constructing the
builder but that seems less consistent.

## Changelog
- gizmos.circle normal is now a Direction3d instead of a Vec3.

## Migration Guide
- Pass a Direction3d for gizmos.circle normal, eg.
`Direction3d::new(vec).unwrap_or(default)` or potentially
`Direction3d::new_unchecked(vec)` if you know your vec is definitely
normalized.
2024-01-21 18:03:26 +00:00
François
259fb6896e
auto create imported asset folder if needed (#11284)
# Objective

- Since #11218, example `asset_processing` fails:
```
thread 'main' panicked at crates/bevy_asset/src/io/source.rs:489:18:
Failed to create file watcher: Error { kind: PathNotFound, paths: ["examples/asset/processing/imported_assets/Default"] }
```

start from a fresh git clone or delete the folder before running to
reproduce, it is in gitignore and should not be present on a fresh run

a657478675/.gitignore (L18)

## Solution

- Auto create the `imported_assets` folder if it is configured

---------

Co-authored-by: Kyle <37520732+nvdaz@users.noreply.github.com>
2024-01-21 09:30:43 +00:00
Doonv
0387331c12
Direction: Rename from_normalized to new_unchecked (#11425)
# Objective

`Direction2d::from_normalized` & `Direction3d::from_normalized` don't
emphasize that importance of the vector being normalized enough.

## Solution

Rename `from_normalized` to `new_unchecked` and add more documentation.

---

`Direction2d` and `Direction3d` were added somewhat recently in
https://github.com/bevyengine/bevy/pull/10466 (after 0.12), so I don't
think documenting the changelog and migration guide is necessary (Since
there is no major previous version to migrate from).

But here it is anyway in case it's needed:

## Changelog

- Renamed `Direction2d::from_normalized` and
`Direction3d::from_normalized` to `new_unchecked`.

## Migration Guide

- Renamed `Direction2d::from_normalized` and
`Direction3d::from_normalized` to `new_unchecked`.

---------

Co-authored-by: Tristan Guichaoua <33934311+tguichaoua@users.noreply.github.com>
Co-authored-by: Joona Aalto <jondolf.dev@gmail.com>
2024-01-20 21:52:09 +00:00
Joona Aalto
c6f45831e9
Add geometric primitives to bevy_math::prelude (#11432)
# Objective

Currently, the `primitives` module is inside of the prelude for
`bevy_math`, but the actual primitives are not. This requires either
importing the shapes everywhere that uses them, or adding the
`primitives::` prefix:

```rust
let rectangle = meshes.add(primitives::Rectangle::new(5.0, 2.5));
```

(Note: meshing isn't actually implemented yet, but it's in #11431)

The primitives are meant to be used for a variety of tasks across
several crates, like for meshing, bounding volumes, gizmos, colliders,
and so on, so I think having them in the prelude is justified. It would
make several common tasks a lot more ergonomic.

```rust
let rectangle = meshes.add(Rectangle::new(5.0, 2.5));
```

## Solution

Add `primitives::*` to `bevy_math::prelude`.

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
2024-01-20 20:15:38 +00:00
Joona Aalto
c31f3aa128
Add Aabb2d::new and Aabb3d::new constructors (#11433)
# Objective

Currently, the only way to create an AABB is to specify its `min` and
`max` coordinates. However, it's often more useful to use the center and
half-size instead.

## Solution

Add `new` constructors for `Aabb2d` and `Aabb3d`.

This:

```rust
let aabb = Aabb3d {
    min: center - half_size,
    max: center + half_size,
}
```

becomes this:

```rust
let aabb = Aabb3d::new(center, half_size);
```

I also made the usage of "half-extents" vs. "half-size" a bit more
consistent.
2024-01-20 20:12:20 +00:00
François
440bba80c4
add a required feature for shader_material_glsl (#11440)
# Objective

- Since https://github.com/bevyengine/bevy/pull/11366, feature `glsl` of
`naga_oil` is not enabled by default
- It is needed for example `shader_material_glsl`

```
thread 'Compute Task Pool (0)' panicked at crates\bevy_render\src\render_resource\shader.rs:238:35:
GLSL is not supported in this configuration; use the feature `shader_format_glsl`
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
Encountered a panic in system `bevy_render::render_resource::pipeline_cache::PipelineCache::process_pipeline_queue_system`!
thread 'main' panicked at crates\bevy_render\src\pipelined_rendering.rs:145:45:
called `Result::unwrap()` on an `Err` value: RecvError
```

## Solution

- Add feature `shader_format_glsl` as a required feature for example
`shader_material_glsl`
2024-01-20 19:55:19 +00:00
Joona Aalto
b592a72916
Change Ellipse representation and improve helpers (#11435)
# Objective

Currently, the `Ellipse` primitive is represented by a `half_width` and
`half_height`. To improve consistency (similarly to #11434), it might
make more sense to use a `Vec2` `half_size` instead.

Alternatively, to make the elliptical nature clearer, the properties
could also be called `radius_x` and `radius_y`.

Secondly, `Ellipse::new` currently takes a *full* width and height
instead of two radii. I would expect it to take the half-width and
half-height because ellipses and circles are almost always defined using
radii. I wouldn't expect `Circle::new` to take a diameter (if we had
that method).

## Solution

Change `Ellipse` to store a `half_size` and `new` to take the half-width
and half-height.

I also added a `from_size` method similar to `Rectangle::from_size`, and
added the `semi_minor` and `semi_major` helpers to get the
semi-minor/major radius.
2024-01-20 18:04:53 +00:00
Joona Aalto
6337fb33ff
Improve Rectangle and Cuboid consistency (#11434)
# Objective

The `Rectangle` and `Cuboid` primitives currently use different
representations:

```rust
pub struct Rectangle {
    /// The half width of the rectangle
    pub half_width: f32,
    /// The half height of the rectangle
    pub half_height: f32,
}

pub struct Cuboid {
    /// Half of the width, height and depth of the cuboid
    pub half_extents: Vec3,
}
```

The property names and helpers are also inconsistent. `Cuboid` has
`half_extents`, but it also has a method called `from_size`. Most
existing code also uses "size" instead of "extents".

## Solution

Represent both `Rectangle` and `Cuboid` with `half_size` properties.
2024-01-20 18:03:47 +00:00
LeshaInc
320ac65a9e
Replace DiagnosticId by DiagnosticPath (#9266)
# Objective

Implements #9216 

## Solution

- Replace `DiagnosticId` by `DiagnosticPath`. It's pre-hashed using
`const-fnv1a-hash` crate, so it's possible to create path in const
contexts.

---

## Changelog

- Replaced `DiagnosticId` by `DiagnosticPath`
- Set default history length to 120 measurements (2 seconds on 60 fps).

I've noticed hardcoded constant 20 everywhere and decided to change it
to `DEFAULT_MAX_HISTORY_LENGTH` , which is set to new diagnostics by
default. To override it, use `with_max_history_length`.


## Migration Guide

```diff
- const UNIQUE_DIAG_ID: DiagnosticId = DiagnosticId::from_u128(42);
+ const UNIQUE_DIAG_PATH: DiagnosticPath = DiagnosticPath::const_new("foo/bar");

- Diagnostic::new(UNIQUE_DIAG_ID, "example", 10)
+ Diagnostic::new(UNIQUE_DIAG_PATH).with_max_history_length(10)

- diagnostics.add_measurement(UNIQUE_DIAG_ID, || 42);
+ diagnostics.add_measurement(&UNIQUE_DIAG_ID, || 42);
```
2024-01-20 15:42:51 +00:00
re0312
04aedf12fa
optimize batch_and_prepare_render_phase (#11323)
# Objective

- since #9685  ,bevy introduce automatic batching of draw commands, 
- `batch_and_prepare_render_phase` take the responsibility for batching
`phaseItem`,
- `GetBatchData` trait is used for indentify each phaseitem how to
batch. it defines a associated type `Data `used for Query to fetch data
from world.

- however,the impl of `GetBatchData ` in bevy always set ` type
Data=Entity` then we acually get following code
`let entity:Entity =query.get(item.entity())` that cause unnecessary
overhead .

## Solution

- remove associated type `Data ` and `Filter` from `GetBatchData `,
- change the type of the `query_item ` parameter in get_batch_data from`
Self::Data` to `Entity`.
- `batch_and_prepare_render_phase ` no longer takes a query using
`F::Data, F::Filter`
- `get_batch_data `now returns `Option<(Self::BufferData,
Option<Self::CompareData>)>`

---

## Performance
based in main merged with #11290 
Window 11 ,Intel 13400kf, NV 4070Ti

![image](https://github.com/bevyengine/bevy/assets/45868716/f63b9d98-6aee-4057-a2c7-a2162b2db765)
frame time from 3.34ms to 3 ms,  ~ 10%


![image](https://github.com/bevyengine/bevy/assets/45868716/a06eea9c-f79e-4324-8392-8d321560c5ba)
`batch_and_prepare_render_phase` from 800us ~ 400 us  

## Migration Guide
trait `GetBatchData` no longer hold associated type  `Data `and `Filter`
`get_batch_data` `query_item `type from `Self::Data` to `Entity` and
return `Option<(Self::BufferData, Option<Self::CompareData>)>`
`batch_and_prepare_render_phase`  should not have a query
2024-01-20 09:30:44 +00:00
BD103
11e43860d8
Bump dev-docs pages actions (#11418)
# Objective

- `actions/upload-pages-artifact` and `actions/deploy-pages` are
outdated.
- Alternative to #11253 and #11252.

## Solution

- Bump the version of both actions.

---


There appear to be no user-facing changes. They just both need to be
updated together. (The `actions: read` permission was a bug that was
fixed later.)
2024-01-20 09:27:00 +00:00
Lee-Orr
63eb151619
Optional state (#11417)
# Objective

Adjust bevy internals to utilize `Option<Res<State<S>>>` instead of
`Res<State<S>>`, to allow for adding/removing states at runtime and
avoid unexpected panics.

As requested here:
https://github.com/bevyengine/bevy/pull/10088#issuecomment-1869185413

---

## Changelog

- Changed the use of `world.resource`/`world.resource_mut` to
`world.get_resource`/`world.get_resource_mut` in the
`run_enter_schedule` and `apply_state_transition` systems and handled
the `None` option.
- `in_state` now returns a ` FnMut(Option<Res<State<S>>>) -> bool +
Clone`, returning `false` if the resource doesn't exist.
- `state_exists_and_equals` was marked as deprecated, and now just runs
and returns `in_state`, since their bevhaviour is now identical
- `state_changed` now takes an `Option<Res<State<S>>>` and returns
`false` if it does not exist.

I would like to remove `state_exists_and_equals` fully, but wanted to
ensure that is acceptable before doing so.

---------

Co-authored-by: Mike <mike.hsu@gmail.com>
2024-01-19 21:38:04 +00:00
Giacomo Stevanato
eff96e20a0
Add ReflectFromWorld and replace the FromWorld requirement on ReflectComponent and ReflectBundle with FromReflect (#9623)
# Objective

- `FromType<T>` for `ReflectComponent` and `ReflectBundle` currently
require `T: FromWorld` for two reasons:
    - they include a `from_world` method;
- they create dummy `T`s using `FromWorld` and then `apply` a `&dyn
Reflect` to it to simulate `FromReflect`.
- However `FromWorld`/`Default` may be difficult/weird/impractical to
implement, while `FromReflect` is easier and also more natural for the
job.
- See also
https://discord.com/channels/691052431525675048/1146022009554337792

## Solution

- Split `from_world` from `ReflectComponent` and `ReflectBundle` into
its own `ReflectFromWorld` struct.
- Replace the requirement on `FromWorld` in `ReflectComponent` and
`ReflectBundle` with `FromReflect`

---

## Changelog

- `ReflectComponent` and `ReflectBundle` no longer offer a `from_world`
method.
- `ReflectComponent` and `ReflectBundle`'s `FromType<T>` implementation
no longer requires `T: FromWorld`, but now requires `FromReflect`.
- `ReflectComponent::insert`, `ReflectComponent::apply_or_insert` and
`ReflectComponent::copy` now take an extra `&TypeRegistry` parameter.
- There is now a new `ReflectFromWorld` struct.

## Migration Guide

- Existing uses of `ReflectComponent::from_world` and
`ReflectBundle::from_world` will have to be changed to
`ReflectFromWorld::from_world`.
- Users of `#[reflect(Component)]` and `#[reflect(Bundle)]` will need to
also implement/derive `FromReflect`.
- Users of `#[reflect(Component)]` and `#[reflect(Bundle)]` may now want
to also add `FromWorld` to the list of reflected traits in case their
`FromReflect` implementation may fail.
- Users of `ReflectComponent` will now need to pass a `&TypeRegistry` to
its `insert`, `apply_or_insert` and `copy` methods.
2024-01-19 16:08:57 +00:00
Patrick Walton
83d6600267
Implement minimal reflection probes (fixed macOS, iOS, and Android). (#11366)
This pull request re-submits #10057, which was backed out for breaking
macOS, iOS, and Android. I've tested this version on macOS and Android
and on the iOS simulator.

# Objective

This pull request implements *reflection probes*, which generalize
environment maps to allow for multiple environment maps in the same
scene, each of which has an axis-aligned bounding box. This is a
standard feature of physically-based renderers and was inspired by [the
corresponding feature in Blender's Eevee renderer].

## Solution

This is a minimal implementation of reflection probes that allows
artists to define cuboid bounding regions associated with environment
maps. For every view, on every frame, a system builds up a list of the
nearest 4 reflection probes that are within the view's frustum and
supplies that list to the shader. The PBR fragment shader searches
through the list, finds the first containing reflection probe, and uses
it for indirect lighting, falling back to the view's environment map if
none is found. Both forward and deferred renderers are fully supported.

A reflection probe is an entity with a pair of components, *LightProbe*
and *EnvironmentMapLight* (as well as the standard *SpatialBundle*, to
position it in the world). The *LightProbe* component (along with the
*Transform*) defines the bounding region, while the
*EnvironmentMapLight* component specifies the associated diffuse and
specular cubemaps.

A frequent question is "why two components instead of just one?" The
advantages of this setup are:

1. It's readily extensible to other types of light probes, in particular
*irradiance volumes* (also known as ambient cubes or voxel global
illumination), which use the same approach of bounding cuboids. With a
single component that applies to both reflection probes and irradiance
volumes, we can share the logic that implements falloff and blending
between multiple light probes between both of those features.

2. It reduces duplication between the existing *EnvironmentMapLight* and
these new reflection probes. Systems can treat environment maps attached
to cameras the same way they treat environment maps applied to
reflection probes if they wish.

Internally, we gather up all environment maps in the scene and place
them in a cubemap array. At present, this means that all environment
maps must have the same size, mipmap count, and texture format. A
warning is emitted if this restriction is violated. We could potentially
relax this in the future as part of the automatic mipmap generation
work, which could easily do texture format conversion as part of its
preprocessing.

An easy way to generate reflection probe cubemaps is to bake them in
Blender and use the `export-blender-gi` tool that's part of the
[`bevy-baked-gi`] project. This tool takes a `.blend` file containing
baked cubemaps as input and exports cubemap images, pre-filtered with an
embedded fork of the [glTF IBL Sampler], alongside a corresponding
`.scn.ron` file that the scene spawner can use to recreate the
reflection probes.

Note that this is intentionally a minimal implementation, to aid
reviewability. Known issues are:

* Reflection probes are basically unsupported on WebGL 2, because WebGL
2 has no cubemap arrays. (Strictly speaking, you can have precisely one
reflection probe in the scene if you have no other cubemaps anywhere,
but this isn't very useful.)

* Reflection probes have no falloff, so reflections will abruptly change
when objects move from one bounding region to another.

* As mentioned before, all cubemaps in the world of a given type
(diffuse or specular) must have the same size, format, and mipmap count.

Future work includes:

* Blending between multiple reflection probes.

* A falloff/fade-out region so that reflected objects disappear
gradually instead of vanishing all at once.

* Irradiance volumes for voxel-based global illumination. This should
reuse much of the reflection probe logic, as they're both GI techniques
based on cuboid bounding regions.

* Support for WebGL 2, by breaking batches when reflection probes are
used.

These issues notwithstanding, I think it's best to land this with
roughly the current set of functionality, because this patch is useful
as is and adding everything above would make the pull request
significantly larger and harder to review.

---

## Changelog

### Added

* A new *LightProbe* component is available that specifies a bounding
region that an *EnvironmentMapLight* applies to. The combination of a
*LightProbe* and an *EnvironmentMapLight* offers *reflection probe*
functionality similar to that available in other engines.

[the corresponding feature in Blender's Eevee renderer]:
https://docs.blender.org/manual/en/latest/render/eevee/light_probes/reflection_cubemaps.html

[`bevy-baked-gi`]: https://github.com/pcwalton/bevy-baked-gi

[glTF IBL Sampler]: https://github.com/KhronosGroup/glTF-IBL-Sampler
2024-01-19 07:33:52 +00:00
François
f795656d65
Winit update: fix suspend on Android (#11403)
# Objective

- Android still plays audio when suspended

## Solution

- When status is `WillSuspend`, trigger an update without requesting a
redraw
2024-01-19 06:26:34 +00:00
François
a00c71ee5b
Cleanup deterministic example (#11416)
# Objective

- Example `deterministic` crashes on CI on Windows because it uses too
much memory

## Solution

- Reduce the number of planes displayed while still having the issue
- While there, add a small margin to the text so that it's prettier
2024-01-19 06:08:19 +00:00
Lee-Orr
e9b8c71da0
move once from bevy_log to bevy_utils, to allow for it's use in bevy_ecs (#11419)
# Objective

When working within `bevy_ecs`, we can't use the `log_once` macros due
to their placement in `bevy_log` - which depends on `bevy_ecs`. All this
create does is migrate those macros to the `bevy_utils` crate, while
still re-exporting them in `bevy_log`.

created to resolve this:
https://github.com/bevyengine/bevy/pull/11417#discussion_r1458100211

---------

Co-authored-by: François <mockersf@gmail.com>
2024-01-19 06:07:41 +00:00
pablo-lua
6fbd585d78
Fix gizmos app new panic (#11420)
# Objective

After the Gizmos changes, `App::init_gizmos_group` turned into a
important function that for sure mustn't panic. The problem is: the
actual implementation causes a panic if somehow the code is runned
before `GizmoPlugin` was added to the App
- The error occurs here for example:
```rust
fn main() {
    App::new()
        .init_gizmo_group::<MyGizmoConfig>()
        .add_plugins(DefaultPlugins)
        .run();
}

#[derive(Default, Reflect, GizmoConfigGroup)]
struct MyGizmoConfig;
```

![image](https://github.com/bevyengine/bevy/assets/126117294/35e75608-0946-4320-8035-00a82562e37e)


## Solution

- Instead of panicking when getting `GizmoConfigStore`, insert the store
in `App::init_gizmos_group` if needed

---

## Changelog

### Changed
- Changed App::init_gizmos_group to insert the resource if it don't
exist

### Removed
- Removed explicit init of `GizmoConfigStore`

---------

Co-authored-by: François <mockersf@gmail.com>
2024-01-19 06:03:27 +00:00
François
cd2cdb475a
Miri is failing on latest nightly: pin nightly to last known working version (#11421)
# Objective

- https://github.com/rust-lang/rust/pull/118553 seems to have broken
miri test

## Solution

- Pin nightly to before it was merged
2024-01-19 05:29:10 +00:00
IceSentry
7125dcb268
Customizable camera main texture usage (#11412)
# Objective

- Some users want to change the default texture usage of the main camera
but they are currently hardcoded

## Solution

- Add a component that is used to configure the main texture usage field

---

## Changelog

Added `CameraMainTextureUsage`
Added `CameraMainTextureUsage` to `Camera3dBundle` and `Camera2dBundle`

## Migration Guide

Add `main_texture_usages: Default::default()` to your camera bundle.

# Notes

Inspired by: #6815
2024-01-18 20:33:42 +00:00
Doonv
03ee959809
Fix panic on Text UI without Cameras (#11405)
# Objective

Fix https://github.com/bevyengine/bevy/issues/11396.

## Solution

Don't panic on taffy node not existing.

Plus minor warning text improvement.
2024-01-18 20:33:22 +00:00
BD103
056b006d4e
Use static_assertions to check for trait impls (#11407)
# Objective

- Tests are manually checking whether derived types implement certain
traits. (Specifically in `bevy_reflect.)
- #11182 introduces
[`static_assertions`](https://docs.rs/static_assertions/) to
automatically check this.
- Simplifies `Reflect` test in #11195.
- Closes #11196.

## Solution

- Add `static_assertions` and replace current tests.

---

I wasn't sure whether to remove the existing test or not. What do you
think?
2024-01-18 17:21:18 +00:00
Eris
d151883f3e
Get Change Tick methods for Resources (#11404)
# Objective

- Add methods to get Change Ticks for a given resource by type or
ComponentId
- Fixes #11390
The `is_resource_id_changed` requested in the Issue already exists, this
adds their request for `get_resource_change_ticks`

## Solution

- Added two methods to get change ticks by Type or ComponentId
2024-01-18 15:58:13 +00:00
Joona Aalto
c62ad4b2c4
Implement bounding volumes for primitive shapes (#11336)
# Objective

Closes #10570.

#10946 added bounding volume types and traits, but didn't use them for
anything yet. This PR implements `Bounded2d` and `Bounded3d` for Bevy's
primitive shapes.

## Solution

Implement `Bounded2d` and `Bounded3d` for primitive shapes. This allows
computing AABBs and bounding circles/spheres for them.

For most shapes, there are several ways of implementing bounding
volumes. I took inspiration from [Parry's bounding
volumes](https://github.com/dimforge/parry/tree/master/src/bounding_volume),
[Inigo Quilez](http://iquilezles.org/articles/diskbbox/), and figured
out the rest myself using geometry. I tried to comment all slightly
non-trivial or unclear math to make it understandable.

Parry uses support mapping (finding the farthest point in some direction
for convex shapes) for some AABBs like cones, cylinders, and line
segments. This involves several quat operations and normalizations, so I
opted for the simpler and more efficient geometric approaches shown in
[Quilez's article](http://iquilezles.org/articles/diskbbox/).

Below you can see some of the bounding volumes working in 2D and 3D.
Note that I can't conveniently add these examples yet because they use
primitive shape meshing, which is still WIP.


https://github.com/bevyengine/bevy/assets/57632562/4465cbc6-285b-4c71-b62d-a2b3ee16f8b4


https://github.com/bevyengine/bevy/assets/57632562/94b4ac84-a092-46d7-b438-ce2e971496a4

---

## Changelog

- Implemented `Bounded2d`/`Bounded3d` for primitive shapes
- Added `from_point_cloud` method for bounding volumes (used by many
bounding implementations)
- Added `point_cloud_2d/3d_center` and `rotate_vec2` utility functions
- Added `RegularPolygon::vertices` method (used in regular polygon AABB
construction)
- Added `Triangle::circumcenter` method (used in triangle bounding
circle construction)
- Added bounding circle/sphere creation from AABBs and vice versa

## Extra

Do we want to implement `Bounded2d` for some "3D-ish" shapes too? For
example, capsules are sort of dimension-agnostic and useful for 2D, so I
think that would be good to implement. But a cylinder in 2D is just a
rectangle, and a cone is a triangle, so they wouldn't make as much sense
to me. A conical frustum would be an isosceles trapezoid, which could be
useful, but I'm not sure if computing the 2D AABB of a 3D frustum makes
semantic sense.
2024-01-18 15:55:36 +00:00
jeliag
f6b40a6e43
Multiple Configurations for Gizmos (#10342)
# Objective

This PR aims to implement multiple configs for gizmos as discussed in
#9187.

## Solution

Configs for the new `GizmoConfigGroup`s are stored in a
`GizmoConfigStore` resource and can be accesses using a type based key
or iterated over. This type based key doubles as a standardized location
where plugin authors can put their own configuration not covered by the
standard `GizmoConfig` struct. For example the `AabbGizmoGroup` has a
default color and toggle to show all AABBs. New configs can be
registered using `app.init_gizmo_group::<T>()` during startup.

When requesting the `Gizmos<T>` system parameter the generic type
determines which config is used. The config structs are available
through the `Gizmos` system parameter allowing for easy access while
drawing your gizmos.

Internally, resources and systems used for rendering (up to an including
the extract system) are generic over the type based key and inserted on
registering a new config.

## Alternatives

The configs could be stored as components on entities with markers which
would make better use of the ECS. I also implemented this approach
([here](https://github.com/jeliag/bevy/tree/gizmo-multiconf-comp)) and
believe that the ergonomic benefits of a central config store outweigh
the decreased use of the ECS.

## Unsafe Code

Implementing system parameter by hand is unsafe but seems to be required
to access the config store once and not on every gizmo draw function
call. This is critical for performance. ~Is there a better way to do
this?~

## Future Work

New gizmos (such as #10038, and ideas from #9400) will require custom
configuration structs. Should there be a new custom config for every
gizmo type, or should we group them together in a common configuration?
(for example `EditorGizmoConfig`, or something more fine-grained)

## Changelog

- Added `GizmoConfigStore` resource and `GizmoConfigGroup` trait
- Added `init_gizmo_group` to `App`
- Added early returns to gizmo drawing increasing performance when
gizmos are disabled
- Changed `GizmoConfig` and aabb gizmos to use new `GizmoConfigStore`
- Changed `Gizmos` system parameter to use type based key to retrieve
config
- Changed resources and systems used for gizmo rendering to be generic
over type based key
- Changed examples (3d_gizmos, 2d_gizmos) to showcase new API

## Migration Guide

- `GizmoConfig` is no longer a resource and has to be accessed through
`GizmoConfigStore` resource. The default config group is
`DefaultGizmoGroup`, but consider using your own custom config group if
applicable.

---------

Co-authored-by: Nicola Papale <nicopap@users.noreply.github.com>
2024-01-18 15:52:50 +00:00
Brian Reavis
c9e1fcdb35
Added AssetLoadFailedEvent, UntypedAssetLoadFailedEvent (#11369)
# Objective

This adds events for assets that fail to load along with minor utility
methods to make them useful. This paves the way for users writing their
own error handling and retry systems, plus Bevy including robust retry
handling: #11349.

* Addresses #11288
* Needed for #11349

# Solution

```rust
/// An event emitted when a specific [`Asset`] fails to load.
#[derive(Event, Clone, Debug)]
pub struct AssetLoadFailedEvent<A: Asset> {
    pub id: AssetId<A>,
    /// The original handle returned when the asset load was requested.
    pub handle: Option<Handle<A>>,
    /// The asset path that was attempted.
    pub path: AssetPath<'static>,
    /// Why the asset failed to load.
    pub error: AssetLoadError,
}
```

I started implementing `AssetEvent::Failed` like suggested in #11288,
but decided it was better as its own type because:

* I think it makes sense for `AssetEvent` to only refer to assets that
actually exist.
* In order to return `AssetLoadError` in the event (which is useful
information for error handlers that might attempt a retry) we would have
to remove `Copy` from `AssetEvent`.
* There are numerous places in the render app that match against
`AssetEvent`, and I don't think it's worth introducing extra noise about
assets that don't exist.

I also introduced `UntypedAssetLoadErrorEvent`, which is very useful in
places that need to support type flexibility, like an Asset-agnostic
retry plugin.

# Changelog

* **Added:** `AssetLoadFailedEvent<A>`
* **Added**: `UntypedAssetLoadFailedEvent`
* **Added:** `AssetReaderError::Http` for status code information on
HTTP errors. Before this, status codes were only available by parsing
the error message of generic `Io` errors.
* **Added:** `asset_server.get_path_id(path)`. This method simply gets
the asset id for the path. Without this, one was left using
`get_path_handle(path)`, which has the overhead of returning a strong
handle.
* **Fixed**: Made `AssetServer` loads return the same handle for assets
that already exist in a failed state. Now, when you attempt a `load`
that's in a `LoadState::Failed` state, it'll re-use the original asset
id. The advantage of this is that any dependent assets created using the
original handle will "unbreak" if a retry succeeds.

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
2024-01-17 21:12:00 +00:00
GitGhillie
9abf565138
Restore brightness in the remaining three examples after exposure PR (#11389)
# Objective

Fixes #11376
During the development of the exposure settings PR (#11347) all examples
with lighting had to be adjusted, but three were missed or simply didn't
exist yet at the time. This PR restores the brightness in those examples
again:

render_ui_to_texture
asset_loading
hot_asset_reloading

All of them are a bit brighter now compared to before the exposure PR,
but it looks better IMO.
2024-01-17 17:10:21 +00:00
Architector #4
8db4723373
[doc] Fix typo and formatting in CONTRIBUTING.md (#11381)
# Objective

Issue: There is a typo in `CONTRIBUTING.md` ("then" used in place of
"them"). There is also an inconsistency of usage of periods at ends of
items in lists, and one section is written with non-breaking spaces
without good reason.

## Solution

Fix the aforementioned typo and consistency issues.

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
Co-authored-by: Rob Parrett <robparrett@gmail.com>
2024-01-17 17:07:53 +00:00
robtfm
30940e5cb4
fix occasional crash moving ui root nodes (#11371)
# Objective

fix an occasional crash when moving ui root nodes between cameras.

occasionally, updating the TargetCamera of a ui element and then
removing the element causes a crash.

i believe that is because when we assign a child in taffy, the old
parent doesn't remove that child from it's children, so we have:

```
user: create root node N1, camera A
-> layout::set_camera_children(A) : 
	- create implicit node A1
	- assign 1 as child -> taffy.children[A1] = [N1], taffy.parents[1] = A1

user: move root node N1 to camera B
-> layout::set_camera_children(B) :
	- create implicit node B1
	- assign 1 as child -> taffy.children[A1] = [N1], taffy.children[B1] = [N1], taffy.parents[1] = B1
-> layout::set_camera_children(A) :
	- remove implicit node A1 (which still has N1 as a child) -> 
		-> taffy sets parent[N1] = None ***
		-> taffy.children[B1] = [N1], taffy.parents[1] = None

user: remove N1
-> layout::remove_entities(N1)
	- since parent[N1] is None, it's not removed from B1 -> taffy.children[B1] = [N1], taffy.parents[1] is removed
-> layout::set_camera_children(B)
	- remove implicit node B1
	- taffy crash accessing taffy.parents[N1]
```

## Solution

we can work around this by making sure to remove the child from the old
parent if one exists (this pr).

i think a better fix may be for taffy to check in `Taffy::remove` and
only set the child's parent to None if it is currently equal to the node
being removed but i'm not sure if there's an explicit assumption we're
violating here (@nicoburns).
2024-01-17 16:53:27 +00:00
wackbyte
43f83d5e7c
Remove duplicate #[automatically_derived] in ECS macro (#11388)
# Objective

It's already provided by `item_attrs`, so it can be removed.

# Solution

Remove the extra `#[automatically_derived]`.
2024-01-17 16:52:45 +00:00
Mateusz Wachowiak
9a8349ac7b
Run markdownlint (#11386)
# Objective

- Fix formatting in markdown file.

## Solution

- Ran `markdownlint -f -c .github/linters/.markdown-lint.yml .` from
[CONTRIBUTING.md](https://github.com/bevyengine/bevy/blob/main/CONTRIBUTING.md?plain=1#L341)

I came across this when working on `bevy_dev_tools`
2024-01-17 14:27:28 +00:00
Rob Parrett
3a666cab23
Fix link to plugin guidelines (#11379)
# Objective

The document was moved in #11242, so this link is now broken.

## Solution

Swap in a working link.
2024-01-17 07:30:03 +00:00
Giacomo Stevanato
39cca41f3f
Make DynamicUniformBuffer::push accept an &T instead of T (#11373)
# Objective

- `DynamicUniformBuffer::push` takes an owned `T` but only uses a shared
reference to it
- This in turn requires users of `DynamicUniformBuffer::push` to
potentially unecessarily clone data

## Solution

- Have `DynamicUniformBuffer::push` take a shared reference to `T`

---

## Changelog

- `DynamicUniformBuffer::push` now takes a `&T` instead of `T`

## Migration Guide

- Users of `DynamicUniformBuffer::push` now need to pass references to
`DynamicUniformBuffer::push` (e.g. existing `uniforms.push(value)` will
now become `uniforms.push(&value)`)
2024-01-16 20:51:56 +00:00