Commit graph

2875 commits

Author SHA1 Message Date
Daniel McNab
7b2cf98896 Make RenderStage::Extract run on the render world (#4402)
# Objective

- Currently, the `Extract` `RenderStage` is executed on the main world, with the render world available as a resource.
- However, when needing access to resources in the render world (e.g. to mutate them), the only way to do so was to get exclusive access to the whole `RenderWorld` resource.
- This meant that effectively only one extract which wrote to resources could run at a time.
- We didn't previously make `Extract`ing writing to the world a non-happy path, even though we want to discourage that.

## Solution

- Move the extract stage to run on the render world.
- Add the main world as a `MainWorld` resource.
- Add an `Extract` `SystemParam` as a convenience to access a (read only) `SystemParam` in the main world during `Extract`.

## Future work

It should be possible to avoid needing to use `get_or_spawn` for the render commands, since now the `Commands`' `Entities` matches up with the world being executed on.
We need to determine how this interacts with https://github.com/bevyengine/bevy/pull/3519
It's theoretically possible to remove the need for the `value` method on `Extract`. However, that requires slightly changing the `SystemParam` interface, which would make it more complicated. That would probably mess up the `SystemState` api too.

## Todo
I still need to add doc comments to `Extract`.

---

## Changelog

### Changed
- The `Extract` `RenderStage` now runs on the render world (instead of the main world as before).
   You must use the `Extract` `SystemParam` to access the main world during the extract phase.
   Resources on the render world can now be accessed using `ResMut` during extract.

### Removed
- `Commands::spawn_and_forget`. Use `Commands::get_or_spawn(e).insert_bundle(bundle)` instead

## Migration Guide

The `Extract` `RenderStage` now runs on the render world (instead of the main world as before).
You must use the `Extract` `SystemParam` to access the main world during the extract phase. `Extract` takes a single type parameter, which is any system parameter (such as `Res`, `Query` etc.). It will extract this from the main world, and returns the result of this extraction when `value` is called on it.

For example, if previously your extract system looked like:
```rust
fn extract_clouds(mut commands: Commands, clouds: Query<Entity, With<Cloud>>) {
    for cloud in clouds.iter() {
        commands.get_or_spawn(cloud).insert(Cloud);
    }
}
```
the new version would be:
```rust
fn extract_clouds(mut commands: Commands, mut clouds: Extract<Query<Entity, With<Cloud>>>) {
    for cloud in clouds.value().iter() {
        commands.get_or_spawn(cloud).insert(Cloud);
    }
}
```
The diff is:
```diff
--- a/src/clouds.rs
+++ b/src/clouds.rs
@@ -1,5 +1,5 @@
-fn extract_clouds(mut commands: Commands, clouds: Query<Entity, With<Cloud>>) {
-    for cloud in clouds.iter() {
+fn extract_clouds(mut commands: Commands, mut clouds: Extract<Query<Entity, With<Cloud>>>) {
+    for cloud in clouds.value().iter() {
         commands.get_or_spawn(cloud).insert(Cloud);
     }
 }
```
You can now also access resources from the render world using the normal system parameters during `Extract`:
```rust
fn extract_assets(mut render_assets: ResMut<MyAssets>, source_assets: Extract<Res<MyAssets>>) {
     *render_assets = source_assets.clone();
}
```
Please note that all existing extract systems need to be updated to match this new style; even if they currently compile they will not run as expected. A warning will be emitted on a best-effort basis if this is not met.

Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2022-07-08 23:56:33 +00:00
Robin KAY
e6faf993b0 Add support for removing attributes from meshes. (#5254)
# Objective

Support removing attributes from meshes. For an example use case, meshes created using the bevy::predule::shape types or loaded from external files may have attributes that are not needed for the materials they will be rendered with.

This was extracted from PR #5222.

## Solution

Implement Mesh::remove_attribute().
2022-07-08 21:18:32 +00:00
Robin KAY
3c51ad2764 Allow rendering meshes without UV coordinate data. (#5222)
# Objective

Bevy requires meshes to include UV coordinates, even if the material does not use any textures, and will fail with an error `ERROR bevy_pbr::material: Mesh is missing requested attribute: Vertex_Uv (MeshVertexAttributeId(2), pipeline type: Some("bevy_pbr::material::MaterialPipeline<bevy_pbr::pbr_material::StandardMaterial>"))` otherwise. The objective of this PR is to permit this.

## Solution

This PR follows the design of #4528, which added support for per-vertex colours. It adds a shader define called VERTEX_UVS which indicates the presence of UV coordinates to the shader.
2022-07-08 20:55:08 +00:00
robtfm
132950cd55 Spotlights (#4715)
# Objective

add spotlight support

## Solution / Changelog

- add spotlight angles (inner, outer) to ``PointLight`` struct. emitted light is linearly attenuated from 100% to 0% as angle tends from inner to outer. Direction is taken from the existing transform rotation.
- add spotlight direction (vec3) and angles (f32,f32) to ``GpuPointLight`` struct (60 bytes -> 80 bytes) in ``pbr/render/lights.rs`` and ``mesh_view_bind_group.wgsl``
- reduce no-buffer-support max point light count to 204 due to above
- use spotlight data to attenuate light in ``pbr.wgsl``
- do additional cluster culling on spotlights to minimise cost in ``assign_lights_to_clusters``
- changed one of the lights in the lighting demo to a spotlight
- also added a ``spotlight`` demo - probably not justified but so reviewers can see it more easily

## notes

increasing the size of the GpuPointLight struct on my machine reduces the FPS of ``many_lights -- sphere`` from ~150fps to 140fps. 

i thought this was a reasonable tradeoff, and felt better than handling spotlights separately which is possible but would mean introducing a new bind group, refactoring light-assignment code and adding new spotlight-specific code in pbr.wgsl. the FPS impact for smaller numbers of lights should be very small.

the cluster culling strategy reintroduces the cluster aabb code which was recently removed... sorry. the aabb is used to get a cluster bounding sphere, which can then be tested fairly efficiently using the strategy described at the end of https://bartwronski.com/2017/04/13/cull-that-cone/. this works well with roughly cubic clusters (where the cluster z size is close to the same as x/y size), less well for other cases like single Z slice / tiled forward rendering. In the worst case we will end up just keeping the culling of the equivalent point light.

Co-authored-by: François <mockersf@gmail.com>
2022-07-08 19:57:43 +00:00
SuperSamus
4c35ecf71f linux_dependencies: fix NixOS (#5251)
I forgot a rec... (and I removed the redundant file name).

# Objective

- Fix the whoopsie from #5086.
2022-07-08 17:14:34 +00:00
Mark Schmale
47f1944959 Adds a "Question" link to the new issue selection (#5169)
This gives users a hint to use the GitHub "Discussions" for questions about bevy, instead of filing an issue.

## Objective
> Users sometimes file unhelpful issues when asking questions about how to use Bevy.

We should provide a link to the Discussion board in the list of "new Issue" options. This hopefully allows users to better find this option and reduces the number of question-issues.

- fixes #5150

## Solution

- add a small config.yml that configures the link

Looks like this (currently live on my local fork https://github.com/themasch/bevy/issues/new/choose):
![grafik](https://user-images.githubusercontent.com/170171/176940564-cd3a4ad1-731b-4417-95c2-3b5285120c88.png)

---

## Open questsions
 - I am unsure about the wording.
2022-07-08 03:46:50 +00:00
Hennadii Chernyshchyk
17e87f116f Improve EntityMap API (#5231)
# Objective

`EntityMap` lacks documentation, don't have `len()` / `is_empty` and `insert` doesn't work as in the regular HashMap`.

## Solution

* Add `len()` method.
* Return previously mapped entity from `insert()` as in the regular `HashMap`.
* Add documentation.

---

## Changelog

* Add `EntityMap::len()`.
* Return previously mapped entity from `EntityMap::insert()` as in the regular `HashMap`.
* Add documentation for `EntityMap` methods.
2022-07-08 01:14:24 +00:00
Tethys Svensson
11c4514023 Move the configuration of the WindowPlugin to a resource (#5227)
# Objective

It is currently hard to configure the `WindowPlugin`, as it is added as part of the `DefaultPlugins`. Ideally this should not be difficult.

## Solution

Remove the configuration from the plugin itself and put it as a `Resource`, similar to how it is done for almost all other plugins.

## Migration Guide

If you are currently configuring the behavior of the `WindowPlugin`, by constructing it manually, then you will need to instead create add the `WindowSettings` as a resource.
2022-07-08 01:14:23 +00:00
Boutillier
6b073ee412 Update shader_material_glsl example to include texture sampling (#5215)
# Objective

Add texture sampling to the GLSL shader example, as naga does not support the commonly used sampler2d type.
Fixes #5059

## Solution

- Align the shader_material_glsl example behaviour with the shader_material example,  as the later includes texture sampling.
- Update the GLSL shader to do texture sampling the way naga supports it, and document the way naga does not support it.

## Changelog

- The shader_material_glsl example has been updated to demonstrate texture sampling using the GLSL shading language.


Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2022-07-08 01:14:22 +00:00
Nicola Papale
4ee73ed904 Rename CameraUi (#5234)
# Objective

In bevy 0.7, `CameraUi` was a component specifically added to cameras
that display the UI. Since camera-driven rendering was merged, it
actually does the opposite! This will make it difficult for current
users to adapt to 0.8.

## Solution

To avoid unnecessary confusion, we rename `CameraUi` into
`UiCameraConfig`.

---

## Changelog

- Rename `CameraUi` to `UiCameraConfig`
2022-07-08 00:59:39 +00:00
Obdzen
cf200f09dd Fix typo in Word::get_by_id docs (#5246)
I believe this should read `immutable` not `mutable`



Co-authored-by: Obdzen <108854527+Obdzen@users.noreply.github.com>
2022-07-07 15:25:17 +00:00
Oliver Pauffley
bf1ca81779 remove component and resource suffixes from reflect structs (#5219)
# Objective

Remove suffixes from reflect component and resource methods to closer match bevy norms.

## Solution

removed suffixes and also fixed a spelling error

---
2022-07-06 02:59:51 +00:00
Alice Cecile
2db1611775 Add troubleshooting command to miri docs (#5116)
# Objective

When `miri` runs in our build system to detect unsoundness, its output can be very unhelpful, as the tests are all run in parallel.

## Solution

Add a comment documenting the extremely obvious 10/10 command used by @BoxyUwU in #4959.

I've stuck this in the CI file, as it seems like the most obvious place to check when frustrated. I didn't put it  in CONTRIBUTING.md because this is an eldritch abomination and will never be useful to new contributors.
2022-07-06 00:11:24 +00:00
François
f73987ae84 add a more helpful error to help debug panicking command on despawned entity (#5198)
# Objective

- Help users fix issue when their app panic when executing a command on a despawned entity

## Solution

- Add an error code and a page describing how to debug the issue
2022-07-05 18:44:54 +00:00
Afonso Lage
40982cd0a2 Make reflect_partial_eq return more accurate results (#5210)
# Objective

Closes #5204

## Solution

- Followed @nicopap suggestion on https://github.com/bevyengine/bevy/pull/4761#discussion_r903982224

## Changelog

- [x] Updated [struct_trait](dfe9690052/crates/bevy_reflect/src/struct_trait.rs (L455-L457)), [tuple_struct](dfe9690052/crates/bevy_reflect/src/tuple_struct.rs (L366-L368)), [tuple](dfe9690052/crates/bevy_reflect/src/tuple.rs (L386)), [array](dfe9690052/crates/bevy_reflect/src/array.rs (L335-L337)), [list](dfe9690052/crates/bevy_reflect/src/list.rs (L309-L311)) and [map](dfe9690052/crates/bevy_reflect/src/map.rs (L361-L363)) to return `None` when comparison couldn't be performed.
- [x] Updated docs comments to reflect above changes.
2022-07-05 17:41:54 +00:00
Mark Lodato
a249e95693 Fix small typo in example name (#5217)
**This Commit**
Renames "Scale Factor Iverride" to
"Scale Factor Override".

**Why?**
I imagine the current name is a typo.
2022-07-05 16:59:31 +00:00
Thierry Berger
faa40bfc82 Fix markdownlint privileges complaint (#5216)
# Objective

Fixes an annoying error message in CI.

more info at https://github.com/github/super-linter/pull/2464

![image](https://user-images.githubusercontent.com/2290685/177364755-fe607c9c-615e-477c-8e91-d35aae07ab0b.png)
2022-07-05 15:49:11 +00:00
Tethys Svensson
aa0cd7c7dc Make the fields of the Material2dKey public (#5212)
# Objective

Make it easier to create pipelines derived from the `Material2dPipeline`. Currently this is made difficult because the fields of `Material2dKey` are private.

## Solution

Make the fields public.
2022-07-05 14:02:00 +00:00
Maksymilian Mozolewski
61e5bfb2ed implement reflection for more glam types (#5194)
# Objective

- To implement `Reflect` for more glam types.  

## Solution

insert `impl_reflect_struct` invocations for more glam types. I am not sure about the boolean vectors, since none of them implement `Serde::Serialize/Deserialize`, and the SIMD versions don't have public fields. 
I do still think implementing reflection is useful for BVec's since then they can be incorporated into `Reflect`'ed components and set dynamically even if as a whole + it's more consistent.

## Changelog
Implemented `Reflect` for the following types
 - BVec2
 - BVec3
 - **BVec3A** (on simd supported platforms only)
 - BVec4
 - **BVec4A** (on simd supported platforms only)
 - Mat2
 - Mat3A
 - DMat2
 - Affine2
 - Affine3A
 - DAffine2
 - DAffine3
 - EulerRot
2022-07-05 13:38:47 +00:00
Robin KAY
5b5013d540 Add ViewRangefinder3d to reduce boilerplate when enqueuing standard 3D PhaseItems. (#5014)
# Objective

Reduce the boilerplate code needed to make draw order sorting work correctly when queuing items through new common functionality. Also fix several instances in the bevy code-base (mostly examples) where this boilerplate appears to be incorrect.

## Solution

- Moved the logic for handling back-to-front vs front-to-back draw ordering into the PhaseItems by inverting the sort key ordering of Opaque3d and AlphaMask3d. The means that all the standard 3d rendering phases measure distance in the same way. Clients of these structs no longer need to know to negate the distance.
- Added a new utility struct, ViewRangefinder3d, which encapsulates the maths needed to calculate a "distance" from an ExtractedView and a mesh's transform matrix.
- Converted all the occurrences of the distance calculations in Bevy and its examples to use ViewRangefinder3d. Several of these occurrences appear to be buggy because they don't invert the view matrix or don't negate the distance where appropriate. This leads me to the view that Bevy should expose a facility to correctly perform this calculation.

## Migration Guide

Code which creates Opaque3d, AlphaMask3d, or Transparent3d phase items _should_ use ViewRangefinder3d to calculate the distance value.

Code which manually calculated the distance for Opaque3d or AlphaMask3d phase items and correctly negated the z value will no longer depth sort correctly. However, incorrect depth sorting for these types will not impact the rendered output as sorting is only a performance optimisation when drawing with depth-testing enabled. Code which manually calculated the distance for Transparent3d phase items will continue to work as before.
2022-07-05 06:13:39 +00:00
Robert Swain
dfe9690052 docs: Add section about using Tracy for profiling (#4534)
# Objective

- Document how to do profiling with Tracy

# Solution

- The documentation of setting `RUST_LOG=info` in order to capture `wgpu` spans depends on https://github.com/bevyengine/bevy/pull/5182
2022-07-04 17:31:47 +00:00
Alice Cecile
2c9bc0b31f Remove dead SystemLabelMarker struct (#5190)
This struct had no internal use, docs, or intuitable external use.

It has been removed.
2022-07-04 15:12:35 +00:00
Jakob Hellermann
d38a8dfdd7 add more SAFETY comments and lint for missing ones in bevy_ecs (#4835)
# Objective

`SAFETY` comments are meant to be placed before `unsafe` blocks and should contain the reasoning of why in this case the usage of unsafe is okay. This is useful when reading the code because it makes it clear which assumptions are required for safety, and makes it easier to spot possible unsoundness holes. It also forces the code writer to think of something to write and maybe look at the safety contracts of any called unsafe methods again to double-check their correct usage.

There's a clippy lint called `undocumented_unsafe_blocks` which warns when using a block without such a comment. 

## Solution

- since clippy expects `SAFETY` instead of `SAFE`, rename those
- add `SAFETY` comments in more places
- for the last remaining 3 places, add an `#[allow()]` and `// TODO` since I wasn't comfortable enough with the code to justify their safety
- add ` #![warn(clippy::undocumented_unsafe_blocks)]` to `bevy_ecs`


### Note for reviewers

The first commit only renames `SAFETY` to `SAFE` so it doesn't need a thorough review.
cb042a416e..55cef2d6fa is the diff for all other changes.

### Safety comments where I'm not too familiar with the code

774012ece5/crates/bevy_ecs/src/entity/mod.rs (L540-L546)

774012ece5/crates/bevy_ecs/src/world/entity_ref.rs (L249-L252)

### Locations left undocumented with a `TODO` comment

5dde944a30/crates/bevy_ecs/src/schedule/executor_parallel.rs (L196-L199)

5dde944a30/crates/bevy_ecs/src/world/entity_ref.rs (L287-L289)

5dde944a30/crates/bevy_ecs/src/world/entity_ref.rs (L413-L415)

Co-authored-by: Jakob Hellermann <hellermann@sipgate.de>
2022-07-04 14:44:24 +00:00
Jakob Hellermann
4d05eb19be bevy_reflect: remove glam from a test which is active without the glam feature (#5195)
# Objective

`glam` is an optional feature in `bevy_reflect` and there is a separate `mod test { #[cfg(feature = "glam")] mod glam { .. }}`.
The `reflect_downcast` test is not in that module and doesn't depend on glam, which breaks `cargo test -p bevy_reflect` without the `glam` feature.

## Solution

- Remove the glam types from the test, they're not relevant to it
2022-07-04 14:17:46 +00:00
ShadowCurse
179f719553 ECS benchmarks organization (#5189)
## Objective

Fixes: #5110

## Solution

- Moved benches into separate modules according to the part of ECS they are testing.
- Made so all ECS benches are included in one `benches.rs` so they don’t need to be added separately in `Cargo.toml`.
- Renamed a bunch of files to have more coherent names.
- Merged `schedule.rs` and `system_schedule.rs` into one file.
2022-07-04 14:17:45 +00:00
Alice Cecile
050251da5a Add standard Bevy boilerplate to README.md (#5191)
@BoxyUwU says that she always looks for this here, following the example of [tetra](https://github.com/17cupsofcoffee/tetra).

I think this is a pretty sensible idea!
2022-07-04 13:04:21 +00:00
Hennadii Chernyshchyk
534cad611d Add reflection for resources (#5175)
# Objective

We don't have reflection for resources.

## Solution

Introduce reflection for resources.

Continues #3580 (by @Davier), related to #3576.

---

## Changelog

### Added

* Reflection on a resource type (by adding `ReflectResource`):

```rust
#[derive(Reflect)]
#[reflect(Resource)]
struct MyResourse;
```

### Changed

* Rename `ReflectComponent::add_component` into `ReflectComponent::insert_component` for consistency.

## Migration Guide

* Rename `ReflectComponent::add_component` into `ReflectComponent::insert_component`.
2022-07-04 13:04:20 +00:00
James Liu
5498ef81fb bevy_reflect: support map insertion (#5173)
# Objective

This is a rebase of #3701 which is currently scheduled for 0.8 but is marked for adoption.

> Fixes https://github.com/bevyengine/bevy/discussions/3609

## Solution
> - add an `insert_boxed()` method on the `Map` trait
> - implement it for `HashMap` using a new `FromReflect` generic bound
> - add a `map_apply()` helper method to implement `Map::apply()`, that inserts new values instead of ignoring them


---

## Changelog
TODO

Co-authored-by: james7132 <contact@jamessliu.com>
2022-07-04 13:04:19 +00:00
Daniel McNab
e64efd399e Remove the dependency cycles (#5171)
# Objective

- I think our codebase is hit badly by rust-lang/rust-analyzer#11410
- None of our uses of cyclic dependencies are remotely necessary
- Note that these are false positives in rust-analyzer, however it's probably easier for us to work around this
- Note also that I haven't confirmed that this is causing rust-analyzer to not work very well, but it's not a bad guess.

## Solution

- Remove our cyclic dependencies
- Import the trick from #2851 for no-op plugin groups.
2022-07-04 13:04:18 +00:00
Alice Cecile
3a102e7dc2 Add Events to bevy_ecs prelude (#5159)
# Objective

This is a common and useful type. I frequently use this when working with `Events` resource directly, typically when caching the data or manipulating the `World` directly.

This is also useful when manually configuring the cleanup strategy for events.
2022-07-04 13:04:17 +00:00
Elijah
5d3fa5e77b Add inverse_projection and inverse_view_proj fields to shader view uniform (#5119)
# Objective

Transform screen-space coordinates into world space in shaders. (My use case is for generating rays for ray tracing with the same perspective as the 3d camera).

## Solution

Add `inverse_projection` and `inverse_view_proj` fields to shader view uniform

---

## Changelog

### Added
`inverse_projection` and `inverse_view_proj` fields to shader view uniform

## Note

It'd probably be good to double-check that I did the matrix multiplication in the right order for `inverse_proj_view`. Thanks!
2022-07-04 21:04:16 +08:00
James O'Brien
46f5411605 Add TextureAtlas stress test based on many_sprites and sprite_sheet examples (#5087)
# Objective

Intended to close #5073

## Solution

Adds a stress test that use TextureAtlas based on the existing many_sprites test using the animated sprite implementation from the sprite_sheet example.

In order to satisfy the goals described in #5073 the animations are all slightly offset.

Of note is that the original stress test was designed to test fullstrum culling. I kept this test similar as to facilitate easy comparisons between the use of TextureAtlas and without.
2022-07-04 13:04:15 +00:00
LoipesMas
49da4e741d Add option to center a window (#4999)
# Objective
- Fixes #4993 

## Solution

- ~~Add `centered` property to `WindowDescriptor`~~
- Add `WindowPosition` enum
- `WindowDescriptor.position` is now `WindowPosition` instead of `Option<Vec2>`
- Add `center_window` function to `Window`

## Migration Guide
- If using `WindowDescriptor`, replace `position: None` with `position: WindowPosition::Default` and `position: Some(vec2)`  with `WindowPosition::At(vec2)`.

I'm not sure if this is the best approach, so feel free to give any feedback.
Also I'm not sure how `Option`s should be handled in `bevy_winit/src/lib.rs:161`.

Also, on window creation we can't (or at least I couldn't) get `outer_size`, so this doesn't include decorations in calculations.
2022-07-04 13:04:14 +00:00
dependabot[bot]
c0f807ce38 Bump peter-evans/create-pull-request from 3 to 4 (#4940)
Bumps [peter-evans/create-pull-request](https://github.com/peter-evans/create-pull-request) from 3 to 4.
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a href="https://github.com/peter-evans/create-pull-request/releases">peter-evans/create-pull-request's releases</a>.</em></p>
<blockquote>
<h2>Create Pull Request v4.0.0</h2>
<h2>Breaking changes</h2>
<ul>
<li>The <code>add-paths</code> input no longer accepts <code>-A</code> as a valid value. When committing all new and modified files the <code>add-paths</code> input should be omitted.</li>
<li>If using self-hosted runners or GitHub Enterprise Server, there are minimum requirements for <code>v4</code> to run. See &quot;What's new&quot; below for details.</li>
</ul>
<h2>What's new</h2>
<ul>
<li>Updated runtime to Node.js 16
<ul>
<li>The action now requires a minimum version of v2.285.0 for the <a href="https://github.com/actions/runner/releases/tag/v2.285.0">Actions Runner</a>.</li>
<li>If using GitHub Enterprise Server, the action requires <a href="https://docs.github.com/en/enterprise-server@3.4/admin/release-notes">GHES 3.4</a> or later.</li>
</ul>
</li>
</ul>
<h2>What's Changed</h2>
<ul>
<li>README.md: Add word &quot;permissions&quot; to part on GITHUB_TOKEN by <a href="https://github.com/hartwork"><code>@​hartwork</code></a> in <a href="https://github-redirect.dependabot.com/peter-evans/create-pull-request/pull/1082">peter-evans/create-pull-request#1082</a></li>
<li>docs: Document how to improve close-and-reopen user experience by <a href="https://github.com/hartwork"><code>@​hartwork</code></a> in <a href="https://github-redirect.dependabot.com/peter-evans/create-pull-request/pull/1084">peter-evans/create-pull-request#1084</a></li>
<li>README.md: Skip follow-up steps if there is no pull request by <a href="https://github.com/hartwork"><code>@​hartwork</code></a> in <a href="https://github-redirect.dependabot.com/peter-evans/create-pull-request/pull/1083">peter-evans/create-pull-request#1083</a></li>
<li>v4 by <a href="https://github.com/peter-evans"><code>@​peter-evans</code></a> in <a href="https://github-redirect.dependabot.com/peter-evans/create-pull-request/pull/1099">peter-evans/create-pull-request#1099</a></li>
</ul>
<h2>New Contributors</h2>
<ul>
<li><a href="https://github.com/hartwork"><code>@​hartwork</code></a> made their first contribution in <a href="https://github-redirect.dependabot.com/peter-evans/create-pull-request/pull/1082">peter-evans/create-pull-request#1082</a></li>
</ul>
<p><strong>Full Changelog</strong>: <a href="https://github.com/peter-evans/create-pull-request/compare/v3.14.0...v4.0.0">https://github.com/peter-evans/create-pull-request/compare/v3.14.0...v4.0.0</a></p>
<h2>Create Pull Request v3.14.0</h2>
<p>This release reverts a commit made to bump the runtime to node 16. It inadvertently caused <a href="https://github-redirect.dependabot.com/peter-evans/create-pull-request/issues/1077">an issue</a> for users on GitHub Enterprise. Apologies. 🙇‍♂️</p>
<h2>What's Changed</h2>
<ul>
<li>feat: revert update action runtime to node 16 by <a href="https://github.com/peter-evans"><code>@​peter-evans</code></a> <a href="18f7dc018c</a></li>
</ul>
<p><strong>Full Changelog</strong>: <a href="https://github.com/peter-evans/create-pull-request/compare/v3.13.0...v3.14.0">https://github.com/peter-evans/create-pull-request/compare/v3.13.0...v3.14.0</a></p>
<h2>Create Pull Request v3.13.0</h2>
<h2>What's Changed</h2>
<ul>
<li>Document that draft status changes are not reflected by <a href="https://github.com/willthames"><code>@​willthames</code></a> in <a href="https://github-redirect.dependabot.com/peter-evans/create-pull-request/pull/1064">peter-evans/create-pull-request#1064</a></li>
<li>fix: remove unused draft param from pull update by <a href="https://github.com/peter-evans"><code>@​peter-evans</code></a> in <a href="https://github-redirect.dependabot.com/peter-evans/create-pull-request/pull/1065">peter-evans/create-pull-request#1065</a></li>
<li>Update action runtime to node 16 by <a href="https://github.com/sibiraj-s"><code>@​sibiraj-s</code></a> in <a href="https://github-redirect.dependabot.com/peter-evans/create-pull-request/pull/1074">peter-evans/create-pull-request#1074</a></li>
</ul>
<h2>New Contributors</h2>
<ul>
<li><a href="https://github.com/willthames"><code>@​willthames</code></a> made their first contribution in <a href="https://github-redirect.dependabot.com/peter-evans/create-pull-request/pull/1064">peter-evans/create-pull-request#1064</a></li>
<li><a href="https://github.com/sibiraj-s"><code>@​sibiraj-s</code></a> made their first contribution in <a href="https://github-redirect.dependabot.com/peter-evans/create-pull-request/pull/1074">peter-evans/create-pull-request#1074</a></li>
</ul>
<p><strong>Full Changelog</strong>: <a href="https://github.com/peter-evans/create-pull-request/compare/v3.12.1...v3.13.0">https://github.com/peter-evans/create-pull-request/compare/v3.12.1...v3.13.0</a></p>
<h2>Create Pull Request v3.12.1</h2>
<h2>What's Changed</h2>
<ul>
<li>ci: remove workflow by <a href="https://github.com/peter-evans"><code>@​peter-evans</code></a> in <a href="https://github-redirect.dependabot.com/peter-evans/create-pull-request/pull/1046">peter-evans/create-pull-request#1046</a></li>
<li>fix: add '--' to checkout command to avoid ambiguity by <a href="https://github.com/kenji-miyake"><code>@​kenji-miyake</code></a> in <a href="https://github-redirect.dependabot.com/peter-evans/create-pull-request/pull/1051">peter-evans/create-pull-request#1051</a></li>
</ul>
<h2>New Contributors</h2>
<ul>
<li><a href="https://github.com/kenji-miyake"><code>@​kenji-miyake</code></a> made their first contribution in <a href="https://github-redirect.dependabot.com/peter-evans/create-pull-request/pull/1051">peter-evans/create-pull-request#1051</a></li>
</ul>
<!-- raw HTML omitted -->
</blockquote>
<p>... (truncated)</p>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a href="923ad837f1"><code>923ad83</code></a> force tryFetch (<a href="https://github-redirect.dependabot.com/peter-evans/create-pull-request/issues/1189">#1189</a>)</li>
<li><a href="f094b77505"><code>f094b77</code></a> fix: avoid issue with case sensitivity of repo names (<a href="https://github-redirect.dependabot.com/peter-evans/create-pull-request/issues/1179">#1179</a>)</li>
<li><a href="af7c021bb9"><code>af7c021</code></a> docs: shorten quote</li>
<li><a href="97872c4843"><code>97872c4</code></a> docs: update GA quote/ref in concepts-guidelines.md (<a href="https://github-redirect.dependabot.com/peter-evans/create-pull-request/issues/1169">#1169</a>)</li>
<li><a href="bd72e1b792"><code>bd72e1b</code></a> fix: use full name for head branch to allow for repo renaming (<a href="https://github-redirect.dependabot.com/peter-evans/create-pull-request/issues/1164">#1164</a>)</li>
<li><a href="f1a7646cea"><code>f1a7646</code></a> build: update distribution (<a href="https://github-redirect.dependabot.com/peter-evans/create-pull-request/issues/1157">#1157</a>)</li>
<li><a href="15b68d176d"><code>15b68d1</code></a> fix: strip optional '.git' suffix from https server remote name. (<a href="https://github-redirect.dependabot.com/peter-evans/create-pull-request/issues/1153">#1153</a>)</li>
<li><a href="0dfc93c104"><code>0dfc93c</code></a> build(deps): bump peter-evans/create-pull-request from 3 to 4 (<a href="https://github-redirect.dependabot.com/peter-evans/create-pull-request/issues/1150">#1150</a>)</li>
<li><a href="252fb19db2"><code>252fb19</code></a> build(deps): bump peter-evans/slash-command-dispatch from 2 to 3 (<a href="https://github-redirect.dependabot.com/peter-evans/create-pull-request/issues/1122">#1122</a>)</li>
<li><a href="4b867c4939"><code>4b867c4</code></a> build(deps): bump actions/setup-node from 2 to 3 (<a href="https://github-redirect.dependabot.com/peter-evans/create-pull-request/issues/1123">#1123</a>)</li>
<li>Additional commits viewable in <a href="https://github.com/peter-evans/create-pull-request/compare/v3...v4">compare view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=peter-evans/create-pull-request&package-manager=github_actions&previous-version=3&new-version=4)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)

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

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

---

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

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


</details>
2022-07-04 13:04:13 +00:00
Nicola Papale
288765930f Rework extract_meshes (#4240)
* Cleanup redundant code
* Use a type alias to make sure the `caster_query` and
  `not_caster_query` really do the same thing and access the same things

**Objective**

Cleanup code that would otherwise be difficult to understand

**Solution**

* `extract_meshes` had two for loops which are functionally identical,
  just copy-pasted code. I extracted the common code between the two
  and put them into an anonymous function.
* I flattened the tuple literal for the bundle batch, it looks much
  less nested and the code is much more readable as a result.
* The parameters of `extract_meshes` were also very daunting, but they
  turned out to be the same query repeated twice. I extracted the query
  into a type alias.

EDIT: I reworked the PR to **not do anything breaking**, and keep the old allocation behavior. Removing the memorized length was clearly a performance loss, so I kept it.
2022-07-04 12:44:23 +00:00
Robert Swain
af48c10b3e Enable wgpu profiling spans when using bevy's trace feature (#5182)
# Objective

- Enable `wgpu` profiling spans

## Solution

- `wgpu` uses the `profiling` crate to add profiling span instrumentation to their code
- `profiling` offers multiple 'backends' for profiling, including `tracing`
- When the `bevy` `trace` feature is used, add the `profiling` crate with its `profile-with-tracing` feature to enable appropriate profiling spans in `wgpu` using `tracing` which fits nicely into our infrastructure
- Bump our default `tracing` subscriber filter to `wgpu=info` from `wgpu=error` so that the profiling spans are not filtered out as they are created at the `info` level.

---

## Changelog

- Added: `tracing` profiling support for `wgpu` when using bevy's `trace` feature
- Changed: The default `tracing` filter statement for `wgpu` has been changed from the `error` level to the `info` level to not filter out the wgpu profiling spans
2022-07-04 09:14:04 +00:00
Elabajaba
72e7358636 Disable Vsync for stress tests. (#5187)
# Objective

Currently stress tests are vsynced. This is undesirable for a stress test, as you want to run them with uncapped framerates.

## Solution

Ensure all stress tests are using PresentMode::Immediate if they render anything.
2022-07-03 20:17:27 +00:00
CGMossa
33f9b3940d Updated glam to 0.21. (#5142)
Removed `const_vec2`/`const_vec3`
and replaced with equivalent `.from_array`.

# Objective

Fixes #5112 

## Solution

- `encase` needs to update to `glam` as well. See teoxoy/encase#4 on progress on that. 
- `hexasphere` also needs to be updated, see OptimisticPeach/hexasphere#12.
2022-07-03 19:55:33 +00:00
Alice Cecile
8f721d8d0a Move get_short_name utility method from bevy_reflect into bevy_utils (#5174)
# Summary

This method strips a long type name like `bevy::render:📷:PerspectiveCameraBundle` down into the bare type name (`PerspectiveCameraBundle`). This is generally useful utility method, needed by #4299 and #5121.

As a result:

- This method was moved to `bevy_utils` for easier reuse.
- The legibility and robustness of this method has been significantly improved.
- Harder test cases have been added.

This change was split out of #4299 to unblock it and make merging / reviewing the rest of those changes easier.

## Changelog

- added `bevy_utils::get_short_name`, which strips the path from a type name for convenient display.
- removed the `TypeRegistry::get_short_name` method. Use the function in `bevy_utils` instead.
2022-07-02 18:30:45 +00:00
LoipesMas
de92054bbe Improve Command(s) docs (#4994)
# Objective

- Improve Command(s) docs
- Fixes #4737 

## Solution

- Update and improve documentation.

---
- "list" -> "queue" in `Commands` doc (this better represents reality)
- expand `Command` doc
- update/improve `Commands::add` doc, as specified in linked issue

Let me know if you want any changes!
2022-07-02 09:49:20 +00:00
Jerome Humbert
382cd49c3b Add documentation to VisibleEntities and related (#5100)
# Objective

Add missing docs

## Solution

Add documentation to the `VisibleEntities` component, its related
`check_visibility()` system, and that system's label.

See Discord discussion here : https://discord.com/channels/691052431525675048/866787577687310356/990432663921901678
2022-07-02 07:00:04 +00:00
Alice Cecile
4c5e30a9f8 Re-enable check-unused-dependencies in CI (#5172)
# Objective

Fixes #5155. This *should* work now that the semver breaking dependency of the CI crate got yanked, but we'll see what CI has to say about it.
2022-07-02 00:55:52 +00:00
Boxy
a1a07945d6 fix some memory leaks detected by miri (#4959)
The first leak:
```rust
    #[test]
    fn blob_vec_drop_empty_capacity() {
        let item_layout = Layout:🆕:<Foo>();
        let drop = drop_ptr::<Foo>;
        let _ = unsafe { BlobVec::new(item_layout, Some(drop), 0) };
    }
```
this is because we allocate the swap scratch in blobvec regardless of what the capacity is, but we only deallocate if capacity is > 0

The second leak:
```rust
    #[test]
    fn panic_while_overwriting_component() {
        let helper = DropTestHelper::new();

        let res = panic::catch_unwind(|| {
            let mut world = World::new();
            world
                .spawn()
                .insert(helper.make_component(true, 0))
                .insert(helper.make_component(false, 1));

            println!("Done inserting! Dropping world...");
        });

        let drop_log = helper.finish(res);

        assert_eq!(
            &*drop_log,
            [
                DropLogItem::Create(0),
                DropLogItem::Create(1),
                DropLogItem::Drop(0),
            ]
        );
    }
```
this is caused by us not running the drop impl on the to-be-inserted component if the drop impl of the overwritten component panics

---

managed to figure out where the leaks were by using this 10/10 command
```
cargo --quiet test --lib -- --list | sed 's/: test$//' | MIRIFLAGS="-Zmiri-disable-isolation" xargs -n1 cargo miri test --lib -- --exact
```
which runs every test one by one rather than all at once which let miri actually tell me which test had the leak 🙃
2022-07-01 21:54:28 +00:00
SarthakSingh31
cdbabb7053 Removed world cell from places where split multable access is not needed (#5167)
Fixes #5109.
2022-07-01 17:03:32 +00:00
Jakob Hellermann
49ff42cc69 fix new clippy lints (#5160)
# Objective

- Nightly clippy lints should be fixed before they get stable and break CI
  
## Solution

- fix new clippy lints
- ignore `significant_drop_in_scrutinee` since it isn't relevant in our loop https://github.com/rust-lang/rust-clippy/issues/8987
```rust
for line in io::stdin().lines() {
    ...
}
```

Co-authored-by: Jakob Hellermann <hellermann@sipgate.de>
2022-07-01 13:41:23 +00:00
François
8ba6be187d unpin nightly and disable weak memory emulation (#4988)
# Objective

- Follow suggestion from https://github.com/bevyengine/bevy/pull/4984#issuecomment-1152949640

## Solution

- Unpin nightly, disable weak memory emulation

---

This failed the miri job in my branch with the following error:
```
error: Undefined Behavior: attempting a read access using <untagged> at alloc198028[0x0], but that tag does not exist in the borrow stack for this location
   --> /home/runner/.cargo/registry/src/github.com-1ecc6299db9ec823/once_cell-1.12.0/src/imp_std.rs:177:28
    |
177 |                 let next = (*waiter).next;
    |                            ^^^^^^^^^^^^^^
    |                            |
    |                            attempting a read access using <untagged> at alloc198028[0x0], but that tag does not exist in the borrow stack for this location
    |                            this error occurs as part of an access at alloc198028[0x0..0x8]
    |
    = help: this indicates a potential bug in the program: it performed an invalid operation, but the rules it violated are still experimental
    = help: see https://github.com/rust-lang/unsafe-code-guidelines/blob/master/wip/stacked-borrows.md for further information
```

@BoxyUwU could you take a look? I guess it's related to the issue mentioned in https://github.com/rust-lang/miri/issues/2223
2022-07-01 13:19:39 +00:00
ira
ea13f0bddf Add helper methods for rotating Transforms (#5151)
# Objective
Users often ask for help with rotations as they struggle with `Quat`s.
`Quat` is rather complex and has a ton of verbose methods.

## Solution
Add rotation helper methods to `Transform`.


Co-authored-by: devil-ira <justthecooldude@gmail.com>
2022-07-01 03:58:54 +00:00
Rob Parrett
5e1756954f Derive default for enums where possible (#5158)
# Objective

Fixes #5153

## Solution

Search for all enums and manually check if they have default impls that can use this new derive.

By my reckoning:

| enum | num |
|-|-|
| total | 159 |
| has default impl | 29 |
| default is unit variant | 23 |
2022-07-01 03:42:15 +00:00
Carter Anderson
747b0c69b0 Better Materials: AsBindGroup trait and derive, simpler Material trait (#5053)
# Objective

This PR reworks Bevy's Material system, making the user experience of defining Materials _much_ nicer. Bevy's previous material system leaves a lot to be desired:
* Materials require manually implementing the `RenderAsset` trait, which involves manually generating the bind group, handling gpu buffer data transfer, looking up image textures, etc. Even the simplest single-texture material involves writing ~80 unnecessary lines of code. This was never the long term plan.
* There are two material traits, which is confusing, hard to document, and often redundant: `Material` and `SpecializedMaterial`. `Material` implicitly implements `SpecializedMaterial`, and `SpecializedMaterial` is used in most high level apis to support both use cases. Most users shouldn't need to think about specialization at all (I consider it a "power-user tool"), so the fact that `SpecializedMaterial` is front-and-center in our apis is a miss.
* Implementing either material trait involves a lot of "type soup". The "prepared asset" parameter is particularly heinous: `&<Self as RenderAsset>::PreparedAsset`. Defining vertex and fragment shaders is also more verbose than it needs to be. 

## Solution

Say hello to the new `Material` system:

```rust
#[derive(AsBindGroup, TypeUuid, Debug, Clone)]
#[uuid = "f690fdae-d598-45ab-8225-97e2a3f056e0"]
pub struct CoolMaterial {
    #[uniform(0)]
    color: Color,
    #[texture(1)]
    #[sampler(2)]
    color_texture: Handle<Image>,
}
impl Material for CoolMaterial {
    fn fragment_shader() -> ShaderRef {
        "cool_material.wgsl".into()
    }
}
```

Thats it! This same material would have required [~80 lines of complicated "type heavy" code](https://github.com/bevyengine/bevy/blob/v0.7.0/examples/shader/shader_material.rs) in the old Material system. Now it is just 14 lines of simple, readable code.

This is thanks to a new consolidated `Material` trait and the new `AsBindGroup` trait / derive.

### The new `Material` trait

The old "split" `Material` and `SpecializedMaterial` traits have been removed in favor of a new consolidated `Material` trait. All of the functions on the trait are optional.

The difficulty of implementing `Material` has been reduced by simplifying dataflow and removing type complexity:

```rust
// Old
impl Material for CustomMaterial {
    fn fragment_shader(asset_server: &AssetServer) -> Option<Handle<Shader>> {
        Some(asset_server.load("custom_material.wgsl"))
    }

    fn alpha_mode(render_asset: &<Self as RenderAsset>::PreparedAsset) -> AlphaMode {
        render_asset.alpha_mode
    }
}

// New
impl Material for CustomMaterial {
    fn fragment_shader() -> ShaderRef {
        "custom_material.wgsl".into()
    }

    fn alpha_mode(&self) -> AlphaMode {
        self.alpha_mode
    }
}
```

Specialization is still supported, but it is hidden by default under the `specialize()` function (more on this later).

### The `AsBindGroup` trait / derive

The `Material` trait now requires the `AsBindGroup` derive. This can be implemented manually relatively easily, but deriving it will almost always be preferable. 

Field attributes like `uniform` and `texture` are used to define which fields should be bindings,
what their binding type is, and what index they should be bound at:

```rust
#[derive(AsBindGroup)]
struct CoolMaterial {
    #[uniform(0)]
    color: Color,
    #[texture(1)]
    #[sampler(2)]
    color_texture: Handle<Image>,
}
```

In WGSL shaders, the binding looks like this:

```wgsl
struct CoolMaterial {
    color: vec4<f32>;
};

[[group(1), binding(0)]]
var<uniform> material: CoolMaterial;
[[group(1), binding(1)]]
var color_texture: texture_2d<f32>;
[[group(1), binding(2)]]
var color_sampler: sampler;
```

Note that the "group" index is determined by the usage context. It is not defined in `AsBindGroup`. Bevy material bind groups are bound to group 1.

The following field-level attributes are supported:
* `uniform(BINDING_INDEX)`
    * The field will be converted to a shader-compatible type using the `ShaderType` trait, written to a `Buffer`, and bound as a uniform. It can also be derived for custom structs.
* `texture(BINDING_INDEX)`
    * This field's `Handle<Image>` will be used to look up the matching `Texture` gpu resource, which will be bound as a texture in shaders. The field will be assumed to implement `Into<Option<Handle<Image>>>`. In practice, most fields should be a `Handle<Image>` or `Option<Handle<Image>>`. If the value of an `Option<Handle<Image>>` is `None`, the new `FallbackImage` resource will be used instead. This attribute can be used in conjunction with a `sampler` binding attribute (with a different binding index).
* `sampler(BINDING_INDEX)`
    * Behaves exactly like the `texture` attribute, but sets the Image's sampler binding instead of the texture. 

Note that fields without field-level binding attributes will be ignored.
```rust
#[derive(AsBindGroup)]
struct CoolMaterial {
    #[uniform(0)]
    color: Color,
    this_field_is_ignored: String,
}
```

As mentioned above, `Option<Handle<Image>>` is also supported:
```rust
#[derive(AsBindGroup)]
struct CoolMaterial {
    #[uniform(0)]
    color: Color,
    #[texture(1)]
    #[sampler(2)]
    color_texture: Option<Handle<Image>>,
}
```
This is useful if you want a texture to be optional. When the value is `None`, the `FallbackImage` will be used for the binding instead, which defaults to "pure white".

Field uniforms with the same binding index will be combined into a single binding:
```rust
#[derive(AsBindGroup)]
struct CoolMaterial {
    #[uniform(0)]
    color: Color,
    #[uniform(0)]
    roughness: f32,
}
```

In WGSL shaders, the binding would look like this:
```wgsl
struct CoolMaterial {
    color: vec4<f32>;
    roughness: f32;
};

[[group(1), binding(0)]]
var<uniform> material: CoolMaterial;
```

Some less common scenarios will require "struct-level" attributes. These are the currently supported struct-level attributes:
* `uniform(BINDING_INDEX, ConvertedShaderType)`
    * Similar to the field-level `uniform` attribute, but instead the entire `AsBindGroup` value is converted to `ConvertedShaderType`, which must implement `ShaderType`. This is useful if more complicated conversion logic is required.
* `bind_group_data(DataType)`
    * The `AsBindGroup` type will be converted to some `DataType` using `Into<DataType>` and stored as `AsBindGroup::Data` as part of the `AsBindGroup::as_bind_group` call. This is useful if data needs to be stored alongside the generated bind group, such as a unique identifier for a material's bind group. The most common use case for this attribute is "shader pipeline specialization".

The previous `CoolMaterial` example illustrating "combining multiple field-level uniform attributes with the same binding index" can
also be equivalently represented with a single struct-level uniform attribute:
```rust
#[derive(AsBindGroup)]
#[uniform(0, CoolMaterialUniform)]
struct CoolMaterial {
    color: Color,
    roughness: f32,
}

#[derive(ShaderType)]
struct CoolMaterialUniform {
    color: Color,
    roughness: f32,
}

impl From<&CoolMaterial> for CoolMaterialUniform {
    fn from(material: &CoolMaterial) -> CoolMaterialUniform {
        CoolMaterialUniform {
            color: material.color,
            roughness: material.roughness,
        }
    }
}
```

### Material Specialization

Material shader specialization is now _much_ simpler:

```rust
#[derive(AsBindGroup, TypeUuid, Debug, Clone)]
#[uuid = "f690fdae-d598-45ab-8225-97e2a3f056e0"]
#[bind_group_data(CoolMaterialKey)]
struct CoolMaterial {
    #[uniform(0)]
    color: Color,
    is_red: bool,
}

#[derive(Copy, Clone, Hash, Eq, PartialEq)]
struct CoolMaterialKey {
    is_red: bool,
}

impl From<&CoolMaterial> for CoolMaterialKey {
    fn from(material: &CoolMaterial) -> CoolMaterialKey {
        CoolMaterialKey {
            is_red: material.is_red,
        }
    }
}

impl Material for CoolMaterial {
    fn fragment_shader() -> ShaderRef {
        "cool_material.wgsl".into()
    }

    fn specialize(
        pipeline: &MaterialPipeline<Self>,
        descriptor: &mut RenderPipelineDescriptor,
        layout: &MeshVertexBufferLayout,
        key: MaterialPipelineKey<Self>,
    ) -> Result<(), SpecializedMeshPipelineError> {
        if key.bind_group_data.is_red {
            let fragment = descriptor.fragment.as_mut().unwrap();
            fragment.shader_defs.push("IS_RED".to_string());
        }
        Ok(())
    }
}
```

Setting `bind_group_data` is not required for specialization (it defaults to `()`). Scenarios like "custom vertex attributes" also benefit from this system:
```rust
impl Material for CustomMaterial {
    fn vertex_shader() -> ShaderRef {
        "custom_material.wgsl".into()
    }

    fn fragment_shader() -> ShaderRef {
        "custom_material.wgsl".into()
    }

    fn specialize(
        pipeline: &MaterialPipeline<Self>,
        descriptor: &mut RenderPipelineDescriptor,
        layout: &MeshVertexBufferLayout,
        key: MaterialPipelineKey<Self>,
    ) -> Result<(), SpecializedMeshPipelineError> {
        let vertex_layout = layout.get_layout(&[
            Mesh::ATTRIBUTE_POSITION.at_shader_location(0),
            ATTRIBUTE_BLEND_COLOR.at_shader_location(1),
        ])?;
        descriptor.vertex.buffers = vec![vertex_layout];
        Ok(())
    }
}
```

### Ported `StandardMaterial` to the new `Material` system

Bevy's built-in PBR material uses the new Material system (including the AsBindGroup derive):

```rust
#[derive(AsBindGroup, Debug, Clone, TypeUuid)]
#[uuid = "7494888b-c082-457b-aacf-517228cc0c22"]
#[bind_group_data(StandardMaterialKey)]
#[uniform(0, StandardMaterialUniform)]
pub struct StandardMaterial {
    pub base_color: Color,
    #[texture(1)]
    #[sampler(2)]
    pub base_color_texture: Option<Handle<Image>>,
    /* other fields omitted for brevity */
```

### Ported Bevy examples to the new `Material` system

The overall complexity of Bevy's "custom shader examples" has gone down significantly. Take a look at the diffs if you want a dopamine spike.

Please note that while this PR has a net increase in "lines of code", most of those extra lines come from added documentation. There is a significant reduction
in the overall complexity of the code (even accounting for the new derive logic).

---

## Changelog

### Added

* `AsBindGroup` trait and derive, which make it much easier to transfer data to the gpu and generate bind groups for a given type.

### Changed

* The old `Material` and `SpecializedMaterial` traits have been replaced by a consolidated (much simpler) `Material` trait. Materials no longer implement `RenderAsset`.
* `StandardMaterial` was ported to the new material system. There are no user-facing api changes to the `StandardMaterial` struct api, but it now implements `AsBindGroup` and `Material` instead of `RenderAsset` and `SpecializedMaterial`.

## Migration Guide
The Material system has been reworked to be much simpler. We've removed a lot of boilerplate with the new `AsBindGroup` derive and the `Material` trait is simpler as well!

### Bevy 0.7 (old)

```rust
#[derive(Debug, Clone, TypeUuid)]
#[uuid = "f690fdae-d598-45ab-8225-97e2a3f056e0"]
pub struct CustomMaterial {
    color: Color,
    color_texture: Handle<Image>,
}

#[derive(Clone)]
pub struct GpuCustomMaterial {
    _buffer: Buffer,
    bind_group: BindGroup,
}

impl RenderAsset for CustomMaterial {
    type ExtractedAsset = CustomMaterial;
    type PreparedAsset = GpuCustomMaterial;
    type Param = (SRes<RenderDevice>, SRes<MaterialPipeline<Self>>);
    fn extract_asset(&self) -> Self::ExtractedAsset {
        self.clone()
    }

    fn prepare_asset(
        extracted_asset: Self::ExtractedAsset,
        (render_device, material_pipeline): &mut SystemParamItem<Self::Param>,
    ) -> Result<Self::PreparedAsset, PrepareAssetError<Self::ExtractedAsset>> {
        let color = Vec4::from_slice(&extracted_asset.color.as_linear_rgba_f32());

        let byte_buffer = [0u8; Vec4::SIZE.get() as usize];
        let mut buffer = encase::UniformBuffer::new(byte_buffer);
        buffer.write(&color).unwrap();

        let buffer = render_device.create_buffer_with_data(&BufferInitDescriptor {
            contents: buffer.as_ref(),
            label: None,
            usage: BufferUsages::UNIFORM | BufferUsages::COPY_DST,
        });

        let (texture_view, texture_sampler) = if let Some(result) = material_pipeline
            .mesh_pipeline
            .get_image_texture(gpu_images, &Some(extracted_asset.color_texture.clone()))
        {
            result
        } else {
            return Err(PrepareAssetError::RetryNextUpdate(extracted_asset));
        };
        let bind_group = render_device.create_bind_group(&BindGroupDescriptor {
            entries: &[
                BindGroupEntry {
                    binding: 0,
                    resource: buffer.as_entire_binding(),
                },
                BindGroupEntry {
                    binding: 0,
                    resource: BindingResource::TextureView(texture_view),
                },
                BindGroupEntry {
                    binding: 1,
                    resource: BindingResource::Sampler(texture_sampler),
                },
            ],
            label: None,
            layout: &material_pipeline.material_layout,
        });

        Ok(GpuCustomMaterial {
            _buffer: buffer,
            bind_group,
        })
    }
}

impl Material for CustomMaterial {
    fn fragment_shader(asset_server: &AssetServer) -> Option<Handle<Shader>> {
        Some(asset_server.load("custom_material.wgsl"))
    }

    fn bind_group(render_asset: &<Self as RenderAsset>::PreparedAsset) -> &BindGroup {
        &render_asset.bind_group
    }

    fn bind_group_layout(render_device: &RenderDevice) -> BindGroupLayout {
        render_device.create_bind_group_layout(&BindGroupLayoutDescriptor {
            entries: &[
                BindGroupLayoutEntry {
                    binding: 0,
                    visibility: ShaderStages::FRAGMENT,
                    ty: BindingType::Buffer {
                        ty: BufferBindingType::Uniform,
                        has_dynamic_offset: false,
                        min_binding_size: Some(Vec4::min_size()),
                    },
                    count: None,
                },
                BindGroupLayoutEntry {
                    binding: 1,
                    visibility: ShaderStages::FRAGMENT,
                    ty: BindingType::Texture {
                        multisampled: false,
                        sample_type: TextureSampleType::Float { filterable: true },
                        view_dimension: TextureViewDimension::D2Array,
                    },
                    count: None,
                },
                BindGroupLayoutEntry {
                    binding: 2,
                    visibility: ShaderStages::FRAGMENT,
                    ty: BindingType::Sampler(SamplerBindingType::Filtering),
                    count: None,
                },
            ],
            label: None,
        })
    }
}
```

### Bevy 0.8 (new)

```rust
impl Material for CustomMaterial {
    fn fragment_shader() -> ShaderRef {
        "custom_material.wgsl".into()
    }
}

#[derive(AsBindGroup, TypeUuid, Debug, Clone)]
#[uuid = "f690fdae-d598-45ab-8225-97e2a3f056e0"]
pub struct CustomMaterial {
    #[uniform(0)]
    color: Color,
    #[texture(1)]
    #[sampler(2)]
    color_texture: Handle<Image>,
}
```

## Future Work

* Add support for more binding types (cubemaps, buffers, etc). This PR intentionally includes a bare minimum number of binding types to keep "reviewability" in check.
* Consider optionally eliding binding indices using binding names. `AsBindGroup` could pass in (optional?) reflection info as a "hint".
    * This would make it possible for the derive to do this:
        ```rust
        #[derive(AsBindGroup)]
        pub struct CustomMaterial {
            #[uniform]
            color: Color,
            #[texture]
            #[sampler]
            color_texture: Option<Handle<Image>>,
            alpha_mode: AlphaMode,
        }
        ```
    * Or this
        ```rust
        #[derive(AsBindGroup)]
        pub struct CustomMaterial {
            #[binding]
            color: Color,
            #[binding]
            color_texture: Option<Handle<Image>>,
            alpha_mode: AlphaMode,
        }
        ```
    * Or even this (if we flip to "include bindings by default")
        ```rust
        #[derive(AsBindGroup)]
        pub struct CustomMaterial {
            color: Color,
            color_texture: Option<Handle<Image>>,
            #[binding(ignore)]
            alpha_mode: AlphaMode,
        }
        ```
* If we add the option to define custom draw functions for materials (which could be done in a type-erased way), I think that would be enough to support extra non-material bindings. Worth considering!
2022-06-30 23:48:46 +00:00
François
d4e4a92982 android - fix issues other than the rendering (#5130)
# Objective

- Make Bevy work on android

## Solution

- Update android metadata and add a few more
- Set the target sdk to 31 as it will soon (in august) be the minimum sdk level for play store
- Remove the custom code to create an activity and use ndk-glue macro instead
- Delay window creation event on android
- Set the example with compatibility settings for wgpu. Those are needed for Bevy to work on my 2019 android tablet
- Add a few details on how to debug in case of failures
- Fix running the example on emulator. This was failing because of the name of the example

Bevy still doesn't work on android with this, audio features need to be disabled because of an ndk-glue version mismatch: rodio depends on 0.6.2, winit on 0.5.2. You can test with:
```
cargo apk run --release --example android_example --no-default-features --features "bevy_winit,render"
```
2022-06-30 19:42:45 +00:00