Commit graph

1404 commits

Author SHA1 Message Date
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
Branan Riley
684c821e96 Schedule gilrs system before input systems (#2989)
# Objective

Previously, the gilrs system had no explicit relationship to the input
systems. This could potentially cause it to be scheduled after the
input systems, leading to a one-frame lag in gamepad inputs.

This was a regression introduced in #1606 which removed the `PreEvent` stage

## Solution

This adds an explicit `before` relationship to the gilrs plugin,
ensuring that raw gamepad events will be processed on the same frame
that they are generated.
2021-12-16 00:04:34 +00:00
Alex
49a4009d5c re-export ClearPassNode (#3336)
Currently the `ClearPassNode` is not exported, due to an additional `use ...;` in the core pipeline's `lib.rs`. This seems unintentional, as there already is a public glob import in the file.

This just removes the explicit use. If it actually was intentional to keep the node internal, let me know.
2021-12-15 22:04:39 +00:00
MrGVSV
add1818a05 Add documentation to KeyCode for Mac users (#3331)
# Objective

`KeyCode::*Win` and `KeyCode::*Alt` might be confusing for some Mac users.

## Solution

Added some small documentation to clarify the mappings for those developing on a Mac.

## Additional Context

Related issue: #3240
2021-12-15 01:23:32 +00:00
Hennadii Chernyshchyk
70c9165886 Fix crash with disabled winit (#3330)
# Objective

This PR fixes a crash when winit is enabled when there is a camera in the world. Part of #3155

## Solution

In this PR, I removed two unwraps and added an example for regression testing.
2021-12-15 00:15:47 +00:00
Robert Swain
c061ec33c8 bevy_pbr2: Fix clustering for orthographic projections (#3316)
# Objective

PBR lighting was broken in the new renderer when using orthographic projections due to the way the depth slicing works for the clusters. Fix it.

## Solution

- The default orthographic projection near plane is 0.0. The perspective projection depth slicing does a division by the near plane which gives a floating point NaN and the clustering all breaks down.
- Orthographic projections have a linear depth mapping, so it made intuitive sense to me to do depth slicing with a linear mapping too. The alternative I saw was to try to handle the near plane being at 0.0 and using the exponential depth slicing, but that felt like a hack that didn't make sense.
- As such, I have added code that detects whether the projection is orthographic based on `projection[3][3] == 1.0` and then implemented the orthographic mapping case throughout (when computing cluster AABBs, and when mapping a view space position (or light) to a cluster id in both the rust and shader code).

## Screenshots
Before:
![before](https://user-images.githubusercontent.com/302146/145847278-5b1bca74-fbad-4cc5-8b49-384f6a377fdc.png)
After:
<img width="1392" alt="Screenshot 2021-12-13 at 16 36 53" src="https://user-images.githubusercontent.com/302146/145847314-6f3a2035-5d87-4896-8032-0c3e35e15b7d.png">
Old renderer (slightly lighter due to slight difference in configured intensity):
<img width="1392" alt="Screenshot 2021-12-13 at 16 42 23" src="https://user-images.githubusercontent.com/302146/145847391-6a5e6fe0-22da-4fc1-a6c7-440543689a63.png">
2021-12-14 23:42:35 +00:00
François
c825fda74a add default standard material in PbrBundle (#3325)
# Objective

- Fix #3323 


## Solution

- Add a default standard material that is very visible. It is similar to the previous standard material that was used

<img width="1392" alt="Screenshot 2021-12-14 at 15 39 01" src="https://user-images.githubusercontent.com/8672791/146019401-ed4b5fc1-7cce-4a8f-a511-a6f9665a51d7.png">



Co-authored-by: François <8672791+mockersf@users.noreply.github.com>
2021-12-14 23:04:26 +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
Niklas Eicker
de8edd3165 Rename fixed timestep state and add a test (#3260)
# Objective

fixes #3234

## Solution

- rename `bevy::core::State` to `LocalFixedTimestepState`
- add a test for FixedTimestep since I am already there
2021-12-12 21:26:40 +00:00
Rostyslav Toch
172f4d6d78 Documented and tested Axis<T> (#3276)
# Objective

Fixes #3247 

## Solution

- Added docs to `Axis<T>`. This one can be extended @alice-i-cecile 
- Added unit tests
- Added `min` and `max` values to the struct. @alice-i-cecile Do we need to these variables?
- Limited `set` method usage with `min` and `max` values


Co-authored-by: CrazyRoka <rokarostuk@gmail.com>
2021-12-11 23:31:46 +00:00
Jakob Hellermann
a5ea38f75e add methods to get reads and writes of Access<T> (#3166)
This makes it possible to e.g. show resource and component access on hover in [bevy_mod_debugdump](https://github.com/jakobhellermann/bevy_mod_debugdump/):
![grafik](https://user-images.githubusercontent.com/22177966/142773962-320f6e5b-608e-4abb-88b8-78da4fefc166.png)
2021-12-11 23:16:01 +00:00
Daniel McNab
0ee4195fb0 Remove some superfluous unsafe code (#3297)
# Objective

- This `unsafe` is weird

## Solution

- Don't use `unsafe` here

Hopefully this isn't already in an open PR.
2021-12-11 22:58:46 +00:00
davier
25b62f9577 Port bevy_ui to pipelined-rendering (#2653)
# Objective

Port bevy_ui to pipelined-rendering (see #2535 )

## Solution

I did some changes during the port:
- [X] separate color from the texture asset (as suggested [here](https://discord.com/channels/691052431525675048/743663924229963868/874353914525413406))
- [X] ~give the vertex shader a per-instance buffer instead of per-vertex buffer~ (incompatible with batching)

Remaining features to implement to reach parity with the old renderer:
- [x] textures
- [X] TextBundle

I'd also like to add these features, but they need some design discussion:
- [x] batching
- [ ] separate opaque and transparent phases
- [ ] multiple windows
- [ ] texture atlases
- [ ] (maybe) clipping
2021-12-10 22:21:23 +00:00
Weasy
a2f0fe24e8 Allow String and &String as Id for AssetServer.get_handle(id) (#3280)
# Objective

Make it easier to build and use an asset path with `format!()`. This can be useful for accessing assets in a loop.

Enabled by this PR:
```rust
let monkey_handle = asset_server.get_handle(&format!("models/monkey/Monkey.gltf#Mesh0/Primitive0"));
let monkey_handle = asset_server.get_handle(format!("models/monkey/Monkey.gltf#Mesh0/Primitive0"));
```

Before this PR:
```rust
let monkey_handle = asset_server.get_handle(format!("models/monkey/Monkey.gltf#Mesh0/Primitive0").as_str());
```

It's just a tiny improvement in ergonomics, but i ran into it and was wondering why the function does not accept a `String` and Bevy is all about simplicity/ergonomics, right? 😄😉

## Solution

Implement `Into<HandleId>` for `String` and `&String`.
2021-12-09 22:40:15 +00:00
TheRawMeatball
6caa2622b0 Add despawn_children (#2903)
Adds a convenience method for despawning all the children of the entity, but not the entity itself.
2021-12-09 20:42:44 +00:00
François
92a7e16aed Update dependencies ron winit& fix cargo-deny lists (#3244)
# Objective

- there are a few new versions for `ron`, `winit`, `ndk`, `raw-window-handle`
- `cargo-deny` is failing due to new security issues / duplicated dependencies

## Solution

- Update our dependencies
- Note all new security issues, with which of Bevy direct dependency it comes from
- Update duplicate crate list, with which of Bevy direct dependency it comes from

`notify` is not updated here as it's in #2993
2021-12-09 20:14:00 +00:00
Carter Anderson
7dd92e72d4 More Bevy ECS schedule spans (#3281)
Fills in some gaps we had in our Bevy ECS tracing spans:

* Exclusive systems
* System Commands (for `apply_buffers = true` cases)
* System archetype updates
* Parallel system execution prep
2021-12-08 23:43:03 +00:00
loui
3ca8844c90 Added transparency to window builder (#3105)
Applogies, had to recreate this pr because of branching issue.
Old PR: https://github.com/bevyengine/bevy/pull/3033

# Objective

Fixes #3032

Allowing a user to create a transparent window 

## Solution

I've allowed the transparent bool to be passed to the winit window builder
2021-12-08 20:53:35 +00:00
Rostyslav Toch
01e2141ce3 Add Gamepads resource (#3257)
# Objective

Fixes #3245 

## Solution

- Move GamepadLobby to lib
- Add connection_system to InputPlugin
- Updated gamepad_input example


Co-authored-by: CrazyRoka <rokarostuk@gmail.com>
Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2021-12-08 20:28:08 +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
bf96f266d7 Added tests to ButtonAxisSettings (#3272)
# Objective

`ButtonAxisSettings` wasn't tested properly.

## Solution

I added tests and fixed issue with `filter` method


Co-authored-by: CrazyRoka <rokarostuk@gmail.com>
2021-12-08 01:12:49 +00:00
Alex Helfet
5e516ab398 Made Time::time_since_startup return from last tick. (#3264)
Also added unit tests for it.

# Objective

- Fixes #3259 

## Solution

- As discussed in #3259

Co-authored-by: Alex Helfet <alex.helfet@gmail.com>
2021-12-07 01:30:08 +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
Joshua Chapman
274ace790b Implement iter() for mutable Queries (#2305)
A sample implementation of how to have `iter()` work on mutable queries without breaking aliasing rules.

# Objective

- Fixes #753

## Solution

- Added a ReadOnlyFetch to WorldQuery that is the `&T` version of `&mut T` that is used to specify the return type for read only operations like `iter()`.
- ~~As the comment suggests specifying the bound doesn't work due to restrictions on defining recursive implementations (like `Or`). However bounds on the functions are fine~~ Never mind I misread how `Or` was constructed, bounds now exist.
- Note that the only mutable one has a new `Fetch` for readonly as the `State` has to be the same for any of this to work


Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2021-12-01 23:28:10 +00:00
Dimitri Bobkov
bab4ee962d Added documentation to WindowMode to better document what 'use_size' … (#3216)
This pull request aims to solve the issue of a lack of documentation in the enum WindowMode

# Objective

- Fixes #3136

## Solution

- Added a few lines of documentation that should document what the enum does better
2021-11-30 23:51:11 +00:00
Jonathan Cornaz
1b8453d9a0 Fix path used by macro not considering that we can use a sub-crate (#3178)
# Problem

Let's say I am writting a simple bevy plugin, and I want to depend on `bevy_ecs` crate instead of depending on the full `bevy`. 

So I write the following:

*Cargo.toml*:
```toml
[dependencies]
bevy_ecs = { git = "https://github.com/bevyengine/bevy.git", rev = "94db0176fecfac7e7e9763f2dc7458a54c105886" }
```

*lib.rs*:
```rust
use bevy_ecs::prelude::*;

#[derive(Debug, Default, Component)
pub struct MyFancyComponent;
```

So far, so good. Everything works. But let's say I want to write some examples for using my plugin. And for theses I'd like to use the `bevy` crate, so that I can write complete examples (rendering stuff, etc.) that are simple and look like what the consumer of my plugin will do (`use bevy::prelude::*` and `DefaultPlugins`)

So I amend my *Cargo.toml*:
```toml
[dependencies]
bevy_ecs = { git = "https://github.com/bevyengine/bevy.git", rev = "94db0176fecfac7e7e9763f2dc7458a54c105886" }

[dev-dependencies]
bevy = { git = "https://github.com/bevyengine/bevy.git", rev = "94db0176fecfac7e7e9763f2dc7458a54c105886", default-features = false }
```

And that  leads to a complilation error 

```
error[E0433]: failed to resolve: use of undeclared crate or module `bevy`
```

Basically, because `bevy` is in the `dev-dependencies`, the macro (of the production code) decides to use the `bevy::ecs` path instead of `bevy_ecs`. But `bevy` is not available there.

## Solution

This PR fixes the problem. I amend the macro utility responsible of finding the path of a module.

If we try to find a path, we first test if this correspond to a crate that the user directly depend on. (Like, if we search for `bevy_ecs`, we first check if there is a `bevy_ecs` dependency). If yes, we can depend on that directly. Otherwise, we proceed with the existing logic (testing `bevy` and `bevy_internal`)
2021-11-29 23:10:31 +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
Carter Anderson
2e79951659 Shader Imports. Decouple Mesh logic from PBR (#3137)
## Shader Imports

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

### Asset Path Imports

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

#import "shaders/custom_material.wgsl"

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

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

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

### Custom Path Imports

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

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

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

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

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

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

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

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

## Decouple Mesh Logic from PBR Logic via MeshRenderPlugin

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

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

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

##  RenderCommands are now fallible

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

# Next Steps

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

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

Original PR is #2884.

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

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

## Solution

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

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

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

## Solution

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

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

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

## Solution

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

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

## Solution

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

Fixes #3117 

## Solution

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


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

- Fix #3058 opened by dependabot

## Solution

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

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

## Solution

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

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

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

(Emphasis in original.)

## Solution

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

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

## Solution

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

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

Fixes #2823.

## Solution

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

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

## Solution

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

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


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

# Objective

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

## Solution

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

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

## Solution

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

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

## Solution

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



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

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

## Solution

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

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

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

The current TODO comment is out of date

## Solution

I switched up the comment


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

- update for Edition 2021

## Solution

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

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

## Solution

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

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

## Solution

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


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

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


## Solution

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

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

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

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

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

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

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

# Objective

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

## Solution

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

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

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

## Solution

- Do the change

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

- Fixes #2904 (see for context)

## Solution

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

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

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

## Solution

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

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

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

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


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

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

## Solution

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

## Todo

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

Currently you can do something like this:

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

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

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

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


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

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

---

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

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


</details>
2021-09-27 23:58:44 +00:00
François
fb0aa8d286 enable change detection for hierarchy maintenance (#2411)
# Objective

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

Fixes #891


## Solution

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

Also modified an existing test to encompass these methods

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

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

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

![grafik](https://user-images.githubusercontent.com/22177966/134387678-28ece4d4-8af6-48de-beb8-973356c3b9f0.png)
2021-09-22 22:11:54 +00:00
TheRawMeatball
29d4faa077 Make events reuse buffers (#2850)
I'm really curious why this wasn't the case already...
2021-09-22 21:45:37 +00:00
Federico Rinaldi
615d43b998 Improve bevy_ecs and bevy_app API docs where referenced by the new Bevy Book (#2365)
## Objective

The upcoming Bevy Book makes many references to the API documentation of bevy.

Most references belong to the first two chapters of the Bevy Book:

- bevyengine/bevy-website#176
- bevyengine/bevy-website#182

This PR attempts to improve the documentation of `bevy_ecs` and `bevy_app` in order to help readers of the Book who want to delve deeper into technical details.

## Solution

- Add crate and level module documentation
- Document the most important items (basically those included in the preludes), with the following style, where applicable:
    - **Summary.** Short description of the item.
    - **Second paragraph.** Detailed description of the item, without going too much in the implementation.
    - **Code example(s).**
    - **Safety or panic notes.**

## Collaboration

Any kind of collaboration is welcome, especially corrections, wording, new ideas and guidelines on where the focus should be put in.

---

### Related issues

- Fixes #2246
2021-09-17 18:00:29 +00:00
Robert Swain
064af63400 Add trace_tracy feature for Tracy profiling (#2832)
# Objective

[Tracy](https://github.com/wolfpld/tracy) is:
> A real time, nanosecond resolution, remote telemetry, hybrid frame and sampling profiler for games and other applications.

With the `trace_tracy` feature enabled, you run your bevy app and either a headless server (`capture`) or a live, interactive profiler UI (`Tracy`), and connect that to your bevy application to then stream the metric data and events, and save it or inspect it live/offline.

Previously when I implemented the spans across systems and stages and I was trying out different profiling tools, Tracy was too unstable on macOS to use. But now, quite some months later, it is working stably with Tracy 0.7.8. You can see timelines, aggregate statistics of mean system/stage execution times, and much more. It's very useful!

![Screenshot_2021-09-15_at_18 07 19](https://user-images.githubusercontent.com/302146/133554920-350d3d45-fbb8-479f-91f7-7a7a4f9f5873.png)

## Solution

- Use the `tracing-tracy` crate which supports our tracing spans
- Expose via the non-default feature `trace_tracy` for consistency with other `trace*` features
2021-09-16 23:39:22 +00:00
Squirrel
42409fc59a unused deps? (#2809)
# Objective

- less deps.

## Solution

- delete button.
2021-09-16 09:37:12 +00:00
Hoidigan
34f0085ba0 Doc warnings (#2577)
Fixes #2576 

Add <> to links where needed, fix typo and refactored names, and add docs.rs links for external items.
2021-09-14 22:46:18 +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
taryn
b91541b6ef fix typo in events test assert message (#2821)
Fixing a 1-character typo in the failure message of an `assert_eq!` in the events tests.
2021-09-13 17:37:51 +00:00
MinerSebas
9effc3e9b3 Replace .insert_resource(T::default()) calls with init_resource::<T>() (#2807)
# Objective

I added the [INSERT_RESOURCE_WITH_DEFAULT](https://minersebas.github.io/bevy_lint/bevy_lint/static.INSERT_RESOURCE_WITH_DEFAULT.html) Lint to [bevy_lint](https://github.com/MinerSebas/bevy_lint) and while Testing it on bevy itself, I found several places where the Lint correctly triggered.



## Solution

Replace `.insert_resource(T::default())` calls with `init_resource::<T>()`
2021-09-13 14:02:28 +00:00
Daniel McNab
e74f7a7335 Fix the new nightly CI errors (#2811)
# Objective

- CI is failing again
- These failures result from https://github.com/rust-lang/rust/pull/85200

## Solution

- Fix the errors which result from this by using the given fields
- I also removed the now unused `Debug` impl.

I suspect that we shouldn't use -D warnings for nightly CI - ideally we'd get a discord webhook message into some (non-#github) dedicated channel on warnings. 

But this does not implement that.
2021-09-12 23:40:22 +00:00
Charles Giguere
51a5070cd2 add get_single variant (#2793)
# Objective

The vast majority of `.single()` usage I've seen is immediately followed by a `.unwrap()`. Since it seems most people use it without handling the error, I think making it easier to just get what you want fast while also having a more verbose alternative when you want to handle the error could help.

## Solution

Instead of having a lot of `.unwrap()` everywhere, this PR introduces a `try_single()` variant that behaves like the current `.single()` and make the new `.single()` panic on error.
2021-09-10 20:23:50 +00:00
Daniel McNab
27bfbda7bc Fix scale_factor_override in the winit backend (#2784)
# Objective

- Fixes #2751

## Solution

- Avoid changing the window size if there is a scale factor override
- Can be tested with the `scale_factor_override` example - use <kbd>⏎</kbd> to active overriding the scale factor
2021-09-10 18:46:16 +00:00
sark
4c3c4b5e40 Nightly clippy fixes (#2702)
A few minor changes to fix warnings emitted from clippy on the nightly toolchain, including redundant_allocation, unwrap_or_else_default, and collapsible_match, fixes #2698
2021-09-09 16:41:21 +00:00
willolisp
cbe9e56d85 Fixes to World's documentation (#2790)
# Objective

Fixes #2787.

## Solution

Fixed doc syntax for `World`'s `get` and `get_mut` methods.
2021-09-09 12:26:43 +00:00
Matthias Seiffert
2f6c464f4b Add builder methods to Transform (#2778)
# Objective

Make it easier to construct transforms. E.g.

```rs
Transform::from_xyz(0.0, 0.0, 10.0).with_scale(Vec3::splat(2.0))
```

I found myself writing an extension method to do this so I don't have to write:

```rs
Transform {
  translation: Vec3::new(0.0, 0.0, 10.0),
  scale: Vec3::splat(2.0),
  ..Default::default()
}
```

## Solution

Add *builder style* methods to `Transform`.

Methods:

- `with_translation`
- `with_rotation`
- `with_scale`

I also added these methods to `GlobalTransform`. But they are probably less useful there.
2021-09-09 00:46:39 +00:00
Patrick Greene
18c08dd860 add get_history function to Diagnostic (#2772)
# Objective

- Allow access to diagnostic history value.
- Fixes #2771.

## Solution

- Add Diagnostic::get_history function.
2021-09-06 19:16:08 +00:00
dependabot[bot]
edd822a2bb Update glam requirement from 0.17.3 to 0.18.0 (#2748)
Updates the requirements on [glam](https://github.com/bitshifter/glam-rs) to permit the latest version.
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a href="https://github.com/bitshifter/glam-rs/blob/main/CHANGELOG.md">glam's changelog</a>.</em></p>
<blockquote>
<h2>[0.18.0] - 2021-08-26</h2>
<h3>Breaking changes</h3>
<ul>
<li>Minimum Supported Version of Rust bumped to 1.51.0 for <code>wasm-bindgen-test</code>
and <code>rustdoc</code> <code>alias</code> support.</li>
</ul>
<h3>Added</h3>
<ul>
<li>Added <code>wasm32</code> SIMD intrinsics support.</li>
<li>Added optional support for the <code>rkyv</code> serialization crate.</li>
<li>Added <code>Rem</code> and <code>RemAssign</code> implementations for all vector types.</li>
<li>Added quaternion <code>xyz()</code> method for returning the vector part of the
quaternion.</li>
<li>Added <code>From((Scalar, Vector3))</code> for 4D vector types.</li>
</ul>
<h3>Changed</h3>
<ul>
<li>Deprecated <code>as_f32()</code>, <code>as_f64()</code>, <code>as_i32()</code> and <code>as_u32()</code> methods in favor
of more specific methods such as <code>as_vec2()</code>, <code>as_dvec2()</code>, <code>as_ivec2()</code> and
<code>as_uvec2()</code> and so on.</li>
</ul>
<h2>[0.17.3] - 2021-07-18</h2>
<h3>Fixed</h3>
<ul>
<li>Fix alignment unit tests on non x86 platforms.</li>
</ul>
<h2>[0.17.2] - 2021-07-15</h2>
<h3>Fixed</h3>
<ul>
<li>Fix alignment unit tests on i686 and S390x.</li>
</ul>
<h2>[0.17.1] - 2021-06-29</h2>
<h3>Added</h3>
<ul>
<li>Added <code>serde</code> support for <code>Affine2</code>, <code>DAffine2</code>, <code>Affine3A</code> and <code>DAffine3</code>.</li>
</ul>
<h2>[0.17.0] - 2021-06-26</h2>
<h3>Breaking changes</h3>
<ul>
<li>The addition of <code>Add</code> and <code>Sub</code> implementations of scalar values for vector
types may create ambiguities with existing calls to <code>add</code> and <code>sub</code>.</li>
<li>Removed <code>From&lt;Mat3&gt;</code> implementation for <code>Mat2</code> and <code>From&lt;DMat3&gt;</code> for <code>DMat2</code>.
These have been replaced by <code>Mat2::from_mat3()</code> and <code>DMat2::from_mat3()</code>.</li>
<li>Removed <code>From&lt;Mat4&gt;</code> implementation for <code>Mat3</code> and <code>From&lt;DMat4&gt;</code> for <code>DMat3</code>.
These have been replaced by <code>Mat3::from_mat4()</code> and <code>DMat3::from_mat4()</code>.</li>
</ul>
<!-- raw HTML omitted -->
</blockquote>
<p>... (truncated)</p>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a href="1b703518e7"><code>1b70351</code></a> Merge pull request <a href="https://github-redirect.dependabot.com/bitshifter/glam-rs/issues/231">#231</a> from bitshifter/prepare-0.18.0</li>
<li><a href="935ad5cf64"><code>935ad5c</code></a> Prepare 0.18.0 release.</li>
<li><a href="8d79d8e907"><code>8d79d8e</code></a> Still managed to mess up the tarpaulin config...</li>
<li><a href="78c30fc72c"><code>78c30fc</code></a> Fix syntax error in tarpaulin config.</li>
<li><a href="0258ce710d"><code>0258ce7</code></a> Can use rustdoc alias after msrv bump to 1.51.0.</li>
<li><a href="f9f7f2407c"><code>f9f7f24</code></a> Tidy up tarpaulin exlcudes.</li>
<li><a href="95dab216e1"><code>95dab21</code></a> Make some dev deps wasm only on not wasm.</li>
<li><a href="342176dde9"><code>342176d</code></a> Merge pull request <a href="https://github-redirect.dependabot.com/bitshifter/glam-rs/issues/230">#230</a> from DJMcNab/bytemuck-spirv</li>
<li><a href="837e5ebf7f"><code>837e5eb</code></a> Bytemuck now compiles on spirv</li>
<li><a href="bb35b1a691"><code>bb35b1a</code></a> Merge pull request <a href="https://github-redirect.dependabot.com/bitshifter/glam-rs/issues/228">#228</a> from bitshifter/wasm32-simd</li>
<li>Additional commits viewable in <a href="https://github.com/bitshifter/glam-rs/compare/0.17.3...0.18.0">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-06 18:49:40 +00:00
Daniel McNab
321d998615 Add convenience methods for checking a set of inputs (#2760)
# Objective

Make it easier to check if some set of inputs matches a key, such as if you want to allow all of space or up or w for jumping.

Currently, this requires:
```rust
if keyboard.pressed(KeyCode::Space)
            || keyboard.pressed(KeyCode::Up)
            || keyboard.pressed(KeyCode::W) {
    // ...
```

## Solution

Add an implementation of the helper methods, which very simply iterate through the items, used as:
```rust
if keyboard.any_pressed([KeyCode::Space, KeyCode::Up, KeyCode::W]) {
```
2021-09-01 21:21:41 +00:00
Daniel McNab
af20cad830 Add error messages for the spooky insertions (#2581)
# Objective

Sometimes, the unwraps in `entity_mut` could fail here, if the entity was despawned *before* this command was applied.

The simplest case involves two command buffers:
```rust
use bevy::prelude::*;
fn b(mut commands1: Commands, mut commands2: Commands) {
    let id = commands2.spawn().insert_bundle(()).id();
    commands1.entity(id).despawn();
}
fn main() {
    App::build().add_system(b.system()).run();
}
```

However, a more complicated version arises in the case of ambiguity:

```rust
use std::time::Duration;

use bevy::{app::ScheduleRunnerPlugin, prelude::*};
use rand::Rng;

fn cleanup(mut e: ResMut<Option<Entity>>) {
    *e = None;
}

fn sleep_randomly() {
    let mut rng = rand::thread_rng();
    std:🧵:sleep(Duration::from_millis(rng.gen_range(0..50)));
}

fn spawn(mut commands: Commands, mut e: ResMut<Option<Entity>>) {
    *e = Some(commands.spawn().insert_bundle(()).id());
}

fn despawn(mut commands: Commands, e: Res<Option<Entity>>) {
    let mut rng = rand::thread_rng();
    std:🧵:sleep(Duration::from_millis(rng.gen_range(0..50)));
    if let Some(e) = *e {
        commands.entity(e).despawn();
    }
}

fn main() {
    App::build()
        .add_system(cleanup.system().label("cleanup"))
        .add_system(sleep_randomly.system().label("before_despawn"))
        .add_system(despawn.system().after("cleanup").after("before_despawn"))
        .add_system(sleep_randomly.system().label("before_spawn"))
        .add_system(spawn.system().after("cleanup").after("before_spawn"))
        .insert_resource(None::<Entity>)
        .add_plugin(ScheduleRunnerPlugin::default())
        .run();
}
```

In the cases where this example crashes, it's because `despawn` was ordered before `spawn` in the topological ordering of systems (which determines when buffers are applied). However, `despawn` actually ran *after* `spawn`, because these systems are ambiguous, so the jiggles in the sleeping time triggered a case where this works.

## Solution

- Give a better error message
2021-09-01 20:59:25 +00:00
bilsen
35979922df Fix Option<NonSend<T>> and Option<NonSendMut<T>> (#2757)
# Objective
Fix `Option<NonSend<T>>` to work when T isn't `Send`
Fix `Option<NonSendMut<T>>` to work when T isnt in the world.

## Solution
Simple two row fix, properly initialize T in `OptionNonSendState` and remove `T: Component` bound for `Option<NonSendMut<T>>`
also added a rudimentary test


Co-authored-by: Ïvar Källström <ivar.kallstrom@gmail.com>
2021-08-31 20:52:21 +00:00
bilsen
c563dd094f Fix comment typos (#2737)
Fix some typos in system_param.rs

Co-authored-by: Ïvar Källström <ivar.kallstrom@gmail.com>
2021-08-31 20:09:38 +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
James Leflang
f38a6e670b Document QueryState (#2298)
# Objective

- QueryState is lacking documentation.

Fixes #2090 

## Solution

- Provide documentation that mirrors Query (as suggested in #2090) and modify as needed.


Co-authored-by: James Leflang <59455417+jleflang@users.noreply.github.com>
2021-08-25 23:56:24 +00:00
Carter Anderson
b47217bfab Spawn specific entities: spawn or insert operations, refactor spawn internals, world clearing (#2673)
This upstreams the code changes used by the new renderer to enable cross-app Entity reuse:

* Spawning at specific entities
* get_or_spawn: spawns an entity if it doesn't already exist and returns an EntityMut
* insert_or_spawn_batch: the batched equivalent to `world.get_or_spawn(entity).insert_bundle(bundle)`
* Clearing entities and storages
* Allocating Entities with "invalid" archetypes. These entities cannot be queried / are treated as "non existent". They serve as "reserved" entities that won't show up when calling `spawn()`. They must be "specifically spawned at" using apis like `get_or_spawn(entity)`.

In combination, these changes enable the "render world" to clear entities / storages each frame and reserve all "app world entities". These can then be spawned during the "render extract step".

This refactors "spawn" and "insert" code in a way that I think is a massive improvement to legibility and re-usability. It also yields marginal performance wins by reducing some duplicate lookups (less than a percentage point improvement on insertion benchmarks). There is also some potential for future unsafe reduction (by making BatchSpawner and BatchInserter generic). But for now I want to cut down generic usage to a minimum to encourage smaller binaries and faster compiles.

This is currently a draft because it needs more tests (although this code has already had some real-world testing on my custom-shaders branch). 

I also fixed the benchmarks (which currently don't compile!) / added new ones to illustrate batching wins.

After these changes, Bevy ECS is basically ready to accommodate the new renderer. I think the biggest missing piece at this point is "sub apps".
2021-08-25 23:34:02 +00:00
Lucas Kent
c5717b5a91 Document collide args (#2721)
Fixes https://github.com/bevyengine/bevy/issues/2720#issuecomment-904623168

Possibly we should omit the extra bit in brackets, not sure if its warranted.
2021-08-24 18:07:51 +00:00
Garett Cooper
47ccebf486 Implement IntoSystemDescriptor for SystemDescriptor (#2718)
# Objective

- Fixes  #2716

## Solution

- Implements the the IntoSystemDescriptor trait for SystemDescriptor, which simply returns itself
2021-08-24 17:46:53 +00:00
Carter Anderson
9898469e9e Sub app label changes (#2717)
Makes some tweaks to the SubApp labeling introduced in #2695:

* Ergonomics improvements
* Removes unnecessary allocation when retrieving subapp label
* Removes the newly added "app macros" crate in favor of bevy_derive
* renamed RenderSubApp to RenderApp

@zicklag (for reference)
2021-08-24 06:37:28 +00:00
Mirko Rainer
958f8b124a Use Explicit Names for Flex Direction (#2672)
# Objective

- Clarify vague meaning of "Ltr" and "Rtl". For someone familiar with Flex Box, this is easy to understand, but being more explicit will help beginners or those unfamiliar, without the need to do research.

## Solution

- Change three letter abbreviation to fully descriptive name.
2021-08-24 01:50:21 +00:00
Christopher Durham
481fa3c7a0 derive Debug, Clone for FixedState (StableAHash) (#2694)
This matches `ahash::RandomState`, which provides both `Debug` and `Clone`.

Notably, implementing `Clone` allows the `StableHashMap`/`Set` to also implement `Clone`.

# Objective

- Allow `bevy_utils::StableHashMap` to be cloned.

## Solution

- Derive `Clone` for `bevy_utils::FixedState`.
- Also derive `Debug`, since we're touching it anyway, and this aligns `FixedState` with `ahash::RandomState`.
2021-08-24 01:31:39 +00:00
Zicklag
e290a7e29c Implement Sub-App Labels (#2695)
This is a rather simple but wide change, and it involves adding a new `bevy_app_macros` crate. Let me know if there is a better way to do any of this!

---

# Objective

- Allow adding and accessing sub-apps by using a label instead of an index

## Solution

- Migrate the bevy label implementation and derive code to the `bevy_utils` and `bevy_macro_utils` crates and then add a new `SubAppLabel` trait to the `bevy_app` crate that is used when adding or getting a sub-app from an app.
2021-08-24 00:31:21 +00:00
bjorn3
d84c7f9066 Reduce visibility of various types and fields (#2690)
See the individual commits.
2021-08-19 20:02:25 +00:00
dependabot[bot]
9788b386c7 Update glam requirement from 0.15.1 to 0.17.3 (#2500)
Updates the requirements on [glam](https://github.com/bitshifter/glam-rs) to permit the latest version.
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a href="https://github.com/bitshifter/glam-rs/blob/master/CHANGELOG.md">glam's changelog</a>.</em></p>
<blockquote>
<h2>[0.17.3] - 2021-07-18</h2>
<h3>Fixed</h3>
<ul>
<li>Fix alignment unit tests on non x86 platforms.</li>
</ul>
<h2>[0.17.2] - 2021-07-15</h2>
<h3>Fixed</h3>
<ul>
<li>Fix alignment unit tests on i686 and S390x.</li>
</ul>
<h2>[0.17.1] - 2021-06-29</h2>
<h3>Added</h3>
<ul>
<li>Added <code>serde</code> support for <code>Affine2</code>, <code>DAffine2</code>, <code>Affine3A</code> and <code>DAffine3</code>.</li>
</ul>
<h2>[0.17.0] - 2021-06-26</h2>
<h3>Breaking changes</h3>
<ul>
<li>The addition of <code>Add</code> and <code>Sub</code> implementations of scalar values for vector
types may create ambiguities with existing calls to <code>add</code> and <code>sub</code>.</li>
<li>Removed <code>From&lt;Mat3&gt;</code> implementation for <code>Mat2</code> and <code>From&lt;DMat3&gt;</code> for <code>DMat2</code>.
These have been replaced by <code>Mat2::from_mat3()</code> and <code>DMat2::from_mat3()</code>.</li>
<li>Removed <code>From&lt;Mat4&gt;</code> implementation for <code>Mat3</code> and <code>From&lt;DMat4&gt;</code> for <code>DMat3</code>.
These have been replaced by <code>Mat3::from_mat4()</code> and <code>DMat3::from_mat4()</code>.</li>
<li>Removed deprecated <code>from_slice_unaligned()</code>, <code>write_to_slice_unaligned()</code>,
<code>from_rotation_mat4</code> and <code>from_rotation_ypr()</code> methods.</li>
</ul>
<h3>Added</h3>
<ul>
<li>Added <code>col_mut()</code> method which returns a mutable reference to a matrix column
to all matrix types.</li>
<li>Added <code>AddAssign</code>, <code>MulAssign</code> and <code>SubAssign</code> implementations for all matrix
types.</li>
<li>Added <code>Add</code> and <code>Sub</code> implementations of scalar values for vector types.</li>
<li>Added more <code>glam_assert!</code> checks and documented methods where they are used.</li>
<li>Added vector projection and rejection methods <code>project_onto()</code>,
<code>project_onto_normalized()</code>, <code>reject_from()</code> and <code>reject_from_normalized()</code>.</li>
<li>Added <code>Mat2::from_mat3()</code>, <code>DMat2::from_mat3()</code>, <code>Mat3::from_mat4()</code>,
<code>DMat3::from_mat4()</code> which create a smaller matrix from a larger one,
discarding a final row and column of the input matrix.</li>
<li>Added <code>Mat3::from_mat2()</code>, <code>DMat3::from_mat2()</code>, <code>Mat4::from_mat3()</code> and
<code>DMat4::from_mat3()</code> which create an affine transform from a smaller linear
transform matrix.</li>
</ul>
<h3>Changed</h3>
<!-- raw HTML omitted -->
</blockquote>
<p>... (truncated)</p>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a href="ecf3904b2f"><code>ecf3904</code></a> Prepare release 0.17.3</li>
<li><a href="95e02bb43e"><code>95e02bb</code></a> Merge branch 'master' of github.com:bitshifter/glam-rs</li>
<li><a href="c6dc702583"><code>c6dc702</code></a> More alignment test fixes for when SSE2 is not avaialable.</li>
<li><a href="87a3b25872"><code>87a3b25</code></a> Merge pull request <a href="https://github-redirect.dependabot.com/bitshifter/glam-rs/issues/216">#216</a> from bitshifter/prepare-0.17.2</li>
<li><a href="269e514090"><code>269e514</code></a> Prepare for 0.17.2 release.</li>
<li><a href="1da7d6459c"><code>1da7d64</code></a> Merge pull request <a href="https://github-redirect.dependabot.com/bitshifter/glam-rs/issues/215">#215</a> from bitshifter/issue-213</li>
<li><a href="dc60e20925"><code>dc60e20</code></a> Fix align asserts on i686 and S390x architectures.</li>
<li><a href="bd8b30e9fb"><code>bd8b30e</code></a> Merge pull request <a href="https://github-redirect.dependabot.com/bitshifter/glam-rs/issues/212">#212</a> from remilauzier/master</li>
<li><a href="a4e97c0b54"><code>a4e97c0</code></a> Update approx to 0.5</li>
<li><a href="059f619525"><code>059f619</code></a> Prepare 0.17.1 release (<a href="https://github-redirect.dependabot.com/bitshifter/glam-rs/issues/211">#211</a>)</li>
<li>Additional commits viewable in <a href="https://github.com/bitshifter/glam-rs/compare/0.15.1...0.17.3">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-08-19 01:32:31 +00:00
François
1a758dd9e2 update ndk-glue to 0.4 (#2684)
# Objective

- We currently depends on ndk 0.2, 0.3, 0.4
- Only 0.2 dependencies comes from Bevy itself

## Solution

- Replace #1371 
- Update Bevy to ndk-glue 0.4
- Also fixes duplicate dependency CI issue
2021-08-19 01:02:15 +00:00
Georg Friedrich Schuppe
98a08cf495 feat: remove_component for ReflectComponent (#2682)
# Objective

While implementing a plugin for my rollback networking library, I needed to load/save parts of the world. For this, I made a WorldSnapshot that works quite like the current DynamicScene. Using a TypeRegistry to register component types I want to save/load and then using ReflectComponents methods to add or apply components of the given types. 

However, I noticed there is no method to remove components from entities through the ReflectComponent.

## Solution

I added a `remove_component` field to the `ReflectComponent` struct, as well as a `pub fn remove_component(&self, world: &mut World, entity: Entity)` to call that function in `remove_component`. This follows exactly the same pattern all other methods/fields in this struct look like.

This is an example how it could be used (at least how I would use it):
6c003f86f1/src/world_snapshot.rs (L133)
2021-08-18 20:57:58 +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
Alice Cecile
d59fc076e8 Comprehensive CONTRIBUTING.md (#2040)
[**RENDERED**](https://github.com/alice-i-cecile/bevy/blob/better-contributing/CONTRIBUTING.md)

Improves #910. As discussed in #1309, we'll need to synchronize content between this and the Bevy website in some way (and clean up the .github file perhaps?).

I think doing it as a root-directory file is nicer for discovery, but that's a conversation I'm interested in having.

This document is intended to be helpful to beginners to open source and Bevy, and captures what I've learned about our informal practices and values.

Reviewers: I'm particularly interested in:
- opinions on the items **What we're trying to build**, where I discuss some of the project's high-level values and goals
- more relevant details on the `bevy` subcrates for **Getting oriented**
- useful tricks and best practices that I missed
- better guidance on how to contribute to the Bevy book from @cart <3
2021-08-14 19:21:36 +00:00
Martin Svanberg
96f0e02728 Implement Clone for Fetches (#2641)
# Objective

This:

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

fn main() {
    App::new()
    .add_system(test)
    .run();
}

fn test(entities: Query<Entity>) {
    let mut combinations = entities.iter_combinations_mut();
    while let Some([e1, e2]) = combinations.fetch_next() {    
        dbg!(e1);
    }
}
```

fails with the message "the trait bound `bevy::ecs::query::EntityFetch: std::clone::Clone` is not satisfied". 


## Solution

It works after adding the naive clone implementation to EntityFetch. I'm not super familiar with ECS internals, so I'd appreciate input on this.
2021-08-14 03:14:16 +00:00
davier
6aedb2500a Cleanup FromResources (#2601)
## Objective

- Clean up remaining references to the trait `FromResources`, which was replaced in favor of `FromWorld` during the ECS rework.

## Solution

- Remove the derive macro for `FromResources`
- Change doc references of `FromResources` to `FromWorld`

(this is the first item in #2576)
2021-08-13 22:21:34 +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
Piotr Balcer
b13472dae4 fix missing paths in ECS SystemParam derive macro v2 (#2550)
This is an updated version of #1434 PR. I've encountered this macro problem while trying to use @woubuc's bevy-event-set crate.

Co-authored-by: Piotr Balcer <piotr@balcer.eu>
2021-08-11 01:32:58 +00:00
Mirko Rainer
a023b687dd Link Minimal and Default plugins in the docs. (#2583)
I didn't know about MinimalPlugins for way too long. This should increase visibility for others.

# Objective

Improve visibility and discover in the docs for Default and Minimal Plugins.

## Solution

Links the two Docs pages. 



Co-authored-by: Mirko Rainer <52899592+mirkoRainer@users.noreply.github.com>
2021-08-10 23:46:39 +00:00
Klim Tsoutsman
0c91317102 Change definition of ScheduleRunnerPlugin (#2606)
# Objective

- Allow `ScheduleRunnerPlugin` to be instantiated without curly braces. Other plugins in the library already use the semicolon syntax.
- Currently, you have to do the following:
```rust
App::build()
    .add_plugin(bevy::core::CorePlugin)
    .add_plugin(bevy::app::ScheduleRunnerPlugin {})
```
- With the proposed change you can do this:
```rust
App::build()
    .add_plugin(bevy::core::CorePlugin)
    .add_plugin(bevy::app::ScheduleRunnerPlugin)
```

## Solution

- Change the `ScheduleRunnerPlugin` definition to use a semicolon instead of curly braces.
2021-08-10 02:48:40 +00:00
Hoidigan
49038d03f5 Remove with bundle filter (#2623)
# Objective

Fixes #2620

## Solution

Remove WithBundle filter and temporarily remove example for query_bundle.
2021-08-10 01:55:52 +00:00
davier
336583a86b Update EntityMut's location in push_children() and insert_children() (#2604)
## Objective

This code would result in a crash:
```rust
use bevy::prelude::*;

fn main() {
    let mut world = World::new();
    let child = world.spawn().id();
    world.spawn().push_children(&[child]);
}
```

## Solution

Update the `EntityMut`'s location after inserting a component on the children entities, as it may have changed.
2021-08-10 01:12:42 +00:00
Protowalker
03e2045c8d fix typo (paramater to parameter) (#2590)
there was a typo 👀 i fixed it 👀
2021-08-06 20:55:24 +00:00
Robert Swain
ae4f809a52 Port bevy_gltf to pipelined-rendering (#2537)
# Objective

Port bevy_gltf to the pipelined-rendering branch.

## Solution

crates/bevy_gltf has been copied and pasted into pipelined/bevy_gltf2 and modifications were made to work with the pipelined-rendering branch. Notably vertex tangents and vertex colours are not supported.

Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2021-07-30 03:37:34 +00:00
Carter Anderson
7b336fd779 fix nightly clippy lints (#2568)
Fix new nightly clippy lints on `pipelined-rendering`
2021-07-30 03:17:27 +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
Josh Kuhn
54ff7aaa1e Bump notify to 5.0.0-pre.11 (#2564)
# Objective

notify 5.0.0-pre.11 breaks the interface again, but apparently in a way that's similar to how it used to be

## Solution

Bump `bevy_asset` dependency on notify to `5.0.0-pre.11` and fix the errors that crop up.

It looks like `pre.11` was mentioned in #2528 by @mockersf but there's no mention of why `pre.10` was chosen ultimately.
2021-07-29 23:56:16 +00:00
Boxy
155068a090 Add 's (state) lifetime to Fetch (#2515)
Allows iterators to return things that borrow data from `QueryState`, needed this in my relations PR figure might be worth landing separately maybe
2021-07-29 21:14:22 +00: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
Carter Anderson
3ec6b3f9a0 move bevy_core_pipeline to its own plugin (#2552)
This decouples the opinionated "core pipeline" from the new (less opinionated) bevy_render crate. The "core pipeline" is intended to be used by crates like bevy_sprites, bevy_pbr, bevy_ui, and 3rd party crates that extends core rendering functionality.
2021-07-28 21:29:32 +00:00
bjorn3
86cc70b902 Refactor ECS to reduce the dependency on a 1-to-1 mapping between components and real rust types (#2490)
# Objective

There is currently a 1-to-1 mapping between components and real rust types. This means that it is impossible for multiple components to be represented by the same rust type or for a component to not have a rust type at all. This means that component types can't be defined in languages other than rust like necessary for scripting or sandboxed (wasm?) plugins.

## Solution

Refactor `ComponentDescriptor` and `Bundle` to remove `TypeInfo`. `Bundle` now uses `ComponentId` instead. `ComponentDescriptor` is now always created from a rust type instead of through the `TypeInfo` indirection. A future PR may make it possible to construct a `ComponentDescriptor` from it's fields without a rust type being involved.
2021-07-28 19:29:12 +00:00
Boxy
4b6238d35a Remove empty module (#2558)
self explanatory
2021-07-28 03:10:55 +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
François
234b2efa71 Inline world get (#2520)
# Objective

While looking at the code of `World`, I noticed two basic functions (`get` and `get_mut`) that are probably called a lot and with simple code that are not `inline`

## Solution

- Add benchmark to check impact
- Add `#[inline]`


```
group                                            this pr                                main
-----                                            ----                                   ----
world_entity/50000_entities                      1.00   115.9±11.90µs        ? ?/sec    1.71   198.5±29.54µs        ? ?/sec
world_get/50000_entities_SparseSet               1.00   409.9±46.96µs        ? ?/sec    1.18   483.5±36.41µs        ? ?/sec
world_get/50000_entities_Table                   1.00   391.3±29.83µs        ? ?/sec    1.16   455.6±57.85µs        ? ?/sec
world_query_for_each/50000_entities_SparseSet    1.02   121.3±18.36µs        ? ?/sec    1.00   119.4±13.88µs        ? ?/sec
world_query_for_each/50000_entities_Table        1.03     13.8±0.96µs        ? ?/sec    1.00     13.3±0.54µs        ? ?/sec
world_query_get/50000_entities_SparseSet         1.00   666.9±54.36µs        ? ?/sec    1.03   687.1±57.77µs        ? ?/sec
world_query_get/50000_entities_Table             1.01   584.4±55.12µs        ? ?/sec    1.00   576.3±36.13µs        ? ?/sec
world_query_iter/50000_entities_SparseSet        1.01   169.7±19.50µs        ? ?/sec    1.00   168.6±32.56µs        ? ?/sec
world_query_iter/50000_entities_Table            1.00     26.2±1.38µs        ? ?/sec    1.91     50.0±4.40µs        ? ?/sec
```

I didn't add benchmarks for the mutable path but I don't see how it could hurt to make it inline too...
2021-07-27 23:19:26 +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
Boxy
c83a184e2f Dedupe move logic in remove_bundle and remove_bundle_intersection (#2521)
This logic was in both `remove_bundle` and ` remove_bundle_intersection` but only differed by whether we call `.._forget_missing_..` or `.._drop_missing_..`
2021-07-27 05:16:47 +00:00
Carter Anderson
2e99d84cdc remove .system from pipelined code (#2538)
Now that we have main features, lets use them!
2021-07-26 23:44:23 +00:00
Carter Anderson
955c79f299 adapt to upstream changes 2021-07-24 16:43:37 -07:00
Robert Swain
326b20643f Directional light and shadow (#6)
Directional light and shadow
2021-07-24 16:43:37 -07:00
Carter Anderson
ac6b27925e fix clippy 2021-07-24 16:43:37 -07:00
Carter Anderson
829f723bf3 Add log crate compatibility to bevy_log 2021-07-24 16:43:37 -07:00
Robert Swain
b1a91a823f bevy_pbr2: Add support for most of the StandardMaterial textures (#4)
* bevy_pbr2: Add support for most of the StandardMaterial textures

Normal maps are not included here as they require tangents in a vertex attribute.

* bevy_pbr2: Ensure RenderCommandQueue is ready for PbrShaders init

* texture_pipelined: Add a light to the scene so we can see stuff

* WIP bevy_pbr2: back to front sorting hack

* bevy_pbr2: Uniform control flow for texture sampling in pbr.frag

From 'fintelia' on the Bevy Render Rework Round 2 discussion:

"My understanding is that GPUs these days never use the "execute both branches
and select the result" strategy. Rather, what they do is evaluate the branch
condition on all threads of a warp, and jump over it if all of them evaluate to
false. If even a single thread needs to execute the if statement body, however,
then the remaining threads are paused until that is completed."

* bevy_pbr2: Simplify texture and sampler names

The StandardMaterial_ prefix is no longer needed

* bevy_pbr2: Match default 'AmbientColor' of current bevy_pbr for now

* bevy_pbr2: Convert from non-linear to linear sRGB for the color uniform

* bevy_pbr2: Add pbr_pipelined example

* Fix view vector in pbr frag to work in ortho

* bevy_pbr2: Use a 90 degree y fov and light range projection for lights

* bevy_pbr2: Add AmbientLight resource

* bevy_pbr2: Convert PointLight color to linear sRGB for use in fragment shader

* bevy_pbr2: pbr.frag: Rename PointLight.projection to view_projection

The uniform contains the view_projection matrix so this was incorrect.

* bevy_pbr2: PointLight is an OmniLight as it has a radius

* bevy_pbr2: Factoring out duplicated code

* bevy_pbr2: Implement RenderAsset for StandardMaterial

* Remove unnecessary texture and sampler clones

* fix comment formatting

* remove redundant Buffer:from

* Don't extract meshes when their material textures aren't ready

* make missing textures in the queue step an error

Co-authored-by: Aevyrie <aevyrie@gmail.com>
Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2021-07-24 16:43:37 -07:00
Carter Anderson
25de2d1819 Port Mesh to RenderAsset, add Slab and FrameSlabMap garbage collection for Bind Groups 2021-07-24 16:43:37 -07:00
Carter Anderson
09043b66ce fix tracing and add graph spans 2021-07-24 16:43:37 -07:00
Carter Anderson
13ca00178a bevy_render now uses wgpu directly 2021-07-24 16:43:37 -07:00
Robert Swain
01116b1fdb StandardMaterial flat values (#3)
StandardMaterial flat values
2021-07-24 16:43:37 -07:00
Carter Anderson
579c769f7c Fix ExclusiveSystemCoerced so it updates system with new archetypes 2021-07-24 16:43:37 -07:00
Carter Anderson
3400fb4e61 SubGraphs, Views, Shadows, and more 2021-07-24 16:43:37 -07:00
StarArawn
cdf06ea293 Added compute to the new pipelined renderer. 2021-07-24 16:43:37 -07:00
Carter Anderson
4ac2ed7cc6 pipelined rendering proof of concept 2021-07-24 16:43:37 -07:00
François
a4e5e2790e fix version of notify to 5.0.0-pre.2 (#2528)
# Objective

- https://github.com/notify-rs/notify changed their api in the latest pre-release of 0.5.0
- This breaks current main AND v0.5.0

## Solution

- Fix the dependency to the known working version

before : https://docs.rs/notify/5.0.0-pre.2/notify/trait.Watcher.html
after : https://docs.rs/notify/5.0.0-pre.11/notify/trait.Watcher.html
2021-07-24 01:41:48 +00: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