Commit graph

2788 commits

Author SHA1 Message Date
Jakob Hellermann
60584139de untyped APIs for components and resources (#4447)
# Objective

Even if bevy itself does not provide any builtin scripting or modding APIs, it should have the foundations for building them yourself.
For that it should be enough to have APIs that are not tied to the actual rust types with generics, but rather accept `ComponentId`s and `bevy_ptr` ptrs.

## Solution

Add the following APIs to bevy
```rust
fn EntityRef::get_by_id(ComponentId) -> Option<Ptr<'w>>;
fn EntityMut::get_by_id(ComponentId) -> Option<Ptr<'_>>;
fn EntityMut::get_mut_by_id(ComponentId) -> Option<MutUntyped<'_>>;

fn World::get_resource_by_id(ComponentId) -> Option<Ptr<'_>>;
fn World::get_resource_mut_by_id(ComponentId) -> Option<MutUntyped<'_>>;

// Safety: `value` must point to a valid value of the component
unsafe fn World::insert_resource_by_id(ComponentId, value: OwningPtr);

fn ComponentDescriptor::new_with_layout(..) -> Self;
fn World::init_component_with_descriptor(ComponentDescriptor) -> ComponentId;
```

~~This PR would definitely benefit from #3001 (lifetime'd pointers) to make sure that the lifetimes of the pointers are valid and the my-move pointer in `insert_resource_by_id` could be an `OwningPtr`, but that can be adapter later if/when #3001 is merged.~~

### Not in this PR
- inserting components on entities (this is very tied to types with bundles and the `BundleInserter`)
- an untyped version of a query (needs good API design, has a large implementation complexity, can be done in a third-party crate)

Co-authored-by: Jakob Hellermann <hellermann@sipgate.de>
2022-05-30 15:32:47 +00:00
Matthias Schiffer
5256561b7a OrthographicProjection: place origin at integer pixel with WindowSize scaling mode (#4085)
# Objective

One way to avoid texture atlas bleeding is to ensure that every vertex is
placed at an integer pixel coordinate. This is a particularly appealing
solution for regular structures like tile maps.

Doing so is currently harder than necessary when the WindowSize scaling
mode and Center origin are used: For odd window width or height, the
origin of the coordinate system is placed in the middle of a pixel at
some .5 offset.

## Solution

Avoid this issue by rounding the half width and height values.
2022-05-30 15:14:12 +00:00
François
d353fbc6ea update image to 0.24 (#4121)
# Objective

- update image to 0.24

## Solution

- `Bgra*` variants support have been removed from image, remove them from Bevy code
- replace #4003 

changeling: https://github.com/image-rs/image/blob/master/CHANGES.md
2022-05-28 02:00:55 +00:00
Thierry Berger
99e689cfd2 remove unneeded msaa explicit addition from examples (#4830)
# Objective

- Coming from 7a596f1910 (r876310734)
- Simplify the examples regarding addition of `Msaa` Resource with default value.

## Solution

- Remove addition of `Msaa` Resource with default value from examples,
2022-05-27 20:52:12 +00:00
dependabot[bot]
c89af06c65 Update tracing-tracy requirement from 0.8.0 to 0.9.0 (#4786)
Updates the requirements on [tracing-tracy](https://github.com/nagisa/rust_tracy_client) to permit the latest version.
<details>
<summary>Commits</summary>
<ul>
<li><a href="13b335a710"><code>13b335a</code></a> Remove ability to disable the client at runtime</li>
<li><a href="69e44977ee"><code>69e4497</code></a> The upgrades to 0.8.1</li>
<li><a href="c204b60c7a"><code>c204b60</code></a> Cancel the old test runs</li>
<li><a href="939bd04c1c"><code>939bd04</code></a> Remove the thread initialization calls</li>
<li><a href="7024e776bb"><code>7024e77</code></a> Update Tracy client bindings to v0.8.1</li>
<li><a href="5c54baa244"><code>5c54baa</code></a> tracy-client 0.12.7</li>
<li><a href="f183050b20"><code>f183050</code></a> Non-allocating <code>span!</code> macro</li>
<li><a href="15936ea751"><code>15936ea</code></a> tracy-client 0.12.6</li>
<li><a href="26d0c50542"><code>26d0c50</code></a> Relax literal the requirement of the create_plot macro so that it can be used...</li>
<li>See full diff in <a href="https://github.com/nagisa/rust_tracy_client/compare/tracing-tracy-v0.8.0...tracing-tracy-v0.9.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>
2022-05-27 11:54:57 +00:00
Christopher Durham
589c52afe5 Make bevy_app's optional bevy_reflect dependency actually optional (#4846)
# Objective

- Make bevy_app's optional bevy_reflect dependency actually optional
- Because bevy_ecs has a default dependency on bevy_reflect, bevy_app includes bevy_reflect transitively even with default-features=false, despite the optional dependency indicating that it was intended to be able to leave out bevy_reflect.

## Solution

- Make bevy_app not enable bevy_ecs's default features, and then use [the `dep:` syntax](https://doc.rust-lang.org/cargo/reference/features.html#optional-dependencies) introduced in 1.60 to make the default bevy_reflect feature enable bevy_ecs's bevy_reflect feature/dependency.

---

## Changelog

- bevy_app no longer enables bevy_ecs's `bevy_reflect` feature when included without its own `bevy_reflect` feature (which is on by default).
2022-05-26 02:04:22 +00:00
Christopher Durham
644bd5dbc6 Split time functionality into bevy_time (#4187)
# Objective

Reduce the catch-all grab-bag of functionality in bevy_core by minimally splitting off time functionality into bevy_time. Functionality like that provided by #3002 would increase the complexity of bevy_time, so this is a good candidate for pulling into its own unit.

A step in addressing #2931 and splitting bevy_core into more specific locations.

## Solution

Pull the time module of bevy_core into a new crate, bevy_time.

# Migration guide

- Time related types (e.g. `Time`, `Timer`, `Stopwatch`, `FixedTimestep`, etc.) should be imported from `bevy::time::*` rather than `bevy::core::*`.
- If you were adding `CorePlugin` manually, you'll also want to add `TimePlugin` from `bevy::time`.
- The `bevy::core::CorePlugin::Time` system label is replaced with `bevy::time::TimeSystem`.

Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2022-05-26 00:27:18 +00:00
Alice Cecile
d683d9b9f5 Improve docs and naming for RawWindowHandle functionality (#4335)
# Objective

- As noticed in #4333 by @x-52, the exact purpose and logic of `HasRawWIndowHandleWrapper` is unclear
- Unfortunately, there are rather good reasons why this design is needed (and why we can't just `impl HasRawWindowHandle for RawWindowHandleWrapper` 

## Solution

- Rename `HasRawWindowHandleWrapper` to `ThreadLockedRawWindowHandleWrapper`, reflecting the primary distinction
- Document how this design is intended to be used
- Leave comments explaining why this design must exist


## Migration Guide

- renamed `HasRawWindowHandleWrapper` to `ThreadLockedRawWindowHandleWrapper`
2022-05-26 00:09:23 +00:00
Niklas Eicker
f271d734e6 Rename Color::as_hlsa_f32 to Color::as_hsla_f32 (#4827)
# Objective

Make the function consistent with returned values and `as_hsla` method

Fixes #4826 

## Solution

- Rename the method


## Migration Guide

- Rename the method
2022-05-25 17:46:58 +00:00
Carter Anderson
5dd30b6279 Remove markdown dead link check (#4839)
# Objective

This fails constantly and causes more pain than it is worth.

## Solution

Remove dead link checks.

Alternative to #4837, which is more granular but ironically still fails to build. I'm in favor of the nuclear option.

Fixes #4575
2022-05-25 05:08:34 +00:00
Carter Anderson
fed93a0edc Optionally resize Window canvas element to fit parent element (#4726)
Currently Bevy's web canvases are "fixed size". They are manually set to specific dimensions. This might be fine for some games and website layouts, but for sites with flexible layouts, or games that want to "fill" the browser window, Bevy doesn't provide the tools needed to make this easy out of the box.

There are third party plugins like [bevy-web-resizer](https://github.com/frewsxcv/bevy-web-resizer/) that listen for window resizes, take the new dimensions, and resize the winit window accordingly. However this only covers a subset of cases and this is common enough functionality that it should be baked into Bevy.

A significant motivating use case here is the [Bevy WASM Examples page](https://bevyengine.org/examples/). This scales the canvas to fit smaller windows (such as mobile). But this approach both breaks winit's mouse events and removes pixel-perfect rendering (which means we might be rendering too many or too few pixels).  https://github.com/bevyengine/bevy-website/issues/371

In an ideal world, winit would support this behavior out of the box. But unfortunately that seems blocked for now: https://github.com/rust-windowing/winit/pull/2074. And it builds on the ResizeObserver api, which isn't supported in all browsers yet (and is only supported in very new versions of the popular browsers).

While we wait for a complete winit solution, I've added a `fit_canvas_to_parent` option to WindowDescriptor / Window, which when enabled will listen for window resizes and resize the Bevy canvas/window to fit its parent element. This enables users to scale bevy canvases using arbitrary CSS, by "inheriting" their parents' size. Note that the wrapper element _is_ required because winit overrides the canvas sizing with absolute values on each resize.

There is one limitation worth calling out here: while the majority of  canvas resizes will be triggered by window resizes, modifying element layout at runtime (css animations, javascript-driven element changes, dev-tool-injected changes, etc) will not be detected here. I'm not aware of a good / efficient event-driven way to do this outside of the ResizeObserver api. In practice, window-resize-driven canvas resizing should cover the majority of use cases. Users that want to actively poll for element resizes can just do that (or we can build another feature and let people choose based on their specific needs).

I also took the chance to make a couple of minor tweaks:
* Made the `canvas` window setting available on all platforms. Users shouldn't need to deal with cargo feature selection to support web scenarios. We can just ignore the value on non-web platforms. I added documentation that explains this.
*  Removed the redundant "initial create windows" handler. With the addition of the code in this pr, the code duplication was untenable.

This enables a number of patterns:

## Easy "fullscreen window" mode for the default canvas

The "parent element" defaults to the `<body>` element.

```rust
app
  .insert_resource(WindowDescriptor {
    fit_canvas_to_parent: true,
    ..default()
  })
``` 
And CSS:
```css
html, body {
    margin: 0;
    height: 100%;
}
```

## Fit custom canvas to "wrapper" parent element

```rust
app
  .insert_resource(WindowDescriptor {
    fit_canvas_to_parent: true,
    canvas: Some("#bevy".to_string()),
    ..default()
  })
``` 
And the HTML:
```html
<div style="width: 50%; height: 100%">
  <canvas id="bevy"></canvas>
</div>
```
2022-05-20 23:13:48 +00:00
Teodor Tanasoaia
b6eededea4 Use uniform buffer usage for SkinnedMeshUniform instead of all usages (#4816)
# Objective

fixes #4811 (caused by #4339 [[exact change](https://github.com/bevyengine/bevy/pull/4339/files#diff-4bf3ed03d4129aad9f5678ba19f9b14ee8e3e61d6f6365e82197b01c74468b10R712-R721)] - where the buffer type has been changed from `UniformVec` to `BufferVec`)

## Solution

Use uniform buffer usage for `SkinnedMeshUniform` instead of all usages due to the `Default` derive.
2022-05-20 22:05:32 +00:00
Gino Valente
3a93b677a1 bevy_reflect: Added get_boxed method to reflect_trait (#4120)
# Objective

Allow `Box<dyn Reflect>` to be converted into a `Box<dyn MyTrait>` using the `#[reflect_trait]` macro. The other methods `get` and `get_mut` only provide a reference to the reflected object.

## Solution

Add a `get_boxed` method to the `Reflect***` struct generated by the `#[reflect_trait]` macro. This method takes in a `Box<dyn Reflect>` and returns a `Box<dyn MyTrait>`.


Co-authored-by: MrGVSV <49806985+MrGVSV@users.noreply.github.com>
2022-05-20 13:31:49 +00:00
Teodor Tanasoaia
7cb4d3cb43 Migrate to encase from crevice (#4339)
# Objective

- Unify buffer APIs
- Also see #4272

## Solution

- Replace vendored `crevice` with `encase`

---

## Changelog

Changed `StorageBuffer`
Added `DynamicStorageBuffer`
Replaced `UniformVec` with `UniformBuffer`
Replaced `DynamicUniformVec` with `DynamicUniformBuffer`

## Migration Guide

### `StorageBuffer`

removed `set_body()`, `values()`, `values_mut()`, `clear()`, `push()`, `append()`
added `set()`, `get()`, `get_mut()`

### `UniformVec` -> `UniformBuffer`

renamed `uniform_buffer()` to `buffer()`
removed `len()`, `is_empty()`, `capacity()`, `push()`, `reserve()`, `clear()`, `values()`
added `set()`, `get()`

### `DynamicUniformVec` -> `DynamicUniformBuffer`

renamed `uniform_buffer()` to `buffer()`
removed `capacity()`, `reserve()`


Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2022-05-18 21:09:21 +00:00
Boxy
1320818f96 Fix unsoundness with Or/AnyOf/Option component access' (#4659)
# Objective

Fixes #4657

Example code that wasnt panic'ing before this PR (and so was unsound):
```rust
    #[test]
    #[should_panic = "error[B0001]"]
    fn option_has_no_filter_with() {
        fn sys(_1: Query<(Option<&A>, &mut B)>, _2: Query<&mut B, Without<A>>) {}
        let mut world = World::default();
        run_system(&mut world, sys);
    }

    #[test]
    #[should_panic = "error[B0001]"]
    fn any_of_has_no_filter_with() {
        fn sys(_1: Query<(AnyOf<(&A, ())>, &mut B)>, _2: Query<&mut B, Without<A>>) {}
        let mut world = World::default();
        run_system(&mut world, sys);
    }

    #[test]
    #[should_panic = "error[B0001]"]
    fn or_has_no_filter_with() {
        fn sys(_1: Query<&mut B, Or<(With<A>, With<B>)>>, _2: Query<&mut B, Without<A>>) {}
        let mut world = World::default();
        run_system(&mut world, sys);
    }
```
## Solution

- Only add the intersection of `with`/`without` accesses of all the elements in `Or/AnyOf` to the world query's `FilteredAccess<ComponentId>` instead of the union.
- `Option`'s fix can be thought of the same way since its basically `AnyOf<T, ()>` but its impl is just simpler as `()` has no `with`/`without` accesses
---

## Changelog

- `Or`/`AnyOf`/`Option` will now report more query conflicts in order to fix unsoundness

## Migration Guide

- If you are now getting query conflicts from `Or`/`AnyOf`/`Option` rip to you and ur welcome for it now being caught
2022-05-18 20:57:24 +00:00
James Liu
2c93b5cf73 Reduce code duplication by using QueryIterationCursor in QueryIter (#4733)
# Objective
We have duplicated code between `QueryIter` and `QueryIterationCursor`. Reuse that code.

## Solution
 - Reuse `QueryIterationCursor` inside `QueryIter`.
 - Slim down `QueryIter` by removing the `&'w World`. It was only being used by the `size_hint` and `ExactSizeIterator` impls, which can use the QueryState and &Archetypes in the type already.
 - Benchmark to make sure there is no significant regression.

Relevant benchmark results seem to show that there is no tangible difference between the two. Everything seems to be either identical or within a workable margin of error here.

```
group                                          embed-cursor                            main
-----                                          ------------                            ----
fragmented_iter/base                           1.00   387.4±19.70ns        ? ?/sec     1.07   413.1±27.95ns        ? ?/sec
many_maps_iter                                 1.00     27.3±0.22ms        ? ?/sec     1.00     27.4±0.10ms        ? ?/sec
simple_iter/base                               1.00     13.8±0.07µs        ? ?/sec     1.00     13.7±0.17µs        ? ?/sec
simple_iter/sparse                             1.00     61.9±0.37µs        ? ?/sec     1.00     62.2±0.64µs        ? ?/sec
simple_iter/system                             1.00     13.7±0.34µs        ? ?/sec     1.00     13.7±0.10µs        ? ?/sec
sparse_fragmented_iter/base                    1.00     11.0±0.54ns        ? ?/sec     1.03     11.3±0.48ns        ? ?/sec
world_query_iter/50000_entities_sparse         1.08    105.0±2.68µs        ? ?/sec     1.00     97.5±2.18µs        ? ?/sec
world_query_iter/50000_entities_table          1.00     27.3±0.13µs        ? ?/sec     1.00     27.3±0.37µs        ? ?/sec
```
2022-05-18 18:34:52 +00:00
MrGVSV
15acd6f45d bevy_reflect: Small refactor and default Reflect methods (#4739)
# Objective

Quick followup to #4712.

While updating some [other PRs](https://github.com/bevyengine/bevy/pull/4218), I realized the `ReflectTraits` struct could be improved. The issue with the current implementation is that `ReflectTraits::get_xxx_impl(...)` returns just the _logic_ to the corresponding `Reflect` trait method, rather than the entire function.

This makes it slightly more annoying to manage since the variable names need to be consistent across files. For example, `get_partial_eq_impl` uses a `value` variable. But the name "value" isn't defined in the `get_partial_eq_impl` method, it's defined in three other methods in a completely separate file.

It's not likely to cause any bugs if we keep it as it is since differing variable names will probably just result in a compile error (except in very particular cases). But it would be useful to someone who wanted to edit/add/remove a method.

## Solution

Made `get_hash_impl`, `get_partial_eq_impl` and `get_serialize_impl` return the entire method implementation for `reflect_hash`, `reflect_partial_eq`, and `serializable`, respectively.

As a result of this, those three `Reflect` methods were also given default implementations. This was fairly simple to do since all three could just be made to return `None`.

---

## Changelog

* Small cleanup/refactor to `ReflectTraits` in `bevy_reflect_derive`
* Gave `Reflect::reflect_hash`, `Reflect::reflect_partial_eq`, and `Reflect::serializable` default implementations
2022-05-18 12:26:11 +00:00
MrGVSV
de2b1a4e94 bevy_reflect: Reflected char (#4790)
# Objective

`char` isn't reflected.

## Solution

Reflected `char`.

---

## Changelog

* Reflected `char`

## Migration Guide

> List too long to display
2022-05-17 23:45:09 +00:00
Alex Saveau
a0a14aa615 Support returning data out of with_children (#4708)
# Objective

Support returning data out of with_children to enable the use case of changing the parent commands with data created inside the child builder.

## Solution

Change the with_children closure to return T.

Closes https://github.com/bevyengine/bevy/pull/2817.

---

## Changelog

`BuildChildren::add_children` was added with the ability to return data to use outside the closure (for spawning a new child builder on a returned entity for example).
2022-05-17 22:37:51 +00:00
Daniel McNab
7da21b12f7 Add some more documentation to SystemParam (#4787)
# Objective

- Fixes https://github.com/bevyengine/bevy/issues/4783

## Solution

- Add more documentation about the derive, and the obscure failure case for this.
- Link to [`StaticSystemParam`](https://docs.rs/bevy/latest/bevy/ecs/system/struct.StaticSystemParam.html) in these docs.
- Also explain the attributes whilst here.
2022-05-17 22:24:50 +00:00
François
ae0cb549ff helper tool to build examples in wasm (#4776)
# Objective

- add an helper to build examples in wasm (from #4700)

## Solution

- `cargo run -p build-wasm-example -- lighting`
2022-05-17 19:04:08 +00:00
Matt Wilkinson
e36bfa21ab Change path to zld on MacOS fast build example (#4778)
# Objective
Fixes #4751, zld link error.

## Solution

- Change the `zld` file path in the example to the one homebrew installs to by default, `/usr/local/bin/zld`.
2022-05-17 16:00:17 +00:00
SarthakSingh31
dbd856de71 Nightly clippy fixes (#3491)
Fixes the following nightly clippy lints:
- ~~[map_flatten](https://rust-lang.github.io/rust-clippy/master/index.html#map_flatten)~~ (Fixed on main)
- ~~[needless_borrow](https://rust-lang.github.io/rust-clippy/master/index.html#needless_borrow)~~ (Fixed on main)
- [return_self_not_must_use](https://rust-lang.github.io/rust-clippy/master/index.html#return_self_not_must_use) (Added in 1.59.0)
- ~~[unnecessary_lazy_evaluations](https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_lazy_evaluations)~~ (Fixed on main)
- [extra_unused_lifetimes](https://rust-lang.github.io/rust-clippy/master/index.html#extra_unused_lifetimes) outside of macros
- [let_unit_value](https://rust-lang.github.io/rust-clippy/master/index.html#let_unit_value)
2022-05-17 04:38:03 +00:00
Daniel McNab
b1b3bd533b Skip drop when needs_drop is false (#4773)
# Objective

- We do a lot of function pointer calls in a hot loop (clearing entities in render). This is slow, since calling function pointers cannot be optimised out. We can avoid that in the cases where the function call is a no-op.
- Alternative to https://github.com/bevyengine/bevy/pull/2897
- On my machine, in `many_cubes`, this reduces dropping time from ~150μs to ~80μs.

## Solution
-  Make `drop` in `BlobVec` an `Option`, recording whether the given drop impl is required or not.
- Note that this does add branching in some cases - we could consider splitting this into two fields, i.e. unconditionally call the `drop` fn pointer.
- My intuition of how often types stored in `World` should have non-trivial drops makes me think that would be slower, however. 

N.B. Even once this lands, we should still test having a 'drop_multiple' variant - for types with a real `Drop` impl, the current implementation is definitely optimal.
2022-05-17 04:16:55 +00:00
KDecay
85dd291b9d Update keyboard.rs docs in bevy_input (#4517)
# Objective

- Part of the splitting process of #3692.

## Solution

- Document `keyboard.rs` inside of `bevy_input`.

Co-authored-by: KDecay <KDecayMusic@protonmail.com>
2022-05-17 04:16:54 +00:00
dataphract
0917c49b9b bench: add bevy_reflect::{List, Map, Struct} benchmarks (#3690)
# Objective

Partially addresses #3594.

## Solution

This adds basic benchmarks for `List`, `Map`, and `Struct` implementors, both concrete (`Vec`, `HashMap`, and defined struct types) and dynamic (`DynamicList`, `DynamicMap` and `DynamicStruct`). 

A few insights from the benchmarks (all measurements are local on my machine):
- Applying a list with many elements to a list with no elements is slower than applying to a list of the same length:
  - 3-4x slower when applying to a `Vec`
  - 5-6x slower when applying to a `DynamicList`
  
  I suspect this could be improved by `reserve()`ing the correct length up front, but haven't tested.
- Applying a `DynamicMap` to another `Map` is linear in the number of elements, but applying a `HashMap` seems to be at least quadratic. No intuition on this one.
- Applying like structs (concrete -> concrete, `DynamicStruct` -> `DynamicStruct`) seems to be faster than applying unlike structs.
2022-05-17 04:16:53 +00:00
Alex Saveau
1648c89b64 Fix frame count being a float (#4493)
Original reasoning: https://github.com/bevyengine/bevy/pull/678#issuecomment-930602773

That reasoning doesn't seem valid IMO since eventually +1 will do nothing. Using an integer is more intuitive and will wrap around which is probably better than getting stuck.
2022-05-17 04:01:54 +00:00
Daniel McNab
84c783b100 Ensure that the parent is always the expected entity (#4717)
# Objective

- Transform propogation could stack overflow when there was a cycle.
- I think https://github.com/bevyengine/bevy/pull/4203 would use all available memory.

## Solution

- Make sure that the child entity's `Parent`s are their parents.

This is also required for when parallelising, although as noted in the comment, the naïve solution would be UB.
(The best way to fix this would probably be an `&mut UnsafeCell<T>` `WorldQuery`, or wrapper type with the same effect)
2022-05-16 21:25:34 +00:00
dependabot[bot]
5422a2bc16 Update ndk-glue requirement from 0.5 to 0.6 (#3624)
Updates the requirements on [ndk-glue](https://github.com/rust-windowing/android-ndk-rs) to permit the latest version.
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a href="https://github.com/rust-windowing/android-ndk-rs/releases">ndk-glue's releases</a>.</em></p>
<blockquote>
<h2>ndk-glue v0.6.0</h2>
<ul>
<li><strong>Breaking:</strong> Update to <code>ndk-sys 0.3.0</code> and <code>ndk 0.6.0</code>. (<a href="https://github-redirect.dependabot.com/rust-windowing/android-ndk-rs/issues/214">#214</a>)</li>
</ul>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a href="f4dc7265aa"><code>f4dc726</code></a> Release ndk-sys-0.3.0, ndk-0.6.0, ndk-glue-0.6.0 (<a href="https://github-redirect.dependabot.com/rust-windowing/android-ndk-rs/issues/214">#214</a>)</li>
<li><a href="8e59a347bd"><code>8e59a34</code></a> ndk-sys: Use <code>jni-sys</code> for low-level JNI bindings (<a href="https://github-redirect.dependabot.com/rust-windowing/android-ndk-rs/issues/209">#209</a>)</li>
<li><a href="240389f1e2"><code>240389f</code></a> ndk-build,cargo-apk: Default <code>target_sdk_version</code> to 30 or lower (<a href="https://github-redirect.dependabot.com/rust-windowing/android-ndk-rs/issues/203">#203</a>)</li>
<li><a href="2d554daa30"><code>2d554da</code></a> Update README.md with links to cargo apk README.md (<a href="https://github-redirect.dependabot.com/rust-windowing/android-ndk-rs/issues/195">#195</a>)</li>
<li><a href="39d4701cc6"><code>39d4701</code></a> cargo-apk: Use <code>min_sdk_version</code> to select compiler target (<a href="https://github-redirect.dependabot.com/rust-windowing/android-ndk-rs/issues/197">#197</a>)</li>
<li><a href="317d71101f"><code>317d711</code></a> ci emulator: Cache AVD emulator setup to speed up repeated jobs (<a href="https://github-redirect.dependabot.com/rust-windowing/android-ndk-rs/issues/202">#202</a>)</li>
<li><a href="6e7658719b"><code>6e76587</code></a> readme: Use <code>console</code> code blocks for shell commands (<a href="https://github-redirect.dependabot.com/rust-windowing/android-ndk-rs/issues/196">#196</a>)</li>
<li><a href="63cbffa77a"><code>63cbffa</code></a> ndk-sys: Add all missing android-related headers with NDK 23.1.7779620 (<a href="https://github-redirect.dependabot.com/rust-windowing/android-ndk-rs/issues/201">#201</a>)</li>
<li><a href="55539dc555"><code>55539dc</code></a> Release ndk-build-0.4.3, cargo-apk-0.8.2 (<a href="https://github-redirect.dependabot.com/rust-windowing/android-ndk-rs/issues/192">#192</a>)</li>
<li>See full diff in <a href="https://github.com/rust-windowing/android-ndk-rs/compare/ndk-glue-0.5.0...ndk-glue-0.6.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>
2022-05-16 18:32:26 +00:00
nihohit
646c7e4c50 Fix mouse_clicked check for touches. (#2029)
This seems like a copy-paste from line 72 that was only partially modified.

I don't know how to test this, so please verify me :)
2022-05-16 18:00:08 +00:00
James Liu
eb2a8b12e9 bevy_ptr works in no_std environments (#4760)
# Objective
`bevy_ptr` works just fine without `std`. Mark it as `no_std`. This should generally be useful for non-bevy use cases, but it also marginally speeds up compilation by allowing the crate to compile without loading the std-lib.

## Solution
Replace `std` with `core`. Added `#![no_std]` to the crate and to the crate's tags.

Also added a missing `#![warn(missing_docs)]` that the other crates have.
2022-05-16 17:45:10 +00:00
Aron Derenyi
2e8dfc02ef Fixing confusing near and far fields in Camera (#4457)
# Objective

- Fixes #4456 

## Solution

- Removed the `near` and `far` fields from the camera and the views.

---

## Changelog

- Removed the `near` and `far` fields from the camera and the views.
- Removed the `ClusterFarZMode::CameraFarPlane` far z mode.

## Migration Guide

- Cameras no longer accept near and far values during initialization
- `ClusterFarZMode::Constant` should be used with the far value instead of `ClusterFarZMode::CameraFarPlane`
2022-05-16 16:37:33 +00:00
Mark Schmale
1ba7429371 Doc/module style doc blocks for examples (#4438)
# Objective

Provide a starting point for #3951, or a partial solution. 
Providing a few comment blocks to discuss, and hopefully find better one in the process. 

## Solution

Since I am pretty new to pretty much anything in this context, I figured I'd just start with a draft for some file level doc blocks. For some of them I found more relevant details (or at least things I considered interessting), for some others there is less. 

## Changelog

- Moved some existing comments from main() functions in the 2d examples to the file header level
- Wrote some more comment blocks for most other 2d examples

TODO: 
- [x] 2d/sprite_sheet, wasnt able to come up with something good yet 
- [x] all other example groups...


Also: Please let me know if the commit style is okay, or to verbose. I could certainly squash these things, or add more details if needed. 
I also hope its okay to raise this PR this early, with just a few files changed. Took me long enough and I dont wanted to let it go to waste because I lost motivation to do the whole thing. Additionally I am somewhat uncertain over the style and contents of the commets. So let me know what you thing please.
2022-05-16 13:53:20 +00:00
Alice Cecile
7462f21be4 Remove strong language from CONTRIBUTING.md (#4755)
The removed line is a) flippantly discouraging and b) no longer entirely accurate, now that we have more team members with merge rights.
2022-05-15 20:00:55 +00:00
TheRawMeatball
516e4aaa10 Add Commands::new_from_entities (#4423)
This change allows for creating `Commands` objects from just an entities reference, which allows for creating multiple dynamically in a normal system.

Context: https://discord.com/channels/691052431525675048/774027865020039209/960857605943726142
2022-05-14 14:40:09 +00:00
François
947d3f9627 add timeout to miri job in CI (#4743)
# Objective

- When Miri is failing, it can be very slow to do so

<img width="1397" alt="Screenshot 2022-05-14 at 03 05 40" src="https://user-images.githubusercontent.com/8672791/168405111-c5e27d63-7a5a-4a5e-b679-abbeeb3201d2.png">

## Solution

- Set the timeout for Miri to 60 minutes (it's 6 hours by default). It runs in around 10 minutes when successful
- Fix cache key as it was set to the same as another task that doesn't build with the same parameters
2022-05-14 02:01:38 +00:00
James Liu
c309acd432 Fail to compile on 16-bit platforms (#4736)
# Objective
`bevy_ecs` assumes that `u32 as usize` is a lossless operation and in a few cases relies on this for soundness and correctness. The only platforms that Rust compiles to where this invariant is broken are 16-bit systems.

A very clear example of this behavior is in the SparseSetIndex impl for Entity, where it converts a u32 into a usize to act as an index. If usize is 16-bit, the conversion will overflow and provide the caller with the wrong index. This can easily result in previously unforseen aliased mutable borrows (i.e. Query::get_many_mut).

## Solution
Explicitly fail compilation on 16-bit platforms instead of introducing UB. 

Properly supporting 16-bit systems will likely need a workable use case first.

---

## Changelog
Removed: Ability to compile `bevy_ecs` on 16-bit platforms.

## Migration Guide
`bevy_ecs` will now explicitly fail to compile on 16-bit platforms.  If this is required, there is currently no alternative. Please file an issue (https://github.com/bevyengine/bevy/issues) to help detail your use case.
2022-05-13 13:18:53 +00:00
MrGVSV
acbee7795d bevy_reflect: Reflect arrays (#4701)
# Objective

> ℹ️ **Note**: This is a rebased version of #2383. A large portion of it has not been touched (only a few minor changes) so that any additional discussion may happen here. All credit should go to @NathanSWard for their work on the original PR.

- Currently reflection is not supported for arrays.
- Fixes #1213

## Solution

* Implement reflection for arrays via the `Array` trait.
* Note, `Array` is different from `List` in the way that you cannot push elements onto an array as they are statically sized.
* Now `List` is defined as a sub-trait of `Array`.

---

## Changelog

* Added the `Array` reflection trait
* Allows arrays up to length 32 to be reflected via the `Array` trait

## Migration Guide

* The `List` trait now has the `Array` supertrait. This means that `clone_dynamic` will need to specify which version to use:
  ```rust
  // Before
  let cloned = my_list.clone_dynamic();
  // After
  let cloned = List::clone_dynamic(&my_list);
  ```
* All implementers of `List` will now need to implement `Array` (this mostly involves moving the existing methods to the `Array` impl)

Co-authored-by: NathanW <nathansward@comcast.net>
Co-authored-by: MrGVSV <49806985+MrGVSV@users.noreply.github.com>
2022-05-13 01:13:30 +00:00
Charles
dfee7879c3 Add a clear() method to the EventReader that consumes the iterator (#4693)
# Objective

- It's pretty common to want to check if an EventReader has received one or multiple events while also needing to consume the iterator to "clear" the EventReader.
- The current approach is to do something like `events.iter().count() > 0` or `events.iter().last().is_some()`. It's not immediately obvious that the purpose of that is to consume the events and check if there were any events. My solution doesn't really solve that part, but it encapsulates the pattern.

## Solution

- Add a `.clear()` method that consumes the iterator.
	- It takes the EventReader by value to make sure it isn't used again after it has been called.

---

## Migration Guide

Not a breaking change, but if you ever found yourself in a situation where you needed to consume the EventReader and check if there was any events you can now use

```rust
fn system(events: EventReader<MyEvent>) {
	if !events.is_empty {
		events.clear();
		// Process the fact that one or more event was received
	}
}
```


Co-authored-by: Charles <IceSentry@users.noreply.github.com>
2022-05-13 00:57:04 +00:00
James Liu
0166c4f7fc Profile par_for_each(_mut) tasks (#4711)
# Objective
`Query::par_for_each` and it's variants do not show up when profiling using `tracy` or other profilers. Failing to show the impact of changing batch size, the overhead of scheduling tasks, overall thread utilization, etc. other than the effect on the surrounding system.

## Solution
Add a child span that is entered on every spawned task.

Example view of the results in `tracy` using a modified `parallel_query`: 
![image](https://user-images.githubusercontent.com/3137680/167560036-626bd091-344b-4664-b323-b692f4f16084.png)

---

## Changelog
Added: `tracing` spans for `Query::par_for_each` and its variants. Spans should now be visible for all
2022-05-13 00:33:13 +00:00
MrGVSV
3d8d922566 bevy_reflect_derive: Tidying up the code (#4712)
# Objective

The `bevy_reflect_derive` crate is not the cleanest or easiest to follow/maintain. The `lib.rs` file is especially difficult with over 1000 lines of code written in a confusing order. This is just a result of growth within the crate and it would be nice to clean it up for future work.

## Solution

Split `bevy_reflect_derive` into many more submodules. The submodules include:

* `container_attributes` - Code relating to container attributes
* `derive_data` - Code relating to reflection-based derive metadata
* `field_attributes` - Code relating to field attributes
* `impls` - Code containing actual reflection implementations
* `reflect_value` - Code relating to reflection-based value metadata
* `registration` - Code relating to type registration
* `utility` - General-purpose utility functions

This leaves the `lib.rs` file to contain only the public macros, making it much easier to digest (and fewer than 200 lines).

By breaking up the code into smaller modules, we make it easier for future contributors to find the code they're looking for or identify which module best fits their own additions.

### Metadata Structs

This cleanup also adds two big metadata structs: `ReflectFieldAttr` and `ReflectDeriveData`. The former is used to store all attributes for a struct field (if any). The latter is used to store all metadata for struct-based derive inputs.

Both significantly reduce code duplication and make editing these macros much simpler. The tradeoff is that we may collect more metadata than needed. However, this is usually a small thing (such as checking for attributes when they're not really needed or creating a `ReflectFieldAttr` for every field regardless of whether they actually have an attribute).

We could try to remove these tradeoffs and squeeze some more performance out, but doing so might come at the cost of developer experience. Personally, I think it's much nicer to create a `ReflectFieldAttr` for every field since it means I don't have to do two `Option` checks. Others may disagree, though, and so we can discuss changing this either in this PR or in a future one.

### Out of Scope

_Some_ documentation has been added or improved, but ultimately good docs are probably best saved for a dedicated PR.

## 🔍 Focus Points (for reviewers)

I know it's a lot to sift through, so here is a list of **key points for reviewers**:

- The following files contain code that was mostly just relocated:
  - `reflect_value.rs`
  - `registration.rs`
- `container_attributes.rs` was also mostly moved but features some general cleanup (reducing nesting, removing hardcoded strings, etc.) and lots of doc comments
- Most impl logic was moved from `lib.rs` to `impls.rs`, but they have been significantly modified to use the new `ReflectDeriveData` metadata struct in order to reduce duplication.
- `derive_data.rs` and `field_attributes.rs` contain almost entirely new code and should probably be given the most attention.
- Likewise, `from_reflect.rs` saw major changes using `ReflectDeriveData` so it should also be given focus.
- There was no change to the `lib.rs` exports so the end-user API should be the same.

## Prior Work

This task was initially tackled by @NathanSWard in #2377 (which was closed in favor of this PR), so hats off to them for beating me to the punch by nearly a year!

---

## Changelog

* **[INTERNAL]** Split `bevy_reflect_derive` into smaller submodules
* **[INTERNAL]** Add `ReflectFieldAttr`
* **[INTERNAL]** Add `ReflectDeriveData`
* Add `BevyManifest::get_path_direct()` method (`bevy_macro_utils`)


Co-authored-by: MrGVSV <49806985+MrGVSV@users.noreply.github.com>
2022-05-12 19:43:23 +00:00
Jakob Hellermann
d3b2439c82 fix tracy frame marker placement (after preseting *all* windows) (#4731)
# Objective

The frame marker event was emitted in the loop of presenting all the windows. This would mark the frame as finished multiple times if more than one window is used.

## Solution

Move the frame marker to after the `for`-loop, so that it gets executed only once.
2022-05-12 18:39:20 +00:00
Troels Jessen
ae580e58dd Added keyboard key to mouse control for scene viewer example (#4411)
# Objective

- Added keyboard control for scene_viewer example. Fixes #4407 


Co-authored-by: Troels Jessen <kairyuka@gmail.com>
2022-05-11 09:31:39 +00:00
Daniel McNab
94d941661d Tidy up the code of events (#4713)
# Objective

- The code in `events.rs` was a bit messy. There was lots of duplication between `EventReader` and `ManualEventReader`, and the state management code is not needed.

## Solution

- Clean it up.

## Future work

Should we remove the type parameter from `ManualEventReader`? 
It doesn't have any meaning outside of its source `Events`. But there's no real reason why it needs to have a type parameter - it's just plain data. I didn't remove it yet to keep the type safety in some of the users of it (primarily related to `&mut World` usage)
2022-05-10 20:18:59 +00:00
Mike
9a54e2bed6 Add a tracing span for run criteria. (#4709)
# Objective

Adds a tracing span for run critieria.

This change will be invalidated by stageless, but it was a simple change.

Fixes #4681.

## Changelog

Shows how long a run criteria takes to run when tracing is enabled.
![image](https://user-images.githubusercontent.com/2180432/167517447-93dba7db-8c85-4686-90e0-30e9636f120f.png)
2022-05-10 20:18:58 +00:00
Jakob Hellermann
e503a31048 fix "unused" warnings when compiling with render feature but without animation (#4714)
# Objective
When running `cargo check --no-default-features --features render` I get
```rust
warning: unused import: `Quat`
  --> crates/bevy_gltf/src/loader.rs:11:23
   |
11 | use bevy_math::{Mat4, Quat, Vec3};
   |                       ^^^^
   |
   = note: `#[warn(unused_imports)]` on by default

warning: function is never used: `paths_recur`
   --> crates/bevy_gltf/src/loader.rs:542:4
    |
542 | fn paths_recur(
    |    ^^^^^^^^^^^
    |
    = note: `#[warn(dead_code)]` on by default
```

## Solution

Put these items behind `#[cfg(feature = "animation")]`.
2022-05-10 20:01:55 +00:00
PROMETHIA-27
aced6aff04 Add macro to implement reflect for struct types and migrate glam types (#4540)
# Objective

Relevant issue: #4474

Currently glam types implement Reflect as a value, which is problematic for reflection, making scripting/editor work much more difficult. This PR re-implements them as structs.

## Solution

Added a new proc macro, `impl_reflect_struct`, which replaces `impl_reflect_value` and `impl_from_reflect_value` for glam types. This macro could also be used for other types, but I don't know of any that would require it. It's specifically useful for foreign types that cannot derive Reflect normally.

---

## Changelog

### Added
- `impl_reflect_struct` proc macro

### Changed
- Glam reflect impls have been replaced with `impl_reflect_struct`
- from_reflect's `impl_struct` altered to take an optional custom constructor, allowing non-default non-constructible foreign types to use it
- Calls to `impl_struct` altered to conform to new signature
- Altered glam types (All vec/mat combinations) have a different serialization structure, as they are reflected differently now.

## Migration Guide

This will break altered glam types serialized to RON scenes, as they will expect to be serialized/deserialized as structs rather than values now. A future PR to add custom serialization for non-value types is likely on the way to restore previous behavior. Additionally, calls to `impl_struct` must add a `None` parameter to the end of the call to restore previous behavior.

Co-authored-by: PROMETHIA-27 <42193387+PROMETHIA-27@users.noreply.github.com>
2022-05-09 16:32:15 +00:00
Daniel McNab
38a940dbbe Make derived SystemParam readonly if possible (#4650)
Required for https://github.com/bevyengine/bevy/pull/4402.

# Objective

- derived `SystemParam` implementations were never `ReadOnlySystemParamFetch`
- We want them to be, e.g. for `EventReader`

## Solution

- If possible, 'forward' the impl of `ReadOnlySystemParamFetch`.
2022-05-09 16:09:33 +00:00
Joy
4c878ef790 Add comparison methods to FilteredAccessSet (#4211)
# Objective

- (Eventually) reduce noise in reporting access conflicts between unordered systems. 
	- `SystemStage` only looks at unfiltered `ComponentId` access, any conflicts reported are potentially `false`.
		- the systems could still be accessing disjoint archetypes
	- Comparing systems' filtered access sets can maybe avoid that (for statically known component types).
		- #4204

## Solution

- Modify `SparseSetIndex` trait to require `PartialEq`, `Eq`, and `Hash` (all internal types except `BundleId` already did).
- Add `is_compatible` and `get_conflicts` methods to `FilteredAccessSet<T>`
	- (existing method renamed to `get_conflicts_single`)
- Add docs for those and all the other methods while I'm at it.
2022-05-09 14:39:22 +00:00
Daniel McNab
33a4df8008 Update layout/style when scale factor changes too (#4689)
# Objective

- Fix https://github.com/bevyengine/bevy/issues/4688

## Solution

- Fixes https://github.com/bevyengine/bevy/issues/4688
- This raises an interesting question about our change detection system - is filtered queries actually a good UX for this? They're ergonomic in the easy case, but what do we recommend when it's not so.
- In this case, the system should have been migrated similary to https://github.com/bevyengine/bevy/pull/4180 anyway, so I've done that.
2022-05-09 14:18:02 +00:00