Commit graph

4959 commits

Author SHA1 Message Date
irate
55e74ea8e9 Revert App::run() behavior/Remove winit specific code from bevy_app (#10389)
# Objective
The way `bevy_app` works was changed unnecessarily in #9826 whose
changes should have been specific to `bevy_winit`.
I'm somewhat disappointed that happened and we can see in
https://github.com/bevyengine/bevy/pull/10195 that it made things more
complicated.

Even worse, in #10385 it's clear that this breaks the clean abstraction
over another engine someone built with Bevy!

Fixes #10385.

## Solution

- Move the changes made to `bevy_app` in #9826 to `bevy_winit`
- Revert the changes to `ScheduleRunnerPlugin` and the `run_once` runner
in #10195 as they're no longer necessary.

While this code is breaking relative to `0.12.0`, it reverts the
behavior of `bevy_app` back to how it was in `0.11`.
Due to the nature of the breakage relative to `0.11` I hope this will be
considered for `0.12.1`.
2023-11-29 16:47:08 -08:00
Markus Ort
44fbc2f717 Fix panic when using image in UiMaterial (#10591)
# Objective

- Fix the panic on using Images in UiMaterials due to assets not being
loaded.
- Fixes #10513 

## Solution

- add `let else` statement that `return`s or `continue`s instead of
unwrapping, causing a panic.
2023-11-29 16:46:44 -08:00
Carter Anderson
0dee514e61 Add missing asset load error logs for load_folder and load_untyped (#10578)
# Objective

Fixes #10515 

## Solution

Add missing error logs.
2023-11-29 16:46:21 -08:00
François
efa8c22ff8 support required features in wasm examples showcase (#10577)
# Objective

- Examples with required features fail to build
- If you're fixing a specific issue, say "Fixes #X".

## Solution

- Pass them along when building examples for wasm showcase
- Also mark example `hot_asset_reloading` as not wasm compatible as it
isn't even with the right features enabled
2023-11-29 16:46:09 -08:00
François
387755748c fix example custom_asset_reader on wasm (#10574)
# Objective

- Example `custom_asset_reader` fails to build in wasm
```
$ cargo build --profile release --target wasm32-unknown-unknown --example custom_asset_reader
   Compiling bevy v0.12.0 (/Users/runner/work/bevy-website/bevy-website)
error[E0432]: unresolved import `bevy::asset::io::file`
 --> examples/asset/custom_asset_reader.rs:7:9
  |
7 |         file::FileAssetReader, AssetReader, AssetReaderError, AssetSource, AssetSourceId,
  |  
```

## Solution

- Wrap the platform default asset reader instead of the
`FileAssetReader`
2023-11-29 16:45:57 -08:00
Testare
ce69959a69 Add load_untyped to LoadContext (#10526)
# Objective

Give us the ability to load untyped assets in AssetLoaders.

## Solution

Basically just copied the code from `load`, but used
`asset_server.load_untyped` instead internally.

## Changelog

Added `load_untyped` method to `LoadContext`
2023-11-29 16:45:37 -08:00
BrayMatter
520a09a083 Ensure ExtendedMaterial works with reflection (to enable bevy_egui_inspector integration) (#10548)
# Objective

- Ensure ExtendedMaterial can be referenced in bevy_egui_inspector
correctly

## Solution

Add a more manual `TypePath` implementation to work around bugs in the
derive macro.
2023-11-29 16:45:06 -08:00
irate
a3a7376034 Fix float precision issue in the gizmo shader (#10408)
Fix a precision issue with in the manual near-clipping function.
This only affected lines that span large distances (starting at 100_000~
units) in my testing.

Fixes #10403
2023-11-29 16:44:26 -08:00
ickshonpe
0483b69a79 Improved Text Rendering (#10537)
# Objective

The quality of Bevy's text rendering can vary wildly depending on the
font, font size, pixel alignment and scale factor.

But this situation can be improved dramatically with some small
adjustments.

## Solution

* Text node positions are rounded to the nearest physical pixel before
rendering.
* Each glyph texture has a 1-pixel wide transparent border added along
its edges.

This means font atlases will use more memory because of the extra pixel
of padding for each glyph but it's more than worth it I think (although
glyph size is increased by 2 pixels on both axes, the net increase is 1
pixel as the font texture atlas's padding has been removed).

## Results

Screenshots are from the 'ui' example with a scale factor of 1.5. 

Things can get much uglier with the right font and worst scale
factor<sup>tm</sup>.

### before 
<img width="300" alt="list-bad-text"
src="https://github.com/bevyengine/bevy/assets/27962798/482b384d-8743-4bae-9a65-468ff1b4c301">

### after
<img width="300" alt="good_list_text"
src="https://github.com/bevyengine/bevy/assets/27962798/34323b0a-f714-47ba-9728-a59804987bc8">
 
---

## Changelog
* Font texture atlases are no longer padded.
* Each glyph texture has a 1-pixel wide padding added along its edges.
* Text node positions are rounded to the nearest physical pixel before
rendering.
2023-11-29 16:44:14 -08:00
Carter Anderson
63828621e8 Fix untyped labeled asset loading (#10514)
# Objective

Fixes #10436
Alternative to #10465 

## Solution

`load_untyped_async` / `load_internal` currently has a bug. In
`load_untyped_async`, we pass None into `load_internal` for the
`UntypedHandle` of the labeled asset path. This results in a call to
`get_or_create_path_handle_untyped` with `loader.asset_type_id()`
This is a new code path that wasn't hit prior to the newly added
`load_untyped` because `load_untyped_async` was a private method only
used in the context of the `load_folder` impl (which doesn't have
labels)

The fix required some refactoring to catch that case and defer handle
retrieval. I have also made `load_untyped_async` public as it is now
"ready for public use" and unlocks new scenarios.
2023-11-29 16:43:44 -08:00
Nicola Papale
f78a9460db Fix animations resetting after repeat count (#10540)
# Objective

After #9002, it seems that "single shot" animations were broken. When
completing, they would reset to their initial value. Which is generally
not what you want.

- Fixes #10480

## Solution

Avoid `%`-ing the animation after the number of completions exceeds the
specified one. Instead, we early-return. This is also true when the
player is playing in reverse.

---

## Changelog

- Avoid resetting animations after `Repeat::Never` animation completion.
2023-11-29 16:42:51 -08:00
Waridley
6dc602da44 Prepend root_path to meta path in HttpWasmAssetReader (#10527)
# Objective

Fixes an issue where Bevy will look for `.meta` files in the root of the
server instead of `imported_assets/Default` on the web.

## Solution

`self.root_path.join` was seemingly forgotten in the `read_meta`
function on `HttpWasmAssetReader`, though it was included in the `read`
function. This PR simply adds the missing function call.
2023-11-29 16:42:40 -08:00
Rafał Harabień
e69ab92baf Make AssetLoader/Saver Error type bounds compatible with anyhow::Error (#10493)
# Objective

* In Bevy 0.11 asset loaders used `anyhow::Error` for returning errors.
In Bevy 0.12 `AssetLoader` (and `AssetSaver`) have associated `Error`
type. Unfortunately it's type bounds does not allow `anyhow::Error` to
be used despite migration guide claiming otherwise. This makes migration
to 0.12 more challenging. Solve this by changing type bounds for
associated `Error` type.
* Fix #10350

## Solution

Change associated `Error` type bounds to require `Into<Box<dyn
std::error::Error + Send + Sync + 'static>>` to be implemented instead
of `std::error::Error + Send + Sync + 'static`. Both `anyhow::Error` and
errors generated by `thiserror` seems to be fine with such type bound.

---

## Changelog

### Fixed
* Fixed compatibility with `anyhow::Error` in `AssetLoader` and
`AssetSaver` associated `Error` type
2023-11-29 16:41:48 -08:00
Rob Parrett
6ebc0a2dfb Fix minor issues with custom_asset example (#10337)
# Objective

- Use bevy's re-exported `AsyncReadExt` so users don't think they need
to depend on `futures-lite`.
- Fix a funky  error text
2023-11-29 16:41:32 -08:00
Carter Anderson
b32976504d Fix shader import hot reloading on windows (#10502)
# Objective

Hot reloading shader imports on windows is currently broken due to
inconsistent `/` and `\` usage ('/` is used in the user facing APIs and
`\` is produced by notify-rs (and likely other OS apis).

Fixes #10500

## Solution

Standardize import paths when loading a `Shader`. The correct long term
fix is to standardize AssetPath on `/`-only, but this is the right scope
of fix for a patch release.

---------

Co-authored-by: François <mockersf@gmail.com>
2023-11-29 16:41:02 -08:00
Sludge
26dfe42623 Don't .unwrap() in AssetPath::try_parse (#10452)
# Objective

- The docs on `AssetPath::try_parse` say that it will return an error
when the string is malformed, but it actually just `.unwrap()`s the
result.

## Solution

- Use `?` instead of unwrapping the result.
2023-11-29 16:40:48 -08:00
Aevyrie
4667d80243 Allow registering boxed systems (#10378)
# Objective

- Allow registration of one-shot systems when those systems have already
been `Box`ed.
- Needed for `bevy_eventlisteners` which allows adding event listeners
with callbacks in normal systems. The current one shot system
implementation requires systems be registered from an exclusive system,
and that those systems be passed in as types that implement
`IntoSystem`. However, the eventlistener callback crate allows users to
define their callbacks in normal systems, by boxing the system and
deferring initialization to an exclusive system.

## Solution

- Separate the registration of the system from the boxing of the system.
This is non-breaking, and adds a new method.

---

## Changelog

- Added `World::register_boxed_system` to allow registration of
already-boxed one shot systems.
2023-11-29 16:40:36 -08:00
kayh
e0a532cb4b Fix bevy_pbr shader function name (#10423)
# Objective

Fix a shader error that happens when using pbr morph targets.

## Solution

Fix the function name in the `prepass.wgsl` shader, which is incorrectly
prefixed with `morph::` (added in
61bad4eb57 (diff-97e4500f0a36bc6206d7b1490c8dd1a69459ee39dc6822eb9b2f7b160865f49fR42)).

This section of the shader is only enabled when using morph targets, so
it seems like there are no tests / examples using it?
2023-11-29 16:40:19 -08:00
François
e8ba68d702 UI Materials: ignore entities with a BackgroundColor component (#10434)
# Objective

- Entities with both a `BackgroundColor` and a
`Handle<CustomUiMaterial>` are extracted by both pipelines and results
in entities being overwritten in the render world
- Fixes #10431 

## Solution

- Ignore entities with `BackgroundColor` when extracting ui material
entities, and document that limit
2023-11-29 16:40:05 -08:00
François
07d6a12f46 UI Material: each material should have its own buffer (#10422)
# Objective

- When having several UI Material, nodes are not correctly placed

## Solution

- have a buffer per material
2023-11-29 16:39:47 -08:00
François
e6695d5e20 ui material: fix right border width (#10421)
# Objective

- When writing a custom UI material, the right border doesn't have the
correct value

## Solution

- Fix the calculation
2023-11-29 16:39:26 -08:00
github-actions[bot]
bf30a25efc
Release 0.12 (#10362)
Preparing next release
This PR has been auto-generated

---------

Co-authored-by: Bevy Auto Releaser <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: François <mockersf@gmail.com>
2023-11-04 17:24:23 +00:00
Aevyrie
1d8d78ef0e
Update color and naming for consistency (#10367)
The `ClearColor` PR was merged before I was quite finished. This fixes a
few errors, and addresses Cart's feedback about the pixel perfect
example by updating the sprite colors to match the existing bevy bird
branding colors.


![image](https://github.com/bevyengine/bevy/assets/2632925/33722c45-ed66-4d3a-af11-f4197611a13c)
2023-11-04 02:09:23 +00:00
robtfm
cd594221cf
gate depth reads on !WEBGL2 (#10365)
# Objective

fix #10364 

## Solution

gate depth prepass reads in pbr_transmission.wgsl by `#ifndef WEBGL2`
2023-11-04 02:02:49 +00:00
Carter Anderson
1e35a06e29
0.12 Changelog (#10361)
Updates the changelog for the upcoming 0.12 release
2023-11-04 01:57:29 +00:00
François
624801b942
Fix example showcase (#10366)
# Objective

- One of the patch for CI was not applied anymore
- a temp file has been committed, remove it and gitignore it
2023-11-04 01:33:51 +00:00
IceSentry
64faadb932
Fix gizmo crash when prepass enabled (#10360)
# Objective

- Fix gizmo crash when prepass enabled

## Solution

- Add the prepass to the view key

Fixes: https://github.com/bevyengine/bevy/issues/10347
2023-11-03 23:38:50 +00:00
François
49bc6cfd62
support file operations in single threaded context (#10312)
# Objective

- Fixes #10209 
- Assets should work in single threaded

## Solution

- In single threaded mode, don't use `async_fs` but fallback on
`std::fs` with a thin layer to mimic the async API
- file `file_asset.rs` is the async imps from `mod.rs`
- file `sync_file_asset.rs` is the same with `async_fs` APIs replaced by
`std::fs`
- which module is used depends on the `multi-threaded` feature

---------

Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2023-11-03 23:00:34 +00:00
Markus Ort
fd232ad360
Add UI Materials (#9506)
# Objective

- Add Ui Materials so that UI can render more complex and animated
widgets.
- Fixes #5607 

## Solution
- Create a UiMaterial trait for specifying a Shader Asset and Bind Group
Layout/Data.
- Create a pipeline for rendering these Materials inside the Ui
layout/tree.
- Create a MaterialNodeBundle for simple spawning.

## Changelog

- Created a `UiMaterial` trait for specifying a Shader asset and Bind
Group.
- Created a `UiMaterialPipeline` for rendering said Materials.
- Added Example [`ui_material`
](https://github.com/MarkusTheOrt/bevy/blob/ui_material/examples/ui/ui_material.rs)
for example usage.
- Created
[`UiVertexOutput`](https://github.com/MarkusTheOrt/bevy/blob/ui_material/crates/bevy_ui/src/render/ui_vertex_output.wgsl)
export as VertexData for shaders.
- Created
[`material_ui`](https://github.com/MarkusTheOrt/bevy/blob/ui_material/crates/bevy_ui/src/render/ui_material.wgsl)
shader as default for both Vertex and Fragment shaders.

---------

Co-authored-by: ickshonpe <david.curthoys@googlemail.com>
Co-authored-by: François <mockersf@gmail.com>
2023-11-03 22:33:01 +00:00
Doonv
6a7b21592f
Fix typo in window.rs (#10358)
# Objective

Fixes a small typo in `bevy_window/src/window.rs`

## Solution

Change `Should be used instead 'scale_factor' when set.` to `Should be
used instead of 'scale_factor' when set.`
2023-11-03 22:04:39 +00:00
François
a1681f43d9
Allow AccessKit to react to WindowEvents before they reach the engine (#10356)
# Objective

- Adopt #10239 to get it in time for the release
- Fix accessibility on macOS and linux

## Solution

- call `on_event` from AcccessKit adapter on winit events

---------

Co-authored-by: Nolan Darilek <nolan@thewordnerd.info>
Co-authored-by: Alice Cecile <alice.i.cecil@gmail.com>
Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
2023-11-03 21:37:25 +00:00
papow65
708569c91e
Corrected incorrect doc comment on read_asset_bytes (#10352)
Fixes #10302 

## Solution

- Removed the incorrect comment.
2023-11-03 21:01:05 +00:00
Aevyrie
1918608b02
Update default ClearColor to better match Bevy's branding (#10339)
# Objective

- Changes the default clear color to match the code block color on
Bevy's website.

## Solution

- Changed the clear color, updated text in examples to ensure adequate
contrast. Inconsistent usage of white text color set to use the default
color instead, which is already white.
- Additionally, updated the `3d_scene` example to make it look a bit
better, and use bevy's branding colors.


![image](https://github.com/bevyengine/bevy/assets/2632925/540a22c0-826c-4c33-89aa-34905e3e313a)
2023-11-03 12:57:38 +00:00
Sélène Amanita
c376954b87
Make DirectionalLight Cascades computation generic over CameraProjection (#9226)
# Objective

Fixes https://github.com/bevyengine/bevy/issues/9077 (see this issue for
motivations)

## Solution

Implement 1 and 2 of the "How to fix it" section of
https://github.com/bevyengine/bevy/issues/9077

`update_directional_light_cascades` is split into
`clear_directional_light_cascades` and a generic
`build_directional_light_cascades`, to clear once and potentially insert
many times.

---

## Changelog

`DirectionalLight`'s computation is now generic over `CameraProjection`
and can work with custom camera projections.

## Migration Guide

If you have a component `MyCustomProjection` that implements
`CameraProjection`:
- You need to implement a new required associated method,
`get_frustum_corners`, returning an array of the corners of a subset of
the frustum with given `z_near` and `z_far`, in local camera space.
- You can now add the
`build_directional_light_cascades::<MyCustomProjection>` system in
`SimulationLightSystems::UpdateDirectionalLightCascades` after
`clear_directional_light_cascades` for your projection to work with
directional lights.

---------

Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2023-11-03 06:07:59 +00:00
Carter Anderson
3ec52c2bdb
Increase default normal bias to avoid common artifacts (#10346)
# Objective

Bevy's default bias values for directional and spot lights currently
cause significant artifacts. We should fix that so shadows look good by
default!

This is a less controversial/invasive alternative to #10188, which might
enable us to keep the default bias value low, but also has its own sets
of concerns and caveats that make it a risky choice for Bevy 0.12.

## Solution

Bump the default normal bias from `0.6` to `1.8`. There is precedent for
values in this general area as Godot has a default normal bias of `2.0`.

### Before


![image](https://github.com/superdump/bevy/assets/2694663/a5828011-33fc-4427-90ed-f093d7389053)

### After


![image](https://github.com/bevyengine/bevy/assets/2694663/0f2b16b0-c116-41ab-9886-1ace9e00efd6)

## Migration Guide

The default `shadow_normal_bias` value for `DirectionalLight` and
`SpotLight` has changed to accommodate artifacts introduced with the new
shadow PCF changes. It is unlikely (especially given the new PCF shadow
behaviors with these values), but you might need to manually tweak this
value if your scene requires a lower bias and it relied on the previous
default value.
2023-11-03 05:44:57 +00:00
ickshonpe
d70b4a3170
UI batching Fix (#9610)
# Objective

Reimplement #8793 on top of the recent rendering changes.

## Solution

The batch creation logic is quite convoluted, but I tested it on enough
examples to convince myself that it works.

The initial value of `batch_image_handle` is changed from
`HandleId::Id(Uuid::nil(), u64::MAX)` to `DEFAULT_IMAGE_HANDLE.id()`,
which allowed me to make the if-block simpler I think.

The default image from `DEFAULT_IMAGE_HANDLE` is always inserted into
`UiImageBindGroups` even if it's not used. I tried to add a check so
that it would be only inserted when there is only one batch using the
default image but this crashed.

---

## Changelog
`prepare_uinodes`
* Changed the initial value of `batch_image_handle` to
`DEFAULT_IMAGE_HANDLE.id()`.
* The default image is added to the UI image bind groups before
assembling the batches.
* A new `UiBatch` isn't created when the next `ExtractedUiNode`s image
is set to `DEFAULT_IMAGE_HANDLE` (unless it is the first item in the UI
phase items list).
2023-11-03 01:14:43 +00:00
robtfm
5cc3352f5b
allow DeferredPrepass to work without other prepass markers (#10223)
# Objective

fix crash / misbehaviour when `DeferredPrepass` is used without
`DepthPrepass`.

- Deferred lighting requires the depth prepass texture to be present, so
that the depth texture is available for binding. without it the deferred
lighting pass will use 0 for depth of all meshes.
- When `DeferredPrepass` is used without other prepass markers, and with
any materials that use `OpaqueRenderMode::Forward`, those entities will
try to queue to the `Opaque3dPrepass` render phase, which doesn't exist,
causing a crash.

## Solution

- check if the prepass phases exist before queueing
- generate prepass textures if `Opaque3dDeferred` is present
- add a note to the DeferredPrepass marker to note that DepthPrepass is
also required by the default deferred lighting pass
- also changed some `With<T>.is_some()`s to `Has<T>`s
2023-11-03 01:09:14 +00:00
Christopher Biscardi
74b5073f75
Make VERTEX_COLORS usable in prepass shader, if available (#10341)
# Objective

I was working with forward rendering prepass fragment shaders and ran
into an issue of not being able to access vertex colors in the prepass.
I was able to access vertex colors in regular fragment shaders as well
as in deferred shaders.

## Solution

It seems like this `if` was nested unintentionally as moving it outside
of the `deferred` block works.

---

## Changelog

Enable vertex colors in forward rendering prepass fragment shaders
2023-11-03 00:54:13 +00:00
Rob Parrett
09c2090c15
Combine visibility queries in check_visibility_system (#10196)
# Objective

Alternative to #7310

## Solution

Implemented the suggestion from
https://github.com/bevyengine/bevy/pull/7310#discussion_r1083356655

I am guessing that these were originally split as an optimization, but I
am not sure since I believe the original author of the code is the one
speculating about combining them up there.

## Benchmarks

I ran three benchmarks to compare main, this PR, and the approach from
#7310
([updated](https://github.com/rparrett/bevy/commits/rebased-parallel-check-visibility)
to the same commit on main).

This seems to perform slightly better than main in scenarios where most
entities have AABBs, and a bit worse when they don't (`many_lights`).
That seems to make sense to me.

Either way, the difference is ~-20 microseconds in the more common
scenarios or ~+100 microseconds in the less common scenario. I would
speculate that this might perform **very slightly** worse in
single-threaded scenarios.

Benches were run in release mode for 2000 frames while capturing a trace
with tracy.

| bench | commit | check_visibility_system mean μs |
| -- | -- | -- |
| many_cubes | main | 929.5 |
| many_cubes | this | 914.0 |
| many_cubes | 7310 | 1003.5 |
| | |
| many_foxes | main | 191.6 |
| many_foxes | this | 173.2 |
| many_foxes | 7310 | 167.9 |
| | |
| many_lights | main | 619.3 |
| many_lights | this | 703.7 |
| many_lights | 7310 | 842.5 |

## Notes

Technically this behaves slightly differently -- prior to this PR, view
visibility was determined even for entities without `GlobalTransform`. I
don't think this has any practical impact though.

IMO, I don't think we need to do this. But I opened a PR because it
seemed like the handiest way to share the code / benchmarks.

## TODO

I have done some rudimentary testing with the examples above, but I can
do some screenshot diffing if it seems like we want to do this.
2023-11-02 22:06:38 +00:00
François
0dfb6cf89b
don't Implement Display for Val (#10345)
# Objective

- Revert #10296 

## Solution

- Avoid implementing `Display` without a justification
- `Display` implementation is a guarantee without a direct use, takes
additional time to compile and require work to maintain
- `Debug`, `Reflect` or `Serialize` should cover all needs
2023-11-02 21:54:41 +00:00
François
6f8848a6c2
double sided normals: fix apply_normal_mapping calls (#10330)
# Objective

- After #10326, examples `array_texture`, `ssao` and `shader_prepass`
don't render correctly
```
error: failed to build a valid final module: Entry point fragment at Fragment is invalid
   ┌─ crates/bevy_pbr/src/render/pbr_prepass.wgsl:26:22
   │
26 │           let normal =  evy_pbr::pbr_functions::31mapply_normal_mapping(
   │ ╭──────────────────────^
27 │ │             bevy_pbr::pbr_bindings::material.flags,
28 │ │             world_normal,
29 │ │
   · │
36 │ │
37 │ │             bevy_pbr::mesh_view_bindings::view.mip_bias,
   │ ╰───────────────────────────────────────────────────────────────────────────────────────^ invalid function call
   │
   = Call to [9] is invalid
   = Requires 6 arguments, but 4 are provided

```

## Solution

- fix `apply_normal_mapping` calls
2023-11-01 16:40:25 +00:00
Talin
d2c754c816
Added 'clear_children' and 'replace_children' methods to BuildWorldChildren to be consistent with BuildChildren. (#10311)
# Objective

The `BuildWorldChildren` API was missing several methods that exist in
`BuildChildren`.

## Solution

Added the methods (and tests) for consistency.
2023-10-31 23:55:33 +00:00
ickshonpe
563d6e36bb
Add stack index to Node (#9853)
# Objective

If we add the stack index to `Node` then we don't need to walk the
`UiStack` repeatedly during extraction.

## Solution

Add a field `stack_index`  to `Node`.
Update it in `ui_stack_system`.
Iterate queries directly in the UI's extraction systems.

### Benchmarks 
```
cargo run --profile stress-test --features trace_tracy --example many_buttons -- --no-text --no-borders
```

frames (yellow this PR, red main):

<img width="447" alt="frames-per-second"
src="https://github.com/bevyengine/bevy/assets/27962798/385c0ccf-c257-42a2-b736-117542d56eff">

`ui_stack_system`:
<img width="585" alt="ui-stack-system"
src="https://github.com/bevyengine/bevy/assets/27962798/2916cc44-2887-4c3b-a144-13250d84f7d5">

extract schedule:
<img width="469" alt="extract-schedule"
src="https://github.com/bevyengine/bevy/assets/27962798/858d4ab4-d99f-48e8-b153-1c92f51e0743">

---

## Changelog

* Added the field `stack_index` to `Node`.
* `ui_stack_system` updates `Node::stack_index` after a new `UiStack` is
generated.
* The UI's extraction functions iterate a query directly rather than
walking the `UiStack` and doing lookups.
2023-10-31 23:32:51 +00:00
Marco Buono
44928e0df4
StandardMaterial Light Transmission (#8015)
# Objective

<img width="1920" alt="Screenshot 2023-04-26 at 01 07 34"
src="https://user-images.githubusercontent.com/418473/234467578-0f34187b-5863-4ea1-88e9-7a6bb8ce8da3.png">

This PR adds both diffuse and specular light transmission capabilities
to the `StandardMaterial`, with support for screen space refractions.
This enables realistically representing a wide range of real-world
materials, such as:

  - Glass; (Including frosted glass)
  - Transparent and translucent plastics;
  - Various liquids and gels;
  - Gemstones;
  - Marble;
  - Wax;
  - Paper;
  - Leaves;
  - Porcelain.

Unlike existing support for transparency, light transmission does not
rely on fixed function alpha blending, and therefore works with both
`AlphaMode::Opaque` and `AlphaMode::Mask` materials.

## Solution

- Introduces a number of transmission related fields in the
`StandardMaterial`;
- For specular transmission:
- Adds logic to take a view main texture snapshot after the opaque
phase; (in order to perform screen space refractions)
- Introduces a new `Transmissive3d` phase to the renderer, to which all
meshes with `transmission > 0.0` materials are sent.
- Calculates a light exit point (of the approximate mesh volume) using
`ior` and `thickness` properties
- Samples the snapshot texture with an adaptive number of taps across a
`roughness`-controlled radius enabling “blurry” refractions
- For diffuse transmission:
- Approximates transmitted diffuse light by using a second, flipped +
displaced, diffuse-only Lambertian lobe for each light source.

## To Do

- [x] Figure out where `fresnel_mix()` is taking place, if at all, and
where `dielectric_specular` is being calculated, if at all, and update
them to use the `ior` value (Not a blocker, just a nice-to-have for more
correct BSDF)
- To the _best of my knowledge, this is now taking place, after
964340cdd. The fresnel mix is actually "split" into two parts in our
implementation, one `(1 - fresnel(...))` in the transmission, and
`fresnel()` in the light implementations. A surface with more
reflectance now will produce slightly dimmer transmission towards the
grazing angle, as more of the light gets reflected.
- [x] Add `transmission_texture`
- [x] Add `diffuse_transmission_texture`
- [x] Add `thickness_texture`
- [x] Add `attenuation_distance` and `attenuation_color`
- [x] Connect values to glTF loader
  - [x] `transmission` and `transmission_texture`
  - [x] `thickness` and `thickness_texture`
  - [x] `ior`
- [ ] `diffuse_transmission` and `diffuse_transmission_texture` (needs
upstream support in `gltf` crate, not a blocker)
- [x] Add support for multiple screen space refraction “steps”
- [x] Conditionally create no transmission snapshot texture at all if
`steps == 0`
- [x] Conditionally enable/disable screen space refraction transmission
snapshots
- [x] Read from depth pre-pass to prevent refracting pixels in front of
the light exit point
- [x] Use `interleaved_gradient_noise()` function for sampling blur in a
way that benefits from TAA
- [x] Drill down a TAA `#define`, tweak some aspects of the effect
conditionally based on it
- [x] Remove const array that's crashing under HLSL (unless a new `naga`
release with https://github.com/gfx-rs/naga/pull/2496 comes out before
we merge this)
- [ ] Look into alternatives to the `switch` hack for dynamically
indexing the const array (might not be needed, compilers seem to be
decent at expanding it)
- [ ] Add pipeline keys for gating transmission (do we really want/need
this?)
- [x] Tweak some material field/function names?

## A Note on Texture Packing

_This was originally added as a comment to the
`specular_transmission_texture`, `thickness_texture` and
`diffuse_transmission_texture` documentation, I removed it since it was
more confusing than helpful, and will likely be made redundant/will need
to be updated once we have a better infrastructure for preprocessing
assets_

Due to how channels are mapped, you can more efficiently use a single
shared texture image
for configuring the following:

- R - `specular_transmission_texture`
- G - `thickness_texture`
- B - _unused_
- A - `diffuse_transmission_texture`

The `KHR_materials_diffuse_transmission` glTF extension also defines a
`diffuseTransmissionColorTexture`,
that _we don't currently support_. One might choose to pack the
intensity and color textures together,
using RGB for the color and A for the intensity, in which case this
packing advice doesn't really apply.

---

## Changelog

- Added a new `Transmissive3d` render phase for rendering specular
transmissive materials with screen space refractions
- Added rendering support for transmitted environment map light on the
`StandardMaterial` as a fallback for screen space refractions
- Added `diffuse_transmission`, `specular_transmission`, `thickness`,
`ior`, `attenuation_distance` and `attenuation_color` to the
`StandardMaterial`
- Added `diffuse_transmission_texture`, `specular_transmission_texture`,
`thickness_texture` to the `StandardMaterial`, gated behind a new
`pbr_transmission_textures` cargo feature (off by default, for maximum
hardware compatibility)
- Added `Camera3d::screen_space_specular_transmission_steps` for
controlling the number of “layers of transparency” rendered for
transmissive objects
- Added a `TransmittedShadowReceiver` component for enabling shadows in
(diffusely) transmitted light. (disabled by default, as it requires
carefully setting up the `thickness` to avoid self-shadow artifacts)
- Added support for the `KHR_materials_transmission`,
`KHR_materials_ior` and `KHR_materials_volume` glTF extensions
- Renamed items related to temporal jitter for greater consistency

## Migration Guide

- `SsaoPipelineKey::temporal_noise` has been renamed to
`SsaoPipelineKey::temporal_jitter`
- The `TAA` shader def (controlled by the presence of the
`TemporalAntiAliasSettings` component in the camera) has been replaced
with the `TEMPORAL_JITTER` shader def (controlled by the presence of the
`TemporalJitter` component in the camera)
- `MeshPipelineKey::TAA` has been replaced by
`MeshPipelineKey::TEMPORAL_JITTER`
- The `TEMPORAL_NOISE` shader def has been consolidated with
`TEMPORAL_JITTER`
2023-10-31 20:59:02 +00:00
TimJentzsch
d67fbd5e90
Add helper function to determine if color is transparent (#10310)
# Objective

- We need to check multiple times if a color is fully transparent, e.g.
for performance optimizations.
- Make code more readable.
- Reduce code duplication, to simplify making changes if needed (e.g. if
we need to take floating point weirdness into account later on).

## Solution

- Introduce a new `Color::is_fully_transparent` helper function to
determine if the alpha of a color is 0.
- Use the helper function in our UI rendering code.

---

## Changelog

- Added `Color::is_fully_transparent` helper function.

---------

Co-authored-by: François <mockersf@gmail.com>
2023-10-31 15:00:49 +00:00
Marco Buono
dc1f76d9a2
Fix handling of double_sided for normal maps (#10326)
# Objective

Right now, we flip the `world_normal` in response to `double_sided &&
!is_front`, however when calculating `N` from tangents and the normal
map, we don't flip the normal read from the normal map, which produces
extremely weird results.

## Solution

- Pass `double_sided` and `is_front` flags to the
`apply_normal_mapping()` function and use them to conditionally flip
`Nt`

## Comparison

Note: These are from a custom scene running with the `transmission`
branch, (#8015) I noticed lighting got pretty weird for the back side of
translucent `double_sided` materials whenever I added a normal map.

### Before

<img width="1392" alt="Screenshot 2023-10-31 at 01 26 06"
src="https://github.com/bevyengine/bevy/assets/418473/d5f8c9c3-aca1-4c2f-854d-f0d0fd2fb19a">

### After

<img width="1392" alt="Screenshot 2023-10-31 at 01 25 42"
src="https://github.com/bevyengine/bevy/assets/418473/fa0e1aa2-19ad-4c27-bb08-37299d97971c">


---

## Changelog

- Fixed a bug where `StandardMaterial::double_sided` would interact
incorrectly with normal maps, producing broken results.
2023-10-31 09:44:40 +00:00
JMS55
3628e09045
Add frustum to shader View (#10306)
# Objective
- Work towards GPU-driven culling
(https://github.com/bevyengine/bevy/pull/10164)

## Solution
- Pass the view frustum to the shader view uniform

---

## Changelog
- View Frustums are now extracted to the render world and made available
to shaders
2023-10-31 02:00:21 +00:00
Griffin
d3e41e2ff7
Fix deferred lighting pass values not all working on M1 in WebGL2 (#10304)
# Objective

- On MacOS M1 WebGL2 the deferred lighting ID depth comparison is
failing for some values (including 1, the default)
Note: this issue is just with WebGL2, native on MacOS M1 is working with
current bevy main.

## Solution

- Use Depth16Unorm for lighting pass id format.

This format is aliasing to the same value consistently (in
[copy_deferred_lighting_id](https://github.com/bevyengine/bevy/blob/main/crates/bevy_core_pipeline/src/deferred/copy_deferred_lighting_id.wgsl#L15)
and
[deferred_lighting](https://github.com/bevyengine/bevy/blob/main/crates/bevy_pbr/src/deferred/deferred_lighting.wgsl#L39))
on MacOS M1 WebGL, and appears to be supported across WebGL2, WebGPU,
DX12, OpenGL 3.3, Vulkan.

Successfully tested all 256 ids on:

- MacOS M1 native and WebGL2
- Window RTX3060 Vulkan/DX12/WebGL2
- Windows Intel UHD Graphics 630 IGP DX12/WebGL2 
(bevy w/ Vulkan doesn't work on this IGP in general
https://github.com/bevyengine/bevy/issues/8037)
2023-10-29 16:47:48 +00:00
CrumbsTrace
e9a0d6ccc5
Update UI alignment docs (#10303)
# Objective

- Address inconsistent term usage in the docs for the alignment
properties for UI nodes. Fixes #10218
- `JustifyContent::Stretch` is missing despite being supported by Taffy,
being as the default value for Grids, so it should be added to Bevy as
well

## Solution

- Consistently provide links to the mdn site for the css equivalent
- Match (mostly) the documentation given on the pub struct and the
underlying enums
- Use the term `items` consistently to refer each child in the container
- Add `JustifyContent::Stretch` and map it to Taffy

## Migration Guide

- The `JustifyContents` enum has been expanded to include
`JustifyContents::Stretch`.
2023-10-29 15:32:11 +00:00
Pascal Hertleif
0c2c52a0cd
Derive Error for more error types (#10240)
# Objective

Align all error-like types to implement `Error`.

Fixes  #10176

## Solution

- Derive `Error` on more types
- Refactor instances of manual implementations that could be derived

This adds thiserror as a dependency to bevy_transform, which might
increase compilation time -- but I don't know of any situation where you
might only use that but not any other crate that pulls in bevy_utils.

The `contributors` example has a `LoadContributorsError` type, but as
it's an example I have not updated it. Doing that would mean either
having a `use bevy_internal::utils::thiserror::Error;` in an example
file, or adding `thiserror` as a dev-dependency to the main `bevy`
crate.

---

## Changelog

- All `…Error` types now implement the `Error` trait
2023-10-28 22:20:37 +00:00