Commit graph

4703 commits

Author SHA1 Message Date
Ben Harper
be03ba1b68
Add reflect impls for bevy_math curve structs (#13348)
# Objective

Fixes #13189

## Solution

To add the reflect impls I needed to make all the struct fields pub. I
don't think there's any harm for these types, but just a note for
review.

---------

Co-authored-by: Ben Harper <ben@tukom.org>
2024-05-16 17:59:56 +00:00
Patrick Walton
19bfa41768
Implement volumetric fog and volumetric lighting, also known as light shafts or god rays. (#13057)
This commit implements a more physically-accurate, but slower, form of
fog than the `bevy_pbr::fog` module does. Notably, this *volumetric fog*
allows for light beams from directional lights to shine through,
creating what is known as *light shafts* or *god rays*.

To add volumetric fog to a scene, add `VolumetricFogSettings` to the
camera, and add `VolumetricLight` to directional lights that you wish to
be volumetric. `VolumetricFogSettings` has numerous settings that allow
you to define the accuracy of the simulation, as well as the look of the
fog. Currently, only interaction with directional lights that have
shadow maps is supported. Note that the overhead of the effect scales
directly with the number of directional lights in use, so apply
`VolumetricLight` sparingly for the best results.

The overall algorithm, which is implemented as a postprocessing effect,
is a combination of the techniques described in [Scratchapixel] and
[this blog post]. It uses raymarching in screen space, transformed into
shadow map space for sampling and combined with physically-based
modeling of absorption and scattering. Bevy employs the widely-used
[Henyey-Greenstein phase function] to model asymmetry; this essentially
allows light shafts to fade into and out of existence as the user views
them.

Volumetric rendering is a huge subject, and I deliberately kept the
scope of this commit small. Possible follow-ups include:

1. Raymarching at a lower resolution.

2. A post-processing blur (especially useful when combined with (1)).

3. Supporting point lights and spot lights.

4. Supporting lights with no shadow maps.

5. Supporting irradiance volumes and reflection probes.

6. Voxel components that reuse the volumetric fog code to create voxel
shapes.

7. *Horizon: Zero Dawn*-style clouds.

These are all useful, but out of scope of this patch for now, to keep
things tidy and easy to review.

A new example, `volumetric_fog`, has been added to demonstrate the
effect.

## Changelog

### Added

* A new component, `VolumetricFog`, is available, to allow for a more
physically-accurate, but more resource-intensive, form of fog.

* A new component, `VolumetricLight`, can be placed on directional
lights to make them interact with `VolumetricFog`. Notably, this allows
such lights to emit light shafts/god rays.

![Screenshot 2024-04-21
162808](https://github.com/bevyengine/bevy/assets/157897/7a1fc81d-eed5-4735-9419-286c496391a9)

![Screenshot 2024-04-21
132005](https://github.com/bevyengine/bevy/assets/157897/e6d3b5ca-8f59-488d-a3de-15e95aaf4995)

[Scratchapixel]:
https://www.scratchapixel.com/lessons/3d-basic-rendering/volume-rendering-for-developers/intro-volume-rendering.html

[this blog post]: https://www.alexandre-pestana.com/volumetric-lights/

[Henyey-Greenstein phase function]:
https://www.pbr-book.org/4ed/Volume_Scattering/Phase_Functions#TheHenyeyndashGreensteinPhaseFunction
2024-05-16 17:13:18 +00:00
charlotte
4c3b7679ec
#12502 Remove limit on RenderLayers. (#13317)
# Objective

Remove the limit of `RenderLayer` by using a growable mask using
`SmallVec`.

Changes adopted from @UkoeHB's initial PR here
https://github.com/bevyengine/bevy/pull/12502 that contained additional
changes related to propagating render layers.

Changes

## Solution

The main thing needed to unblock this is removing `RenderLayers` from
our shader code. This primarily affects `DirectionalLight`. We are now
computing a `skip` field on the CPU that is then used to skip the light
in the shader.

## Testing

Checked a variety of examples and did a quick benchmark on `many_cubes`.
There were some existing problems identified during the development of
the original pr (see:
https://discord.com/channels/691052431525675048/1220477928605749340/1221190112939872347).
This PR shouldn't change any existing behavior besides removing the
layer limit (sans the comment in migration about `all` layers no longer
being possible).

---

## Changelog

Removed the limit on `RenderLayers` by using a growable bitset that only
allocates when layers greater than 64 are used.

## Migration Guide

- `RenderLayers::all()` no longer exists. Entities expecting to be
visible on all layers, e.g. lights, should compute the active layers
that are in use.

---------

Co-authored-by: robtfm <50659922+robtfm@users.noreply.github.com>
2024-05-16 16:15:47 +00:00
Lynn
05e2552a68
Add Rounded box gizmos (#11948)
# Objective

- Implement rounded cuboids and rectangles, suggestion of #9400 

## Solution

- Added `Gizmos::rounded_cuboid`, `Gizmos::rounded_rect` and
`Gizmos::rounded_rect_2d`.
- All of these return builders that allow configuring of the corner/edge
radius using `.corner_radius(...)` or `.edge_radius(...)` as well as the
line segments of each arc using `.arc_segments(...)`.

---

## Changelog

- Added a new `rounded_box` module to `bevy_gizmos` containing all of
the above methods and builders.
- Updated the examples `2d_gizmos` and `3d_gizmos`

## Additional information

The 3d example now looks like this:

<img width="1440" alt="Screenshot 2024-02-28 at 01 47 28"
src="https://github.com/bevyengine/bevy/assets/62256001/654e30ca-c091-4f14-a402-90138e95c71b">

And this is the updated 2d example showcasing negative corner radius:

<img width="1440" alt="Screenshot 2024-02-28 at 01 59 37"
src="https://github.com/bevyengine/bevy/assets/62256001/3904697a-5462-4ee7-abd9-3e893ca07082">
<img width="1440" alt="Screenshot 2024-02-28 at 01 59 47"
src="https://github.com/bevyengine/bevy/assets/62256001/a8892cfd-3aad-4c0c-87eb-559c17c8864c">

---------

Co-authored-by: JMS55 <47158642+JMS55@users.noreply.github.com>
Co-authored-by: James Gayfer <10660608+jgayfer@users.noreply.github.com>
2024-05-16 16:13:49 +00:00
Adith Ramachandran
65e62ba5eb
Revert "Support calculating normals for indexed meshes" (#12716) and add support for calculating smooth normals (#13333)
# Objective

- Refactor the changes merged in #11654 to compute flat normals for
indexed meshes instead of smooth normals.
- Fixes #12716 

## Solution

- Partially revert the changes in #11654 to compute flat normals for
both indexed and unindexed meshes in `compute_flat_normals`
- Create a new method, `compute_smooth_normals`, that computes smooth
normals for indexed meshes
- Create a new method, `compute_normals`, that computes smooth normals
for indexed meshes and flat normals for unindexed meshes by default. Use
this new method instead of `compute_flat_normals`.

## Testing

- Run the example with and without the changes to ensure that the
results are identical.
2024-05-16 14:54:35 +00:00
Johannes Hackel
1efa578ffb
Fix transmission by setting the correct value for transmissive_lighting_input.F_ab (#13379)
# Objective

- The clearcoat PR #13031 had a small typo which broke transmission
- Fixes #13284

## Solution

- Set transmissive_lighting_input.F_ab to the correct value


![transmission_fix](https://github.com/bevyengine/bevy/assets/688816/92158117-de3a-4fa5-8af8-dcbd1d5eee04)
2024-05-16 14:33:32 +00:00
Xzihnago
eba8744a70
Add Debug derive for ScreenSpaceAmbientOcclusionSettings struct (#13387)
# Objective

To streamline the code which utilizes `Debug` in user's struct like
`GraphicsSettings`. This addition aims to enhance code simplicity and
readability.

## Solution

Add `Debug` derive for `ScreenSpaceAmbientOcclusionSettings` struct.

## Testing

Should have no impact.
2024-05-16 11:29:34 +00:00
IceSentry
d9993a8092
Enable depth of field on webgpu (#13374)
# Objective

- Depth of field is currently disabled on any wasm targets, but the bug
it's trying to avoid is only an issue in webgl.

## Solution

- Enable dof when compiling for webgpu
- I also remove the msaa check because sampling a depth texture doesn't
work with or without msaa in webgl
- Unfortunately, Bokeh seems to be broken when using webgpu, so default
to Gaussian instead to make sure the defaults have the broadest platform
support

## Testing

- I added dof to the 3d_shapes example and compiled it to webgpu to
confirm it works
- I also tried compiling to webgl to confirm things still works and dof
isn't rendered.

---------

Co-authored-by: James Liu <contact@jamessliu.com>
2024-05-16 06:48:28 +00:00
IcyLeave6109
f61c55fd90
Allow shapes to be constructed with zero values (#13365)
# Objective

Fixes #13332.

## Solution

The assertion `circumradius >= 0.0` to allow zero.

Are there any other shapes that need to be allowed to be constructed
with zero?

---------

Co-authored-by: François Mockers <francois.mockers@vleue.com>
2024-05-16 02:22:50 +00:00
Pietro
d17fb160b0
Fix ClearColor in 2d pipelines (#13378)
# Objective

- Fixes #13377
- Fixes https://github.com/bevyengine/bevy/issues/13383

## Solution

- Even if the number of renderables is empty, the transparent phase need
to run to set the clear color.

## Testing

- Tested on the `clear_color` example
2024-05-15 20:36:02 +00:00
floppyhammer
8da4fcb616
Fix UI border artifacts caused by incorrect blending (#12725)
Fixes https://github.com/bevyengine/bevy/issues/12702.

Co-authored-by: François Mockers <mockersf@gmail.com>
2024-05-15 18:50:30 +00:00
JMS55
debcf3fb1d
Misc asset code quality and docs (#13382)
* Fix a doc comment for AssetSources
* Move some complicated generics to a where clause and write out T ->
Transformer fully
2024-05-15 18:49:04 +00:00
Csányi István
f91fd322b7
Skip redundant mesh_position_local_to_world call in vertex prepass shader (#13158)
# Objective

Optimize vertex prepass shader maybe?
Make it consistent with the base vertex shader

## Solution

`mesh_position_local_to_clip` just calls `mesh_position_local_to_world`
and then `position_world_to_clip`
since `out.world_position` is getting calculated anyway a few lines
below, just move it up and use it's output to calculate `out.position`.

It is the same as in the base vertex shader (`mesh.wgsl`).

Note: I have no idea if there is a reason that it was this way. I'm not
an expert, just noticed this inconsistency while messing with custom
shaders.
2024-05-14 16:31:58 +00:00
Jamie Ridding
dcf24dfd6b
Implement WorldQuery and QueryData on Mut. (#13338)
# Objective

Provides a `WorldQuery` implementation on `Mut<T>` that forwards to the
implementation on `&mut T`, and give users a way to opt-in to change
detection in auto-generated `QueryData::ReadOnly` types.

Fixes #13329.

## Solution

I implemented `WorldQuery` on `Mut<'w, T>` as a forwarding
implementation to `&mut T`, setting the `QueryData::ReadOnly` associated
type to `Ref<'w, T>`. This provides users the ability to explicitly
opt-in to change detection in the read-only forms of queries.

## Testing

A documentation test was added to `Mut` showcasing the new
functionality.

---

## Changelog

### Added

- Added an implementation of `WorldQuery` and `QueryData` on
`bevy_ecs::change_detection::Mut`.
2024-05-14 12:38:31 +00:00
Zachary Harrold
6482a036cb
Implement Color Operations for Color (#13285)
# Objective

- Fixes #13214

## Solution

Delegates to internal type when possible, otherwise uses
`ChosenColorSpace` as an intermediary. This _will_ double convert, but
this is considered an acceptable compromise since use of specific colour
types in performance critical colour operations is already encouraged.

`ChosenColorSpace` is `Oklcha` since it's perceptually uniform while
supporting all required operations, and in my opinion is the "best" for
this task. Using different spaces for different operations will make
documenting this double-conversion behaviour more challenging.

## Testing

Changes straightforward enough to not require testing beyond current CI
in my opinion.

---

## Changelog

- Implemented the following traits for `Color`:
  - `Luminance`
  - `Hue`
  - `Mix`
  - `EuclideanDistance`
  - `ClampColor`
- Added documentation to `Color` explaining the behaviour of these
operations (possible conversion, etc.)
2024-05-14 10:15:47 +00:00
Griffin
519ed5de42
Apply uv transform in the prepass (#13250)
# Objective

- The UV transform was applied in the main pass but not the prepass.

## Solution

- Apply the UV transform in the prepass.

## Testing

- The normals in my scene now look correct when using the prepass.
2024-05-13 22:33:09 +00:00
Vic
0eb4bb6bab
constrain WorldQuery::get_state to only use &Components (#13343)
# Objective

Passing `&World` in the `WorldQuery::get_state` method is unnecessary,
as all implementations of this method in the engine either only access
`Components` in `&World`, or do nothing with it.
It can introduce UB by necessitating the creation of a `&World` from a
`UnsafeWorldCell`.
This currently happens in `Query::transmute_lens`, which obtains a
`&World` from the internal `UnsafeWorldCell` solely to pass to
`get_state`. `Query::join` suffers from the same issue.
Other cases of UB come from allowing implementors of `WorldQuery` to
freely access `&World`, like in the `bevy-trait-query` crate, where a
[reference to a resource is
obtained](0c0e7dd646/src/lib.rs (L445))
inside of
[`get_state`](0c0e7dd646/src/one.rs (L245)),
potentially aliasing with a `ResMut` parameter in the same system.

`WorldQuery::init_state` currently requires `&mut World`, which doesn't
suffer from these issues.
But that too can be changed to receive a wrapper around `&mut
Components` and `&mut Storages` for consistency in a follow-up PR.

## Solution

Replace the `&World` parameter in `get_state` with `&Components`.

## Changelog

 `WorldQuery::get_state` now takes `&Components` instead of `&World`.
The `transmute`, `transmute_filtered`, `join` and `join_filtered`
methods on `QueryState` now similarly take `&Components` instead of
`&World`.

## Migration Guide

Users of `WorldQuery::get_state` or `transmute`, `transmute_filtered`,
`join` and `join_filtered` methods on `QueryState` now need to pass
`&Components` instead of `&World`.
`&Components` can be trivially obtained from either `components` method
on `&World` or `UnsafeWorldCell`.
For implementors of `WorldQuery::get_state` that were accessing more
than the `Components` inside `&World` and its methods, this is no longer
allowed.
2024-05-13 21:00:01 +00:00
JoshValjosh
2037b880ac
Add docs for PointLight (#13355)
Fixes #13106
2024-05-13 18:55:36 +00:00
Brezak
cbda71c2b3
Determine msrv for every standalone bevy_* crate. (#13211)
# Objective

As was pointed out in #13183, `bevy_mikktspace` is missing it's msrv
from it `Cargo.toml`. This promted me to check the msrv of every
`bevy_*` crate. Closes #13183.

## Solution

- Call `cargo check` with different rust versions on every bevy crate
until it doesn't complain.
- Write down the rust version `cargo check` started working.

## Testing

- Install `cargo-msrv`.
- Run `cargo msrv verify`.
- Rejoice.

---

## Changelog

Every published bevy crate now specifies a MSRV. If your rust toolchain
isn't at least version `1.77.0` You'll likely not be able to compile
most of bevy.

## Migration Guide

If your rust toolchain is bellow version`1.77.0, update.
2024-05-13 18:26:41 +00:00
Patrick Walton
df31b808c3
Implement fast depth of field as a postprocessing effect. (#13009)
This commit implements the [depth of field] effect, simulating the blur
of objects out of focus of the virtual lens. Either the [hexagonal
bokeh] effect or a faster Gaussian blur may be used. In both cases, the
implementation is a simple separable two-pass convolution. This is not
the most physically-accurate real-time bokeh technique that exists;
Unreal Engine has [a more accurate implementation] of "cinematic depth
of field" from 2018. However, it's simple, and most engines provide
something similar as a fast option, often called "mobile" depth of
field.

The general approach is outlined in [a blog post from 2017]. We take
advantage of the fact that both Gaussian blurs and hexagonal bokeh blurs
are *separable*. This means that their 2D kernels can be reduced to a
small number of 1D kernels applied one after another, asymptotically
reducing the amount of work that has to be done. Gaussian blurs can be
accomplished by blurring horizontally and then vertically, while
hexagonal bokeh blurs can be done with a vertical blur plus a diagonal
blur, plus two diagonal blurs. In both cases, only two passes are
needed. Bokeh requires the first pass to have a second render target and
requires two subpasses in the second pass, which decreases its
performance relative to the Gaussian blur.

The bokeh blur is generally more aesthetically pleasing than the
Gaussian blur, as it simulates the effect of a camera more accurately.
The shape of the bokeh circles are determined by the number of blades of
the aperture. In our case, we use a hexagon, which is usually considered
specific to lower-quality cameras. (This is a downside of the fast
hexagon approach compared to the higher-quality approaches.) The blur
amount is generally specified by the [f-number], which we use to compute
the focal length from the film size and FOV. By default, we simulate
standard cinematic cameras of f/1 and [Super 35]. The developer can
customize these values as desired.

A new example has been added to demonstrate depth of field. It allows
customization of the mode (Gaussian vs. bokeh), focal distance and
f-numbers. The test scene is inspired by a [blog post on depth of field
in Unity]; however, the effect is implemented in a completely different
way from that blog post, and all the assets (textures, etc.) are
original.

Bokeh depth of field:
![Screenshot 2024-04-17
152535](https://github.com/bevyengine/bevy/assets/157897/702f0008-1c8a-4cf3-b077-4110f8c46584)

Gaussian depth of field:
![Screenshot 2024-04-17
152542](https://github.com/bevyengine/bevy/assets/157897/f4ece47a-520e-4483-a92d-f4fa760795d3)

No depth of field:
![Screenshot 2024-04-17
152547](https://github.com/bevyengine/bevy/assets/157897/9444e6aa-fcae-446c-b66b-89469f1a1325)

[depth of field]: https://en.wikipedia.org/wiki/Depth_of_field

[hexagonal bokeh]:
https://colinbarrebrisebois.com/2017/04/18/hexagonal-bokeh-blur-revisited/

[a more accurate implementation]:
https://epicgames.ent.box.com/s/s86j70iamxvsuu6j35pilypficznec04

[a blog post from 2017]:
https://colinbarrebrisebois.com/2017/04/18/hexagonal-bokeh-blur-revisited/

[f-number]: https://en.wikipedia.org/wiki/F-number

[Super 35]: https://en.wikipedia.org/wiki/Super_35

[blog post on depth of field in Unity]:
https://catlikecoding.com/unity/tutorials/advanced-rendering/depth-of-field/

## Changelog

### Added

* A depth of field postprocessing effect is now available, to simulate
objects being out of focus of the camera. To use it, add
`DepthOfFieldSettings` to an entity containing a `Camera3d` component.

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
Co-authored-by: Bram Buurlage <brambuurlage@gmail.com>
2024-05-13 18:23:56 +00:00
Johannes Hackel
3f5a090b1b
Add UV channel selection to StandardMaterial (#13200)
# Objective

- The StandardMaterial always uses ATTRIBUTE_UV_0 for each texture
except lightmap. This is not flexible enough for a lot of gltf Files.
- Fixes #12496
- Fixes #13086
- Fixes #13122
- Closes #13153

## Solution

- The StandardMaterial gets extended for each texture by an UvChannel
enum. It defaults to Uv0 but can also be set to Uv1.
- The gltf loader now handles the texcoord information. If the texcoord
is not supported it creates a warning.
- It uses StandardMaterial shader defs to define which attribute to use.

## Testing

This fixes #12496 for example:

![wall_fixed](https://github.com/bevyengine/bevy/assets/688816/bc37c9e1-72ba-4e59-b092-5ee10dade603)

For testing of all kind of textures I used the TextureTransformMultiTest
from
https://github.com/KhronosGroup/glTF-Sample-Assets/tree/main/Models/TextureTransformMultiTest
Its purpose is to test multiple texture transfroms but it is also a good
test for different texcoords.
It also shows the issue with emission #13133.

Before:

![TextureTransformMultiTest_main](https://github.com/bevyengine/bevy/assets/688816/aa701d04-5a3f-4df1-a65f-fc770ab6f4ab)

After:

![TextureTransformMultiTest_texcoord](https://github.com/bevyengine/bevy/assets/688816/c3f91943-b830-4068-990f-e4f2c97771ee)
2024-05-13 18:23:09 +00:00
Joona Aalto
ac1f135e20
Add meshing for Cone (#11820)
# Objective

The `Cone` primitive should support meshing.

## Solution

Implement meshing for the `Cone` primitive. The default cone has a
height of 1 and a base radius of 0.5, and is centered at the origin.

An issue with cone meshes is that the tip does not really have a normal
that works, even with duplicated vertices. This PR uses only a single
vertex for the tip, with a normal of zero; this results in an "invalid"
normal that gets ignored by the fragment shader. This seems to be the
only approach we have for perfectly smooth cones. For discussion on the
topic, see #10298 and #5891.

Another thing to note is that the cone uses polar coordinates for the
UVs:

<img
src="https://github.com/bevyengine/bevy/assets/57632562/e101ded9-110a-4ac4-a98d-f1e4d740a24a"
alt="cone" width="400" />

This way, textures are applied as if looking at the cone from above:

<img
src="https://github.com/bevyengine/bevy/assets/57632562/8dea00f1-a283-4bc4-9676-91e8d4adb07a"
alt="texture" width="200" />

<img
src="https://github.com/bevyengine/bevy/assets/57632562/d9d1b5e6-a8ba-4690-b599-904dd85777a1"
alt="cone" width="200" />
2024-05-13 18:00:59 +00:00
moonlightaria
1a3549a916
State example (#13322)
# Objective
adopted from #10716
adds example for updating state

---------

Co-authored-by: Stepan Koltsov <stepan.koltsov@gmail.com>
Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
2024-05-13 13:03:42 +00:00
Bram Buurlage
bfc13383e0
Fix incorrect workgroupBarrier and OOB array access in auto_exposure (#13283)
This commit fixes two issues in auto_exposure.wgsl:
* A `storageBarrier()` was incorrectly used where a `workgroupBarrier()`
should be used instead;
* Resetting the `histogram_shared` array would write beyond the 64th
index, which is out of bounds.

## Solution

The first issue is fixed by using the appropriate workgroupBarrier
instead;
The second issue is fixed by adding a range check before setting
`histogram_shared[local_invocation_index] = 0u`.

## Testing

These changes were tested using the Xcode metal profiler, and I could
not find any noticable change in compute shader performance.
2024-05-12 23:24:58 +00:00
IcyLeave6109
de7ff295e1
Make bevy_time optionally depend on bevy_reflect (#13263)
# Objective

Fixes #13246.
2024-05-12 23:19:07 +00:00
François Mockers
173db7726f
remove unused warnings in release (#13344)
# Objective

- When building for release, there are "unused" warnings:
```
warning: unused import: `bevy_utils::warn_once`
  --> crates/bevy_pbr/src/render/mesh_view_bindings.rs:32:5
   |
32 | use bevy_utils::warn_once;
   |     ^^^^^^^^^^^^^^^^^^^^^
   |
   = note: `#[warn(unused_imports)]` on by default

warning: unused variable: `texture_count`
   --> crates/bevy_pbr/src/render/mesh_view_bindings.rs:371:17
    |
371 |             let texture_count: usize = entries
    |                 ^^^^^^^^^^^^^ help: if this is intentional, prefix it with an underscore: `_texture_count`
    |
    = note: `#[warn(unused_variables)]` on by default
```

## Solution

- Gate the import and definition by the same cfg as their uses
2024-05-12 22:30:34 +00:00
ickshonpe
be217ab037
Add doc comments explaining the different behaviours of alignment and Anchor with text_2d (#8022)
# Objective
Add an explanation of the differences between `alignment` and `Anchor`
to the `Text2dBundle` docs.

---------

Co-authored-by: Rob Parrett <robparrett@gmail.com>
Co-authored-by: François Mockers <mockersf@gmail.com>
2024-05-12 21:42:04 +00:00
Periwink
ded5d523bd
Improve tracing layer customization (#13159)
# Objective

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

The current tracing customization option (the `update_subscriber` field)
was basically unusable because it provides a `dyn Subscriber` and most
layers require a `Subscriber` that also implements `for<'a>
LookupSpan<'a, Data=Data<'a>>`, so it was impossible to add a layer on
top of the `dyn Subscriber`.

This PR provides an alternative way of adding additional tracing layers
to the LogPlugin by instead creating an `Option<Layer>`.

This is enough for most situations because `Option<Layer>` and
`Vec<Layer>` both implement `Layer`.

## Solution

- Replace the `update_subscriber` field of `LogPlugin` with a
`custom_layer` field which is function pointer returning an
`Option<BoxedLayer>`
- Update the examples to showcase that this works:
  - with multiple additional layers
- with Layers that were previously problematic, such as
`bevy::log::tracing_subscriber::fmt::layer().with_file(true)` (mentioned
in the issue)
  
Note that in the example this results in duplicate logs, since we have
our own layer on top of the default `fmt_layer` added in the LogPlugin;
maybe in the future we might want to provide a single one? Or to let the
user customize the default `fmt_layer` ? I still think this change is an
improvement upon the previous solution, which was basically broken.

---

## Changelog

> This section is optional. If this was a trivial fix, or has no
externally-visible impact, you can delete this section.

- The `LogPlugin`'s `update_subscriber` field has been replaced with
`custom_layer` to allow the user to flexibly add a `tracing::Layer` to
the layer stack

## Migration Guide

- The `LogPlugin`'s `update_subscriber` field has been replaced with
`custom_layer`

---------

Co-authored-by: BD103 <59022059+BD103@users.noreply.github.com>
2024-05-12 21:16:56 +00:00
Rob Parrett
2fd432c463
Fix motion blur on wasm (#13099)
# Objective

Fixes #13097 and other issues preventing the motion blur example from
working on wasm

## Solution

- Use a vec2 for padding
- Fix error initializing the `MotionBlur` struct on wasm+webgl2
- Disable MSAA on wasm+webgl2
- Fix `GlobalsUniform` padding getting added on the shader side for
webgpu builds

## Notes

The motion blur example now runs, but with artifacts. In addition to the
obvious black artifacts, the motion blur or dithering seem to just look
worse in a way I can't really describe. That may be expected.

```
AdapterInfo { name: "ANGLE (Apple, ANGLE Metal Renderer: Apple M1 Max, Unspecified Version)", vendor: 4203, device: 0, device_type: IntegratedGpu, driver: "", driver_info: "", backend: Gl }
```
<img width="1276" alt="Screenshot 2024-04-25 at 6 51 21 AM"
src="https://github.com/bevyengine/bevy/assets/200550/65401d4f-92fe-454b-9dbc-a2d89d3ad963">
2024-05-12 21:03:36 +00:00
Sean Sullivan
a4597a9c14
bevy_asset: Add missing web-sys feature and cleanup unused ones (#13281)
# Objective

- **Describe the objective or issue this PR addresses.**

`bevy_asset` includes code
[here](4350ad0bd1/crates/bevy_asset/src/io/wasm.rs (L61))
that references `web_sys::WorkerGlobalScope`. However, `bevy_asset` does
not enable this feature, see
[here](4350ad0bd1/crates/bevy_asset/Cargo.toml (L50)).
Running examples does not catch this problem because the feature is
implicitly included by `wgpu` when `bevy_render` is also a dependency,
see
[bevy_render](4350ad0bd1/crates/bevy_render/Cargo.toml (L73-L80))
and
[wgpu](3b6112d45d/wgpu/Cargo.toml (L201)).
This results in compile errors for environments that are not using
`bevy_render`.

To reproduce the problem, try to build the crate individually for wasm
targets by running `cargo build -p bevy_asset --target
wasm32-unknown-unknown`.

Running `cargo tree -e features --target wasm32-unknown-unknown` helped
diagnose the issue.

## Solution

- **Describe the solution used to achieve the objective above.**

This PR adds the `WorkerGlobalScope` feature to the `web-sys` portion of
`bevy_asset`'s `Cargo.toml`.

It also seems to be the case that `bevy_asset` no longer needs the
`Request` feature, since no code for `Request` is present anymore. I
confirmed that building the crate individually for wasm succeeds without
the feature, so that change is also included here.

This is a little off-topic, but the repository would probably benefit
from some automation around these types of changes, but I'm not sure
what would work there. For example, building each crate individually for
some key targets would work, but is...well, a lot. Happy to follow up if
there is agreement on a good direction.

## Testing

- **Did you test these changes? If so, how?**
- **How can other people (reviewers) test your changes? Is there
anything specific they need to know?**

Building the crate individually for wasm by running `cargo build -p
bevy_asset --target wasm32-unknown-unknown`.

- **Are there any parts that need more testing?**

I don't believe so.
2024-05-12 20:53:59 +00:00
Ben Harper
6f641e9f9b
Add copy, clone, and debug derives to cubic spline structs (#13293)
# Objective

Fixes #13190

---------

Co-authored-by: Ben Harper <ben@tukom.org>
2024-05-12 20:48:08 +00:00
charlotte
dc0fdd6ad9
Ensure clean exit (#13236)
# Objective

Fixes two issues related to #13208.

First, we ensure render resources for a window are always dropped first
to ensure that the `winit::Window` always drops on the main thread when
it is removed from `WinitWindows`. Previously, changes in #12978 caused
the window to drop in the render world, causing issues.

We accomplish this by delaying despawning the window by a frame by
inserting a marker component `ClosingWindow` that indicates the window
has been requested to close and is in the process of closing. The render
world now responds to the equivalent `WindowClosing` event rather than
`WindowCloseed` which now fires after the render resources are
guarunteed to be cleaned up.

Secondly, fixing the above caused (revealed?) that additional events
were being delivered to the the event loop handler after exit had
already been requested: in my testing `RedrawRequested` and
`LoopExiting`. This caused errors to be reported try to send an exit
event on the close channel. There are two options here:
- Guard the handler so no additional events are delivered once the app
is exiting. I ~considered this but worried it might be confusing or bug
prone if in the future someone wants to handle `LoopExiting` or some
other event to clean-up while exiting.~ We are now taking this approach.
- Only send an exit signal if we are not already exiting. ~It doesn't
appear to cause any problems to handle the extra events so this seems
safer.~
 
Fixing this also appears to have fixed #13231.

Fixes #10260.

## Testing

Tested on mac only.

---

## Changelog

### Added
- A `WindowClosing` event has been added that indicates the window will
be despawned on the next frame.

### Changed
- Windows now close a frame after their exit has been requested.

## Migration Guide
- Ensure custom exit logic does not rely on the app exiting the same
frame as a window is closed.
2024-05-12 15:56:01 +00:00
rmsthebest
278380394f
Avoid bevy_reflect::List::iter wrapping in release mode (#13271)
# Objective
Fixes  #13230

## Solution
Uses solution described in  #13230
They mention a worry about adding a branch, but I'm not sure there is
one.

This code
```Rust
#[no_mangle]
pub fn next_if_some(num: i32, b: Option<bool>) -> i32 {
    num + b.is_some() as i32
}
```
produces this assembly with opt-level 3
```asm
next_if_some:
        xor     eax, eax
        cmp     sil, 2
        setne   al
        add     eax, edi
        ret
```

## Testing
Added test from #13230, tagged it as ignore as it is only useful in
release mode and very slow if you accidentally invoke it in debug mode.

---

## Changelog
Iterationg of ListIter will no longer overflow and wrap around

## Migration Guide
2024-05-12 15:01:05 +00:00
François Mockers
443ce9a62b
gizmos: take normal of normal on plane 3d before rotation (#13326)
# Objective

- Example `render_primitives` is painful to look at for the plane in 3d,
the gizmo seems to have extra rotations


https://github.com/bevyengine/bevy/assets/8672791/08509624-14ac-4f00-a758-9a14233ef1a9

## Solution

- Take the normal of the normal before rotation, then rotate it

## Testing

- Run the example, rotations are more in sync


https://github.com/bevyengine/bevy/assets/8672791/91c26ce4-4b7b-4575-ba32-7c32026e4596
2024-05-11 19:32:31 +00:00
Zachary Harrold
dcb8a13b22
Remove ClampColor (#13307)
# Objective

- Fixes #12543

## Solution

- Removed `ClampColor`

## Testing

- CI Passed

---

## Migration Guide

Manually clamp the various colour components yourself if this behaviour
is still required.

```rust
fn clamped_srgba(color: Srgba) -> Srgba {
    Srgba {
        red: color.red.clamp(0., 1.),
        green: color.green.clamp(0., 1.),
        blue: color.blue.clamp(0., 1.),
        alpha: color.alpha.clamp(0., 1.),
    }
}
```
2024-05-10 13:15:56 +00:00
Sean Sullivan
4b61bbe4e1
bevy_core: Derive useful traits on FrameCount (#13291)
# Objective

I am emboldened by my last small PR and am here with another.

- **Describe the objective or issue this PR addresses.**

It would be nice if `FrameCount` could be used by downstream plugins
that want to use frame data. The example that I have in mind is
[`leafwing_input_playback`](https://github.com/Leafwing-Studios/leafwing_input_playback/issues/29)
which has a [duplicate implementation of
`FrameCount`](https://github.com/Leafwing-Studios/leafwing_input_playback/blob/main/src/frame_counting.rs#L9-L37)
used in several structs which rely on those derives (or otherwise the
higher-level structs would have to implement these traits manually).
That crate, using `FrameCount`, tracks input frames and timestamps and
enables various playback modes.

I am aware that bevy org refrains from deriving lots of unnecessary
stuff on bevy types to avoid compile time creep. It is worth mentioning
the (equally reasonable) alternative that downstream crates _should_
implement some `FrameCount` themselves if they want special behavior
from it.

## Solution

- **Describe the solution used to achieve the objective above.**

I added derives for `PartialEq, Eq, PartialOrd, Ord` and implementations
for `serde::{Deserialize, Serialize}` to `FrameCount`.

## Testing

Manually confirmed that the serde implementation works, but that's all.
Let me know if I should do more here.

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
2024-05-10 10:00:08 +00:00
Matty
4da11fda77
Add AXES iterators for Dir types (#13305)
# Objective

Sometimes it's nice to iterate over all the coordinate axes using
something like `Vec3::AXES`. This was not available for the
corresponding `Dir` types and now it is.

## Solution

We already have things like `Dir2::X`, `Dir3::Z` and so on, so I just
threw them in an array like the vector types do it. I also slightly
refactored the sphere gizmo code to use `Dir3::AXES` and operate on
directions instead of using `Dir3::new_unchecked`.

## Testing

I looked at the sphere in the `3d_gizmos` example and it seems to work,
so I assume I didn't break anything.
2024-05-09 23:30:44 +00:00
Gino Valente
705c144259
bevy_reflect: Remove ContainerAttributes::merge (#13303)
# Objective

Unblocks #11659.

Currently the `Reflect` derive macro has to go through a merge process
for each `#[reflect]`/`#[reflet_value]` attribute encountered on a
container type.

Not only is this a bit inefficient, but it also has a soft requirement
that we can compare attributes such that an error can be thrown on
duplicates, invalid states, etc.

While working on #11659 this proved to be challenging due to the fact
that `syn` types don't implement `PartialEq` or `Hash` without enabling
the `extra-traits` feature.

Ideally, we wouldn't have to enable another feature just to accommodate
this one use case.

## Solution

Removed `ContainerAttributes::merge`.

This was a fairly simple change as we could just have the parsing
functions take `&mut self` instead of returning `Self`.

## Testing

CI should build as there should be no user-facing change.
2024-05-09 18:17:54 +00:00
Lee-Orr
42ba9dfaea
Separate state crate (#13216)
# Objective

Extracts the state mechanisms into a new crate called "bevy_state".

This comes with a few goals:

- state wasn't really an inherent machinery of the ecs system, and so
keeping it within bevy_ecs felt forced
- by mixing it in with bevy_ecs, the maintainability of our more robust
state system was significantly compromised

moving state into a new crate makes it easier to encapsulate as it's own
feature, and easier to read and understand since it's no longer a
single, massive file.

## Solution

move the state-related elements from bevy_ecs to a new crate

## Testing

- Did you test these changes? If so, how? all the automated tests
migrated and passed, ran the pre-existing examples without changes to
validate.

---

## Migration Guide

Since bevy_state is now gated behind the `bevy_state` feature, projects
that use state but don't use the `default-features` will need to add
that feature flag.

Since it is no longer part of bevy_ecs, projects that use bevy_ecs
directly will need to manually pull in `bevy_state`, trigger the
StateTransition schedule, and handle any of the elements that bevy_app
currently sets up.

---------

Co-authored-by: Kristoffer Søholm <k.soeholm@gmail.com>
2024-05-09 18:06:05 +00:00
moonlightaria
3f2cc244d7
Add color conversions #13224 (#13276)
# Objective
fixes #13224
adds conversions for Vec3 and Vec4 since these appear so often

## Solution
added Covert trait (couldn't think of good name) for [f32; 4], [f32, 3],
Vec4, and Vec3 along with the symmetric implementation

## Changelog
added conversions between arrays and vector to colors and vice versa

#migration
LinearRgba appears to have already had implicit conversions for [f32;4]
and Vec4
2024-05-09 18:01:52 +00:00
Brezak
9c4ac7c297
Finish the work on try_apply (#12646)
# Objective

Finish the `try_apply` implementation started in #6770 by @feyokorenhof.
Supersedes and closes #6770. Closes #6182

## Solution

Add `try_apply` to `Reflect` and implement it in all the places that
implement `Reflect`.

---

## Changelog

Added `try_apply` to `Reflect`.

---------

Co-authored-by: Feyo Korenhof <feyokorenhof@gmail.com>
Co-authored-by: Gino Valente <49806985+MrGVSV@users.noreply.github.com>
2024-05-08 14:26:01 +00:00
IceSentry
64e1a7835a
Clean up 2d render phases (#12982)
# Objective

Currently, the 2d pipeline only has a transparent pass that is used for
everything. I want to have separate passes for opaque/alpha
mask/transparent meshes just like in 3d.

This PR does the basic work to start adding new phases to the 2d
pipeline and get the current setup a bit closer to 3d.

## Solution

- Use `ViewNode` for `MainTransparentPass2dNode`
- Added `Node2d::StartMainPass`, `Node2d::EndMainPass`
- Rename everything to clarify that the main pass is currently the
transparent pass

---

## Changelog

- Added `Node2d::StartMainPass`, `Node2d::EndMainPass`

## Migration Guide

If you were using `Node2d::MainPass` to order your own custom render
node. You now need to order it relative to `Node2d::StartMainPass` or
`Node2d::EndMainPass`.
2024-05-08 08:13:39 +00:00
Patrick Walton
0dddfa07ab
Fix the WebGL 2 backend by giving the visibility_ranges array a fixed length. (#13210)
WebGL 2 doesn't support variable-length uniform buffer arrays. So we
arbitrarily set the length of the visibility ranges field to 64 on that
platform.

---------

Co-authored-by: IceSentry <c.giguere42@gmail.com>
2024-05-08 07:34:59 +00:00
Brezak
4350ad0bd1
Make AssetMetaCheck a field on the asset plugin (#13177)
# Objective

There's a TODO comment above the `AssetMetaCheck` enum mentioning this
should have been done in 0.13

## Solution

Do it in 0.14

## Testing

I've checked that all the asset tests compile. I've also run the
asset_processing and asset_settings tests and they both work.

---

## Changelog

### Changed
-
[`AssetMetaCheck`](https://docs.rs/bevy/latest/bevy/asset/enum.AssetMetaCheck.html)
is no longer a resource and is now a field on the
[`AssetPlugin`](https://docs.rs/bevy/latest/bevy/asset/struct.AssetPlugin.html).

## Migration Guide

Changes to how bevy handles asset meta files now need to be specified
when inserting the `AssetPlugin`.
2024-05-07 23:52:30 +00:00
Lynn
03f4cc5dde
Extrusion (#13270)
# Objective

- Adds a basic `Extrusion<T: Primitive2d>` shape, suggestion of #10572 

## Solution

- Adds `Measured2d` and `Measured3d` traits for getting the
perimeter/area or area/volume of shapes. This allows implementing
`.volume()` and `.area()` for all extrusions `Extrusion<T: Primitive2d +
Measured2d>` within `bevy_math`
- All existing perimeter, area and volume implementations for primitves
have been moved into implementations of `Measured2d` and `Measured3d`
- Shapes should be extruded along the Z-axis since an extrusion of depth
`0.` should be equivalent in everything but name to the base shape

## Caviats

- I am not sure about the naming. `Extrusion<T>` could also be
`Prism<T>` and the `MeasuredNd` could also be something like
`MeasuredPrimitiveNd`. If you have any other suggestions, please fell
free to share them :)

## Future work

This PR adds a basic `Extrusion` shape and does not implement a lot of
things you might want it to. Some of the future possibilities include:
- [ ] bounding for extrusions
- [ ] making extrusions work with gizmos
- [ ] meshing

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
2024-05-07 14:41:55 +00:00
BD103
22305acf66
Rename bevy_reflect_derive folder to derive (#13269)
# Objective

- Some of the "large" crates have sub-crates, usually for things such as
macros.
- For an example, see [`bevy_ecs_macros` at
`bevy_ecs/macros`](4f9f987099/crates/bevy_ecs/macros).
- The one crate that does not follow this convention is
[`bevy_reflect_derive`](4f9f987099/crates/bevy_reflect/bevy_reflect_derive),
which is in the `bevy_reflect/bevy_reflect_derive` folder and not
`bevy_reflect/derive` or `bevy_reflect/macros`.

## Solution

- Rename folder `bevy_reflect_derive` to `derive`.
- I chose to use `derive` instead of `macros` because the crate name
itself ends in `_derive`. (One of only two crates to actually use this
convention, funnily enough.)

## Testing

- Build and test `bevy_reflect` and `bevy_reflect_derive`.
- Apply the following patch to `publish.sh` to run it in `--dry-run`
mode, to test that the path has been successfully updated:
- If you have any security concerns about applying random diffs, feel
free to skip this step. Worst case scenario it fails and Cart has to
manually publish a few crates.

```bash
# Apply patch to make `publish.sh` *not* actually publish anything.
git apply path/to/foo.patch
# Make `publish.sh` executable.
chmod +x tools/publish.sh
# Execute `publish.sh`.
./tools/publish.sh
```

```patch
diff --git a/tools/publish.sh b/tools/publish.sh
index b020bad28..fbcc09281 100644
--- a/tools/publish.sh
+++ b/tools/publish.sh
@@ -49,7 +49,7 @@ crates=(
 
 if [ -n "$(git status --porcelain)" ]; then
     echo "You have local changes!"
-    exit 1
+    # exit 1
 fi
 
 pushd crates
@@ -61,15 +61,15 @@ do
   cp ../LICENSE-APACHE "$crate"
   pushd "$crate"
   git add LICENSE-MIT LICENSE-APACHE
-  cargo publish --no-verify --allow-dirty
+  cargo publish --no-verify --allow-dirty --dry-run
   popd
-  sleep 20
+  # sleep 20
 done
 
 popd
 
 echo "Publishing root crate"
-cargo publish --allow-dirty
+cargo publish --allow-dirty --dry-run
 
 echo "Cleaning local state"
 git reset HEAD --hard
```

---

## Changelog

- Moved `bevy_reflect_derive` from
`crates/bevy_reflect/bevy_reflect_derive` to
`crates/bevy_reflect/derive`.
2024-05-07 07:55:32 +00:00
IceSentry
4737106bdd
Extract mesh view layouts logic (#13266)
Copied almost verbatim from the volumetric fog PR

# Objective

- Managing mesh view layouts is complicated

## Solution

- Extract it to it's own struct
- This was done as part of #13057 and is copied almost verbatim. I
wanted to keep this part of the PR it's own atomic commit in case we
ever have to revert fog or run a bisect. This change is good whether or
not we have volumetric fog.

Co-Authored-By: @pcwalton
2024-05-07 06:46:41 +00:00
moonlightaria
1126b5a3d6
replace std::f32::EPSILON with f32::EPSILON (#13267)
# Objective
fixes clippy warning related to using a std::f32::EPSILON which is
planned to be depreciated for f32::EPSILON
2024-05-07 05:23:53 +00:00
Lynn
4f9f987099
Ellipse functions (#13025)
# Objective

- Add some useful methods to `Ellipse`

## Solution

- Added `Ellipse::perimeter()` and `::focal_length()`

---------

Co-authored-by: IQuick 143 <IQuick143cz@gmail.com>
2024-05-06 21:31:51 +00:00
Mike
fa0745fdd0
Remove bevy log's usage of non send resource (#13252)
# Objective

I'm adopting #9122 and pulling some of the non controversial changes out
to make the final pr easier to review.

This pr removes the NonSend resource usage from `bevy_log`. 

## Solution

`tracing-chrome` uses a guard that is stored in the world, so that when
it is dropped the json log file is written out. The guard is Send +
!Sync, so we can store it in a SyncCell to hold it in a regular resource
instead of using a non send resource.

## Testing

Tested by running an example with `-F tracing chrome` and making sure
there weren't any errors and the json file was created.

---

## Changelog

- replaced `bevy_log`'s usage of a non send resource.
2024-05-06 21:15:10 +00:00