Commit graph

5242 commits

Author SHA1 Message Date
Joseph
df2ba09989
Restore support for running fn EntityCommands on entities that might be despawned (#11107)
# Objective

In #9604 we removed the ability to define an `EntityCommand` as
`fn(Entity, &mut World)`. However I have since realized that `fn(Entity,
&mut World)` is an incredibly expressive and powerful way to define a
command for an entity that may or may not exist (`fn(EntityWorldMut)`
only works on entities that are alive).

## Solution

Support `EntityCommand`s in the style of `fn(Entity, &mut World)`, as
well as `fn(EntityWorldMut)`. Use a marker generic on the
`EntityCommand` trait to allow multiple impls.

The second commit in this PR replaces all of the internal command
definitions with ones using `fn` definitions. This is mostly just to
show off how expressive this style of command is -- we can revert this
commit if we'd rather avoid breaking changes.

---

## Changelog

Re-added support for expressively defining an `EntityCommand` as a
function that takes `Entity, &mut World`.

## Migration Guide

All `Command` types in `bevy_ecs`, such as `Spawn`, `SpawnBatch`,
`Insert`, etc., have been made private. Use the equivalent methods on
`Commands` or `EntityCommands` instead.
2024-01-08 22:32:28 +00:00
Connor King
1260b7bcf1
StateTransitionEvent (#11089)
# Objective

- Make it possible to react to arbitrary state changes
- this will be useful regardless of the other changes to states
currently being discussed

## Solution

- added `StateTransitionEvent<S>` struct
- previously, this would have been impossible:

```rs
#[derive(States, Eq, PartialEq, Hash, Copy, Clone, Default)]
enum MyState {
  #[default]
  Foo,
  Bar(MySubState),
}

enum MySubState {
  Spam,
  Eggs,
}

app.add_system(Update, on_enter_bar);

fn on_enter_bar(trans: EventReader<StateTransition<MyState>>){
  for (befoare, after) in trans.read() {
    match before, after {
      MyState::Foo, MyState::Bar(_) => info!("detected transition foo => bar");
      _, _ => ();
    }
  }
}
```

---

## Changelog

- Added
  - `StateTransitionEvent<S>` - Fired on state changes of `S`

## Migration Guide

N/A no breaking changes

---------

Co-authored-by: Federico Rinaldi <gisquerin@gmail.com>
2024-01-08 22:27:00 +00:00
Stepan Koltsov
8d9a0a883f
Mul<f32> for ScalingMode (#11030)
Complement to https://github.com/bevyengine/bevy/pull/11022: if
`OrthographicProjection.scale` is removed, this can be used instead.

CC @doonv @Davier
2024-01-08 22:24:32 +00:00
Stepan Koltsov
38ef170b86
Explain OrthographicProjection.scale (#11023)
Alternative to https://github.com/bevyengine/bevy/pull/11022.

(Also remove "in world units", it is probably a mistake.)
2024-01-08 22:22:03 +00:00
andriyDev
da485c29b3
Add reserve_handle to Assets. (#10939)
# Objective

Fixes #10938.

## Solution

Adds `reserve_handle` to `Assets`.

---

## Changelog

- Added `reserve_handle` to `Assets`.
2024-01-08 22:17:29 +00:00
Joona Aalto
a795de30b4
Use impl Into<A> for Assets::add (#10878)
# Motivation

When spawning entities into a scene, it is very common to create assets
like meshes and materials and to add them via asset handles. A common
setup might look like this:

```rust
fn setup(
    mut commands: Commands,
    mut meshes: ResMut<Assets<Mesh>>,
    mut materials: ResMut<Assets<StandardMaterial>>,
) {
    commands.spawn(PbrBundle {
        mesh: meshes.add(Mesh::from(shape::Cube { size: 1.0 })),
        material: materials.add(StandardMaterial::from(Color::RED)),
        ..default()
    });
}
```

Let's take a closer look at the part that adds the assets using `add`.

```rust
mesh: meshes.add(Mesh::from(shape::Cube { size: 1.0 })),
material: materials.add(StandardMaterial::from(Color::RED)),
```

Here, "mesh" and "material" are both repeated three times. It's very
explicit, but I find it to be a bit verbose. In addition to being more
code to read and write, the extra characters can sometimes also lead to
the code being formatted to span multiple lines even though the core
task, adding e.g. a primitive mesh, is extremely simple.

A way to address this is by using `.into()`:

```rust
mesh: meshes.add(shape::Cube { size: 1.0 }.into()),
material: materials.add(Color::RED.into()),
```

This is fine, but from the names and the type of `meshes`, we already
know what the type should be. It's very clear that `Cube` should be
turned into a `Mesh` because of the context it's used in. `.into()` is
just seven characters, but it's so common that it quickly adds up and
gets annoying.

It would be nice if you could skip all of the conversion and let Bevy
handle it for you:

```rust
mesh: meshes.add(shape::Cube { size: 1.0 }),
material: materials.add(Color::RED),
```

# Objective

Make adding assets more ergonomic by making `Assets::add` take an `impl
Into<A>` instead of `A`.

## Solution

`Assets::add` now takes an `impl Into<A>` instead of `A`, so e.g. this
works:

```rust
    commands.spawn(PbrBundle {
        mesh: meshes.add(shape::Cube { size: 1.0 }),
        material: materials.add(Color::RED),
        ..default()
    });
```

I also changed all examples to use this API, which increases consistency
as well because `Mesh::from` and `into` were being used arbitrarily even
in the same file. This also gets rid of some lines of code because
formatting is nicer.

---

## Changelog

- `Assets::add` now takes an `impl Into<A>` instead of `A`
- Examples don't use `T::from(K)` or `K.into()` when adding assets

## Migration Guide

Some `into` calls that worked previously might now be broken because of
the new trait bounds. You need to either remove `into` or perform the
conversion explicitly with `from`:

```rust
// Doesn't compile
let mesh_handle = meshes.add(shape::Cube { size: 1.0 }.into()),

// These compile
let mesh_handle = meshes.add(shape::Cube { size: 1.0 }),
let mesh_handle = meshes.add(Mesh::from(shape::Cube { size: 1.0 })),
```

## Concerns

I believe the primary concerns might be:

1. Is this too implicit?
2. Does this increase codegen bloat?

Previously, the two APIs were using `into` or `from`, and now it's
"nothing" or `from`. You could argue that `into` is slightly more
explicit than "nothing" in cases like the earlier examples where a
`Color` gets converted to e.g. a `StandardMaterial`, but I personally
don't think `into` adds much value even in this case, and you could
still see the actual type from the asset type.

As for codegen bloat, I doubt it adds that much, but I'm not very
familiar with the details of codegen. I personally value the user-facing
code reduction and ergonomics improvements that these changes would
provide, but it might be worth checking the other effects in more
detail.

Another slight concern is migration pain; apps might have a ton of
`into` calls that would need to be removed, and it did take me a while
to do so for Bevy itself (maybe around 20-40 minutes). However, I think
the fact that there *are* so many `into` calls just highlights that the
API could be made nicer, and I'd gladly migrate my own projects for it.
2024-01-08 22:14:43 +00:00
Patrick Walton
54a943d232
Implement minimal reflection probes. (#10057)
# 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-08 22:09:17 +00:00
Kyle
2847cc6933
Don't auto create assets folder (#11218)
# Objective

- Don't automatically create an assets folder
- resolves #11208

## Solution

- Removes directory creation from file reader.
- Clearer panic when using file watcher and asset folder doesn't exist

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
Co-authored-by: Nicola Papale <nicopap@users.noreply.github.com>
2024-01-08 21:45:26 +00:00
François
371cd69d4b
example showcase patches: use default instead of game mode for desktop (#11250)
# Objective

- After https://github.com/bevyengine/bevy/pull/11227, example showcase
timeouts
- `ReactiveLowPower` now can wait indefinitely depending on "platform
specifics"

## Solution

- Patch desktop mode in example showcase to use default mode which is
always `Continuous`
2024-01-08 20:52:43 +00:00
TrialDragon
c1b785c360
Migrate third party plugins guidelines to the book (#11242)
# Objective

- Describe the objective or issue this PR addresses.
- If you're fixing a specific issue, say "Fixes #X".

Removes the old third party plugin guidelines section and related links
since it is being moved to the Bevy book in the site per
https://github.com/bevyengine/bevy-website/pull/848 and
https://github.com/bevyengine/bevy-website/issues/298

## Solution

- Describe the solution used to achieve the objective above. 

Removes the old links and files.
2024-01-07 23:19:37 +00:00
re0312
101037d0c2
update Outdated comment (#11243)
# Objective

- since #9236 queue_mesh_bind_group has been renamed to
prepare_mesh_bind_group,but the comment referring to it has not been
updated. .
2024-01-07 15:02:43 +00:00
thebluefish
cfcb6885e3
Change SceneSpawner::spawn_dynamic_sync to return InstanceID (#11239)
# Objective

`SceneSpawner::spawn_dynamic_sync` currently returns `()` on success,
which is inconsistent with the other `SceneSpawner::spawn_` methods that
all return an `InstanceId`. We need this ID to do useful work with the
newly-created data.

## Solution

Updated `SceneSpawner::spawn_dynamic_sync` to return `Result<InstanceId,
SceneSpawnError>` instead of `Result<(), SceneSpawnError>`
2024-01-06 22:26:32 +00:00
Joona Aalto
0349809420
Add libm feature to bevy_math (#11238)
# Objective

Different platforms use their own implementations of several
mathematical functions (especially transcendental functions like sin,
cos, tan, atan, and so on) to provide hardware-level optimization using
intrinsics. This is good for performance, but bad when you expect
consistent outputs across machines.

[`libm`](https://github.com/rust-lang/libm) is a widely used crate that
provides mathematical functions that don't use intrinsics like `std`
functions. This allows bit-for-bit deterministic math across hardware,
which is crucial for things like cross-platform deterministic physics
simulation.

Glam has the `libm` feature for using [`libm` for the
math](d2871a151b/src/f32/math.rs (L35))
in its own types. This would be nice to expose as a feature in
`bevy_math`.

## Solution

Add `libm` feature to `bevy_math`. We could name it something like
`enhanced-determinism`, but this wouldn't be accurate for the rest of
Bevy, so I think just `libm` is more fitting and explicit.
2024-01-06 22:01:57 +00:00
Nicola Papale
79021c78c6
Fix perf degradation on web builds (#11227)
# Objective

- Since #10702, the way bevy updates the window leads to major slowdowns
as seen in
    - #11122 
    - #11220
- Slow is bad, furthermore, _very_ slow is _very_ bad. We should fix
this issue.

## Solution

- Move the app update code into the `Event::WindowEvent { event:
WindowEvent::RedrawRequested }` branch of the event loop.
- Run `window.request_redraw()` When `runner_state.redraw_requested`
- Instead of swapping `ControlFlow` between `Poll` and `Wait`, we always
keep it at `Wait`, and use `window.request_redraw()` to schedule an
immediate call to the event loop.
- `runner_state.redraw_requested` is set to `true` when
`UpdateMode::Continuous` and when a `RequestRedraw` event is received.
- Extract the redraw code into a separate function, because otherwise
I'd go crazy with the indentation level.
- Fix #11122.

## Testing

I tested the WASM builds as follow:

```sh
cargo run -p build-wasm-example -- --api webgl2 bevymark
python -m http.server --directory examples/wasm/ 8080
# Open browser at http://localhost:8080
```

On main, even spawning a couple sprites is super choppy. Even if it says
"300 FPS". While on this branch, it is smooth as butter.

I also found that it fixes all choppiness on window resize (tested on
Linux/X11). This was another issue from #10702 IIRC.

So here is what I tested:

- On `wasm`: `many_foxes` and `bevymark`, with `argh::from_env()`
commented out, otherwise we get a cryptic error.
- Both with `PresentMode::AutoVsync` and `PresentMode::AutoNoVsync`
  - On main, it is consistently choppy.
- With this PR, the visible frame rate is consistent with the diagnostic
numbers
- On native (linux/x11) I ran similar tests, making sure that
`AutoVsync` limits to monitor framerate, and `AutoNoVsync` doesn't.

## Future work

Code could be improved, I wanted a quick solution easy to review, but we
really need to make the code more accessible.

- #9768
- ~~**`WinitSettings::desktop_app()` is completely borked.**~~ actually
broken on main as well

### Review guide

Consider enable the non-whitespace diff to see the _real_ change set.
2024-01-06 19:40:13 +00:00
Stepan Koltsov
a35a151f47
Fix integer overflow in BlobVec::reserve_exact (#11234)
# Objective

When `BlobVec::reserve` is called with an argument causing capacity
overflow, in release build capacity overflow is ignored, and capacity is
decreased.

I'm not sure it is possible to exploit this issue using public API of
`bevy_ecs`, but better fix it anyway.

## Solution

Check for capacity overflow.
2024-01-06 17:31:01 +00:00
François
425570aa75
assets should be kept on CPU by default (#11212)
# Objective

- Since #10520, assets are unloaded from RAM by default. This breaks a
number of scenario:
  - using `load_folder`
- loading a gltf, then going through its mesh to transform them /
compute a collider / ...
- any assets/subassets scenario should be `Keep` as you can't know what
the user will do with the assets
  - android suspension, where GPU memory is unloaded

- Alternative to #11202 

## Solution

- Keep assets on CPU memory by default
2024-01-05 05:53:47 +00:00
Mateusz Wachowiak
759b3985d8
Extend Touches with clear and reset methods (#10930)
# Objective

- Resolves #10913.
- Extend `Touches` with methods that are implemented on `ButtonInput`.

## Solution

- Add function `clear_just_pressed` that clears the `just_pressed` state
of the touch input.
- Add function `clear_just_released` that clears the `just_released`
state of the touch input.
- Add function `clear_just_canceled` that clears the `just_canceled`
state of the touch input.
- Add function `release` that changes state of the touch input from
`pressed` to `just_released`.
- Add function `release_all` that changes state of every touch input
from `pressed` to `just_released`
- Add function `clear` that clears `just_pressed`, `just_released` and
`just_canceled` data for every input.
- Add function `reset_all` that clears `pressed`, `just_pressed`,
`just_released` and `just_canceled` data for every input.
- Add tests for functions above.
2024-01-04 23:13:29 +00:00
Stepan Koltsov
cf70f53227
Fix integer overflow in BlobVec::push for ZST (#10799)
`reserve_exact` is no-op for ZST because `self.item_layout.size() > 0`
is always `false`.


daa8bf20df/crates/bevy_ecs/src/storage/blob_vec.rs (L112-L120)

Then in `push` we just increase `.len` ignoring integer overflow.


daa8bf20df/crates/bevy_ecs/src/storage/blob_vec.rs (L232-L237)
2024-01-04 21:32:05 +00:00
Stepan Koltsov
cc2a77b5c5
Explain Camera physical size is in pixel (#11189)
# Objective

It may be not be obviously clear what is physical size. Is it inches? Is
it scaled somehow?

## Solution

Add rustdoc comments.
2024-01-04 18:28:36 +00:00
Adam
fe68005f71
Implement TypePath for EntityHash (#11195)
# Objective

- Fix #11117 by implementing `Reflect` for `EntityHashMap`

## Solution

- By implementing `TypePath` for `EntityHash`, Bevy will automatically
implement `Reflect` for `EntityHashMap`

---

## Changelog

- `TypePath` is implemented for `EntityHash`
- A test called `entity_hashmap_should_impl_reflect` was created to
verify that #11117 was solved.
2024-01-04 18:28:31 +00:00
Torstein Grindvik
99c43fabdf
Usability methods for RenderTargets and image handles (#10736)
# Objective

In my code I use a lot of images as render targets.
I'd like some convenience methods for working with this type.

## Solution

- Allow `.into()` to construct a `RenderTarget`
- Add `.as_image()` 

---

## Changelog

### Added

- `RenderTarget` can be constructed via `.into()` on a `Handle<Image>`
- `RenderTarget` new method: `as_image`

---------

Signed-off-by: Torstein Grindvik <torstein.grindvik@muybridge.com>
Co-authored-by: Torstein Grindvik <torstein.grindvik@muybridge.com>
2024-01-04 17:01:04 +00:00
Chia-Hsiang Cheng
93c7e7cf4d
Rename "AddChild" to "PushChild" (#11194)
# Objective

- Fixes #11187 

## Solution

- Rename the `AddChild` struct to `PushChild`
- Rename the `AddChildInPlace` struct to `PushChildInPlace`

## Migration Guide

The struct `AddChild` has been renamed to `PushChild`, and the struct
`AddChildInPlace` has been renamed to `PushChildInPlace`.
2024-01-04 16:06:14 +00:00
François
5511483408
missed negation during accessibility refactor (#11206)
# Objective

- Since #10911, example `button` crashes when clicking the button
```
thread 'main' panicked at .cargo/registry/src/index.crates.io-6f17d22bba15001f/accesskit_consumer-0.16.1/src/tree.rs:139:9:
assertion `left == right` failed
  left: 1
 right: 0
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
Encountered a panic in system `bevy_winit::accessibility::update_accessibility_nodes`!
Encountered a panic in system `bevy_app::main_schedule::Main::run_main`!
```


## Solution

- Re-add lost negation
2024-01-03 23:14:22 +00:00
Atomei Alexandru
3f535d54eb
Made the remaining types from bevy_ui to reflect the Default trait if… (#11199)
# Objective

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

## Solution

- Made the remaining types from bevy_ui that do not reflect the Default
trait to do it if possible.
2024-01-03 18:57:05 +00:00
pablo-lua
41c362051c
Create serialize feature for bevy_ui (#11188)
# Objective

- Fixes #11119  

## Solution

- Creation of the serialize feature to ui

---

## Changelog

### Changed
- Changed all the structs that implement Serialize and Deserialize to
only implement when feature is on

## Migration Guide

- If you want to use serialize and deserialize with types from bevy_ui,
you need to use the feature serialize in your TOML
```toml
[dependencies.bevy]
features = ["serialize"]
```
2024-01-03 17:52:16 +00:00
Chia-Hsiang Cheng
b6da40cfe6
Print a warning for un-applied commands being dropped from a CommandQueue (#11146)
# Objective

- Fixes #11125 
## Solution

Add a warning for un-applied commands to the `drop` function.
2024-01-03 15:32:57 +00:00
TheBlckbird
19f5222c29
Fix typos plugin.rs (#11193)
# Objective

- There are multiple grammar mistakes in the `plugin.rs` file.

## Solution

- Corrects the grammar and spelling in the docs of `plugin.rs`
2024-01-03 15:30:35 +00:00
Eye
07cd955c02
Fix: Gizmos crash due to the persistence policy being set to Unload. Change it to Keep (#11192)
# Objective

Fixes Gizmos crash due to the persistence policy being set to `Unload`

## Solution

Change it to `Keep`

Co-authored-by: rqg <ranqingguo318@gmail.com>
2024-01-03 11:03:18 +00:00
Patrick Walton
5697fee3ad
Bump the vertex attribute index for prepass joints. (#11191)
This was missed in #10231.

Fixes #11190.
2024-01-03 10:35:39 +00:00
JMS55
44424391fe
Unload render assets from RAM (#10520)
# Objective
- No point in keeping Meshes/Images in RAM once they're going to be sent
to the GPU, and kept in VRAM. This saves a _significant_ amount of
memory (several GBs) on scenes like bistro.
- References
  - https://github.com/bevyengine/bevy/pull/1782
  - https://github.com/bevyengine/bevy/pull/8624 

## Solution
- Augment RenderAsset with the capability to unload the underlying asset
after extracting to the render world.
- Mesh/Image now have a cpu_persistent_access field. If this field is
RenderAssetPersistencePolicy::Unload, the asset will be unloaded from
Assets<T>.
- A new AssetEvent is sent upon dropping the last strong handle for the
asset, which signals to the RenderAsset to remove the GPU version of the
asset.

---

## Changelog
- Added `AssetEvent::NoLongerUsed` and
`AssetEvent::is_no_longer_used()`. This event is sent when the last
strong handle of an asset is dropped.
- Rewrote the API for `RenderAsset` to allow for unloading the asset
data from the CPU.
- Added `RenderAssetPersistencePolicy`.
- Added `Mesh::cpu_persistent_access` for memory savings when the asset
is not needed except for on the GPU.
- Added `Image::cpu_persistent_access` for memory savings when the asset
is not needed except for on the GPU.
- Added `ImageLoaderSettings::cpu_persistent_access`.
- Added `ExrTextureLoaderSettings`.
- Added `HdrTextureLoaderSettings`.

## Migration Guide
- Asset loaders (GLTF, etc) now load meshes and textures without
`cpu_persistent_access`. These assets will be removed from
`Assets<Mesh>` and `Assets<Image>` once `RenderAssets<Mesh>` and
`RenderAssets<Image>` contain the GPU versions of these assets, in order
to reduce memory usage. If you require access to the asset data from the
CPU in future frames after the GLTF asset has been loaded, modify all
dependent `Mesh` and `Image` assets and set `cpu_persistent_access` to
`RenderAssetPersistencePolicy::Keep`.
- `Mesh` now requires a new `cpu_persistent_access` field. Set it to
`RenderAssetPersistencePolicy::Keep` to mimic the previous behavior.
- `Image` now requires a new `cpu_persistent_access` field. Set it to
`RenderAssetPersistencePolicy::Keep` to mimic the previous behavior.
- `MorphTargetImage::new()` now requires a new `cpu_persistent_access`
parameter. Set it to `RenderAssetPersistencePolicy::Keep` to mimic the
previous behavior.
- `DynamicTextureAtlasBuilder::add_texture()` now requires that the
`TextureAtlas` you pass has an `Image` with `cpu_persistent_access:
RenderAssetPersistencePolicy::Keep`. Ensure you construct the image
properly for the texture atlas.
- The `RenderAsset` trait has significantly changed, and requires
adapting your existing implementations.
  - The trait now requires `Clone`.
- The `ExtractedAsset` associated type has been removed (the type itself
is now extracted).
  - The signature of `prepare_asset()` is slightly different
- A new `persistence_policy()` method is now required (return
RenderAssetPersistencePolicy::Unload to match the previous behavior).
- Match on the new `NoLongerUsed` variant for exhaustive matches of
`AssetEvent`.
2024-01-03 03:31:04 +00:00
Charles Bournhonesque
02755086e8
Add static assertions to bevy_utils for compile-time checks (#11182)
# Objective

- We want to use `static_assertions` to perform precise compile time
checks at testing time. In this PR, we add those checks to make sure
that `EntityHashMap` and `PreHashMap` are `Clone` (and we replace the
more clumsy previous tests)
- Fixes #11181 

(will need to be rebased once
https://github.com/bevyengine/bevy/pull/11178 is merged)

---------

Co-authored-by: Charles Bournhonesque <cbournhonesque@snapchat.com>
2024-01-02 22:08:30 +00:00
Patrick Walton
dd14f3a477
Implement lightmaps. (#10231)
![Screenshot](https://i.imgur.com/A4KzWFq.png)

# Objective

Lightmaps, textures that store baked global illumination, have been a
mainstay of real-time graphics for decades. Bevy currently has no
support for them, so this pull request implements them.

## Solution

The new `Lightmap` component can be attached to any entity that contains
a `Handle<Mesh>` and a `StandardMaterial`. When present, it will be
applied in the PBR shader. Because multiple lightmaps are frequently
packed into atlases, each lightmap may have its own UV boundaries within
its texture. An `exposure` field is also provided, to control the
brightness of the lightmap.

Note that this PR doesn't provide any way to bake the lightmaps. That
can be done with [The Lightmapper] or another solution, such as Unity's
Bakery.

---

## Changelog

### Added
* A new component, `Lightmap`, is available, for baked global
illumination. If your mesh has a second UV channel (UV1), and you attach
this component to the entity with that mesh, Bevy will apply the texture
referenced in the lightmap.

[The Lightmapper]: https://github.com/Naxela/The_Lightmapper

---------

Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2024-01-02 20:38:47 +00:00
Federico Rinaldi
2440aa8475
Add bevy_hierarchy Crate and plugin documentation (#10951)
This PR is part of a project aimed at improving the API documentation of
`bevy_hierarchy`. Other PRs will be based on this.

This PR in particular is also an experiment in providing a high level
overview of the tools provided by a Bevy plugin/crate. It also provides
general information about universal invariants, so statement repetition
in crate items can be dramatically reduced.

## Other changes

The other PRs of this project that expand on this one:

- #10952
- #10953
- #10954
- #10955
- #10956
- #10957

---------

Co-authored-by: GitGhillie <jillisnoordhoek@gmail.com>
2024-01-02 19:40:14 +00:00
Stepan Koltsov
0f71dcbf1a
Simplify examples/3d/orthographic (#11045)
Current example may mislead into thinking both parameters are mandatory
to make orthographic projection work.
2024-01-02 19:27:22 +00:00
BD103
1a2a184350
Publish dev-docs with Github Pages artifacts (2nd attempt) (#10892)
Supersedes #10888.

# Objective

Closes #10821

## Solution

- Replaced
[JamesIves/github-pages-deploy-action](https://github.com/JamesIves/github-pages-deploy-action)
with
[actions/upload-pages-artifact](https://github.com/actions/upload-pages-artifact)
and [actions/deploy-pages](https://github.com/actions/deploy-pages).

## Notes

- I made this workflow possible to run through dispatch
(`workflow_dispatch`), in case something goes wrong.
- I restricted the permissions to just the things Github Pages needs.
- I made it so that only one deployments can happen at a time, the other
deployment requests will be queued up and the latest one will be run.
2024-01-02 18:13:31 +00:00
Charles Bournhonesque
ab10e85558
Enable cloning EntityHashMap and PreHashMap (#11178)
# Objective

- `EntityHashMap`, `EntityHashSet` and `PreHashMap` are currently not
Cloneable because of a missing trivial `Clone` bound for `EntityHash`
and `PreHash`. This PR makes them Cloneable.

(the parent struct `hashbrown::HashMap` requires the `HashBuilder` to be
`Clone` for the `HashMap` to be `Clone`, see:
https://github.com/rust-lang/hashbrown/blob/master/src/map.rs#L195)


## Solution

- Add a `Clone` bound to `PreHash` and `EntityHash`

---------

Co-authored-by: Charles Bournhonesque <cbournhonesque@snapchat.com>
2024-01-02 18:11:47 +00:00
Joona Aalto
536a7bd810
Add approx feature to bevy_math (#11176)
# Objective

`bevy_math` re-exports Glam, but doesn't have a feature for enabling
`approx` for it. Many projects (including some of Bevy's own crates)
need `approx`, and it'd be nice if you didn't have to manually add Glam
to specify the feature for it.

## Solution

Add an `approx` feature to `bevy_math`.
2024-01-02 18:10:44 +00:00
Joona Aalto
2c5439b25e
Add constants for Direction2d and Direction3d (#11180)
# Objective

I often need a direction along one of the cartesian XYZ axes, and it
currently requires e.g. `Direction2d::from_normalized(Vec2::X)`, which
isn't ideal.

## Solution

Add direction constants that are the same as the ones on Glam types. I
also copied the doc comment format "A unit vector pointing along the ...
axis", but I can change it if there's a better wording for directions.
2024-01-02 17:00:23 +00:00
Joona Aalto
6086d4193e
Implement Neg for Direction2d and Direction3d (#11179)
# Objective

I frequently encounter cases where I need to get the opposite direction.
This currently requires something like
`Direction2d::from_normalized(-*direction)`, which is very inconvenient.

## Solution

Implement `Neg` for `Direction2d` and `Direction3d`.
2024-01-02 16:46:03 +00:00
Miles Silberling-Cook
4034740396
Add window entity to TouchInput events (#11128)
# Objective

If you have multiple windows, there is no way to determine which window
a `TouchInput` event applies to. This fixes that.

## Solution

- Add the window entity directly to `TouchInput`, just like the other
input events.
- Fixes #6011.

## Migration Guide

+ Add a `window` field when constructing or destructuring a `TouchInput`
struct.
2024-01-02 03:03:05 +00:00
Stepan Koltsov
d8d8bcfb21
Add ability to panic to logs example (#11171)
# Objective

To debug issues like https://github.com/bevyengine/bevy/pull/11169.

## Solution

When P is pressed in logs example, call `panic!()`.

<img width="1392" alt="Screenshot 2024-01-02 at 01 10 16"
src="https://github.com/bevyengine/bevy/assets/28969/a788737e-d23c-43a3-bc68-d6c5b0ab88ad">
2024-01-02 03:02:56 +00:00
Brian Reavis
846a871cb2
Export tonemapping_pipeline_key (2d), alpha_mode_pipeline_key (#11166)
This expands upon https://github.com/bevyengine/bevy/pull/11134.

I found myself needing `tonemapping_pipeline_key` for some custom 2d
draw functions. #11134 exported the 3d version of
`tonemapping_pipeline_key` and this PR exports the 2d version. I also
made `alpha_mode_pipeline_key` public for good measure.
2024-01-01 23:57:12 +00:00
Stepan Koltsov
443b64a612
Print to stderr from panic handler in LogPlugin (#11170)
# Objective

When panic handler prints to stdout instead of stderr, I've observed two
outcomes with this PR test #11169:
- Sometimes output is mixed up, so it is not clear where one record ends
and another stards
- Sometimes output is lost

## Solution

Print to stderr.

## Changelog

- Panic handler in `LogPlugin` writes to stderr instead of stdin.
2024-01-01 17:10:20 +00:00
Stepan Koltsov
6bc2686a7a
impl ExclusiveSystemParam for SystemName (#11163)
# Objective

`SystemName` might be useful in systems which accept `&mut World`.

## Solution

- `impl ExclusiveSystemParam for SystemName`
- move `SystemName` into a separate file, because it no longer belongs
to a file which defines `SystemParam`
- add a test for new impl, and for existing impl

## Changelog

- `impl ExclusiveSystemParam for SystemName`
2024-01-01 17:08:29 +00:00
Marco Buono
c2ab3a0402
Do not load prepass normals for transmissive materials (#11140)
Turns out whenever a normal prepass was active (which includes whenever
you use SSAO) we were attempting to read the normals from the prepass
for the specular transmissive material. Since transmissive materials
don't participate in the prepass (unlike opaque materials) we were
reading the normals from “behind” the mesh, producing really weird
visual results.

# Objective

- Fixes #11112.

## Solution

- We introduce a new `READS_VIEW_TRANSMISSION_TEXTURE` mesh pipeline
key;
- We set it whenever the material properties has the
`reads_view_transmission_texture` flag set; (i.e. the material is
transmissive)
- If this key is set we prevent the reading of normals from the prepass,
by not setting the `LOAD_PREPASS_NORMALS` shader def.

---

## Changelog

### Fixed

- Specular transmissive materials no longer attempt to erroneously load
prepass normals, and now work correctly even with the normal prepass
active (e.g. when using SSAO)
2024-01-01 17:04:20 +00:00
Stepan Koltsov
17ef73199b
Fix Mesh::ATTRIBUTE_UV_0 documentation (#11110)
Comment incorrect suggests that texture is clamped outside of `0..=1`
range, while it can actually be configured.

CC https://github.com/bevyengine/bevy/pull/11109
2024-01-01 16:58:48 +00:00
Tygyh
55c9958dd0
refactor collide code (Adopted) (#11106)
# Objective

- Refactor collide code and add tests.

## Solution

- Rebase the changes made in #4485.

Co-authored-by: Eduardo Canellas de Oliveira <eduardo.canellas@bemobi.com>
2024-01-01 16:57:27 +00:00
Adam
8baefa1570
Implement Deref and DerefMut for In (#11104)
# Objective

Implement Deref and DerefMut for In<T>

makes it so the user doesn't have to add ".0" in most cases
2024-01-01 16:55:07 +00:00
Kees van Beilen
2fd0043cfd
Fixed Typo in the description of EntityMut (#11103)
# Objective
Fix a typo in the description of the  `EntityMut` struct
2024-01-01 16:51:25 +00:00
Doonv
189ceaf0d3
Replace or document ignored doctests (#11040)
# Objective

There are a lot of doctests that are `ignore`d for no documented reason.
And that should be fixed.

## Solution

I searched the bevy repo with the regex ` ```[a-z,]*ignore ` in order to
find all `ignore`d doctests. For each one of the `ignore`d doctests, I
did the following steps:
1. Attempt to remove the `ignored` attribute while still passing the
test. I did this by adding hidden dummy structs and imports.
2. If step 1 doesn't work, attempt to replace the `ignored` attribute
with the `no_run` attribute while still passing the test.
3. If step 2 doesn't work, keep the `ignored` attribute but add
documentation for why the `ignored` attribute was added.

---------

Co-authored-by: François <mockersf@gmail.com>
2024-01-01 16:50:56 +00:00