Commit graph

712 commits

Author SHA1 Message Date
Nionidh
558530871d StorageBuffer uses wrong type to calculate the buffer size. (#4557)
# Objective
Fixes #4556

## Solution
StorageBuffer must use the Size of the std430 representation to calculate the buffer size, as the std430 representation is the data that will be written to it.
2022-05-05 02:12:16 +00:00
Dusty DeWeese
82d849d3dc Add support for vertex colors (#4528)
# Objective

Add support for vertex colors

## Solution

This change is modeled after how vertex tangents are handled, so the shader is conditionally compiled with vertex color support if the mesh has the corresponding attribute set.

Vertex colors are multiplied by the base color. I'm not sure if this is the best for all cases, but may be useful for modifying vertex colors without creating a new mesh.

I chose `VertexFormat::Float32x4`, but I'd prefer 16-bit floats if/when support is added.

## Changelog

### Added
- Vertex colors can be specified using the `Mesh::ATTRIBUTE_COLOR` mesh attribute.
2022-05-05 00:46:32 +00:00
Rob Parrett
f8e0fc190a Add RegularPolygon and Circle meshes (#3730)
# Objective

Bevy users often want to create circles and other simple shapes.

All the machinery is in place to accomplish this, and there are external crates that help. But when writing code for e.g. a new bevy example, it's not really possible to draw a circle without bringing in a new asset, writing a bunch of scary looking mesh code, or adding a dependency.

In particular, this PR was inspired by this interaction in another PR: https://github.com/bevyengine/bevy/pull/3721#issuecomment-1016774535

## Solution

This PR adds `shape::RegularPolygon` and `shape::Circle` (which is just a `RegularPolygon` that defaults to a large number of sides)

## Discussion

There's a lot of ongoing discussion about shapes in <https://github.com/bevyengine/rfcs/pull/12> and at least one other lingering shape PR (although it seems incomplete).

That RFC currently includes `RegularPolygon` and `Circle` shapes, so I don't think that having working mesh generation code in the engine for those shapes would add much burden to an author of an implementation.

But if we'd prefer not to add additional shapes until after that's sorted out, I'm happy to close this for now.

## Alternatives for users

For any users stumbling on this issue, here are some plugins that will help if you need more shapes.

https://github.com/Nilirad/bevy_prototype_lyon
https://github.com/johanhelsing/bevy_smud
https://github.com/Weasy666/bevy_svg
https://github.com/redpandamonium/bevy_more_shapes
https://github.com/ForesightMiningSoftwareCorporation/bevy_polyline
2022-05-05 00:03:47 +00:00
François
4a9932fa8e simplified API to get NDC from camera and world position (#4041)
# Objective

- After #3412, `Camera::world_to_screen` got a little bit uglier to use by needing to provide both `Windows` and `Assets<Image>`, even though only one would be needed b697e73c3d/crates/bevy_render/src/camera/camera.rs (L117-L123)
- Some time, exact coordinates are not needed but normalized device coordinates is enough

## Solution

- Add a function to just get NDC
2022-05-03 19:51:18 +00:00
Jakob Hellermann
2b6e67f4cb add #[reflect(Default)] to create default value for reflected types (#3733)
### Problem
It currently isn't possible to construct the default value of a reflected type. Because of that, it isn't possible to use `add_component` of `ReflectComponent` to add a new component to an entity because you can't know what the initial value should be.

### Solution

1. add `ReflectDefault` type
```rust
#[derive(Clone)]
pub struct ReflectDefault {
    default: fn() -> Box<dyn Reflect>,
}

impl ReflectDefault {
    pub fn default(&self) -> Box<dyn Reflect> {
        (self.default)()
    }
}

impl<T: Reflect + Default> FromType<T> for ReflectDefault {
    fn from_type() -> Self {
        ReflectDefault {
            default: || Box::new(T::default()),
        }
    }
}
```

2. add `#[reflect(Default)]` to all component types that implement `Default` and are user facing (so not `ComputedSize`, `CubemapVisibleEntities` etc.)



This makes it possible to add the default value of a component to an entity without any compile-time information:

```rust
fn main() {
    let mut app = App::new();
    app.register_type::<Camera>();

    let type_registry = app.world.get_resource::<TypeRegistry>().unwrap();
    let type_registry = type_registry.read();

    let camera_registration = type_registry.get(std::any::TypeId::of::<Camera>()).unwrap();
    let reflect_default = camera_registration.data::<ReflectDefault>().unwrap();
    let reflect_component = camera_registration
        .data::<ReflectComponent>()
        .unwrap()
        .clone();

    let default = reflect_default.default();

    drop(type_registry);

    let entity = app.world.spawn().id();
    reflect_component.add_component(&mut app.world, entity, &*default);

    let camera = app.world.entity(entity).get::<Camera>().unwrap();
    dbg!(&camera);
}
```

### Open questions
- should we have `ReflectDefault` or `ReflectFromWorld` or both?
2022-05-03 19:20:13 +00:00
Robert Swain
479f43bbf3 Filter material handles on extraction (#4178)
# Objective

- While optimising many_cubes, I noticed that all material handles are extracted regardless of whether the entity to which the handle belongs is visible or not. As such >100k handles are extracted when only <20k are visible.

## Solution

- Only extract material handles of visible entities.
- This improves `many_cubes -- sphere` from ~42fps to ~48fps. It reduces not only the extraction time but also system commands time. `Handle<StandardMaterial>` extraction and its system commands went from 0.522ms + 3.710ms respectively, to 0.267ms + 0.227ms an 88% reduction for this system for this case. It's very view dependent but...
2022-05-03 18:28:04 +00:00
TheRawMeatball
73c78c3667 Use lifetimed, type erased pointers in bevy_ecs (#3001)
# Objective

`bevy_ecs` has large amounts of unsafe code which is hard to get right and makes it difficult to audit for soundness.

## Solution

Introduce lifetimed, type-erased pointers: `Ptr<'a>` `PtrMut<'a>` `OwningPtr<'a>'` and `ThinSlicePtr<'a, T>` which are newtypes around a raw pointer with a lifetime and conceptually representing strong invariants about the pointee and validity of the pointer.

The process of converting bevy_ecs to use these has already caught multiple cases of unsound behavior.

## Changelog

TL;DR for release notes: `bevy_ecs` now uses lifetimed, type-erased pointers internally, significantly improving safety and legibility without sacrificing performance. This should have approximately no end user impact, unless you were meddling with the (unfortunately public) internals of `bevy_ecs`.

- `Fetch`, `FilterFetch` and `ReadOnlyFetch` trait no longer have a `'state` lifetime
    - this was unneeded
- `ReadOnly/Fetch` associated types on `WorldQuery` are now on a new `WorldQueryGats<'world>` trait
    - was required to work around lack of Generic Associated Types (we wish to express `type Fetch<'a>: Fetch<'a>`)
- `derive(WorldQuery)` no longer requires `'w` lifetime on struct
    - this was unneeded, and improves the end user experience
- `EntityMut::get_unchecked_mut` returns `&'_ mut T` not `&'w mut T`
    - allows easier use of unsafe API with less footguns, and can be worked around via lifetime transmutery as a user
- `Bundle::from_components` now takes a `ctx` parameter to pass to the `FnMut` closure
    - required because closure return types can't borrow from captures
- `Fetch::init` takes `&'world World`, `Fetch::set_archetype` takes `&'world Archetype` and `&'world Tables`, `Fetch::set_table` takes `&'world Table`
    - allows types implementing `Fetch` to store borrows into world
- `WorldQuery` trait now has a `shrink` fn to shorten the lifetime in `Fetch::<'a>::Item`
    - this works around lack of subtyping of assoc types, rust doesnt allow you to turn `<T as Fetch<'static>>::Item'` into `<T as Fetch<'a>>::Item'`
    - `QueryCombinationsIter` requires this
- Most types implementing `Fetch` now have a lifetime `'w`
    - allows the fetches to store borrows of world data instead of using raw pointers

## Migration guide

- `EntityMut::get_unchecked_mut` returns a more restricted lifetime, there is no general way to migrate this as it depends on your code
- `Bundle::from_components` implementations must pass the `ctx` arg to `func`
- `Bundle::from_components` callers have to use a fn arg instead of closure captures for borrowing from world
- Remove lifetime args on `derive(WorldQuery)` structs as it is nonsensical
- `<Q as WorldQuery>::ReadOnly/Fetch` should be changed to either `RO/QueryFetch<'world>` or `<Q as WorldQueryGats<'world>>::ReadOnly/Fetch`
- `<F as Fetch<'w, 's>>` should be changed to `<F as Fetch<'w>>`
- Change the fn sigs of `Fetch::init/set_archetype/set_table` to match respective trait fn sigs
- Implement the required `fn shrink` on any `WorldQuery` implementations
- Move assoc types `Fetch` and `ReadOnlyFetch` on `WorldQuery` impls to `WorldQueryGats` impls
- Pass an appropriate `'world` lifetime to whatever fetch struct you are for some reason using

### Type inference regression

in some cases rustc may give spurrious errors when attempting to infer the `F` parameter on a query/querystate this can be fixed by manually specifying the type, i.e. `QueryState:🆕:<_, ()>(world)`. The error is rather confusing:

```rust=
error[E0271]: type mismatch resolving `<() as Fetch<'_>>::Item == bool`
    --> crates/bevy_pbr/src/render/light.rs:1413:30
     |
1413 |             main_view_query: QueryState::new(world),
     |                              ^^^^^^^^^^^^^^^ expected `bool`, found `()`
     |
     = note: required because of the requirements on the impl of `for<'x> FilterFetch<'x>` for `<() as WorldQueryGats<'x>>::Fetch`
note: required by a bound in `bevy_ecs::query::QueryState::<Q, F>::new`
    --> crates/bevy_ecs/src/query/state.rs:49:32
     |
49   |     for<'x> QueryFetch<'x, F>: FilterFetch<'x>,
     |                                ^^^^^^^^^^^^^^^ required by this bound in `bevy_ecs::query::QueryState::<Q, F>::new`
```

---

Made with help from @BoxyUwU and @alice-i-cecile 

Co-authored-by: Boxy <supbscripter@gmail.com>
2022-04-27 23:44:06 +00:00
bjorn3
ddce22b614 Decouple some dependencies (#3886)
# Objective

Reduce from scratch build time.

## Solution

Reduce the size of the critical path by removing dependencies between crates where not necessary. For `cargo check --no-default-features` this reduced build time from ~51s to ~45s. For some commits I am not completely sure if the tradeoff between build time reduction and convenience caused by the commit is acceptable. If not, I can drop them.
2022-04-27 19:08:11 +00:00
Rob Parrett
dafd7a14c9 Fix torus normals (#4520)
# Objective

Fix wonky torus normals.

## Solution

I attempted this previously in #3549, but it looks like I botched it. It seems like I mixed up the y/z axes. Somehow, the result looked okay from that particular camera angle.

This video shows toruses generated with
- [left, orange] original torus mesh code
- [middle, pink] PR 3549
- [right, purple] This PR

https://user-images.githubusercontent.com/200550/164093183-58a7647c-b436-4512-99cd-cf3b705cefb0.mov
2022-04-26 18:42:43 +00:00
SarthakSingh31
5155034a58 Converted exclusive systems to parallel systems wherever possible (#2774)
Closes #2767.

Converted:
- `play_queued_audio_system`
- `change_window`
2022-04-25 14:32:56 +00:00
KDecay
7a7f097485 Move Size to bevy_ui (#4285)
# Objective

- Related #4276.
- Part of the splitting process of #3503.

## Solution

- Move `Size` to `bevy_ui`.

## Reasons

- `Size` is only needed in `bevy_ui` (because it needs to use `Val` instead of `f32`), but it's also used as a worse `Vec2`  replacement in other areas.
- `Vec2` is more powerful than `Size` so it should be used whenever possible.
- Discussion in #3503.

## Changelog

### Changed

- The `Size` type got moved from `bevy_math` to `bevy_ui`.

## Migration Guide

- The `Size` type got moved from `bevy::math` to `bevy::ui`. To migrate you just have to import `bevy::ui::Size` instead of `bevy::math::Math` or use the `bevy::prelude` instead.

Co-authored-by: KDecay <KDecayMusic@protonmail.com>
2022-04-25 13:54:46 +00:00
nsarlin
0850975192 Add the possibility to create custom 2d orthographic cameras (#4048)
# Objective

- The `OrthographicCameraBundle` constructor for 2d cameras uses a hardcoded value for Z position and scale of the camera. It could be useful to be able to customize these values.

## Solution

- Add a new constructor `custom_2d` that takes `far` (Z position) and `scale` as parameters. The default constructor `new_2d` uses this constructor with `far = 1000.0` and `scale = 1.0`.
2022-04-25 13:54:44 +00:00
Yutao Yuan
8d67832dfa Bump Bevy to 0.8.0-dev (#4505)
# Objective

We should bump our version to 0.8.0-dev after releasing 0.7.0, according to our release checklist.

## Solution

Do it.
2022-04-17 23:04:52 +00:00
Carter Anderson
83c6ffb73c release 0.7.0 (#4487) 2022-04-15 18:05:37 +00:00
Dusty DeWeese
0d2b527faf Avoid windows with a physical size of zero (#4098)
# Objective

Fix #4097

## Solution

Return `None` from `RenderTarget::get_physical_size` if either dimension is zero.
2022-04-15 07:32:21 +00:00
Robert Swain
c2a9d5843d Faster assign lights to clusters (#4345)
# Objective

- Fixes #4234
- Fixes #4473 
- Built on top of #3989
- Improve performance of `assign_lights_to_clusters`

## Solution

- Remove the OBB-based cluster light assignment algorithm and calculation of view space AABBs
- Implement the 'iterative sphere refinement' algorithm used in Just Cause 3 by Emil Persson as documented in the Siggraph 2015 Practical Clustered Shading talk by Persson, on pages 42-44 http://newq.net/dl/pub/s2015_practical.pdf
- Adapt to also support orthographic projections
- Add `many_lights -- orthographic` for testing many lights using an orthographic projection

## Results

- `assign_lights_to_clusters` in `many_lights` before this PR on an M1 Max over 1500 frames had a median execution time of 1.71ms. With this PR it is 1.51ms, a reduction of 0.2ms or 11.7% for this system.

---

## Changelog

- Changed: Improved cluster light assignment performance

Co-authored-by: robtfm <50659922+robtfm@users.noreply.github.com>
Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2022-04-15 02:53:20 +00:00
Dusty DeWeese
5a297d7903 Reuse texture when resolving multiple passes (#3552)
# Objective

Fixes https://github.com/bevyengine/bevy/issues/3499

## Solution

Uses a `HashMap` from `RenderTarget` to sampled textures when preparing `ViewTarget`s to ensure that two passes with the same render target get sampled to the same texture.

This builds on and depends on https://github.com/bevyengine/bevy/pull/3412, so this will be a draft PR until #3412 is merged. All changes for this PR are in the last commit.
2022-04-12 19:27:30 +00:00
Jakob Hellermann
193e8c4ada scene_viewer: load cameras (#4425)
# Objective

glTF files can contain cameras. Currently the scene viewer example uses _a_ camera defined in the file if possible, otherwise it spawns a new one. It would be nice if instead it could load all the cameras and cycle through them, while also having a separate user-controller camera.

## Solution

- instead of just a camera that is already defined, always spawn a new separate user-controller camera
- maintain a list of loaded cameras and cycle through them (wrapping to the user-controller camera) when pressing `C`

This matches the behavious that https://github.khronos.org/glTF-Sample-Viewer-Release/ has.

## Implementation notes

- The gltf scene asset loader just spawns the cameras into the world, but does not return a mapping of camera index to bevy entity. So instead the scene_viewer example just collects all spawned cameras with a good old `query.iter().collect()`, so the order is unspecified and may change between runs.

## Demo

https://user-images.githubusercontent.com/22177966/161826637-40161482-5b3b-4df5-aae8-1d5e9b918393.mp4


using the virtual city glTF sample file: https://github.com/KhronosGroup/glTF-Sample-Models/tree/master/2.0/VC

Co-authored-by: Jakob Hellermann <hellermann@sipgate.de>
2022-04-11 22:56:06 +00:00
Jakob Hellermann
c12ee81822 bevy_app: add tracing event with tracy.frame_mark (#4320)
Currently `tracy` interprets the entire trace as one frame because the marker for frames isn't being recorded.

~~When an event with `tracy.trace_marker=true` is recorded, `tracing-tracy` will mark the frame as finished:
<aa0b96b2ae/tracing-tracy/src/lib.rs (L240)>~~

~~Unfortunately this leads to~~
```rs
INFO bevy_app:frame: bevy_app::app: finished frame tracy.frame_mark=true
```
~~being printed every frame (we can't use DEBUG because bevy_log sets `max_release_level_info`.~~

Instead of emitting an event that gets logged every frame, we can depend on tracy-client itself and call `finish_continuous_frame!();`
2022-04-08 22:50:23 +00:00
Kirillov Kirill
01bdf67c33 Improve the set_active_camera system (#4251)
# Objective

- Make `set_active_camera` system correctly respond to camera deletion, while preserving its correct behavior on first ever frame and any consequent frame, and with multiple cameras of the same type available in the world.
- Fixes #4227

## Solution

- Add a check that the entity referred to by `ActiveCamera` still exists in the world.
2022-04-07 23:30:47 +00:00
Robert Swain
c5963b4fd5 Use storage buffers for clustered forward point lights (#3989)
# Objective

- Make use of storage buffers, where they are available, for clustered forward bindings to support far more point lights in a scene
- Fixes #3605 
- Based on top of #4079 

This branch on an M1 Max can keep 60fps with about 2150 point lights of radius 1m in the Sponza scene where I've been testing. The bottleneck is mostly assigning lights to clusters which grows faster than linearly (I think 1000 lights was about 1.5ms and 5000 was 7.5ms). I have seen papers and presentations leveraging compute shaders that can get this up to over 1 million. That said, I think any further optimisations should probably be done in a separate PR.

## Solution

- Add `RenderDevice` to the `Material` and `SpecializedMaterial` trait `::key()` functions to allow setting flags on the keys depending on feature/limit availability
- Make `GpuPointLights` and `ViewClusterBuffers` into enums containing `UniformVec` and `StorageBuffer` variants. Implement the necessary API on them to make usage the same for both cases, and the only difference is at initialisation time.
- Appropriate shader defs in the shader code to handle the two cases

## Context on some decisions / open questions

- I'm using `max_storage_buffers_per_shader_stage >= 3` as a check to see if storage buffers are supported. I was thinking about diving into 'binding resource management' but it feels like we don't have enough use cases to understand the problem yet, and it is mostly a separate concern to this PR, so I think it should be handled separately.
- Should `ViewClusterBuffers` and `ViewClusterBindings` be merged, duplicating the count variables into the enum variants?


Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2022-04-07 16:16:35 +00:00
Hennadii Chernyshchyk
ea6e6f7db2 Do not crash if RenderDevice doesn't exist (#4427)
# Objective

Avoid crashing if `RenderDevice` doesn't exist (required for headless mode).
Fixes #4392.

## Solution

Use `CompressedImageFormats::all()` if there is no `RenderDevice`.
2022-04-05 19:37:23 +00:00
Francesco Giordana
dbd5e7ab6b Fixed case of R == G, following original conversion formula (#4383)
https://en.wikipedia.org/wiki/HSL_and_HSV#From_RGB

# Objective
Fixes #4382

## Solution

- Describe the solution used to achieve the objective above.
Fixed conversion formula to account for red and green component being max and equal
---

## Changelog
Fixed RGB -> HSL colorspace conversion

## Migration Guide


Co-authored-by: Francesco Giordana <fgiordana@netflix.com>
2022-04-04 18:59:00 +00:00
Light Ning
dd2001f2f1 bevy_render: add a small color box to each color (#4387)
# Objective

- bevy_render: add a small color box to each color

## Solution

![bevy_color_doc](https://user-images.githubusercontent.com/1318472/161241226-e7632a90-f526-44de-a68e-ff63b848164b.png)

---

## Changelog
2022-04-01 20:52:22 +00:00
devil ira
48ac955afd Fix loading non-TriangleList meshes without normals in gltf loader (#4376)
# Objective
Make it so that loading in a mesh without normals that is not a `TriangleList` succeeds.

## Solution
Flat normals can only be calculated on a mesh made of triangles.
Check whether the mesh is a `TriangleList` before trying to compute missing normals.

## Additional changes
The panic condition in `duplicate_vertices` did not make sense to me. I moved it to `compute_flat_normals` where the algorithm would produce incorrect results if the mesh is not a `TriangleList`.

Co-authored-by: devil-ira <justthecooldude@gmail.com>
2022-03-31 20:43:01 +00:00
Boxy
637a149910 unsafeify World::entities_mut (#4093)
# Objective
make bevy ecs a lil bit less unsound

## Solution
make unsound API unsafe so that there is an unsafe block to blame:

```rust
use bevy_ecs::prelude::*;

#[derive(Debug, Component)]
struct Foo(u8);

fn main() {
    let mut world = World::new();
    let e1 = world.spawn().id();
    let e2 = world.spawn().insert(Foo(2)).id();
    world.entities_mut().meta[0] = world.entities_mut().meta[1].clone();
    let foo = world.entity(e1).get::<Foo>().unwrap();
    // whoo i love having components i dont have
    dbg!(foo);
}
```

This is not _strictly_ speaking UB, however: 
- `Query::get_multiple` cannot work if this is allowed
- bevy_ecs is a pile of unsafe code whose soundness generally depends on the world being in a "correct" state with "no funny business" so it seems best to disallow this
- it is trivial to get bevy to panic inside of functions with safety invariants that have been violated (the entity location is not valid)
- it seems to violate what the safety invariant on `Entities::flush` is trying to ensure
2022-03-30 23:52:45 +00:00
bilsen
63fee2572b ParamSet for conflicting SystemParam:s (#2765)
# Objective
Add a system parameter `ParamSet` to be used as container for conflicting parameters.

## Solution
Added two methods to the SystemParamState trait, which gives the access used by the parameter. Did the implementation. Added some convenience methods to FilteredAccessSet. Changed `get_conflicts` to return every conflicting component instead of breaking on the first conflicting `FilteredAccess`.


Co-authored-by: bilsen <40690317+bilsen@users.noreply.github.com>
2022-03-29 23:39:38 +00:00
Jakob Hellermann
551d9f6cd7 use error scope to handle errors on shader module creation (#3675)
related: https://github.com/bevyengine/bevy/pull/3289

In addition to validating shaders early when debug assertions are enabled, use the new [error scopes](https://gpuweb.github.io/gpuweb/#error-scopes) API when creating a shader module.

I chose to keep the early validation (and thereby parsing twice) when debug assertions are enabled in, because it lets as handle errors ourselves and display them with pretty colors, while the error scopes API just gives us a string we can display.



This change pulls in `futures-util` as a new dependency for `future.now_or_never()`. I can inline that part of futures-lite into `bevy_render` to keep the compilation time lower if that's preferred.
2022-03-29 22:39:14 +00:00
Mika
6844a6f4fd Introduce SystemLabel's for RenderAssetPlugin, and change Image preparation system to run before others (#3917)
# Objective

Fixes `StandardMaterial` texture update (see sample code below).

Most probably fixes #3674 (did not test)

## Solution

Material updates, such as PBR update, reference the underlying `GpuImage`. Like here: 9a7852db0f/crates/bevy_pbr/src/pbr_material.rs (L177)

However, currently the `GpuImage` update may actually happen *after* the material update fetches the gpu image. Resulting in the material actually not being updated for the correct gpu image.

In this pull req, I introduce new systemlabels for the renderassetplugin. Also assigned the RenderAssetPlugin::<Image> to the `PreAssetExtract` stage, so that it is executed before any material updates.

Code to test.

Expected behavior:
* should update to red texture

Unexpected behavior (before this merge):
* texture stays randomly as green one (depending on the execution order of systems)

```rust
use bevy::{
    prelude::*,
    render::render_resource::{Extent3d, TextureDimension, TextureFormat},
};

fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        .add_startup_system(setup)
        .add_system(changes)
        .run();
}

struct Iteration(usize);

#[derive(Component)]
struct MyComponent;

fn setup(
    mut commands: Commands,
    mut meshes: ResMut<Assets<Mesh>>,
    mut materials: ResMut<Assets<StandardMaterial>>,
    mut images: ResMut<Assets<Image>>,
) {
    commands.spawn_bundle(PointLightBundle {
        point_light: PointLight {
            ..Default::default()
        },
        transform: Transform::from_xyz(4.0, 8.0, 4.0),
        ..Default::default()
    });

    commands.spawn_bundle(PerspectiveCameraBundle {
        transform: Transform::from_xyz(-2.0, 0.0, 5.0)
            .looking_at(Vec3::new(0.0, 0.0, 0.0), Vec3::Y),
        ..Default::default()
    });

    commands.insert_resource(Iteration(0));

    commands
        .spawn_bundle(PbrBundle {
            mesh: meshes.add(Mesh::from(shape::Quad::new(Vec2::new(3., 2.)))),
            material: materials.add(StandardMaterial {
                base_color_texture: Some(images.add(Image::new(
                    Extent3d {
                        width: 600,
                        height: 400,
                        depth_or_array_layers: 1,
                    },
                    TextureDimension::D2,
                    [0, 255, 0, 128].repeat(600 * 400), // GREEN
                    TextureFormat::Rgba8Unorm,
                ))),
                ..Default::default()
            }),
            ..Default::default()
        })
        .insert(MyComponent);
}

fn changes(
    mut materials: ResMut<Assets<StandardMaterial>>,
    mut images: ResMut<Assets<Image>>,
    mut iteration: ResMut<Iteration>,
    webview_query: Query<&Handle<StandardMaterial>, With<MyComponent>>,
) {
    if iteration.0 == 2 {
        let material = materials.get_mut(webview_query.single()).unwrap();

        let image = images
            .get_mut(material.base_color_texture.as_ref().unwrap())
            .unwrap();

        image
            .data
            .copy_from_slice(&[255, 0, 0, 255].repeat(600 * 400));
    }

    iteration.0 += 1;
}
```

Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2022-03-29 19:44:45 +00:00
James Liu
31bd4ecbbc Mesh Skinning. Attempt #3 (#4238)
# Objective
Load skeletal weights and indices from GLTF files. Animate meshes.

## Solution
 - Load skeletal weights and indices from GLTF files.
 - Added `SkinnedMesh` component and ` SkinnedMeshInverseBindPose` asset
 - Added `extract_skinned_meshes` to extract joint matrices.
 - Added queue phase systems for enqueuing the buffer writes.

Some notes:

 -  This ports part of # #2359 to the current main.
 -  This generates new `BufferVec`s and bind groups every frame. The expectation here is that the number of `Query::get` calls during extract is probably going to be the stronger bottleneck, with up to 256 calls per skinned mesh. Until that is optimized, caching buffers and bind groups is probably a non-concern.
 - Unfortunately, due to the uniform size requirements, this means a 16KB buffer is allocated for every skinned mesh every frame. There's probably a few ways to get around this, but most of them require either compute shaders or storage buffers, which are both incompatible with WebGL2.

Co-authored-by: james7132 <contact@jamessliu.com>
Co-authored-by: François <mockersf@gmail.com>
Co-authored-by: James Liu <contact@jamessliu.com>
2022-03-29 18:31:13 +00:00
Kurt Kühnert
9e450f2827 Compute Pipeline Specialization (#3979)
# Objective

- Fixes #3970
- To support Bevy's shader abstraction(shader defs, shader imports and hot shader reloading) for compute shaders, I have followed carts advice and change the `PipelinenCache` to accommodate both compute and render pipelines.

## Solution

- renamed `RenderPipelineCache` to `PipelineCache`
- Cached Pipelines are now represented by an enum (render, compute)
- split the `SpecializedPipelines` into `SpecializedRenderPipelines` and `SpecializedComputePipelines`
- updated the game of life example

## Open Questions

- should `SpecializedRenderPipelines` and `SpecializedComputePipelines` be merged and how would we do that?
- should the `get_render_pipeline` and `get_compute_pipeline` methods be merged?
- is pipeline specialization for different entry points a good pattern




Co-authored-by: Kurt Kühnert <51823519+Ku95@users.noreply.github.com>
Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2022-03-23 00:27:26 +00:00
Robert Swain
0a4136d266 Add a helper for storage buffers similar to UniformVec (#4079)
# Objective

- Add a helper for storage buffers similar to `UniformVec`

## Solution

- Add a `StorageBuffer<T, U>` where `T` is the main body of the shader struct without any final variable-sized array member, and `U` is the type of the items in a variable-sized array.
- Use `()` as the type for unwanted parts, e.g. `StorageBuffer<(), Vec4>::default()` would construct a binding that would work with `struct MyType { data: array<vec4<f32>>; }` in WGSL and `StorageBuffer<MyType, ()>::default()` would work with `struct MyType { ... }` in WGSL as long as there are no variable-sized arrays.
- Std430 requires that there is at most one variable-sized array in a storage buffer, that if there is one it is the last member of the binding, and that it has at least one item. `StorageBuffer` handles all of these constraints.
2022-03-22 21:23:50 +00:00
Robert Swain
6c085cba47 bevy_render: Support removal of nodes, edges, subgraphs (#3048)
Add support for removing nodes, edges, and subgraphs. This enables live re-wiring of the render graph.

This was something I did to support the MSAA implementation, but it turned out to be unnecessary there. However, it is still useful so here it is in its own PR.

Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2022-03-21 23:58:37 +00:00
Jakob Hellermann
685b6e59be register Camera{2,3}d components for reflection (#4269)
# Objective

When loading a gltf scene with a camera, bevy will panic at ``thread 'main' panicked at 'scene contains the unregistered type `bevy_render:📷:bundle::Camera3d`. consider registering the type using `app.register_type::<T>()`', /home/jakob/dev/rust/contrib/bevy/bevy/crates/bevy_scene/src/scene_spawner.rs:332:35``.

## Solution

Register the camera types to fix the panic.
2022-03-20 21:54:11 +00:00
Robert Swain
ac8bbafc5c Faster view frustum culling (#4181)
# Objective

- Reduce time spent in the `check_visibility` system

## Solution

- Use `Vec3A` for all bounding volume types to leverage SIMD optimisations and to avoid repeated runtime conversions from `Vec3` to `Vec3A`
- Inline all bounding volume intersection methods
- Add on-the-fly calculated `Aabb` -> `Sphere` and do `Sphere`-`Frustum` intersection tests before `Aabb`-`Frustum` tests. This is faster for `many_cubes` but could be slower in other cases where the sphere test gives a false-positive that the `Aabb` test discards. Also, I tested precalculating the `Sphere`s and inserting them alongside the `Aabb` but this was slower. 
- Do not test meshes against the far plane. Apparently games don't do this anymore with infinite projections, and it's one fewer plane to test against. I made it optional and still do the test for culling lights but that is up for discussion.
- These collectively reduce `check_visibility` execution time in `many_cubes -- sphere` from 2.76ms to 1.48ms and increase frame rate from ~42fps to ~44fps
2022-03-19 04:41:28 +00:00
Alice Cecile
7ce3ae43e3 Bump Bevy to 0.7.0-dev (#4230)
# Objective

- The [dev docs](https://dev-docs.bevyengine.org/bevy/index.html#) show version 0.6.0, which is actively misleading.

[Image of the problem](https://cdn.discordapp.com/attachments/695741366520512563/953513612943704114/Screenshot_20220316-154100_Firefox-01.jpeg)

Noticed by @ickk, fix proposed by @mockersf.

## Solution

- Bump the version across all Bevy crates to 0.7.0 dev.
- Set a reminder in the Release Checklist to remember to do this each release.
2022-03-19 03:54:15 +00:00
Carter Anderson
de677dbfc9 Use more ergonomic span syntax (#4246)
Tracing added support for "inline span entering", which cuts down on a lot of complexity:

```rust
let span = info_span!("my_span").entered();
```

This adapts our code to use this pattern where possible, and updates our docs to recommend it.

This produces equivalent tracing behavior. Here is a side by side profile of "before" and "after" these changes.
![image](https://user-images.githubusercontent.com/2694663/158912137-b0aa6dc8-c603-425f-880f-6ccf5ad1b7ef.png)
2022-03-18 04:19:21 +00:00
Robert Swain
0529f633f9 KTX2/DDS/.basis compressed texture support (#3884)
# Objective

- Support compressed textures including 'universal' formats (ETC1S, UASTC) and transcoding of them to 
- Support `.dds`, `.ktx2`, and `.basis` files

## Solution

- Fixes https://github.com/bevyengine/bevy/issues/3608 Look there for more details.
- Note that the functionality is all enabled through non-default features. If it is desirable to enable some by default, I can do that.
- The `basis-universal` crate, used for `.basis` file support and for transcoding, is built on bindings against a C++ library. It's not feasible to rewrite in Rust in a short amount of time. There are no Rust alternatives of which I am aware and it's specialised code. In its current state it doesn't support the wasm target, but I don't know for sure. However, it is possible to build the upstream C++ library with emscripten, so there is perhaps a way to add support for web too with some shenanigans.
- There's no support for transcoding from BasisLZ/ETC1S in KTX2 files as it was quite non-trivial to implement and didn't feel important given people could use `.basis` files for ETC1S.
2022-03-15 22:26:46 +00:00
Daniel McNab
6e61fef67d Obviate the need for RunSystem, and remove it (#3817)
# Objective

- Fixes #3300
- `RunSystem` is messy

## Solution

- Adds the trick theorised in https://github.com/bevyengine/bevy/issues/3300#issuecomment-991791234

P.S. I also want this for an experimental refactoring of `Assets`, to remove the duplication of `Events<AssetEvent<T>>`


Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2022-03-15 02:16:55 +00:00
Alice Cecile
a304fd9a99 Split bevy_hierarchy out from bevy_transform (#4168)
# Objective

- Hierarchy tools are not just used for `Transform`: they are also used for scenes.
- In the future there's interest in using them for other features, such as visiibility inheritance.
- The fact that these tools are found in `bevy_transform` causes a great deal of user and developer confusion
- Fixes #2758.

## Solution

- Split `bevy_transform` into two!
- Make everything work again.

Note that this is a very tightly scoped PR: I *know* there are code quality and docs issues that existed in bevy_transform that I've just moved around. We should fix those in a seperate PR and try to merge this ASAP to reduce the bitrot involved in splitting an entire crate.

## Frustrations

The API around `GlobalTransform` is a mess: we have massive code and docs duplication, no link between the two types and no clear way to extend this to other forms of inheritance.

In the medium-term, I feel pretty strongly that `GlobalTransform` should be replaced by something like `Inherited<Transform>`, which lives in `bevy_hierarchy`:

- avoids code duplication
- makes the inheritance pattern extensible
- links the types at the type-level
- allows us to remove all references to inheritance from `bevy_transform`, making it more useful as a standalone crate and cleaning up its docs

## Additional context

- double-blessed by @cart in https://github.com/bevyengine/bevy/issues/4141#issuecomment-1063592414 and https://github.com/bevyengine/bevy/issues/2758#issuecomment-913810963
- preparation for more advanced / cleaner hierarchy tools: go read https://github.com/bevyengine/rfcs/pull/53 !
- originally attempted by @finegeometer in #2789. It was a great idea, just needed more discussion!

Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2022-03-15 01:54:05 +00:00
Jakob Hellermann
bf6de89622 use marker components for cameras instead of name strings (#3635)
**Problem**
- whenever you want more than one of the builtin cameras (for example multiple windows, split screen, portals), you need to add a render graph node that executes the correct sub graph, extract the camera into the render world and add the correct `RenderPhase<T>` components
- querying for the 3d camera is annoying because you need to compare the camera's name to e.g. `CameraPlugin::CAMERA_3d`

**Solution**
- Introduce the marker types `Camera3d`, `Camera2d` and `CameraUi`
-> `Query<&mut Transform, With<Camera3d>>` works
- `PerspectiveCameraBundle::new_3d()` and `PerspectiveCameraBundle::<Camera3d>::default()` contain the `Camera3d` marker
- `OrthographicCameraBundle::new_3d()` has `Camera3d`, `OrthographicCameraBundle::new_2d()` has `Camera2d`
- remove `ActiveCameras`, `ExtractedCameraNames`
- run 2d, 3d and ui passes for every camera of their respective marker
-> no custom setup for multiple windows example needed

**Open questions**
- do we need a replacement for `ActiveCameras`? What about a component `ActiveCamera { is_active: bool }` similar to `Visibility`?

Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2022-03-12 00:41:06 +00:00
Robert Swain
0e821da704 bevy_render: Batch insertion for prepare_uniform_components (#4179)
# Objective

- Make insertion of uniform components faster

## Solution

- Use batch insertion in the prepare_uniform_components system
- Improves `many_cubes -- sphere` from ~42fps to ~43fps


Co-authored-by: François <mockersf@gmail.com>
2022-03-11 23:20:18 +00:00
François
4add96b1be Cleanup doc / comments about changed defaults (#4144)
# Objective

- Update comment about default audio format
- remove doc about msaa in wasm
2022-03-08 02:11:59 +00:00
Alix Bott
e36c9b6cf0 Add conversions from Color to u32 (#4088)
# Objective

- `Mesh::ATTRIBUTE_COLOR` expects colors as `u32`s but there is no function for easy conversion.
- See https://github.com/bevyengine/bevy/pull/4037#pullrequestreview-894448677

## Solution

- Added `Color::as_rgba_u32` and `Color::as_linear_rgba_u32`
2022-03-08 00:46:03 +00:00
josh65536
e3a3b5b9c2 Fixed the frustum-sphere collision and added tests (#4035)
# Objective

Fixes #3744 

## Solution

The old code used the formula `normal . center + d + radius <= 0` to determine if the sphere with center `center` and radius `radius` is outside the plane with normal `normal` and distance from origin `d`. This only works if `normal` is normalized, which is not necessarily the case. Instead, `normal` and `d` are both multiplied by some factor that `radius` isn't multiplied by. So the additional code multiplied `radius` by that factor.
2022-03-08 00:30:41 +00:00
dataphract
cba9bcc7ba improve error messages for render graph runner (#3930)
# Objective

Currently, errors in the render graph runner are exposed via a `Result::unwrap()` panic message, which dumps the debug representation of the error.

## Solution

This PR updates `render_system` to log the chain of errors, followed by an explicit panic:

```
ERROR bevy_render::renderer: Error running render graph:
ERROR bevy_render::renderer: > encountered an error when running a sub-graph
ERROR bevy_render::renderer: > tried to pass inputs to sub-graph "outline_graph", which has no input slots
thread 'main' panicked at 'Error running render graph: encountered an error when running a sub-graph', /[redacted]/bevy/crates/bevy_render/src/renderer/mod.rs:44:9
```

Some errors' `Display` impls (via `thiserror`) have also been updated to provide more detail about the cause of the error.
2022-03-07 09:09:24 +00:00
pubrrr
caf6611c62 remove Events from bevy_app, they now live in bevy_ecs (#4066)
# Objective

Fixes #4064.

## Solution

- remove Events from bevy_app
2022-03-01 19:33:56 +00:00
Kurt Kühnert
40b36927f5 Expose draw indirect (#4056)
# Objective

- Currently there is now way of making an indirect draw call from a tracked render pass.
- This is a very useful feature for GPU based rendering.

## Solution

- Expose the `draw_indirect` and `draw_indexed_indirect` methods from the wgpu `RenderPass` in the `TrackedRenderPass`.

## Alternative

- #3595: Expose the underlying `RenderPass` directly
2022-02-28 10:26:49 +00:00
Alice Cecile
557ab9897a Make get_resource (and friends) infallible (#4047)
# Objective

- In the large majority of cases, users were calling `.unwrap()` immediately after `.get_resource`.
- Attempting to add more helpful error messages here resulted in endless manual boilerplate (see #3899 and the linked PRs).

## Solution

- Add an infallible variant named `.resource` and so on.
- Use these infallible variants over `.get_resource().unwrap()` across the code base.

## Notes

I did not provide equivalent methods on `WorldCell`, in favor of removing it entirely in #3939.

## Migration Guide

Infallible variants of `.get_resource` have been added that implicitly panic, rather than needing to be unwrapped.

Replace `world.get_resource::<Foo>().unwrap()` with `world.resource::<Foo>()`.

## Impact

- `.unwrap` search results before: 1084
- `.unwrap` search results after: 942
- internal `unwrap_or_else` calls added: 4
- trivial unwrap calls removed from tests and code: 146
- uses of the new `try_get_resource` API: 11
- percentage of the time the unwrapping API was used internally: 93%
2022-02-27 22:37:18 +00:00
Dusty DeWeese
81d57e129b Add capability to render to a texture (#3412)
# Objective

Will fix #3377 and #3254

## Solution

Use an enum to represent either a `WindowId` or `Handle<Image>` in place of `Camera::window`.


Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2022-02-24 00:40:24 +00:00
Carter Anderson
e369a8ad51 Mesh vertex buffer layouts (#3959)
This PR makes a number of changes to how meshes and vertex attributes are handled, which the goal of enabling easy and flexible custom vertex attributes:
* Reworks the `Mesh` type to use the newly added `VertexAttribute` internally
  * `VertexAttribute` defines the name, a unique `VertexAttributeId`, and a `VertexFormat`
  *  `VertexAttributeId` is used to produce consistent sort orders for vertex buffer generation, replacing the more expensive and often surprising "name based sorting"  
  * Meshes can be used to generate a `MeshVertexBufferLayout`, which defines the layout of the gpu buffer produced by the mesh. `MeshVertexBufferLayouts` can then be used to generate actual `VertexBufferLayouts` according to the requirements of a specific pipeline. This decoupling of "mesh layout" vs "pipeline vertex buffer layout" is what enables custom attributes. We don't need to standardize _mesh layouts_ or contort meshes to meet the needs of a specific pipeline. As long as the mesh has what the pipeline needs, it will work transparently. 
* Mesh-based pipelines now specialize on `&MeshVertexBufferLayout` via the new `SpecializedMeshPipeline` trait (which behaves like `SpecializedPipeline`, but adds `&MeshVertexBufferLayout`). The integrity of the pipeline cache is maintained because the `MeshVertexBufferLayout` is treated as part of the key (which is fully abstracted from implementers of the trait ... no need to add any additional info to the specialization key).    
* Hashing `MeshVertexBufferLayout` is too expensive to do for every entity, every frame. To make this scalable, I added a generalized "pre-hashing" solution to `bevy_utils`: `Hashed<T>` keys and `PreHashMap<K, V>` (which uses `Hashed<T>` internally) . Why didn't I just do the quick and dirty in-place "pre-compute hash and use that u64 as a key in a hashmap" that we've done in the past? Because its wrong! Hashes by themselves aren't enough because two different values can produce the same hash. Re-hashing a hash is even worse! I decided to build a generalized solution because this pattern has come up in the past and we've chosen to do the wrong thing. Now we can do the right thing! This did unfortunately require pulling in `hashbrown` and using that in `bevy_utils`, because avoiding re-hashes requires the `raw_entry_mut` api, which isn't stabilized yet (and may never be ... `entry_ref` has favor now, but also isn't available yet). If std's HashMap ever provides the tools we need, we can move back to that. Note that adding `hashbrown` doesn't increase our dependency count because it was already in our tree. I will probably break these changes out into their own PR.
* Specializing on `MeshVertexBufferLayout` has one non-obvious behavior: it can produce identical pipelines for two different MeshVertexBufferLayouts. To optimize the number of active pipelines / reduce re-binds while drawing, I de-duplicate pipelines post-specialization using the final `VertexBufferLayout` as the key.  For example, consider a pipeline that needs the layout `(position, normal)` and is specialized using two meshes: `(position, normal, uv)` and `(position, normal, other_vec2)`. If both of these meshes result in `(position, normal)` specializations, we can use the same pipeline! Now we do. Cool!

To briefly illustrate, this is what the relevant section of `MeshPipeline`'s specialization code looks like now:

```rust
impl SpecializedMeshPipeline for MeshPipeline {
    type Key = MeshPipelineKey;

    fn specialize(
        &self,
        key: Self::Key,
        layout: &MeshVertexBufferLayout,
    ) -> RenderPipelineDescriptor {
        let mut vertex_attributes = vec![
            Mesh::ATTRIBUTE_POSITION.at_shader_location(0),
            Mesh::ATTRIBUTE_NORMAL.at_shader_location(1),
            Mesh::ATTRIBUTE_UV_0.at_shader_location(2),
        ];

        let mut shader_defs = Vec::new();
        if layout.contains(Mesh::ATTRIBUTE_TANGENT) {
            shader_defs.push(String::from("VERTEX_TANGENTS"));
            vertex_attributes.push(Mesh::ATTRIBUTE_TANGENT.at_shader_location(3));
        }

        let vertex_buffer_layout = layout
            .get_layout(&vertex_attributes)
            .expect("Mesh is missing a vertex attribute");
```

Notice that this is _much_ simpler than it was before. And now any mesh with any layout can be used with this pipeline, provided it has vertex postions, normals, and uvs. We even got to remove `HAS_TANGENTS` from MeshPipelineKey and `has_tangents` from `GpuMesh`, because that information is redundant with `MeshVertexBufferLayout`.

This is still a draft because I still need to:

* Add more docs
* Experiment with adding error handling to mesh pipeline specialization (which would print errors at runtime when a mesh is missing a vertex attribute required by a pipeline). If it doesn't tank perf, we'll keep it.
* Consider breaking out the PreHash / hashbrown changes into a separate PR.
* Add an example illustrating this change
* Verify that the "mesh-specialized pipeline de-duplication code" works properly

Please dont yell at me for not doing these things yet :) Just trying to get this in peoples' hands asap.

Alternative to #3120
Fixes #3030


Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2022-02-23 23:21:13 +00:00
François
e4203c3925 shader preprocessor - do not import if scope is not valid (#4012)
# Objective

- fix #4011 
- imports are not limited by the current `ifdef` they are in

## Solution

- process imports only if the current scope is enabled
2022-02-22 20:21:04 +00:00
Patrik Buhring
fb8af3aec3 Update Hexasphere to 7.0.0 (#4001)
The new update includes wireframe generation capabilities. 

I didn't integrate that in this PR, however with some guidance, I'd be happy to do so.
2022-02-21 23:49:07 +00:00
Carter Anderson
98938a8555 Internal Asset Hot Reloading (#3966)
Adds "hot reloading" of internal assets, which is normally not possible because they are loaded using `include_str` / direct Asset collection access.

This is accomplished via the following:
* Add a new `debug_asset_server` feature flag
* When that feature flag is enabled, create a second App with a second AssetServer that points to a configured location (by default the `crates` folder). Plugins that want to add hot reloading support for their assets can call the new `app.add_debug_asset::<T>()` and `app.init_debug_asset_loader::<T>()` functions.
* Load "internal" assets using the new `load_internal_asset` macro. By default this is identical to the current "include_str + register in asset collection" approach. But if the `debug_asset_server` feature flag is enabled, it will also load the asset dynamically in the debug asset server using the file path. It will then set up a correlation between the "debug asset" and the "actual asset" by listening for asset change events.

This is an alternative to #3673. The goal was to keep the boilerplate and features flags to a minimum for bevy plugin authors, and allow them to home their shaders near relevant code. 

This is a draft because I haven't done _any_ quality control on this yet. I'll probably rename things and remove a bunch of unwraps. I just got it working and wanted to use it to start a conversation.

Fixes #3660
2022-02-18 22:56:57 +00:00
Carter Anderson
e9f52b9dd2 Move import_path definitions into shader source (#3976)
This enables shaders to (optionally) define their import path inside their source. This has a number of benefits:

1. enables users to define their own custom paths directly in their assets
2. moves the import path "close" to the asset instead of centralized in the plugin definition, which seems "better" to me. 
3. makes "internal hot shader reloading" way more reasonable (see #3966)
4. logically opens the door to importing "parts" of a shader by defining "import_path blocks".

```rust
#define_import_path bevy_pbr::mesh_struct

struct Mesh {
    model: mat4x4<f32>;
    inverse_transpose_model: mat4x4<f32>;
    // 'flags' is a bit field indicating various options. u32 is 32 bits so we have up to 32 options.
    flags: u32;
};

let MESH_FLAGS_SHADOW_RECEIVER_BIT: u32 = 1u;
```
2022-02-18 21:54:03 +00:00
Carter Anderson
b3a1db60f2 Proper prehashing (#3963)
For some keys, it is too expensive to hash them on every lookup. Historically in Bevy, we have regrettably done the "wrong" thing in these cases (pre-computing hashes, then re-hashing them) because Rust's built in hashed collections don't give us the tools we need to do otherwise. Doing this is "wrong" because two different values can result in the same hash. Hashed collections generally get around this by falling back to equality checks on hash collisions. You can't do that if the key _is_ the hash. Additionally, re-hashing a hash increase the odds of collision!
 
#3959 needs pre-hashing to be viable, so I decided to finally properly solve the problem. The solution involves two different changes:

1. A new generalized "pre-hashing" solution in bevy_utils: `Hashed<T>` types, which store a value alongside a pre-computed hash. And `PreHashMap<K, V>` (which uses `Hashed<T>` internally) . `PreHashMap` is just an alias for a normal HashMap that uses `Hashed<T>` as the key and a new `PassHash` implementation as the Hasher. 
2. Replacing the `std::collections` re-exports in `bevy_utils` with equivalent `hashbrown` impls. Avoiding re-hashes requires the `raw_entry_mut` api, which isn't stabilized yet (and may never be ... `entry_ref` has favor now, but also isn't available yet). If std's HashMap ever provides the tools we need, we can move back to that. The latest version of `hashbrown` adds support for the `entity_ref` api, so we can move to that in preparation for an std migration, if thats the direction they seem to be going in. Note that adding hashbrown doesn't increase our dependency count because it was already in our tree.

In addition to providing these core tools, I also ported the "table identity hashing" in `bevy_ecs` to `raw_entry_mut`, which was a particularly egregious case.

The biggest outstanding case is `AssetPathId`, which stores a pre-hash. We need AssetPathId to be cheaply clone-able (and ideally Copy), but `Hashed<AssetPath>` requires ownership of the AssetPath, which makes cloning ids way more expensive. We could consider doing `Hashed<Arc<AssetPath>>`, but cloning an arc is still a non-trivial expensive that needs to be considered. I would like to handle this in a separate PR. And given that we will be re-evaluating the Bevy Assets implementation in the very near future, I'd prefer to hold off until after that conversation is concluded.
2022-02-18 03:26:01 +00:00
Robert Swain
936468aa1e bevy_render: Use RenderDevice to get limits/features and expose AdapterInfo (#3931)
# Objective

- `WgpuOptions` is mutated to be updated with the actual device limits and features, but this information is readily available to both the main and render worlds through the `RenderDevice` which has .limits() and .features() methods
- Information about the adapter in terms of its name, the backend in use, etc were not being exposed but have clear use cases for being used to take decisions about what rendering code to use. For example, if something works well on AMD GPUs but poorly on Intel GPUs. Or perhaps something works well in Vulkan but poorly in DX12.

## Solution

- Stop mutating `WgpuOptions `and don't insert the updated values into the main and render worlds
- Return `AdapterInfo` from `initialize_renderer` and insert it into the main and render worlds
- Use `RenderDevice` limits in the lighting code that was using `WgpuOptions.limits`.
- Renamed `WgpuOptions` to `WgpuSettings`
2022-02-16 21:17:37 +00:00
danieleades
d8974e7c3d small and mostly pointless refactoring (#2934)
What is says on the tin.

This has got more to do with making `clippy` slightly more *quiet* than it does with changing anything that might greatly impact readability or performance.

that said, deriving `Default` for a couple of structs is a nice easy win
2022-02-13 22:33:55 +00:00
Robert Swain
803e8cdf80 bevy_render: Support overriding wgpu features and limits (#3912)
# Objective

- Support overriding wgpu features and limits that were calculated from default values or queried from the adapter/backend.
- Fixes #3686

## Solution

- Add `disabled_features: Option<wgpu::Features>` to `WgpuOptions`
- Add `constrained_limits: Option<wgpu::Limits>` to `WgpuOptions`
- After maybe obtaining updated features and limits from the adapter/backend in the case of `WgpuOptionsPriority::Functionality`, enable the `WgpuOptions` `features`, disable the `disabled_features`, and constrain the `limits` by `constrained_limits`.
  - Note that constraining the limits means for `wgpu::Limits` members named `max_.*` we take the minimum of that which was configured/queried for the backend/adapter and the specified constrained limit value. This means the configured/queried value is used if the constrained limit is larger as that is as much as the device/API supports, or the constrained limit value is used if it is smaller as we are imposing an artificial constraint. For members named `min_.*` we take the maximum instead. For example, a minimum stride might be 256 but we set constrained limit value of 1024, then 1024 is the more conservative value. If the constrained limit value were 16, then 256 would be the more conservative.
2022-02-13 04:24:52 +00:00
dataphract
5bb4201f2e add informative panic message when adding render commands to a DrawFunctions that does not exist (#3924)
# Objective

If a user attempts to `.add_render_command::<P, C>()` on a world that does not contain `DrawFunctions<P>`, the engine panics with a generic `Option::unwrap` message:

```
thread 'main' panicked at 'called `Option::unwrap()` on a `None` value', /[redacted]/bevy/crates/bevy_render/src/render_phase/draw.rs:318:76
```

## Solution

This PR adds a panic message describing the problem:

```
thread 'main' panicked at 'DrawFunctions<outline::MeshStencil> must be added to the world as a resource before adding render commands to it', /[redacted]/bevy/crates/bevy_render/src/render_phase/draw.rs:322:17
```
2022-02-13 00:14:37 +00:00
Robert Swain
0ccb9dd07e bevy_render: Fix Quad flip (#3741)
# Objective

The documentation was unclear but it seemed like it was intended to _only_ flip the texture coordinates of the quad. However, it was also swapping the vertex positions, which resulted in inverted winding order so the front became a back face, and the normal was pointing into the face instead of out of it.

## Solution

- This change makes the only difference the UVs being horizontally flipped.
2022-02-12 00:46:04 +00:00
Loch Wansbrough
56b0e88b53 Add view transform to view uniform (#3885)
(cherry picked from commit de943381bd2a8b242c94db99e6c7bbd70006d7c3)

# Objective

The view uniform lacks view transform information. The inverse transform is currently provided but this is not sufficient if you do not have access to an `inverse` function (such as in WGSL).

## Solution

Grab the view transform, put it in the view uniform, use the same matrix to compute the inverse as well.
2022-02-08 04:14:34 +00:00
Daniel McNab
6615b7bf64 Deprecate .system (#3302)
# Objective

- Using `.system()` is no longer idiomatic.

## Solution

- Give a warning when using it
2022-02-08 04:00:58 +00:00
dataphract
f7478f448a doc: remove mention of void return type in entry_point docs (#3881)
# Objective

The docs for `{VertexState, FragmentState}::entry_point` stipulate that the entry point function in the shader must return void. This seems to be specific to GLSL; WGSL has no `void` type and its entry point functions return values that describe their output.

## Solution

Remove the mention of the `void` return type.
2022-02-07 22:07:43 +00:00
TheRawMeatball
865698548f Fix HDR asset support (#3795)
The HDR texture loader was never added to the app, this PR makes sure it is added when the relevant feature is enabled.
2022-02-04 21:22:12 +00:00
aloucks
1477765f62 Replace VSync with PresentMode (#3812)
# Objective

Enable the user to specify any presentation modes (including `Mailbox`).

Fixes #3807

## Solution

I've added a new `PresentMode` enum in `bevy_window` that mirrors the `wgpu` enum 1:1. Alternatively, I could add a new dependency on `wgpu-types` if that would be preferred.
2022-02-04 03:37:44 +00:00
Jakob Hellermann
b7dfe1677f include sources in shader validation error (#3724)
## Objective

When print shader validation error messages, we didn't print the sources and error message text, which led to some confusing error messages.

```cs
error: 
   ┌─ wgsl:15:11
   │
15 │     return material.color + 1u;
   │           ^^^^^^^^^^^^^^^^^^^^ naga::Expression [11]
```

## Solution

New error message:
```cs
error: Entry point fragment at Vertex is invalid
   ┌─ wgsl:15:11
   │
15 │     return material.color + 1u;
   │           ^^^^^^^^^^^^^^^^^^^^ naga::Expression [11]
   │
   = Expression [11] is invalid
   = Operation Add can't work with [8] and [10]
```
2022-02-04 03:37:38 +00:00
Boutillier
aa7b158893 Add a size method on Image. (#3696)
# Objective

Add a simple way for user to get the size of a loaded texture in an Image object.
Aims to solve #3689

## Solution

Add a `size() -> Vec2` method
Add two simple tests for this method.

Updates:
. method named changed from `size_2d` to `size`
2022-02-04 03:21:33 +00:00
Robert Swain
33ef5b5039 bevy_render: Only auto-disable mappable primary buffers for discrete GPUs (#3803)
# Objective

- While it is not safe to enable mappable primary buffers for all GPUs, it should be preferred for integrated GPUs where an integrated GPU is one that is sharing system memory.

## Solution

- Auto-disable mappable primary buffers only for discrete GPUs. If the GPU is integrated and mappable primary buffers are supported, use them.
2022-01-31 01:22:17 +00:00
sark
ca029ef0eb Naga export (#3714)
# Objective

In order to create a glsl shader, we must provide the `naga::ShaderStage` type which is not exported by bevy, meaning a user would have to manually include naga just to access this type.

`pub fn from_glsl(source: impl Into<Cow<'static, str>>, stage: naga::ShaderStage) -> Shader {`

## Solution

Re-rexport naga::ShaderStage from `render_resources`
2022-01-31 00:32:47 +00:00
François
cb2ba19d97 rename Texture to Image in doc of from_buffer function (#3713)
This doc link was missed when changing the type name.

Noticed in https://github.com/bevyengine/bevy/pull/3706 which will not be merged
2022-01-18 01:28:09 +00:00
Robert Swain
55da315432 bevy_render: Provide a way to opt-out of the built-in frustum culling (#3711)
# Objective

- Allow opting-out of the built-in frustum culling for cases where its behaviour would be incorrect
- Make use of the this in the shader_instancing example that uses a custom instancing method. The built-in frustum culling breaks the custom instancing in the shader_instancing example if the camera is moved to:

```rust
    commands.spawn_bundle(PerspectiveCameraBundle {
        transform: Transform::from_xyz(12.0, 0.0, 15.0)
            .looking_at(Vec3::new(12.0, 0.0, 0.0), Vec3::Y),
        ..Default::default()
    });
```

...such that the Aabb of the cube Mesh that is at the origin goes completely out of view. This incorrectly (for the purpose of the custom instancing) culls the `Mesh` and so culls all instances even though some may be visible.


## Solution

- Add a `NoFrustumCulling` marker component
- Do not compute and add an `Aabb` to `Mesh` entities without an `Aabb` if they have a `NoFrustumCulling` marker component
- Do not apply frustum culling to entities with the `NoFrustumCulling` marker component
2022-01-17 22:55:44 +00:00
Robert Swain
ef823d369f bevy_render: Do not automatically enable MAPPABLE_PRIMARY_BUFFERS (#3698)
# Objective

- When using `WgpuOptionsPriority::Functionality`, which is the default, wgpu::Features::MAPPABLE_PRIMARY_BUFFERS would be automatically enabled. This feature can and does have a significant negative impact on performance for discrete GPUs where resizable bar is not supported, which is a common case. As such, this feature should not be automatically enabled.
- Fixes the performance regression part of https://github.com/bevyengine/bevy/issues/3686 and at least some, if not all cases of https://github.com/bevyengine/bevy/issues/3687

## Solution

- When using `WgpuOptionsPriority::Functionality`, use the adapter-supported features, enable `TEXTURE_ADAPTER_SPECIFIC_FORMAT_FEATURES` and disable `MAPPABLE_PRIMARY_BUFFERS`
2022-01-17 22:03:14 +00:00
Linden Krouse
d11cd63452 Fixed doc comment with render Node input/output methods (#3642)
Fixed doc comment where render Node input/output methods refered to using `RenderContext` for interaction instead of `RenderGraphContext`

# Objective

The doc comments for `Node` refer to `RenderContext` for slots instead of `RenderGraphContext`, which is only confusing because `Node::run` is passed both `RenderContext` and `RenderGraphContext`

## Solution

Fixed the typo
2022-01-17 20:44:22 +00:00
Wybe Westra
3fcdc5a492 Expanded Msaa documentation. (#3693)
- Added default value.
- Links to the explanation of Msaa on wikipedia.
- Added a short example to show how to use the struct on an app.

Fixes #3167.
2022-01-16 21:09:15 +00:00
Pascal Hertleif
bc499591c2 Use use instead of lots of full paths (#3564)
Super tiny thing. Found this while reviewing #3479.

# Objective

- Simplify code
- Fix the link in the doc comment

## Solution

- Import a single item :)


Co-authored-by: Pascal Hertleif <pascal@technocreatives.com>
2022-01-11 01:08:39 +00:00
Michael Dorst
130953c717 Enable the doc_markdown clippy lint (#3457)
# Objective

CI should check for missing backticks in doc comments.

Fixes #3435

## Solution

`clippy` has a lint for this: `doc_markdown`. This enables that lint in the CI script.

Of course, enabling this lint in CI causes a bunch of lint errors, so I've gone through and fixed all of them. This was a huge edit that touched a ton of files, so I split the PR up by crate.

When all of the following are merged, the CI should pass and this can be merged.

+ [x] #3467
+ [x] #3468
+ [x] #3470 
+ [x] #3469
+ [x] #3471 
+ [x] #3472 
+ [x] #3473 
+ [x] #3474 
+ [x] #3475 
+ [x] #3476 
+ [x] #3477 
+ [x] #3478 
+ [x] #3479 
+ [x] #3480 
+ [x] #3481 
+ [x] #3482 
+ [x] #3483 
+ [x] #3484 
+ [x] #3485 
+ [x] #3486
2022-01-09 23:20:13 +00:00
François
600ee7eee6 support all line endings in shader preprocessor (#3603)
# Objective

- Advance uses of shaders seems to often fail for Windows users
- Bevy split lines on `'\n'` which messes with windows line endings

## Solution

- Uses Rust built in https://doc.rust-lang.org/std/primitive.str.html#method.lines
2022-01-09 18:52:18 +00:00
Michael Dorst
e56685370b Fix doc_markdown lints in bevy_render (#3479)
#3457 adds the `doc_markdown` clippy lint, which checks doc comments to make sure code identifiers are escaped with backticks. This causes a lot of lint errors, so this is one of a number of PR's that will fix those lint errors one crate at a time.

This PR fixes lints in the `bevy_render` crate.
2022-01-09 11:09:46 +00:00
Hennadii Chernyshchyk
458cb7a9e9 Add headless mode (#3439)
# Objective

In this PR I added the ability to opt-out graphical backends. Closes #3155.

## Solution

I turned backends into `Option` ~~and removed panicking sub app API to force users handle the error (was suggested by `@cart`)~~.
2022-01-08 10:39:43 +00:00
Carter Anderson
2ee38cb9e0 Release 0.6.0 (#3587) 2022-01-08 10:18:22 +00:00
davier
c2da7800e3 Add 2d meshes and materials (#3460)
# Objective

The current 2d rendering is specialized to render sprites, we need a generic way to render 2d items, using meshes and materials like we have for 3d.

## Solution

I cloned a good part of `bevy_pbr` into `bevy_sprite/src/mesh2d`, removed lighting and pbr itself, adapted it to 2d rendering, added a `ColorMaterial`, and modified the sprite rendering to break batches around 2d meshes.

~~The PR is a bit crude; I tried to change as little as I could in both the parts copied from 3d and the current sprite rendering to make reviewing easier. In the future, I expect we could make the sprite rendering a normal 2d material, cleanly integrated with the rest.~~ _edit: see <https://github.com/bevyengine/bevy/pull/3460#issuecomment-1003605194>_

## Remaining work

- ~~don't require mesh normals~~ _out of scope_
- ~~add an example~~ _done_
- support 2d meshes & materials in the UI?
- bikeshed names (I didn't think hard about naming, please check if it's fine)

## Remaining questions

- ~~should we add a depth buffer to 2d now that there are 2d meshes?~~ _let's revisit that when we have an opaque render phase_
- ~~should we add MSAA support to the sprites, or remove it from the 2d meshes?~~ _I added MSAA to sprites since it's really needed for 2d meshes_
- ~~how to customize vertex attributes?~~ _#3120_



Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2022-01-08 01:29:08 +00:00
Niklas Eicker
fbab01a40d Add missing closing ticks for inline examples and some cleanup (#3573)
# Objective

- clean up documentation and inline examples

## Solution

- add missing closing "```"
- remove stray "```"
- remove whitespace in inline examples
- unify inline examples (remove some `rust` labels)
2022-01-07 09:25:12 +00:00
yetanothercheer
fda0b2c911 Fix typo (#3578) 2022-01-07 06:25:38 +00:00
TheRawMeatball
f3fba09615 Add MapMode to wgpu reexports (#3558)
This type can be needed by API s on other reexported types, so it should be included too
2022-01-05 19:19:22 +00:00
Rob Parrett
24b21ea35e Fix torus normals (#3549)
# Objective

Fixes #3547 

## Solution

Normal calc adapted from https://web.cs.ucdavis.edu/~amenta/s12/findnorm.pdf

## Before
<img width="1392" alt="before" src="https://user-images.githubusercontent.com/200550/148125212-fb1c083e-3c57-4330-a656-df34513c36ab.png">

## After
<img width="1392" alt="after" src="https://user-images.githubusercontent.com/200550/148125223-174dc956-37df-4ac2-8983-b18e1e2a9a7d.png">

I'm assuming that the greyness and the self-shadowing artifacts are... normal for the new renderer.
2022-01-04 21:30:46 +00:00
Robert Swain
b9c623e4f3 Configurable wgpu features/limits priority (#3452)
# Objective

- Allow the user to specify the priority when configuring wgpu features/limits and by default use the maximum capabilities of the chosen adapter.

## Solution

- Add a `WgpuOptionsPriority` enum with `Compatibility`, `Functionality` and `WebGL2` options.
- Add a `priority: WgpuOptionsPriority` member to `WgpuOptions`.
- When initialising the renderer, if `WgpuOptions::priority == WgpuOptionsPriority::Functionality`, query the adapter for the available features and limits, use them when creating a device, and update `WgpuOptions` with those values. If `Compatibility` use the behaviour as before this PR. If `WebGL2` then use the WebGL2 downlevel limits as used when when building for wasm, for convenience of testing WebGL2 limits without having to build for wasm.
- Add an environment variable `WGPU_OPTIONS_PRIO` that takes `compatibility`, `functionality`, `webgl2`.
- Default to `WgpuOptionsPriority::Functionality`.
- Insert updated `WgpuOptions` into render app world as well. This is useful for applying the limits when rendering, such as limiting the directional light shadow map texture to 2048x2048 when using WebGL2 downlevel limits but not on wasm.
- Reduced `draw_state` logs from `debug` to `trace` and added `debug` level logs for the wgpu features and limits. Use `RUST_LOG=bevy_render=debug` to see the output.
2022-01-04 20:08:12 +00:00
yetanothercheer
1bae879bf3 Fix typo (#3538) 2022-01-03 08:51:44 +00:00
Robert Swain
85b7589388 bevy_gltf: Add support for loading lights (#3506)
# Objective

- Add support for loading lights from glTF 2.0 files

## Solution

- This adds support for the KHR_punctual_lights extension which supports point, directional, and spot lights, though we don't yet support spot lights.
- Inserting light bundles when creating scenes required registering some more light bundle component types.
2022-01-03 07:59:25 +00:00
James Liu
dc8fefe27f Remove Bytes, FromBytes, Labels, EntityLabels. Document rest of bevy_core and enable warning on missing docs. (#3521)
This PR is part of the issue #3492.

# Objective

 - Clean up dead code in `bevy_core`.
 - Add and update the `bevy_core` documentation to achieve a 100% documentation coverage.
 - Add the #![warn(missing_docs)] lint to keep the documentation coverage for the future.

# Solution

 - Remove unused `Bytes`, `FromBytes`, `Labels`, and `EntityLabels` types and associated systems.
 - Made several types private that really only have use as internal types, mostly pertaining to fixed timestep execution.
 - Add and update the bevy_core documentation.
 - Add the #![warn(missing_docs)] lint.

# Open Questions

Should more of the internal states of `FixedTimestep` be public? Seems mostly to be an implementation detail unless someone really needs that fixed timestep state.
2022-01-02 20:36:40 +00:00
Jerome Humbert
e43e36696d Minor docs edit/add in bevy_render (#3447)
# Objective

Docs updates.

## Solution

- Detail what `OrthographicCameraBundle::new_2d()` creates.
- Fix a few renamed parameters in comments of `TrackedRenderPass`.
- Add missing comments for viewport and debug markers.

Co-authored-by: Jerome Humbert <djeedai@gmail.com>
2022-01-02 17:40:03 +00:00
Minghao Liu
3ac55f0bcf load spirv using correct API (#3466)
# Objective

currently spirv source loading parse then desterilize it to make wgpu happy.

## Solution

Use the right API to get spirv
2021-12-30 19:55:01 +00:00
François
db68704231 Enable Msaa for webgl by default (#3489)
# Objective

- `Msaa` was disabled in webgl due to a bug in wgpu
- Bug has been fixed (https://github.com/gfx-rs/wgpu/pull/2307) and backported (https://github.com/gfx-rs/wgpu/pull/2327), and updates for [`wgpu-core`](https://crates.io/crates/wgpu-core/0.12.1) and [`wgpu-hal`](https://crates.io/crates/wgpu-hal/0.12.1) have been released

## Solution

- Remove custom config for `Msaa` in webgl
- I also changed two options that were using the arch instead of the `webgl` feature. it shouldn't change much for webgl, but could help if someone wants to target wasm but not webgl2


Co-authored-by: François <8672791+mockersf@users.noreply.github.com>
2021-12-29 21:04:28 +00:00
Jakob Hellermann
66b517ef81 fix shader compilation error reporting for non-wgsl shaders (#3441)
in #3289 I accidentally only logged errors for wgsl shaders, this PR expands the error reporting the the other supported shader types.
2021-12-29 21:04:27 +00:00
davier
06d9384447 Add FromReflect trait to convert dynamic types to concrete types (#1395)
Dynamic types (`DynamicStruct`, `DynamicTupleStruct`, `DynamicTuple`, `DynamicList` and `DynamicMap`) are used when deserializing scenes, but currently they can only be applied to existing concrete types. This leads to issues when trying to spawn non trivial deserialized scene.
For components, the issue is avoided by requiring that reflected components implement ~~`FromResources`~~ `FromWorld` (or `Default`). When spawning, a new concrete type is created that way, and the dynamic type is applied to it. Unfortunately, some components don't have any valid implementation of these traits.
In addition, any `Vec` or `HashMap` inside a component will panic when a dynamic type is pushed into it (for instance, `Text` panics when adding a text section).

To solve this issue, this PR adds the `FromReflect` trait that creates a concrete type from a dynamic type that represent it, derives the trait alongside the `Reflect` trait, drops the ~~`FromResources`~~ `FromWorld` requirement on reflected components, ~~and enables reflection for UI and Text bundles~~. It also adds the requirement that fields ignored with `#[reflect(ignore)]` implement `Default`, since we need to initialize them somehow.

Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2021-12-26 18:49:01 +00:00
François
22c665fa39 re-export BufferBinding and BufferDescriptor (#3429)
# Objective

- I want to port `bevy_egui` to Bevy main and only reuse re-exports from Bevy

## Solution

- Add exports for `BufferBinding` and `BufferDescriptor`


Co-authored-by: François <8672791+mockersf@users.noreply.github.com>
2021-12-24 16:53:49 +00:00
davier
76ec709ede Add Visibility component to UI (#3426)
# Objective

Fixes #3422 

## Solution

Adds the existing `Visibility` component to UI bundles and checks for it in the extract phase of the render app.

The `ComputedVisibility` component was not added. I don't think the UI camera needs frustum culling, but having `RenderLayers` work may be desirable. However I think we would need to change `check_visibility()` to differentiate between 2d, 3d and UI entities.
2021-12-24 07:10:12 +00:00
Jakob Hellermann
adb3ad399c make sub_app return an &App and add sub_app_mut() -> &mut App (#3309)
It's sometimes useful to have a reference to an app a sub app at the same time, which is only possible with an immutable reference.
2021-12-24 06:57:30 +00:00
François
79d36e7c28 Prepare crevice for vendored release (#3394)
# Objective

- Our crevice is still called "crevice", which we can't use for a release
- Users would need to use our "crevice" directly to be able to use the derive macro

## Solution

- Rename crevice to bevy_crevice, and crevice-derive to bevy-crevice-derive
- Re-export it from bevy_render, and use it from bevy_render everywhere
- Fix derive macro to work either from bevy_render, from bevy_crevice, or from bevy

## Remaining

- It is currently re-exported as `bevy::render::bevy_crevice`, is it the path we want?
- After a brief suggestion to Cart, I changed the version to follow Bevy version instead of crevice, do we want that?
- Crevice README.md need to be updated
- in the `Cargo.toml`, there are a few things to change. How do we want to change them? How do we keep attributions to original Crevice?
```
authors = ["Lucien Greathouse <me@lpghatguy.com>"]
documentation = "https://docs.rs/crevice"
homepage = "https://github.com/LPGhatguy/crevice"
repository = "https://github.com/LPGhatguy/crevice"
```


Co-authored-by: François <8672791+mockersf@users.noreply.github.com>
Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2021-12-23 22:49:12 +00:00
Nicola Papale
035ec7b763 Implement non-indexed mesh rendering (#3415)
# Objective

Instead of panicking when the `indices` field of a mesh is `None`, actually manage it.

This is just a question of keeping track of the vertex buffer size.

## Notes

* Relying on this change to improve performance on [bevy_debug_lines using the new renderer](https://github.com/Toqozz/bevy_debug_lines/pull/10)
* I'm still new to rendering, my only expertise with wgpu is the learn-wgpu tutorial, likely I'm overlooking something.
2021-12-23 19:19:13 +00:00
Jakob Hellermann
081350916c report shader processing errors in RenderPipelineCache (#3289)
### Problem
- shader processing errors are not displayed
- during hot reloading when encountering a shader with errors, the whole app crashes

### Solution
- log `error!`s for shader processing errors 
- when `cfg(debug_assertions)` is enabled (i.e. you're running in `debug` mode), parse shaders before passing them to wgpu. This lets us handle errors early.
2021-12-22 22:16:42 +00:00
François
6c479649bf enable Webgl2 optimisation in pbr under feature (#3291)
# Objective

- 3d examples fail to run in webgl2 because of unsupported texture formats or texture too large

## Solution

- switch to supported formats if a feature is enabled. I choose a feature instead of a build target to not conflict with a potential webgpu support

Very inspired by 6813b2edc5, and need #3290 to work.

I named the feature `webgl2`, but it's only needed if one want to use PBR in webgl2. Examples using only 2D already work.

Co-authored-by: François <8672791+mockersf@users.noreply.github.com>
2021-12-22 20:59:48 +00:00
François
a3c53e689d Shader Processor: process imported shader (#3290)
# Objective

- I want to be able to use `#ifdef` and other processor directives in an imported shader

## Solution

- Process imported shader strings


Co-authored-by: François <8672791+mockersf@users.noreply.github.com>
2021-12-22 01:01:39 +00:00
aloucks
c04dfc1174 Add some of the missing methods to TrackedRenderPass (#3401)
# Objective

Add missing methods to `TrackedRenderPass`

- `set_push_constants`
- `set_viewport`
- `insert_debug_marker`
- `push_debug_group`
- `pop_debug_group`
- `set_blend_constant`

https://docs.rs/wgpu/0.12.0/wgpu/struct.RenderPass.html

I need `set_push_constants` but started adding the others as I noticed they were also missing. The `draw indirect` family of methods are still missing as are the `timestamp query` methods.
2021-12-20 23:16:54 +00:00
François
c61fbcb7db Only bevy_render should depend directly on wgpu (#3393)
# Objective

- Only bevy_render should depend directly on wgpu
- This helps to make sure bevy_render re-exports everything needed from wgpu

## Solution

- Remove bevy_pbr, bevy_sprite and bevy_ui dependency on wgpu


Co-authored-by: François <8672791+mockersf@users.noreply.github.com>
2021-12-20 20:50:52 +00:00
Vabka
9a89295a17 Update wgpu to 0.12 and naga to 0.8 (#3375)
# Objective

Fixes #3352
Fixes #3208

## Solution

- Update wgpu to 0.12
- Update naga to 0.8
- Resolve compilation errors
- Remove [[block]] from WGSL shaders (because it is depracated and now wgpu cant parse it)
- Replace `elseif` with `else if` in pbr.wgsl
2021-12-19 03:03:06 +00:00
Dusty DeWeese
73f524f61c Support topologies other than TriangleList (#3349)
# Objective

Fixes https://github.com/bevyengine/bevy/issues/3346

## Solution

I've encoded the topology in the `MeshKey` similar to how MSAA samples are handled.
2021-12-18 20:55:40 +00:00
Daniel McNab
ed9d45fae5 Add an example 'showcasing' using multiple windows (#3367)
# Objective

- The multiple windows example which was viciously murdered in #3175.
- cart asked me to

## Solution

- Rework the example to work on pipelined-rendering, based on the work from #2898
2021-12-18 19:38:05 +00:00
François
6a0008f3d3 Fix doc warnings (#3339)
# Objective

- There are a few warnings when building Bevy docs for dead links
- CI seems to not catch those warnings when it should

## Solution

- Enable doc CI on all Bevy workspace
- Fix warnings
- Also noticed plugin GilrsPlugin was not added anymore when feature was enabled


First commit to check that CI would actually fail with it: https://github.com/bevyengine/bevy/runs/4532652688?check_suite_focus=true

Co-authored-by: François <8672791+mockersf@users.noreply.github.com>
2021-12-18 00:09:23 +00:00
John
9a16a4d018 Added set_scissor_rect to tracked render pass. (#3320)
# Objective And Solution
Add `set_scissor_rect` from wgpu-rs to the `TrackedRenderPass`. wgpu documentation can be found here:
https://docs.rs/wgpu/latest/wgpu/struct.RenderPass.html#method.set_scissor_rect

The reason for adding this is to cull fragments that are outside of the given rect. For my purposes this is extremely useful for UI.
2021-12-17 22:26:59 +00:00
Carter Anderson
ffecb05a0a Replace old renderer with new renderer (#3312)
This makes the [New Bevy Renderer](#2535) the default (and only) renderer. The new renderer isn't _quite_ ready for the final release yet, but I want as many people as possible to start testing it so we can identify bugs and address feedback prior to release.

The examples are all ported over and operational with a few exceptions:

* I removed a good portion of the examples in the `shader` folder. We still have some work to do in order to make these examples possible / ergonomic / worthwhile: #3120 and "high level shader material plugins" are the big ones. This is a temporary measure.
* Temporarily removed the multiple_windows example: doing this properly in the new renderer will require the upcoming "render targets" changes. Same goes for the render_to_texture example.
* Removed z_sort_debug: entity visibility sort info is no longer available in app logic. we could do this on the "render app" side, but i dont consider it a priority.
2021-12-14 03:58:23 +00:00
Aevyrie
38c7d5eb9e Check for NaN in Camera::world_to_screen() (#3268)
# Objective

- Checks for NaN in computed NDC space coordinates, fixing unexpected NaN in a fallible (`Option<T>`) function.

## Solution

- Adds a NaN check, in addition to the existing NDC bounds checks.
- This is a helper function, and should have no performance impact to the engine itself.
- This will help prevent hard-to-trace NaN propagation in user code, by returning `None` instead of `Some(NaN)`.


Depends on https://github.com/bevyengine/bevy/pull/3269 for CI error fix.
2021-12-08 01:31:31 +00:00
Rostyslav Toch
a4e85536c1 Fix clippy errors related to IntoIter::new (#3269)
# Objective

Fixes recent pipeline errors:
```
error: use of deprecated associated function `std::array::IntoIter::<T, N>::new`: use `IntoIterator::into_iter` instead
   --> crates/bevy_render/src/mesh/mesh.rs:467:54
    |
467 |             .flat_map(|normal| std::array::IntoIter::new([normal, normal, normal]))
    |                                                      ^^^
    |
    = note: `-D deprecated` implied by `-D warnings`

   Compiling bevy_render2 v0.5.0 (/home/runner/work/bevy/bevy/pipelined/bevy_render2)
error: use of deprecated associated function `std::array::IntoIter::<T, N>::new`: use `IntoIterator::into_iter` instead
   --> pipelined/bevy_render2/src/mesh/mesh/mod.rs:287:54
    |
287 |             .flat_map(|normal| std::array::IntoIter::new([normal, normal, normal]))
    |                                                      ^^^
    |
    = note: `-D deprecated` implied by `-D warnings`

error: could not compile `bevy_render` due to previous error
```

## Solution

- Replaced `IntoIter::new` with `IntoIterator::into_iter`

## Suggestions

For me it looks like two equivalent `Mesh` structs with the same methods. Should we refactor it? Or, they will be different in the near future?


Co-authored-by: CrazyRoka <rokarostuk@gmail.com>
2021-12-06 22:26:35 +00:00
François
c6fec1f0c2 Fix clippy lints for 1.57 (#3238)
# Objective

- New clippy lints with rust 1.57 are failing

## Solution

- Fixed clippy lints following suggestions
- I ignored clippy in old renderer because there was many and it will be removed soon
2021-12-02 23:40:37 +00:00
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
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
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
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
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
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
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
Carter Anderson
11b41206eb Add upstream bevy_ecs and prepare for custom-shaders merge (#2815)
This updates the `pipelined-rendering` branch to use the latest `bevy_ecs` from `main`. This accomplishes a couple of goals:

1. prepares for upcoming `custom-shaders` branch changes, which were what drove many of the recent bevy_ecs changes on `main`
2. prepares for the soon-to-happen merge of `pipelined-rendering` into `main`. By including bevy_ecs changes now, we make that merge simpler / easier to review. 

I split this up into 3 commits:

1. **add upstream bevy_ecs**: please don't bother reviewing this content. it has already received thorough review on `main` and is a literal copy/paste of the relevant folders (the old folders were deleted so the directories are literally exactly the same as `main`).
2. **support manual buffer application in stages**: this is used to enable the Extract step. we've already reviewed this once on the `pipelined-rendering` branch, but its worth looking at one more time in the new context of (1).
3. **support manual archetype updates in QueryState**: same situation as (2).
2021-09-14 06:14:19 +00:00
Johan Klokkhammer Helsing
dea292d199 Derive thiserror::Error for HexColorError (#2740)
# Objective

- Make it easy to use HexColorError with `thiserror`, i.e. converting it into other error types.

Makes this possible:

```rust
#[derive(Debug, thiserror::Error)]
pub enum LdtkError {
    #[error("An error occured while deserializing")]
    Json(#[from] serde_json::Error),
    #[error("An error occured while parsing a color")]
    HexColor(#[from] bevy::render::color::HexColorError),
}
```

## Solution

- Derive thiserror::Error the same way we do elsewhere (see query.rs for instance)
2021-08-30 21:56:13 +00:00
Carter Anderson
9d453530fa System Param Lifetime Split (#2605)
# Objective

Enable using exact World lifetimes during read-only access . This is motivated by the new renderer's need to allow read-only world-only queries to outlive the query itself (but still be constrained by the world lifetime).

For example:
115b170d1f/pipelined/bevy_pbr2/src/render/mod.rs (L774)

## Solution

Split out SystemParam state and world lifetimes and pipe those lifetimes up to read-only Query ops (and add into_inner for Res). According to every safety test I've run so far (except one), this is safe (see the temporary safety test commit). Note that changing the mutable variants to the new lifetimes would allow aliased mutable pointers (try doing that to see how it affects the temporary safety tests).

The new state lifetime on SystemParam does make `#[derive(SystemParam)]` more cumbersome (the current impl requires PhantomData if you don't use both lifetimes). We can make this better by detecting whether or not a lifetime is used in the derive and adjusting accordingly, but that should probably be done in its own pr.  

## Why is this a draft?

The new lifetimes break QuerySet safety in one very specific case (see the query_set system in system_safety_test). We need to solve this before we can use the lifetimes given.

This is due to the fact that QuerySet is just a wrapper over Query, which now relies on world lifetimes instead of `&self` lifetimes to prevent aliasing (but in systems, each Query has its own implied lifetime, not a centralized world lifetime).  I believe the fix is to rewrite QuerySet to have its own World lifetime (and own the internal reference). This will complicate the impl a bit, but I think it is doable. I'm curious if anyone else has better ideas.

Personally, I think these new lifetimes need to happen. We've gotta have a way to directly tie read-only World queries to the World lifetime. The new renderer is the first place this has come up, but I doubt it will be the last. Worst case scenario we can come up with a second `WorldLifetimeQuery<Q, F = ()>` parameter to enable these read-only scenarios, but I'd rather not add another type to the type zoo.
2021-08-15 20:51:53 +00:00
Carter Anderson
a89a954a17 Not me ... us (#2654)
I don't see much of a reason at this point to boost my name over anyone elses. We are all Bevy Contributors.
2021-08-15 20:08:52 +00:00
Isaak Eriksson
5eeba1556d Better error message for unsupported shader features Fixes #869 (#2598)
# Objective

- Provides more useful error messages when using unsupported shader features.

## Solution Fixes #869

- Provided a error message as follows (adding name, set and binding): 
```
Unsupported shader bind type CombinedImageSampler (name noiseVol0, set 0, binding 9)
```
2021-08-13 22:21:33 +00:00
Boxy
0b800e547b Fix some nightly clippy lints (#2522)
on nightly these two clippy lints fail:
- [needless_borrow](https://rust-lang.github.io/rust-clippy/master/#needless_borrow)
- [unused_unit](https://rust-lang.github.io/rust-clippy/master/#unused_unit)
2021-07-29 19:36:39 -07:00
Boxy
5ffff03b33 Fix some nightly clippy lints (#2522)
on nightly these two clippy lints fail:
- [needless_borrow](https://rust-lang.github.io/rust-clippy/master/#needless_borrow)
- [unused_unit](https://rust-lang.github.io/rust-clippy/master/#unused_unit)
2021-07-29 20:52:15 +00:00
François
b724a0f586 Down with the system! (#2496)
# Objective

- Remove all the `.system()` possible.
- Check for remaining missing cases.

## Solution

- Remove all `.system()`, fix compile errors
- 32 calls to `.system()` remains, mostly internals, the few others should be removed after #2446
2021-07-27 23:42:36 +00:00
bjorn3
6d6bc2a8b4 Merge AppBuilder into App (#2531)
This is extracted out of eb8f973646476b4a4926ba644a77e2b3a5772159 and includes some additional changes to remove all references to AppBuilder and fix examples that still used App::build() instead of App::new(). In addition I didn't extract the sub app feature as it isn't ready yet.

You can use `git diff --diff-filter=M eb8f973646476b4a4926ba644a77e2b3a5772159` to find all differences in this PR. The `--diff-filtered=M` filters all files added in the original commit but not in this commit away.

Co-Authored-By: Carter Anderson <mcanders1@gmail.com>
2021-07-27 20:21:06 +00:00
Carter Anderson
13ca00178a bevy_render now uses wgpu directly 2021-07-24 16:43:37 -07:00
Carter Anderson
3400fb4e61 SubGraphs, Views, Shadows, and more 2021-07-24 16:43:37 -07:00
Carter Anderson
4ac2ed7cc6 pipelined rendering proof of concept 2021-07-24 16:43:37 -07:00
Carter Anderson
e167a1d9cf Relicense Bevy under the dual MIT or Apache-2.0 license (#2509)
This relicenses Bevy under the dual MIT or Apache-2.0 license. For rationale, see #2373.

* Changes the LICENSE file to describe the dual license. Moved the MIT license to docs/LICENSE-MIT. Added the Apache-2.0 license to docs/LICENSE-APACHE. I opted for this approach over dumping both license files at the root (the more common approach) for a number of reasons:
  * Github links to the "first" license file (LICENSE-APACHE) in its license links (you can see this in the wgpu and rust-analyzer repos). People clicking these links might erroneously think that the apache license is the only option. Rust and Amethyst both use COPYRIGHT or COPYING files to solve this problem, but this creates more file noise (if you do everything at the root) and the naming feels way less intuitive. 
  * People have a reflex to look for a LICENSE file. By providing a single license file at the root, we make it easy for them to understand our licensing approach. 
  * I like keeping the root clean and noise free
  * There is precedent for putting the apache and mit license text in sub folders (amethyst) 
* Removed the `Copyright (c) 2020 Carter Anderson` copyright notice from the MIT license. I don't care about this attribution, it might make license compliance more difficult in some cases, and it didn't properly attribute other contributors. We shoudn't replace it with something like "Copyright (c) 2021 Bevy Contributors" because "Bevy Contributors" is not a legal entity. Instead, we just won't include the copyright line (which has precedent ... Rust also uses this approach).
* Updates crates to use the new "MIT OR Apache-2.0" license value
* Removes the old legion-transform license file from bevy_transform. bevy_transform has been its own, fully custom implementation for a long time and that license no longer applies.
* Added a License section to the main readme
* Updated our Bevy Plugin licensing guidelines.

As a follow-up we should update the website to properly describe the new license.

Closes #2373
2021-07-23 21:11:51 +00:00
bjorn3
fbf561c2bb Update minimal version requirements for dependencies (#2460)
This was tested using cargo generate-lockfile -Zminimal-versions.
The following indirect dependencies also have minimal version
dependencies. For at least num, rustc-serialize and rand this is
necessary to compile on rustc versions that are not older than 1.0.

* num = "0.1.27"
* rustc-serialize = "0.3.20"
* termcolor = "1.0.4"
* libudev-sys = "0.1.1"
* rand = "0.3.14"
* ab_glyph = "0.2.7

Based on https://github.com/bevyengine/bevy/pull/2455
2021-07-15 21:25:49 +00:00
bjorn3
ebd10681ac Remove unused deps (#2455)
# Objective

Reduce compilation time

# Solution

Remove unused dependencies. While this PR doesn't remove any crates from `Cargo.lock`, it may unlock more build parallelism.
2021-07-14 20:52:50 +00:00
andoco
941a8fb8a3 Fix unsetting RenderLayers bit in without fn (#2409)
# Objective

Fixes how the layer bit is unset in the RenderLayers bit mask when calling the `without` method.

## Solution

Unsets the layer bit using `&=` and the inverse of the layer bit mask.
2021-07-01 20:41:40 +00:00
Patrik Buhring
7602317087 Update hexasphere to 4.0.0. (#2390)
# Objective

- Update `hexasphere` to 4.0.0, which is now licensed with dual MIT/Apache-2.0.
2021-06-25 00:35:41 +00:00
Nathan Ward
00d8d5d5a0 fix clippy warning failing on CI (#2353)
# Objective

- CI jobs are starting to fail due to `clippy::bool-assert-comparison` and `clippy::single_component_path_imports` being triggered.

## Solution

- Fix all uses where `asset_eq!(<condition>, <bool>)` could be replace by `assert!`
- Move the `#[allow()]` for `single_component_path_imports` to `#![allow()]` at the start of the files.
2021-06-18 00:08:39 +00:00
Callum Tolley
a40ec1c6b6 Add minimum sizes to textures to prevent crash (#2300)
# Objective
- Fixes #2299

## Solution
- Ensures that textures are never requested with 0 height/width.
2021-06-09 18:07:40 +00:00
François
c2722f713a expose texture/image conversions as From/TryFrom (#2175)
fixes #2169 

Instead of having custom methods with reduced visibility, implement `From<image::DynamicImage> for Texture` and `TryFrom<Texture> for image::DynamicImage`
2021-06-08 02:26:51 +00:00
Yoh Deadfall
a404eb2acf Removed redundant visibility check (#2311)
Since `visible_entities_system` already checks `Visiblie::is_visible` for each entity and requires it to be `true`, there's no reason to verify visibility in `PassNode::prepare` which consumes entities produced by the system.
2021-06-07 19:02:02 +00:00
MinerSebas
4fed2ee858 Use cfg attribute to filter supported extensions (#2297)
When implementing `AssetLoader ` you need to specify which File extensions are supported by that loader.
Currently, Bevy always says it supports extensions that actually require activating a Feature beforehand.

This PR adds cf attributes, so Bevy only tries to load those Extensions whose Features were activated.

This prevents Bevy from Panicking and reports such a warning:
```
Jun 02 23:05:57.139  WARN bevy_asset::asset_server: no `AssetLoader` found for the following extension: ogg
```

This also fixes the Bug, that the `png Feature had to be activated even if you wanted to load a different image format.

Fixes #640
2021-06-03 19:58:08 +00:00
Nathan Ward
173bb48d78 Refactor ResMut/Mut/ReflectMut to remove duplicated code (#2217)
`ResMut`, `Mut` and `ReflectMut` all share very similar code for change detection.
This PR is a first pass at refactoring these implementation and removing a lot of the duplicated code.

Note, this introduces a new trait `ChangeDetectable`.

Please feel free to comment away and let me know what you think!
2021-05-30 19:29:31 +00:00
Jonathan Behrens
4b1d47da99 Enable downcasting of RenderContext (#2240)
Related to https://github.com/bevyengine/bevy/discussions/2210. This may make it possible to have external `wgpu` libraries work with `bevy`.
2021-05-24 19:38:33 +00:00
Yoh Deadfall
653c10371e Use bevy_reflect as path in case of no direct references (#1875)
Fixes #1844


Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2021-05-19 19:03:36 +00:00
Nathan Ward
4563e69e06 Update glam (0.15.1) and hexasphere (3.4) (#2199)
This is a version of #2195 which addresses the `glam` breaking changes.
Also update hexasphere to ensure versions of `glam` are matching
2021-05-18 18:56:15 +00:00
Paweł Grabarz
189df30a83 use bytemuck crate instead of Byteable trait (#2183)
This gets rid of multiple unsafe blocks that we had to maintain ourselves, and instead depends on library that's commonly used and supported by the ecosystem. We also get support for glam types for free.

There is still some things to clear up with the `Bytes` trait, but that is a bit more substantial change and can be done separately. Also there are already separate efforts to use `crevice` crate, so I've just added that as a TODO.
2021-05-17 22:29:10 +00:00
Jonas Matser
d1f40148fd Allows a number of clippy lints and fixes 2 (#1999)
Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2021-05-14 20:37:32 +00:00
Jonas Matser
bfd15d2d4b Fixes incorrect PipelineCompiler::compile_pipeline() step_mode (#2126)
There's what might be considered a proper bug in `PipelineCompiler::compile_pipeline()`, where it overwrites the `step_mode` for the passed in `VertexBufferLayout` with `InputStepMode::Vertex`. Due to this some ugly workarounds are needed to do any kind of instancing.

In the somewhat longer term, `PipelineCompiler::compile_pipeline()` should probably also handle a `Vec<VertexBufferLayout>`, but that would be a (slightly) larger PR, rather than a bugfix. And I'd love to have this fix in sooner than we can deal with a bigger PR.

Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2021-05-07 00:28:35 +00:00
Felipe Jorge
41d9122740 Mesh vertex attributes for skinning and animation (#1831)
Required by #1429,

- Adds the `Ushort4` vertex attribute for joint indices
- `Mesh::ATTRIBUTE_JOINT_WEIGHT` and `Mesh::ATTRIBUTE_JOINT_INDEX` to import vertex attributes related to skinning from GLTF
- impl `Default` for `Mesh` a empty triangle mesh is created (needed by reflect)
- impl `Reflect` for `Mesh` all attributes are ignored (needed by the animation system)
2021-05-06 03:31:20 +00:00
Patrik Buhring
4e524841a1 Bump glam and hexasphere versions (#2111)
Also fixes typo "feautres" in smallvec dependency.
2021-05-06 00:41:18 +00:00
TheRawMeatball
81279f3090 Move to smallvec v1.6 (#2074) 2021-05-05 19:14:39 +00:00
François
afaf4ad3da update for wgpu 0.8 (#1959)
Changes to get Bevy to compile with wgpu master.

With this, on a Mac:
* 2d examples look fine
* ~~3d examples crash with an error specific to metal about a compilation error~~
* 3d examples work fine after enabling feature `wgpu/cross`


Feature `wgpu/cross` seems to be needed only on some platforms, not sure how to know which. It was introduced in https://github.com/gfx-rs/wgpu-rs/pull/826
2021-05-02 20:45:25 +00:00
bjorn3
3af3334cfe Various cleanups (#2046)
This includes a few safety improvements and a variety of other cleanups. See the individual commits.
2021-05-01 20:07:06 +00:00
Nathan Ward
b07db8462f Bevy derives handling generics in impl definitions. (#2044)
Fixes #2037 (and then some)

Problem:
- `TypeUuid`, `RenderResource`, and `Bytes` derive macros did not properly handle generic structs. 

Solution:
- Rework the derive macro implementations to handle the generics.
2021-05-01 02:57:20 +00:00
TehPers
cf40f4ab08 Fix mesh with no vertex attributes causing panic (#2036)
If a mesh without any vertex attributes is rendered (for example, one that only has indices), bevy will crash since the mesh still creates a vertex buffer even though it's empty. Later code assumes that there is vertex data, causing an index-out-of-bounds panic. This PR fixes the issue by adding a check that there is any vertex data before creating a vertex buffer.

I ran into this issue while rendering a tilemap without any vertex attributes (only indices).

Stack trace:
```
thread 'main' panicked at 'index out of bounds: the len is 0 but the index is 0', C:\Dev\Games\bevy\crates\bevy_render\src\render_graph\nodes\pass_node.rs:346:9
stack backtrace:
   0: std::panicking::begin_panic_handler
             at /rustc/bb491ed23937aef876622e4beb68ae95938b3bf9\/library\std\src\panicking.rs:493
   1: core::panicking::panic_fmt
             at /rustc/bb491ed23937aef876622e4beb68ae95938b3bf9\/library\core\src\panicking.rs:92
   2: core::panicking::panic_bounds_check
             at /rustc/bb491ed23937aef876622e4beb68ae95938b3bf9\/library\core\src\panicking.rs:69
   3: core::slice::index::{{impl}}::index<core::option::Option<tuple<bevy_render::renderer::render_resource::buffer::BufferId, u64>>>
             at C:\Users\tehpe\.rustup\toolchains\nightly-x86_64-pc-windows-msvc\lib\rustlib\src\rust\library\core\src\slice\index.rs:184
   4: core::slice::index::{{impl}}::index<core::option::Option<tuple<bevy_render::renderer::render_resource::buffer::BufferId, u64>>,usize>
             at C:\Users\tehpe\.rustup\toolchains\nightly-x86_64-pc-windows-msvc\lib\rustlib\src\rust\library\core\src\slice\index.rs:15
   5: alloc::vec::{{impl}}::index<core::option::Option<tuple<bevy_render::renderer::render_resource::buffer::BufferId, u64>>,usize,alloc::alloc::Global>
             at C:\Users\tehpe\.rustup\toolchains\nightly-x86_64-pc-windows-msvc\lib\rustlib\src\rust\library\alloc\src\vec\mod.rs:2386
   6: bevy_render::render_graph::nodes::pass_node::DrawState::is_vertex_buffer_set
             at C:\Dev\Games\bevy\crates\bevy_render\src\render_graph\nodes\pass_node.rs:346
   7: bevy_render::render_graph::nodes::pass_node::{{impl}}::update::{{closure}}<bevy_render::render_graph::base::MainPass*>
             at C:\Dev\Games\bevy\crates\bevy_render\src\render_graph\nodes\pass_node.rs:285
   8: bevy_wgpu::renderer::wgpu_render_context::{{impl}}::begin_pass
             at C:\Dev\Games\bevy\crates\bevy_wgpu\src\renderer\wgpu_render_context.rs:196
   9: bevy_render::render_graph::nodes::pass_node::{{impl}}::update<bevy_render::render_graph::base::MainPass*>
             at C:\Dev\Games\bevy\crates\bevy_render\src\render_graph\nodes\pass_node.rs:244
  10: bevy_wgpu::renderer::wgpu_render_graph_executor::WgpuRenderGraphExecutor::execute
             at C:\Dev\Games\bevy\crates\bevy_wgpu\src\renderer\wgpu_render_graph_executor.rs:75
  11: bevy_wgpu::wgpu_renderer::{{impl}}::run_graph::{{closure}}
             at C:\Dev\Games\bevy\crates\bevy_wgpu\src\wgpu_renderer.rs:115
  12: bevy_ecs::world::World::resource_scope<bevy_render::render_graph::graph::RenderGraph,tuple<>,closure-0>
             at C:\Dev\Games\bevy\crates\bevy_ecs\src\world\mod.rs:715
  13: bevy_wgpu::wgpu_renderer::WgpuRenderer::run_graph
             at C:\Dev\Games\bevy\crates\bevy_wgpu\src\wgpu_renderer.rs:104
  14: bevy_wgpu::wgpu_renderer::WgpuRenderer::update
             at C:\Dev\Games\bevy\crates\bevy_wgpu\src\wgpu_renderer.rs:121
  15: bevy_wgpu::get_wgpu_render_system::{{closure}}
             at C:\Dev\Games\bevy\crates\bevy_wgpu\src\lib.rs:112
  16: alloc::boxed::{{impl}}::call_mut<tuple<mut bevy_ecs::world::World*>,FnMut<tuple<mut bevy_ecs::world::World*>>,alloc::alloc::Global>
             at C:\Users\tehpe\.rustup\toolchains\nightly-x86_64-pc-windows-msvc\lib\rustlib\src\rust\library\alloc\src\boxed.rs:1553
  17: bevy_ecs::system::exclusive_system::{{impl}}::run
             at C:\Dev\Games\bevy\crates\bevy_ecs\src\system\exclusive_system.rs:41
  18: bevy_ecs::schedule::stage::{{impl}}::run
             at C:\Dev\Games\bevy\crates\bevy_ecs\src\schedule\stage.rs:812
  19: bevy_ecs::schedule::Schedule::run_once
             at C:\Dev\Games\bevy\crates\bevy_ecs\src\schedule\mod.rs:201
  20: bevy_ecs::schedule::{{impl}}::run
             at C:\Dev\Games\bevy\crates\bevy_ecs\src\schedule\mod.rs:219
  21: bevy_app::app::App::update
             at C:\Dev\Games\bevy\crates\bevy_app\src\app.rs:58
  22: bevy_winit::winit_runner_with::{{closure}}
             at C:\Dev\Games\bevy\crates\bevy_winit\src\lib.rs:485
  23: winit::platform_impl::platform::event_loop::{{impl}}::run_return::{{closure}}<tuple<>,closure-1>
             at C:\Users\tehpe\.cargo\registry\src\github.com-1ecc6299db9ec823\winit-0.24.0\src\platform_impl\windows\event_loop.rs:203
  24: alloc::boxed::{{impl}}::call_mut<tuple<winit::event::Event<tuple<>>, mut winit::event_loop::ControlFlow*>,FnMut<tuple<winit::event::Event<tuple<>>, mut winit::event_loop::ControlFlow*>>,alloc::alloc::Global>
             at C:\Users\tehpe\.rustup\toolchains\nightly-x86_64-pc-windows-msvc\lib\rustlib\src\rust\library\alloc\src\boxed.rs:1553
  25: winit::platform_impl::platform::event_loop:🏃:{{impl}}::call_event_handler::{{closure}}<tuple<>>
             at C:\Users\tehpe\.cargo\registry\src\github.com-1ecc6299db9ec823\winit-0.24.0\src\platform_impl\windows\event_loop\runner.rs:245
  26: std::panic::{{impl}}::call_once<tuple<>,closure-0>
             at C:\Users\tehpe\.rustup\toolchains\nightly-x86_64-pc-windows-msvc\lib\rustlib\src\rust\library\std\src\panic.rs:344
  27: std::panicking::try::do_call<std::panic::AssertUnwindSafe<closure-0>,tuple<>>
             at C:\Users\tehpe\.rustup\toolchains\nightly-x86_64-pc-windows-msvc\lib\rustlib\src\rust\library\std\src\panicking.rs:379
  28: hashbrown::set::HashSet<mut winapi::shared::windef::HWND__*, std::collections:#️⃣:map::RandomState, alloc::alloc::Global>::iter<mut winapi::shared::windef::HWND__*,std::collections:#️⃣:map::RandomState,alloc::alloc::Global>
  29: std::panicking::try<tuple<>,std::panic::AssertUnwindSafe<closure-0>>
             at C:\Users\tehpe\.rustup\toolchains\nightly-x86_64-pc-windows-msvc\lib\rustlib\src\rust\library\std\src\panicking.rs:343
  30: std::panic::catch_unwind<std::panic::AssertUnwindSafe<closure-0>,tuple<>>
             at C:\Users\tehpe\.rustup\toolchains\nightly-x86_64-pc-windows-msvc\lib\rustlib\src\rust\library\std\src\panic.rs:431
  31: winit::platform_impl::platform::event_loop:🏃:EventLoopRunner<tuple<>>::catch_unwind<tuple<>,tuple<>,closure-0>
             at C:\Users\tehpe\.cargo\registry\src\github.com-1ecc6299db9ec823\winit-0.24.0\src\platform_impl\windows\event_loop\runner.rs:152
  32: winit::platform_impl::platform::event_loop:🏃:EventLoopRunner<tuple<>>::call_event_handler<tuple<>>
             at C:\Users\tehpe\.cargo\registry\src\github.com-1ecc6299db9ec823\winit-0.24.0\src\platform_impl\windows\event_loop\runner.rs:239
  33: winit::platform_impl::platform::event_loop:🏃:EventLoopRunner<tuple<>>::move_state_to<tuple<>>
             at C:\Users\tehpe\.cargo\registry\src\github.com-1ecc6299db9ec823\winit-0.24.0\src\platform_impl\windows\event_loop\runner.rs:341
  34: winit::platform_impl::platform::event_loop:🏃:EventLoopRunner<tuple<>>::main_events_cleared<tuple<>>
             at C:\Users\tehpe\.cargo\registry\src\github.com-1ecc6299db9ec823\winit-0.24.0\src\platform_impl\windows\event_loop\runner.rs:227
  35: winit::platform_impl::platform::event_loop::flush_paint_messages<tuple<>>
             at C:\Users\tehpe\.cargo\registry\src\github.com-1ecc6299db9ec823\winit-0.24.0\src\platform_impl\windows\event_loop.rs:676
  36: winit::platform_impl::platform::event_loop::thread_event_target_callback::{{closure}}<tuple<>>
             at C:\Users\tehpe\.cargo\registry\src\github.com-1ecc6299db9ec823\winit-0.24.0\src\platform_impl\windows\event_loop.rs:1967
  37: std::panic::{{impl}}::call_once<isize,closure-0>
             at C:\Users\tehpe\.rustup\toolchains\nightly-x86_64-pc-windows-msvc\lib\rustlib\src\rust\library\std\src\panic.rs:344
  38: std::panicking::try::do_call<std::panic::AssertUnwindSafe<closure-0>,isize>
             at C:\Users\tehpe\.rustup\toolchains\nightly-x86_64-pc-windows-msvc\lib\rustlib\src\rust\library\std\src\panicking.rs:379
  39: hashbrown::set::HashSet<mut winapi::shared::windef::HWND__*, std::collections:#️⃣:map::RandomState, alloc::alloc::Global>::iter<mut winapi::shared::windef::HWND__*,std::collections:#️⃣:map::RandomState,alloc::alloc::Global>
  40: std::panicking::try<isize,std::panic::AssertUnwindSafe<closure-0>>
             at C:\Users\tehpe\.rustup\toolchains\nightly-x86_64-pc-windows-msvc\lib\rustlib\src\rust\library\std\src\panicking.rs:343
  41: std::panic::catch_unwind<std::panic::AssertUnwindSafe<closure-0>,isize>
             at C:\Users\tehpe\.rustup\toolchains\nightly-x86_64-pc-windows-msvc\lib\rustlib\src\rust\library\std\src\panic.rs:431
  42: winit::platform_impl::platform::event_loop:🏃:EventLoopRunner<tuple<>>::catch_unwind<tuple<>,isize,closure-0>
             at C:\Users\tehpe\.cargo\registry\src\github.com-1ecc6299db9ec823\winit-0.24.0\src\platform_impl\windows\event_loop\runner.rs:152
  43: winit::platform_impl::platform::event_loop::thread_event_target_callback<tuple<>>
             at C:\Users\tehpe\.cargo\registry\src\github.com-1ecc6299db9ec823\winit-0.24.0\src\platform_impl\windows\event_loop.rs:2151
  44: DefSubclassProc
  45: DefSubclassProc
  46: CallWindowProcW
  47: DispatchMessageW
  48: SendMessageTimeoutW
  49: KiUserCallbackDispatcher
  50: NtUserDispatchMessage
  51: DispatchMessageW
  52: winit::platform_impl::platform::event_loop::EventLoop<tuple<>>::run_return<tuple<>,closure-1>
             at C:\Users\tehpe\.cargo\registry\src\github.com-1ecc6299db9ec823\winit-0.24.0\src\platform_impl\windows\event_loop.rs:218
  53: winit::platform_impl::platform::event_loop::EventLoop<tuple<>>::run<tuple<>,closure-1>
             at C:\Users\tehpe\.cargo\registry\src\github.com-1ecc6299db9ec823\winit-0.24.0\src\platform_impl\windows\event_loop.rs:188
  54: winit::event_loop::EventLoop<tuple<>>::run<tuple<>,closure-1>
             at C:\Users\tehpe\.cargo\registry\src\github.com-1ecc6299db9ec823\winit-0.24.0\src\event_loop.rs:154
  55: bevy_winit::run<closure-1>
             at C:\Dev\Games\bevy\crates\bevy_winit\src\lib.rs:171
  56: bevy_winit::winit_runner_with
             at C:\Dev\Games\bevy\crates\bevy_winit\src\lib.rs:493
  57: bevy_winit::winit_runner
             at C:\Dev\Games\bevy\crates\bevy_winit\src\lib.rs:211
  58: core::ops::function::Fn::call<fn(bevy_app::app::App),tuple<bevy_app::app::App>>
             at C:\Users\tehpe\.rustup\toolchains\nightly-x86_64-pc-windows-msvc\lib\rustlib\src\rust\library\core\src\ops\function.rs:70
  59: alloc::boxed::{{impl}}::call<tuple<bevy_app::app::App>,Fn<tuple<bevy_app::app::App>>,alloc::alloc::Global>
             at C:\Users\tehpe\.rustup\toolchains\nightly-x86_64-pc-windows-msvc\lib\rustlib\src\rust\library\alloc\src\boxed.rs:1560
  60: bevy_app::app::App::run
             at C:\Dev\Games\bevy\crates\bevy_app\src\app.rs:68
  61: bevy_app::app_builder::AppBuilder::run
             at C:\Dev\Games\bevy\crates\bevy_app\src\app_builder.rs:54
  62: game_main::main
             at .\crates\game_main\src\main.rs:23
  63: core::ops::function::FnOnce::call_once<fn(),tuple<>>
             at C:\Users\tehpe\.rustup\toolchains\nightly-x86_64-pc-windows-msvc\lib\rustlib\src\rust\library\core\src\ops\function.rs:227
note: Some details are omitted, run with `RUST_BACKTRACE=full` for a verbose backtrace.
Apr 27 21:51:01.026 ERROR gpu_descriptor::allocator: `DescriptorAllocator` is dropped while some descriptor sets were not deallocated
error: process didn't exit successfully: `target/cargo\debug\game_main.exe` (exit code: 0xc000041d)
```
2021-04-28 19:04:01 +00:00
Lucas Rocha
b1ed28e17e Hide re-exported docs (#1985)
Solves #1957 

Co-authored-by: caelumLaron <caelum.laron@gmail.com>
2021-04-27 18:29:33 +00:00
TheRawMeatball
c32c37d737 Detect camera projection changes (#2015) 2021-04-27 01:11:04 +00:00
Carter Anderson
1248a639ee EnumVariantMeta derive (#1972)
There are cases where we want an enum variant name. Right now the only way to do that with rust's std is to derive Debug, but this will also print out the variant's fields. This creates the unfortunate situation where we need to manually write out each variant's string name (ex: in #1963), which is both boilerplate-ey and error-prone. Crates such as `strum` exist for this reason, but it includes a lot of code and complexity that we don't need.

This adds a dead-simple `EnumVariantMeta` derive that exposes `enum_variant_index` and `enum_variant_name` functions. This allows us to make cases like #1963 much cleaner (see the second commit). We might also be able to reuse this logic for `bevy_reflect` enum derives.
2021-04-21 23:46:54 +00:00
Alice Cecile
e4e32598a9 Cargo fmt with unstable features (#1903)
Fresh version of #1670 off the latest main.

Mostly fixing documentation wrapping.
2021-04-21 23:19:34 +00:00
François
30c6ca6166 don't panic when no RenderResourceContext can be found (#1971)
In bevy_webgl2, the `RenderResourceContext` is created after startup as it needs to first wait for an event from js side:
f31e5d49de/src/lib.rs (L117)

remove `panic` introduced in #1965 and log as a `warn` instead
2021-04-20 21:44:32 +00:00
MinerSebas
80df583a21 When missing a render backend also mention the bevy_wgpu feature (#1970) 2021-04-20 21:04:09 +00:00
simens_green
c74994ba69 Added TryFrom for VertexAttributeValues (#1963)
This implementations allows you
convert std::vec::Vec<T> to VertexAttributeValues::T and back.

# Examples

```rust
use std::convert::TryInto;
use bevy_render::mesh::VertexAttributeValues;

// creating vector of values
let before = vec![[0_u32; 4]; 10];
let values = VertexAttributeValues::from(before.clone());
let after: Vec<[u32; 4]> = values.try_into().unwrap();

assert_eq!(before, after);
```

Co-authored-by: aloucks <aloucks@cofront.net>
Co-authored-by: simens_green <34134129+simensgreen@users.noreply.github.com>
Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2021-04-20 20:41:32 +00:00
MinerSebas
ad43f52bd2 Provide better error message when missing a render backend (#1965)
Fixes #626
2021-04-19 22:16:24 +00:00
François
f1ddd7a2ad change how to select bevy-glsl-to-spirv or shaderc (#1819)
`cfg` for `bevy-glsl-to-spirv` use now mimics https://github.com/cart/glsl-to-spirv/blob/master/Cargo.toml

fixes #898 
fixes #1348 
fixes #1942 
fixes #1078
2021-04-19 21:28:30 +00:00
Mariusz Kryński
fa6d4dbd53 add render_to_texture example (#1927)
Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2021-04-19 21:07:19 +00:00
Jakob Hellermann
cf221f9659 calculate flat normals for mesh if missing (#1808)
If the gltf loader encounters a mesh without normal attributes, it will duplicate the vertex attributes and compute flat normals, as defined by https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#meshes:

> **Implementation Note**: When normals are not specified, client implementations should calculate flat normals.

![image](https://user-images.githubusercontent.com/22177966/113483243-bb204880-94a2-11eb-8fa1-c4828a4882c5.png)

Helps with #1802 

Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2021-04-15 21:06:49 +00:00
bg
55d6c2c34a fixing compilation error on macos aarch64 (#1905)
just so
2021-04-14 23:58:29 +00:00
TehPers
e0b52079da Implement RenderResource for Box<T> (#1893)
Allows render resources to move data to the heap by boxing them. I did this as a workaround to #1892, but it seems like it'd be useful regardless. If not, feel free to close this PR.
2021-04-14 23:58:25 +00:00
Denis Laprise
d8392e7a3e Add a UV sphere implementation (#1887)
Added a UV sphere implementation
2021-04-14 23:39:58 +00:00
aloucks
294feeedc0 Add additional vertex formats (#1878)
- `Short2`
- `Short2Norm`
- `Ushort2`
- `Ushort2Norm`
- `Short4`
- `Short4Norm`
- `Ushort4`
- `Ushort4Norm`
- `Char2`
- `Char2Norm`
- `Uchar2`
- `Uchar2Norm`
- `Char4`
- `Char4Norm`
- `Uchar4`
2021-04-14 23:21:53 +00:00
TehPers
deb9f23667 Implement Byteable and RenderResource for [T; N] (#1872)
Implements `Byteable` and `RenderResource` for any array containing `Byteable` elements. This allows `RenderResources` to be implemented on structs with arbitrarily-sized arrays, among other things:

```rust
#[derive(RenderResources, TypeUuid)]
#[uuid = "2733ff34-8f95-459f-bf04-3274e686ac5f"]
struct Foo {
    buffer: [i32; 256],
}
```
2021-04-14 22:20:25 +00:00
Patrik Buhring
df3f40afd4 Fix IcoSphere UV coordinates (#1871)
Changes made:
- Swap Y/Z when calculating UV coordinates
- Correct mapping in the UV coordinates
- Fix typo in Azimuth
2021-04-14 22:20:24 +00:00
Yoh Deadfall
04a37f722a Moved events to ECS (#1823)
Fixes #1809. It makes it also possible to use `derive` for `SystemParam` inside ECS and avoid manual implementation. An alternative solution to macro changes is to use `use crate as bevy_ecs;` in `event.rs`.
2021-04-13 20:36:37 +00:00
Jonas Matser
7342d463b8 Use a sorted Map for vertex buffer attributes (#1796)
The `VertexBufferLayout` returned by `crates\bevy_render\src\mesh\mesh.rs:308` was unstable, because `HashMap.iter()` has a random order. This caused the pipeline_compiler to wrongly consider a specialization to be different (`crates\bevy_render\src\pipeline\pipeline_compiler.rs:123`), causing each mesh changed event to potentially result in a different `PipelineSpecialization`. This in turn caused `Draw` to emit a `set_pipeline` much more often than needed.

This fix shaves off a `BindPipeline` and two `BindDescriptorSets` (for the Camera and for global renderresources) for every mesh after the first that can now use the same specialization, where it didn't before (which was random).

`StableHashMap` was not a good replacement, because it isn't `Clone`, so instead I replaced it with a `BTreeMap` which is OK in this instance, because there shouldn't be many insertions on `Mesh.attributes` after the mesh is created.
2021-04-13 03:31:29 +00:00
Jakob Hellermann
9e55d8dbb4 Error message improvements for shader compilation/gltf loading (#1786)
- prints glsl compile error message in multiple lines instead of `thread 'main' panicked at 'called Result::unwrap() on an Err value: Compilation("glslang_shader_parse:\nInfo log:\nERROR: 0:335: \'assign\' :  l-value required \"anon@7\" (can\'t modify a uniform)\nERROR: 0:335: \'\' : compilation terminated \nERROR: 2 compilation errors.  No code generated.\n\n\nDebug log:\n\n")', crates/bevy_render/src/pipeline/pipeline_compiler.rs:161:22`
- makes gltf error messages have more context

New error:
```rust
thread 'Compute Task Pool (5)' panicked at 'Shader compilation error:
glslang_shader_parse:
Info log:
ERROR: 0:12: 'assign' :  l-value required "anon@1" (can't modify a uniform)
ERROR: 0:12: '' : compilation terminated 
ERROR: 2 compilation errors.  No code generated.
', crates/bevy_render/src/pipeline/pipeline_compiler.rs:364:5
```


These changes are a bit unrelated. I can open separate PRs if someone wants that.
2021-04-13 02:56:30 +00:00
MinerSebas
0fce6f0406 Override size_hint for all Iterators and add ExactSizeIterator where applicable (#1734)
After #1697 I looked at all other Iterators from Bevy and added overrides for `size_hint` where it wasn't done.
Also implemented `ExactSizeIterator` where applicable.
2021-04-13 01:28:14 +00:00
Carter Anderson
97d8e4e179 Release 0.5.0 (#1835) 2021-04-06 18:48:48 +00:00
Jakob Hellermann
aaf204cbac remove active camera entity when despawned (#1825)
fixes #1452

This should probably be in 0.5, as the previous workaround isn't possible after dd4a196329 because the hashmap is now private.
2021-04-06 17:09:28 +00:00
François
9098df3034 make pbr shader std140 compatible (#1798)
In shaders, `vec3` should be avoided for `std140` layout, as they take the size of a `vec4` and won't support manual padding by adding an additional `float`.

This change is needed for 3D to work in WebGL2. With it, I get PBR to render
<img width="1407" alt="Screenshot 2021-04-02 at 02 57 14" src="https://user-images.githubusercontent.com/8672791/113368551-5a3c2780-935f-11eb-8c8d-e9ba65b5ee98.png">

Without it, nothing renders... @cart Could this be considered for 0.5 release?

Also, I learned shaders 2 days ago, so don't hesitate to correct any issue or misunderstanding I may have

bevy_webgl2 PR in progress for Bevy 0.5 is here if you want to test: https://github.com/rparrett/bevy_webgl2/pull/1
2021-04-03 23:30:28 +00:00
Carter Anderson
f520a341d5 flip resource scope order (#1793)
I think [collection, thing_removed_from_collection] is a more natural order than [thing_removed_from_collection, collection]. Just a small tweak that I think we should include in 0.5.
2021-04-01 02:24:42 +00:00
Jonas Matser
9a78addff0 Add PBR textures (#1632)
This PR adds normal maps on top of PBR #1554. Once that PR lands, the changes should look simpler.

Edit: Turned out to be so little extra work, I added metallic/roughness texture too. And occlusion and emissive.

Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2021-03-26 21:00:34 +00:00
Jakob Hellermann
ad60046982 fix clippy lints (#1756) 2021-03-25 20:48:18 +00:00
Aaron Winter
b65ec82d46 Frustum Culling (for Sprites) (#1492)
This PR adds two systems to the sprite module that culls Sprites and AtlasSprites that are not within the camera's view.
This is achieved by removing / adding a new  `Viewable` Component dynamically.

Some of the render queries now use a `With<Viewable>` filter to only process the sprites that are actually on screen, which improves performance drastically for scene swith a large amount of sprites off-screen.

https://streamable.com/vvzh2u

This scene shows a map with a 320x320 tiles, with a grid size of 64p.
This is exactly 102400 Sprites in the entire scene.

Without this PR, this scene runs with 1 to 4 FPS.

With this PR..
.. at 720p, there are around 600 visible sprites and runs at ~215 FPS
.. at 1440p there are around 2000 visible sprites and runs at ~135 FPS

The Systems this PR adds take around 1.2ms (with 100K+ sprites in the scene)

Note:
This is only implemented for Sprites and AtlasTextureSprites.
There is no culling for 3D in this PR.

Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2021-03-24 21:29:53 +00:00
Jonas Matser
cd8025d0a7 Remove remaining camerapos bindings (#1708)
Fixes #1706

@JeanMertz already solved it. I just ran all examples and tests.
2021-03-22 18:10:35 +00:00
Jonas Matser
45b2db7070 Rebase of existing PBR work (#1554)
This is a rebase of StarArawns PBR work from #261 with IngmarBitters work from #1160 cherry-picked on top.

I had to make a few minor changes to make some intermediate commits compile and the end result is not yet 100% what I expected, so there's a bit more work to do.

Co-authored-by: John Mitchell <toasterthegamer@gmail.com>
Co-authored-by: Ingmar Bitter <ingmar.bitter@gmail.com>
2021-03-20 03:22:33 +00:00
Carter Anderson
dd4a196329 Flexible camera bindings (#1689)
Alternative to #1203 and #1611

Camera bindings have historically been "hacked in". They were _required_ in all shaders and only supported a single Mat4. PBR (#1554) requires the CameraView matrix, but adding this using the "hacked" method forced users to either include all possible camera data in a single binding (#1203) or include all possible bindings (#1611).

This approach instead assigns each "active camera" its own RenderResourceBindings, which are populated by CameraNode. The PassNode then retrieves (and initializes) the relevant bind groups for all render pipelines used by visible entities. 

* Enables any number of camera bindings , including zero (with any set or binding number ... set 0 should still be used to avoid rebinds).
* Renames Camera binding to CameraViewProj
* Adds CameraView binding
2021-03-19 20:36:40 +00:00
Alice Cecile
6121e5f933 Reliable change detection (#1471)
# Problem Definition

The current change tracking (via flags for both components and resources) fails to detect changes made by systems that are scheduled to run earlier in the frame than they are.

This issue is discussed at length in [#68](https://github.com/bevyengine/bevy/issues/68) and [#54](https://github.com/bevyengine/bevy/issues/54).

This is very much a draft PR, and contributions are welcome and needed.

# Criteria
1. Each change is detected at least once, no matter the ordering.
2. Each change is detected at most once, no matter the ordering.
3. Changes should be detected the same frame that they are made.
4. Competitive ergonomics. Ideally does not require opting-in.
5. Low CPU overhead of computation.
6. Memory efficient. This must not increase over time, except where the number of entities / resources does.
7. Changes should not be lost for systems that don't run.
8. A frame needs to act as a pure function. Given the same set of entities / components it needs to produce the same end state without side-effects.

**Exact** change-tracking proposals satisfy criteria 1 and 2.
**Conservative** change-tracking proposals satisfy criteria 1 but not 2.
**Flaky** change tracking proposals satisfy criteria 2 but not 1.

# Code Base Navigation

There are three types of flags: 
- `Added`: A piece of data was added to an entity / `Resources`.
- `Mutated`: A piece of data was able to be modified, because its `DerefMut` was accessed
- `Changed`: The bitwise OR of `Added` and `Changed`

The special behavior of `ChangedRes`, with respect to the scheduler is being removed in [#1313](https://github.com/bevyengine/bevy/pull/1313) and does not need to be reproduced.

`ChangedRes` and friends can be found in "bevy_ecs/core/resources/resource_query.rs".

The `Flags` trait for Components can be found in "bevy_ecs/core/query.rs".

`ComponentFlags` are stored in "bevy_ecs/core/archetypes.rs", defined on line 446.

# Proposals

**Proposal 5 was selected for implementation.**

## Proposal 0: No Change Detection

The baseline, where computations are performed on everything regardless of whether it changed.

**Type:** Conservative

**Pros:**
- already implemented
- will never miss events
- no overhead

**Cons:**
- tons of repeated work
- doesn't allow users to avoid repeating work (or monitoring for other changes)

## Proposal 1: Earlier-This-Tick Change Detection

The current approach as of Bevy 0.4. Flags are set, and then flushed at the end of each frame.

**Type:** Flaky

**Pros:**
- already implemented
- simple to understand
- low memory overhead (2 bits per component)
- low time overhead (clear every flag once per frame)

**Cons:**
- misses systems based on ordering
- systems that don't run every frame miss changes
- duplicates detection when looping
- can lead to unresolvable circular dependencies

## Proposal 2: Two-Tick Change Detection

Flags persist for two frames, using a double-buffer system identical to that used in events.

A change is observed if it is found in either the current frame's list of changes or the previous frame's.

**Type:** Conservative

**Pros:**
- easy to understand
- easy to implement
- low memory overhead (4 bits per component)
- low time overhead (bit mask and shift every flag once per frame)

**Cons:**
- can result in a great deal of duplicated work
- systems that don't run every frame miss changes
- duplicates detection when looping

## Proposal 3: Last-Tick Change Detection

Flags persist for two frames, using a double-buffer system identical to that used in events.

A change is observed if it is found in the previous frame's list of changes.

**Type:** Exact

**Pros:**
- exact
- easy to understand
- easy to implement
- low memory overhead (4 bits per component)
- low time overhead (bit mask and shift every flag once per frame)

**Cons:**
- change detection is always delayed, possibly causing painful chained delays
- systems that don't run every frame miss changes
- duplicates detection when looping

## Proposal 4: Flag-Doubling Change Detection

Combine Proposal 2 and Proposal 3. Differentiate between `JustChanged` (current behavior) and `Changed` (Proposal 3).

Pack this data into the flags according to [this implementation proposal](https://github.com/bevyengine/bevy/issues/68#issuecomment-769174804).

**Type:** Flaky + Exact

**Pros:**
- allows users to acc
- easy to implement
- low memory overhead (4 bits per component)
- low time overhead (bit mask and shift every flag once per frame)

**Cons:**
- users must specify the type of change detection required
- still quite fragile to system ordering effects when using the flaky `JustChanged` form
- cannot get immediate + exact results
- systems that don't run every frame miss changes
- duplicates detection when looping

## [SELECTED] Proposal 5: Generation-Counter Change Detection

A global counter is increased after each system is run. Each component saves the time of last mutation, and each system saves the time of last execution. Mutation is detected when the component's counter is greater than the system's counter. Discussed [here](https://github.com/bevyengine/bevy/issues/68#issuecomment-769174804). How to handle addition detection is unsolved; the current proposal is to use the highest bit of the counter as in proposal 1.

**Type:** Exact (for mutations), flaky (for additions)

**Pros:**
- low time overhead (set component counter on access, set system counter after execution)
- robust to systems that don't run every frame
- robust to systems that loop

**Cons:**
- moderately complex implementation
- must be modified as systems are inserted dynamically
- medium memory overhead (4 bytes per component + system)
- unsolved addition detection

## Proposal 6: System-Data Change Detection

For each system, track which system's changes it has seen. This approach is only worth fully designing and implementing if Proposal 5 fails in some way.  

**Type:** Exact

**Pros:**
- exact
- conceptually simple

**Cons:**
- requires storing data on each system
- implementation is complex
- must be modified as systems are inserted dynamically

## Proposal 7: Total-Order Change Detection

Discussed [here](https://github.com/bevyengine/bevy/issues/68#issuecomment-754326523). This proposal is somewhat complicated by the new scheduler, but I believe it should still be conceptually feasible. This approach is only worth fully designing and implementing if Proposal 5 fails in some way.  

**Type:** Exact

**Pros:**
- exact
- efficient data storage relative to other exact proposals

**Cons:**
- requires access to the scheduler
- complex implementation and difficulty grokking
- must be modified as systems are inserted dynamically

# Tests

- We will need to verify properties 1, 2, 3, 7 and 8. Priority: 1 > 2 = 3 > 8 > 7
- Ideally we can use identical user-facing syntax for all proposals, allowing us to re-use the same syntax for each.
- When writing tests, we need to carefully specify order using explicit dependencies.
- These tests will need to be duplicated for both components and resources.
- We need to be sure to handle cases where ambiguous system orders exist.

`changing_system` is always the system that makes the changes, and `detecting_system` always detects the changes.

The component / resource changed will be simple boolean wrapper structs.

## Basic Added / Mutated / Changed

2 x 3 design:
- Resources vs. Components
- Added vs. Changed vs. Mutated
- `changing_system` runs before `detecting_system`
- verify at the end of tick 2

## At Least Once

2 x 3 design:
- Resources vs. Components
- Added vs. Changed vs. Mutated
- `changing_system` runs after `detecting_system`
- verify at the end of tick 2

## At Most Once

2 x 3 design:
- Resources vs. Components
- Added vs. Changed vs. Mutated
- `changing_system` runs once before `detecting_system`
- increment a counter based on the number of changes detected
- verify at the end of tick 2

## Fast Detection
2 x 3 design:
- Resources vs. Components
- Added vs. Changed vs. Mutated
- `changing_system` runs before `detecting_system`
- verify at the end of tick 1

## Ambiguous System Ordering Robustness
2 x 3 x 2 design:
- Resources vs. Components
- Added vs. Changed vs. Mutated
- `changing_system` runs [before/after] `detecting_system` in tick 1
- `changing_system` runs [after/before] `detecting_system` in tick 2

## System Pausing
2 x 3 design:
- Resources vs. Components
- Added vs. Changed vs. Mutated
- `changing_system` runs in tick 1, then is disabled by run criteria
- `detecting_system` is disabled by run criteria until it is run once during tick 3
- verify at the end of tick 3

## Addition Causes Mutation

2 design:
- Resources vs. Components
- `adding_system_1` adds a component / resource
- `adding system_2` adds the same component / resource
- verify the `Mutated` flag at the end of the tick
- verify the `Added` flag at the end of the tick

First check tests for: https://github.com/bevyengine/bevy/issues/333
Second check tests for: https://github.com/bevyengine/bevy/issues/1443

## Changes Made By Commands

- `adding_system` runs in Update in tick 1, and sends a command to add a component 
- `detecting_system` runs in Update in tick 1 and 2, after `adding_system`
- We can't detect the changes in tick 1, since they haven't been processed yet
- If we were to track these changes as being emitted by `adding_system`, we can't detect the changes in tick 2 either, since `detecting_system` has already run once after `adding_system` :( 

# Benchmarks

See: [general advice](https://github.com/bevyengine/bevy/blob/master/docs/profiling.md), [Criterion crate](https://github.com/bheisler/criterion.rs)

There are several critical parameters to vary: 
1. entity count (1 to 10^9)
2. fraction of entities that are changed (0% to 100%)
3. cost to perform work on changed entities, i.e. workload (1 ns to 1s)

1 and 2 should be varied between benchmark runs. 3 can be added on computationally.

We want to measure:
- memory cost
- run time

We should collect these measurements across several frames (100?) to reduce bootup effects and accurately measure the mean, variance and drift.

Entity-component change detection is much more important to benchmark than resource change detection, due to the orders of magnitude higher number of pieces of data.

No change detection at all should be included in benchmarks as a second control for cases where missing changes is unacceptable.

## Graphs
1. y: performance, x: log_10(entity count), color: proposal, facet: performance metric. Set cost to perform work to 0. 
2. y: run time, x: cost to perform work, color: proposal, facet: fraction changed. Set number of entities to 10^6
3. y: memory, x: frames, color: proposal

# Conclusions
1. Is the theoretical categorization of the proposals correct according to our tests?
2. How does the performance of the proposals compare without any load?
3. How does the performance of the proposals compare with realistic loads?
4. At what workload does more exact change tracking become worth the (presumably) higher overhead?
5. When does adding change-detection to save on work become worthwhile?
6. Is there enough divergence in performance between the best solutions in each class to ship more than one change-tracking solution?

# Implementation Plan

1. Write a test suite.
2. Verify that tests fail for existing approach.
3. Write a benchmark suite.
4. Get performance numbers for existing approach.
5. Implement, test and benchmark various solutions using a Git branch per proposal.
6. Create a draft PR with all solutions and present results to team.
7. Select a solution and replace existing change detection.

Co-authored-by: Brice DAVIER <bricedavier@gmail.com>
Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2021-03-19 17:53:26 +00:00
François
bcd5318247 color spaces and representation (#1572)
`Color` can now be from different color spaces or representation:
- sRGB
- linear RGB
- HSL

This fixes #1193 by allowing the creation of const colors of all types, and writing it to the linear RGB color space for rendering.

I went with an enum after trying with two different types (`Color` and `LinearColor`) to be able to use the different variants in all place where a `Color` is expected.

I also added the HLS representation because:
- I like it
- it's useful for some case, see example `contributors`: I can just change the saturation and lightness while keeping the hue of the color
- I think adding another variant not using `red`, `green`, `blue` makes it clearer there are differences

Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2021-03-17 23:59:51 +00:00
Alice Cecile
ab0165d20d Improved documentation for Events (#1669)
Explains subtle behavior more explicitly, documents `add_event`, mentions `EventWriter`.

Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2021-03-17 23:42:19 +00:00
Jakob Hellermann
f6ff80c5b1
add Debug, Copy, Clone for all shapes (#1653) 2021-03-14 12:45:00 -07:00
François
bbb9849506 Replace default method calls from Glam types with explicit const (#1645)
it's a followup of #1550 

I think calling explicit methods/values instead of default makes the code easier to read: "what is `Quat::default()`" vs "Oh, it's `Quat::IDENTITY`"

`Transform::identity()` and `GlobalTransform::identity()` can also be consts and I replaced the calls to their `default()` impl with `identity()`
2021-03-13 18:23:39 +00:00
davier
8acb0d2012 Fix cargo doc warnings (#1640)
Fixes all warnings from `cargo doc --all`.
Those related to code blocks were introduced in #1612, but re-formatting using the experimental features in `rustfmt.toml` doesn't seem to reintroduce them.
2021-03-13 18:23:38 +00:00
Simon Guillot
785aad92f4 Fix pipeline initialisation of wireframe mode (fixes #1609) (#1623)
More details are in the associated issue #1609.

While looking for the source of this issue, I've noticed that the `set` and `set_untracked` methods aren't really DRY:
68606934e3/crates/bevy_asset/src/assets.rs (L76-L85)

68606934e3/crates/bevy_asset/src/assets.rs (L91-L99)

Shouldn't `set` call `set_untracked`? Also, given the bug that arose from a misusage of these functions, maybe some refactoring is needed?
2021-03-12 22:12:07 +00:00
Carter Anderson
b17f8a4bce format comments (#1612)
Uses the new unstable comment formatting features added to rustfmt.toml.
2021-03-11 00:27:30 +00:00
Carter Anderson
be1c317d4e Resolve (most) internal system ambiguities (#1606)
* Adds labels and orderings to systems that need them (uses the new many-to-many labels for InputSystem)
* Removes the Event, PreEvent, Scene, and Ui stages in favor of First, PreUpdate, and PostUpdate (there is more collapsing potential, such as the Asset stages and _maybe_ removing First, but those have more nuance so they should be handled separately)
* Ambiguity detection now prints component conflicts
* Removed broken change filters from flex calculation (which implicitly relied on the z-update system always modifying translation.z). This will require more work to make it behave as expected so i just removed it (and it was already doing this work every frame).
2021-03-10 22:37:02 +00:00