Commit graph

1277 commits

Author SHA1 Message Date
Minghao Liu
73fd6a6f6f fix: as_rgba_linear used wrong variant (#3192)
# Objective

as_rgba_linear used wrong variant

## Solution

Fixed it.
2021-11-26 12:57:05 +00:00
Carter Anderson
8009af3879 Merge New Renderer 2021-11-22 23:57:42 -08:00
Carter Anderson
2e79951659 Shader Imports. Decouple Mesh logic from PBR (#3137)
## Shader Imports

This adds "whole file" shader imports. These come in two flavors:

### Asset Path Imports

```rust
// /assets/shaders/custom.wgsl

#import "shaders/custom_material.wgsl"

[[stage(fragment)]]
fn fragment() -> [[location(0)]] vec4<f32> {
    return get_color();
}
```

```rust
// /assets/shaders/custom_material.wgsl

[[block]]
struct CustomMaterial {
    color: vec4<f32>;
};
[[group(1), binding(0)]]
var<uniform> material: CustomMaterial;
```

### Custom Path Imports

Enables defining custom import paths. These are intended to be used by crates to export shader functionality:

```rust
// bevy_pbr2/src/render/pbr.wgsl

#import bevy_pbr::mesh_view_bind_group
#import bevy_pbr::mesh_bind_group

[[block]]
struct StandardMaterial {
    base_color: vec4<f32>;
    emissive: vec4<f32>;
    perceptual_roughness: f32;
    metallic: f32;
    reflectance: f32;
    flags: u32;
};

/* rest of PBR fragment shader here */
```

```rust
impl Plugin for MeshRenderPlugin {
    fn build(&self, app: &mut bevy_app::App) {
        let mut shaders = app.world.get_resource_mut::<Assets<Shader>>().unwrap();
        shaders.set_untracked(
            MESH_BIND_GROUP_HANDLE,
            Shader::from_wgsl(include_str!("mesh_bind_group.wgsl"))
                .with_import_path("bevy_pbr::mesh_bind_group"),
        );
        shaders.set_untracked(
            MESH_VIEW_BIND_GROUP_HANDLE,
            Shader::from_wgsl(include_str!("mesh_view_bind_group.wgsl"))
                .with_import_path("bevy_pbr::mesh_view_bind_group"),
        );
```

By convention these should use rust-style module paths that start with the crate name. Ultimately we might enforce this convention.

Note that this feature implements _run time_ import resolution. Ultimately we should move the import logic into an asset preprocessor once Bevy gets support for that.

## Decouple Mesh Logic from PBR Logic via MeshRenderPlugin

This breaks out mesh rendering code from PBR material code, which improves the legibility of the code, decouples mesh logic from PBR logic, and opens the door for a future `MaterialPlugin<T: Material>` that handles all of the pipeline setup for arbitrary shader materials.

## Removed `RenderAsset<Shader>` in favor of extracting shaders into RenderPipelineCache

This simplifies the shader import implementation and removes the need to pass around `RenderAssets<Shader>`.

##  RenderCommands are now fallible

This allows us to cleanly handle pipelines+shaders not being ready yet. We can abort a render command early in these cases, preventing bevy from trying to bind group / do draw calls for pipelines that couldn't be bound. This could also be used in the future for things like "components not existing on entities yet". 

# Next Steps

* Investigate using Naga for "partial typed imports" (ex: `#import bevy_pbr::material::StandardMaterial`, which would import only the StandardMaterial struct)
* Implement `MaterialPlugin<T: Material>` for low-boilerplate custom material shaders
* Move shader import logic into the asset preprocessor once bevy gets support for that.

Fixes #3132
2021-11-18 03:45:02 +00:00
dataphract
1076a8f2b5 Document the new pipelined renderer (#3094)
This is a squash-and-rebase of @Ku95's documentation of the new renderer onto the latest `pipelined-rendering` branch.

Original PR is #2884.

Co-authored-by: dataphract <dataphract@gmail.com>
Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2021-11-16 03:37:48 +00:00
Niklas Eicker
94db0176fe Add readme to errors crate and clean up cargo files (#3125)
# Objective

- Document that the error codes will be rendered on the bevy website (see bevyengine/bevy-website#216)
- Some Cargo.toml files did not include the license or a description field

## Solution

- Readme for the errors crate
- Mark internal/development crates with `publish = false`
- Add missing license/descriptions to some crates

- [x] merge bevyengine/bevy-website#216
2021-11-13 23:06:48 +00:00
Niklas Eicker
d0f423d653 Assert compiler errors for compile_fail tests (#3067)
# Objective

bevy_ecs has several compile_fail tests that assert lifetime safety. In the past, these tests have been green for the wrong reasons (see e.g. #2984). This PR makes sure, that they will fail if the compiler error changes.

## Solution

Use [trybuild](https://crates.io/crates/trybuild) to assert the compiler errors.

The UI tests are in a separate crate that is not part of the Bevy workspace. This is to ensure that they do not break Bevy's crater builds. The tests get executed by the CI workflow on the stable toolchain.
2021-11-13 22:43:19 +00:00
Jerome Humbert
94f5d194f4 Doc AssetServer::load() is async (#3129)
# Objective

Document that `AssetServer::load()` is asynchronous.

## Solution

Document that `AssetServer::load()` is asynchronous, and that the asset
will not be immediately available once the call returns. Instead,
explain that the user must call `AssetServer::get_load_state()` to
monitor the loading state of an asset.
2021-11-13 22:07:19 +00:00
François
ac06ea3d17 default features from bevy_asset and bevy_ecs can actually be disabled (#3097)
# Objective

- `bevy_ecs` exposes as an optional feature `bevy_reflect`. Disabling it doesn't compile.
- `bevy_asset` exposes as an optional feature `filesystem_watcher`. Disabling it doesn't compile. It is also not possible to disable this feature from Bevy

## Solution

- Fix compilation errors when disabling the default features. Make it possible to disable the feature `filesystem_watcher` from Bevy
2021-11-13 21:15:22 +00:00
MiniaczQ
8b30dc6354 iter_mut() for Assets type (#3118)
# Objective

Fixes #3117 

## Solution

I took `get_mut()` and did it for all the elements 😏 


Co-authored-by: MiniaczQ <jakub.motyka.2000@gmail.com>
2021-11-13 04:26:42 +00:00
François
5127274b31 Update tracing-subscriber requirement from 0.2.22 to 0.3.1 (#3076)
# Objective

- Fix #3058 opened by dependabot

## Solution

- A new feature need to be added to `tracing-subscriber`
2021-11-12 03:08:27 +00:00
François
290b7dd9ab Update vendored Crevice to 0.8.0 + PR for arrays (#3059)
# Objective

- Update vendor crevice to have the latest update from crevice 0.8.0
- Using https://github.com/ElectronicRU/crevice/tree/arrays which has the changes to make arrays work

## Solution

- Also updated glam and hexasphere to only have one version of glam
- From the original PR, using crevice to write GLSL code containing arrays would probably not work but it's not something used by Bevy
2021-11-12 01:39:25 +00:00
Jay Oster
76cb662be1 Fix MIME type support for glTF buffer Data URIs (#3101)
# Objective

- The glTF 2.0 spec requires that Data URIs use one of two valid MIME types. `bevy_gltf` only supports one of these.
- See:
  - https://www.khronos.org/registry/glTF/specs/2.0/glTF-2.0.html#_media_type_registrations
  - https://www.khronos.org/registry/glTF/specs/2.0/glTF-2.0.html#file-extensions-and-media-types
  - https://www.khronos.org/registry/glTF/specs/2.0/glTF-2.0.html#binary-data-storage

> Buffer data **MAY** alternatively be embedded in the glTF file via `data:` URI with base64 encoding. When `data:` URI is used for buffer storage, its mediatype field **MUST** be set to `application/octet-stream` or `application/gltf-buffer`.

(Emphasis in original.)

## Solution

- Check for both MIME types.
2021-11-11 01:58:57 +00:00
Jerome Humbert
0db1f4cd16 Clarify RUST_LOG override over LogSettings (#3095)
# Objective

Clarify the fact that setting the `RUST_LOG` environment variable
overrides any setting from the `LogSettings` resource.

## Solution

Update docstring comment for `LogSettings`.
2021-11-11 01:43:51 +00:00
Ixentus
36394adb2f Remove wasm audio feature flag for 2021 (#3000)
- Requires #2997 
- Removes `wasm_audio` feature as discussed in #2397
- Closes only task in #2479 

Open questions:
Should we enable wasm audio by default or only when building for wasm using `cfg`?
Maybe there should be a global wasm feature for bevy?
2021-11-11 01:17:38 +00:00
François
12e0b80cd0 fix tracing-subscriber to =0.2.24 (#3102)
temporary fix until rest of ecosystem is updated
2021-11-10 22:56:14 +00:00
François
db35ffbece fix tracing dependencies to before 0.3 update (#3103)
same as #3102 on branch pipelined-rendering
2021-11-10 22:17:54 +00:00
dataphract
f4cfcc0e44 explain absence of new constructor in Hash{Map, Set} docs; suggest default (#3077)
# Objective

Fixes #2823.

## Solution

This PR adds notes to the `HashMap` and `HashSet` docs explaining why `HashMap::new()` (resp. `HashSet::new()`) is not available, and guiding the user toward using the `Default` implementation for an empty collection.
2021-11-06 20:53:12 +00:00
François
b3cd48228b add detailed errors (#2994)
# Objective

- Improve error descriptions and help understand how to fix them
- I noticed one today that could be expanded, it seemed like a good starting point

## Solution

- Start something like https://github.com/rust-lang/rust/tree/master/compiler/rustc_error_codes/src/error_codes
- Remove sentence about Rust mutability rules which is not very helpful in the error message

I decided to start the error code with B for Bevy so that they're not confused with error code from rust (which starts with E)


Longer term, there are a few more evolutions that can continue this:
- the code samples should be compiled check, and even executed for some of them to check they have the correct error code in a panic
- the error could be build on a page in the website like https://doc.rust-lang.org/error-index.html
- most panic should have their own error code
2021-11-06 20:53:11 +00:00
Jerome Humbert
a5c675f336 Add docstring comment to Style to reference CSS (#2936)
Mention the fact that the UI layout system is based on the CSS layout
model through a docstring comment on the `Style` type.

# Objective

Explain to new users that the Bevy UI uses the CSS layout model, to lower the barrier to entry given the fact documentation (book and code) is fairly limited on the topic.

## Solution

Fix as discussed with @alice-i-cecile on #2918.
2021-11-06 20:53:10 +00:00
Minghao Liu
aac09353fd add position to WindowDescriptor (#3070)
# Objective

Set initial position of the window, so I can start it at the left side of the view automatically, used with `cargo watch`

## Solution

add window position to WindowDescriptor
2021-11-06 20:34:31 +00:00
Carter Anderson
fde5d2fe46 Add System Command apply and RenderGraph node spans (#3069)
This fills in most of the gaps in tracing visualizations and should help with discovering bottlenecks.
2021-11-06 20:15:36 +00:00
Marc Parenteau
225d6a138f remove Box from ExclusiveSystemFn (#3063)
Minor refactor to remove the boxing of the function pointer stored in ExclusiveSystemFn.
2021-11-04 20:55:28 +00:00
Mariusz Kryński
7d932ac1d8 WebGL2 support (#3039)
# Objective

Make possible to use wgpu gles backend on in the browser (wasm32 + WebGL2). 

## Solution

It is built on top of old @cart patch initializing windows before wgpu. Also:
- initializes wgpu with `Backends::GL` and proper `wgpu::Limits` on wasm32
- changes default texture format to `wgpu::TextureFormat::Rgba8UnormSrgb`



Co-authored-by: Mariusz Kryński <mrk@sed.pl>
2021-10-29 00:46:18 +00:00
François
a2ea9279b2 use correct size of pixel instead of 4 (#2977)
# Objective

- Fixes #2919 
- Initial pixel was hard coded and not dependent on texture format
- Replace #2920 as I noticed this needed to be done also on pipeline rendering branch

## Solution

- Replace the hard coded pixel with one using the texture pixel size
2021-10-28 23:10:45 +00:00
Iaiao
91c3b210a2 Update derive(DynamicPlugin) to edition 2021 (#3038)
# Objective
Edition 2021 requires `dyn Trait` and it won't compile without `dyn`.

## Solution
Added `dyn`.
2021-10-27 19:48:12 +00:00
Yoh Deadfall
ffde86efa0 Update to edition 2021 on master (#3028)
Objective
During work on #3009 I've found that not all jobs use actions-rs, and therefore, an previous version of Rust is used for them. So while compilation and other stuff can pass, checking markup and Android build may fail with compilation errors.

Solution
This PR adds `action-rs` for any job running cargo, and updates the edition to 2021.
2021-10-27 00:12:14 +00:00
William Batista
9f47697e40 Switched the TODO comment in image_texture_conversion.rs (#2981)
# Objective

The current TODO comment is out of date

## Solution

I switched up the comment


Co-authored-by: William Batista <45850508+billyb2@users.noreply.github.com>
2021-10-25 21:59:24 +00:00
François
2f4bcc5bf7 Update for edition 2021 (#2997)
# Objective

- update for Edition 2021

## Solution

- remove the `resolver = "2"`
- update for https://doc.rust-lang.org/edition-guide/rust-2021/reserving-syntax.html by adding a few ` `
2021-10-25 18:00:13 +00:00
MinerSebas
6a8a8c9d21 Fix compile_fail tests (#2984)
# Objective

- Bevy has several `compile_fail` test
- #2254 added `#[derive(Component)]`
- Those tests now fail for a different reason.
- This was not caught as these test still "successfully" failed to compile.

## Solution

- Add `#[derive(Component)]` to the doctest
- Also changed their cfg attribute from `doc` to `doctest`, so that these tests don't appear when running `cargo doc` with `--document-private-items`
2021-10-18 20:39:51 +00:00
François
d65fbd7b9d Fix scale factor for cursor position (#2932)
# Objective

- Fixes #2501 
- Builds up on #2639 taking https://github.com/bevyengine/bevy/pull/2639#issuecomment-898701047 into account

## Solution

- keep the physical cursor position in `Window`, and expose it.
- still convert to logical position in event, and when getting `cursor_position`


Co-authored-by: Ahmed Charles <acharles@outlook.com>
2021-10-15 23:47:42 +00:00
davier
b13357e7b2 Fix CI for android (#2971)
# Objective

The update to wgpu 0.11 broke CI for android. This was due to a confusion between `bevy::render::ShaderStage` and `wgpu::ShaderStage`.


## Solution

Revert the incorrect change
2021-10-15 23:08:15 +00:00
Boxy
099386f184 Fix unsound lifetime annotation on Query::get_component (#2964)
#2605 changed the lifetime annotations on `get_component` introducing unsoundness as you could keep the returned borrow even after using the query.

Example unsoundness:
```rust
use bevy::prelude::*;

fn main() {
    App::new()
        .add_startup_system(startup)
        .add_system(unsound)
        .run();
}

#[derive(Debug, Component, PartialEq, Eq)]
struct Foo(Vec<u32>);

fn startup(mut c: Commands) {
    let e = c.spawn().insert(Foo(vec![10])).id();
    c.insert_resource(e);
}

fn unsound(mut q: Query<&mut Foo>, res: Res<Entity>) {
    let foo = q.get_component::<Foo>(*res).unwrap();
    let mut foo2 = q.iter_mut().next().unwrap();

    let first_elem = &foo.0[0];
    for _ in 0..16 {
        foo2.0.push(12);
    }
    dbg!(*first_elem);
}
```
output:
`[src/main.rs:26] *first_elem = 0`
2021-10-15 16:59:29 +00:00
Jerome Humbert
f4776f2ec4 Add entity ID to expect() message (#2943)
Add the entity ID and generation to the expect() message of two
world accessors, to make it easier to debug use-after-free issues.
Coupled with e.g. bevy-inspector-egui which also displays the entity ID,
this makes it much easier to identify what entity is being misused.

# Objective

Make it easier to identity an entity being accessed after being deleted.

## Solution

Augment the error message of some `expect()` call with the entity ID and
generation. Combined with some external tool like `bevy-inspector-egui`, which
also displays the entity ID, this increases the chances to be able to identify
the entity, and therefore find the error that led to a use-after-despawn.
2021-10-10 23:04:05 +00:00
terrarier2111
db013b664e Fix typo (#2944) 2021-10-10 22:42:01 +00:00
Carter Anderson
43e8a156fb Upgrade to wgpu 0.11 (#2933)
Upgrades both the old and new renderer to wgpu 0.11 (and naga 0.7). This builds on @zicklag's work here #2556.

Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2021-10-08 19:55:24 +00:00
Christopher Durham
997eae6185 Remove double Events::update in bevy-gilrs (#2894)
# Objective

- Remove duplicate `Events::update` call in `gilrs_event_system` (fixes #2893)
  - See #2893 for context
- While there, make the systems no longer exclusive, as that is not required of them

## Solution

- Do the change

r? @alice-i-cecile
2021-10-08 00:37:08 +00:00
TheRawMeatball
2974293682 Add ControlNode for UI (#2908)
This PR adds a ControlNode which marks an entity as "transparent" to the UI layout system, meaning the children of this entity will be treated as the children of this entity s parent by the layout system(s).
2021-10-06 19:00:36 +00:00
Christopher Durham
0887f41b58 Fix bevy_ecs::schedule::executor_parallel::system span management (#2905)
# Objective

- Fixes #2904 (see for context)

## Solution

- Simply hoist span creation out of the threaded task
- Confirmed to solve the issue locally

Now all events have the full span parent tree up through `bevy_ecs::schedule::stage` all the way to `bevy_app::app::bevy_app` (and its parents in bevy-consumer code, if any).
2021-10-06 19:00:35 +00:00
Christopher Durham
a60fe30ada Avoid some format! into immediate format! (#2913)
# Objective

- Avoid usages of `format!` that ~immediately get passed to another `format!`. This avoids a temporary allocation and is just generally cleaner.

## Solution

- `bevy_derive::shader_defs` does a `format!("{}", val.to_string())`, which is better written as just `format!("{}", val)`
- `bevy_diagnostic::log_diagnostics_plugin` does a `format!("{:>}", format!(...))`, which is better written as `format!("{:>}", format_args!(...))`
- `bevy_ecs::schedule` does `tracing::info!(..., name = &*format!("{:?}", val))`, which is better written with the tracing shorthand `tracing::info!(..., name = ?val)`
- `bevy_reflect::reflect` does `f.write_str(&format!(...))`, which is better written as `write!(f, ...)` (this could also be written using `f.debug_tuple`, but I opted to maintain alt debug behavior)
- `bevy_reflect::serde::{ser, de}` do `serde::Error::custom(format!(...))`, which is better written as `Error::custom(format_args!(...))`, as `Error::custom` takes `impl Display` and just immediately calls `format!` again
2021-10-06 18:34:33 +00:00
Paweł Grabarz
07ed1d053e Implement and require #[derive(Component)] on all component structs (#2254)
This implements the most minimal variant of #1843 - a derive for marker trait. This is a prerequisite to more complicated features like statically defined storage type or opt-out component reflection.

In order to make component struct's purpose explicit and avoid misuse, it must be annotated with `#[derive(Component)]` (manual impl is discouraged for compatibility). Right now this is just a marker trait, but in the future it might be expanded. Making this change early allows us to make further changes later without breaking backward compatibility for derive macro users.

This already prevents a lot of issues, like using bundles in `insert` calls. Primitive types are no longer valid components as well. This can be easily worked around by adding newtype wrappers and deriving `Component` for them.

One funny example of prevented bad code (from our own tests) is when an newtype struct or enum variant is used. Previously, it was possible to write `insert(Newtype)` instead of `insert(Newtype(value))`. That code compiled, because function pointers (in this case newtype struct constructor) implement `Send + Sync + 'static`, so we allowed them to be used as components. This is no longer the case and such invalid code will trigger a compile error.


Co-authored-by: = <=>
Co-authored-by: TheRawMeatball <therawmeatball@gmail.com>
Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2021-10-03 19:23:44 +00:00
Robert Swain
44ed7e32d8 bevy_render2: Add tracing spans around render subapp and stages (#2907)
Add tracing spans around the renderer subapp and render stages in bevy_render2 to allow profiling / visualisation of stages.
From:
<img width="1181" alt="Screenshot 2021-10-02 122336" src="https://user-images.githubusercontent.com/302146/135712361-8aec28ae-0f1e-4c27-9b6e-ca5e5f45d6b9.png">
To:
<img width="1229" alt="Screenshot 2021-10-02 122509" src="https://user-images.githubusercontent.com/302146/135712365-6414d424-4e15-4265-9952-483876da9f9a.png">
2021-10-02 19:16:32 +00:00
Daniel McNab
5ba2b9adcf Unique WorldId (#2827)
# Objective

Fixes these issues:
- `WorldId`s currently aren't necessarily unique
    - I want to guarantee that they're unique to safeguard my librarified version of https://github.com/bevyengine/bevy/discussions/2805
    - There probably hasn't been a collision yet, but they could technically collide
- `SystemId` isn't used for anything
  - It's no longer used now that `Locals` are stored within the `System`.
- `bevy_ecs` depends on rand

## Solution

- Instead of randomly generating `WorldId`s, just use an incrementing atomic counter, panicing on overflow.
- Remove `SystemId` 
    - We do need to allow Locals for exclusive systems at some point, but exclusive systems couldn't access their own `SystemId` anyway.
- Now that these don't depend on rand, move it to a dev-dependency

## Todo

Determine if `WorldId` should be `u32` based instead
2021-09-30 20:54:47 +00:00
Mike
99199338ad add_texture returns index to texture (#2864)
If you need to build a texture atlas from an already created texture that is not match a grid, you need to use new_empty and add_texture to create it.  However it is not straight forward to get the index to be used with TextureAtlasSprite. add_texture should be changed to return the index to the texture.

Currently you can do something like this:

```rs
let texture = asset_server.load::<Texture>::("texture.png");
let texture_atlas = TextureAtlas::new_empty(texture, Vec2::new(40.0, 40.0));

texture_atlas.add_texture(Rect { 
  min: Vec2::new(20.0, 20.0),
  max: Vec2::new(40.0, 40.0),
});
let index = (texture_atlas.len() - 1) as u32;

let texture_atlas_sprite = TextureAtlasSprite {
  index,
  Default::default()
};
```

But this is more clear
```rs
let index = texture_atlas.add_texture(Rect { 
  min: Vec2::new(20.0, 20.0),
  max: Vec2::new(40.0, 40.0),
});
```
2021-09-28 20:54:16 +00:00
TheRawMeatball
c207950172 Add despawn_recursive to EntityMut (#2855) 2021-09-28 20:35:11 +00:00
dependabot[bot]
10cbe05175 Update hexasphere requirement from 4.0.0 to 5.0.0 (#2880)
Updates the requirements on [hexasphere](https://github.com/OptimisticPeach/hexasphere) to permit the latest version.
<details>
<summary>Commits</summary>
<ul>
<li>See full diff in <a href="https://github.com/OptimisticPeach/hexasphere/commits">compare view</a></li>
</ul>
</details>
<br />


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>
2021-09-27 23:58:44 +00:00
François
fb0aa8d286 enable change detection for hierarchy maintenance (#2411)
# Objective

Noticed a comment saying changed detection should be enabled for hierarchy maintenance once stable

Fixes #891


## Solution

Added `Changed<Parent>` filter on the query
2021-09-27 23:32:05 +00:00
Will Dixon
d158e0893e Fix panic on is_resource_* calls (#2828) (#2863)
Changed out unwraps to use if let syntax instead. Returning false when None.

Also modified an existing test to encompass these methods

This PR fixes #2828
2021-09-24 20:42:58 +00:00
Carter Anderson
08969a24b8 Modular Rendering (#2831)
This changes how render logic is composed to make it much more modular. Previously, all extraction logic was centralized for a given "type" of rendered thing. For example, we extracted meshes into a vector of ExtractedMesh, which contained the mesh and material asset handles, the transform, etc. We looked up bindings for "drawn things" using their index in the `Vec<ExtractedMesh>`. This worked fine for built in rendering, but made it hard to reuse logic for "custom" rendering. It also prevented us from reusing things like "extracted transforms" across contexts.

To make rendering more modular, I made a number of changes:

* Entities now drive rendering:
  * We extract "render components" from "app components" and store them _on_ entities. No more centralized uber lists! We now have true "ECS-driven rendering"
  * To make this perform well, I implemented #2673 in upstream Bevy for fast batch insertions into specific entities. This was merged into the `pipelined-rendering` branch here: #2815
* Reworked the `Draw` abstraction:
  * Generic `PhaseItems`: each draw phase can define its own type of "rendered thing", which can define its own "sort key"
  * Ported the 2d, 3d, and shadow phases to the new PhaseItem impl (currently Transparent2d, Transparent3d, and Shadow PhaseItems)
  * `Draw` trait and and `DrawFunctions` are now generic on PhaseItem
  * Modular / Ergonomic `DrawFunctions` via `RenderCommands`
    * RenderCommand is a trait that runs an ECS query and produces one or more RenderPass calls. Types implementing this trait can be composed to create a final DrawFunction. For example the DrawPbr DrawFunction is created from the following DrawCommand tuple. Const generics are used to set specific bind group locations:
        ```rust
         pub type DrawPbr = (
            SetPbrPipeline,
            SetMeshViewBindGroup<0>,
            SetStandardMaterialBindGroup<1>,
            SetTransformBindGroup<2>,
            DrawMesh,
        );
        ```
    * The new `custom_shader_pipelined` example illustrates how the commands above can be reused to create a custom draw function:
       ```rust
       type DrawCustom = (
           SetCustomMaterialPipeline,
           SetMeshViewBindGroup<0>,
           SetTransformBindGroup<2>,
           DrawMesh,
       );
       ``` 
* ExtractComponentPlugin and UniformComponentPlugin:
  * Simple, standardized ways to easily extract individual components and write them to GPU buffers
* Ported PBR and Sprite rendering to the new primitives above.
* Removed staging buffer from UniformVec in favor of direct Queue usage
  * Makes UniformVec much easier to use and more ergonomic. Completely removes the need for custom render graph nodes in these contexts (see the PbrNode and view Node removals and the much simpler call patterns in the relevant Prepare systems).
* Added a many_cubes_pipelined example to benchmark baseline 3d rendering performance and ensure there were no major regressions during this port. Avoiding regressions was challenging given that the old approach of extracting into centralized vectors is basically the "optimal" approach. However thanks to a various ECS optimizations and render logic rephrasing, we pretty much break even on this benchmark!
* Lifetimeless SystemParams: this will be a bit divisive, but as we continue to embrace "trait driven systems" (ex: ExtractComponentPlugin, UniformComponentPlugin, DrawCommand), the ergonomics of `(Query<'static, 'static, (&'static A, &'static B, &'static)>, Res<'static, C>)` were getting very hard to bear. As a compromise, I added "static type aliases" for the relevant SystemParams. The previous example can now be expressed like this: `(SQuery<(Read<A>, Read<B>)>, SRes<C>)`. If anyone has better ideas / conflicting opinions, please let me know!
* RunSystem trait: a way to define Systems via a trait with a SystemParam associated type. This is used to implement the various plugins mentioned above. I also added SystemParamItem and QueryItem type aliases to make "trait stye" ecs interactions nicer on the eyes (and fingers).
* RenderAsset retrying: ensures that render assets are only created when they are "ready" and allows us to create bind groups directly inside render assets (which significantly simplified the StandardMaterial code). I think ultimately we should swap this out on "asset dependency" events to wait for dependencies to load, but this will require significant asset system changes.
* Updated some built in shaders to account for missing MeshUniform fields
2021-09-23 06:16:11 +00:00
Jakob Hellermann
b9e0241071 update cargo-manifest (#2859)
On older versions, people with `edition = 2021` would get this error:

![grafik](https://user-images.githubusercontent.com/22177966/134387678-28ece4d4-8af6-48de-beb8-973356c3b9f0.png)
2021-09-22 22:11:54 +00:00
TheRawMeatball
29d4faa077 Make events reuse buffers (#2850)
I'm really curious why this wasn't the case already...
2021-09-22 21:45:37 +00:00