Commit graph

3505 commits

Author SHA1 Message Date
ira
0761594dd8 Use World helper methods for sending HierarchyEvents (#6921)
A code-quality PR

Also cleans up the helper methods by just importing the `Event` type

Co-authored-by: devil-ira <justthecooldude@gmail.com>
2022-12-20 16:17:07 +00:00
James Liu
1523c38ce8 Directly extract joints into SkinnedMeshJoints (#6833)
# Objective
Following #4402, extract systems run on the render world instead of the main world, and allow retained state operations on it's resources. We're currently extracting to `ExtractedJoints` and then copying it twice during Prepare. Once into `SkinnedMeshJoints` and again into the actual GPU buffer.

This makes #4902 obsolete.

## Solution
Cut out the middle copy and directly extract joints into `SkinnedMeshJoints` and remove `ExtractedJoints` entirely.

This also removes the per-frame allocation that is being made to send `ExtractedJoints` into the render world.

## Performance
On my local machine, this halves the time for `prepare_skinned _meshes` on `many_foxes` (195.75us -> 93.93us on average).

![image](https://user-images.githubusercontent.com/3137680/205427455-ab91a8a3-a6b0-4f0a-bd48-e54482c563b2.png)

---

## Changelog
Added: `BufferVec::truncate`
Added: `BufferVec::extend`
Changed: `SkinnedMeshJoints::build` now takes a `&mut BufferVec` instead of a `&mut Vec` as a parameter.
Removed: `ExtractedJoints`.

## Migration Guide
`ExtractedJoints` has been removed. Read the bound bones from `SkinnedMeshJoints` instead.
2022-12-20 16:17:05 +00:00
James Liu
53a5bbe2d5 Add thread create/destroy callbacks to TaskPool (#6561)
# Objective
Fix #1991. Allow users to have a bit more control over the creation and finalization of the threads in `TaskPool`.

## Solution
Add new methods to `TaskPoolBuilder` that expose callbacks that are called to initialize and finalize each thread in the `TaskPool`.

Unlike the proposed solution in #1991, the callback is argument-less. If an an identifier is needed, `std:🧵:current` should provide that information easily.

Added a unit test to ensure that they're being called correctly.
2022-12-20 16:17:02 +00:00
François
e8b28547bf Cleanup dynamic scene before building (#6254)
# Objective

- Dynamic scene builder can build scenes without components, if they didn't have any matching the type registry
- Those entities are not really useful in the final `DynamicScene`

## Solution

- Add a method `remove_empty_entities` that will remove empty entities. It's not called by default when calling `build`, I'm not sure if that's a good idea or not.
2022-12-20 16:16:58 +00:00
James Liu
5b8b7dc08f Add a stress test profile (#6901)
# Objective
This adds a custom profile for testing against stress tests. Bevy seemingly gets notably faster with LTO turned on. To more accurately depict production level performance, LTO and other rustc-level optimizations should be enabled when performance testing on stress tests.

Also updated the stress test docs to reflect that users should be using it.
2022-12-20 15:59:41 +00:00
James Liu
bd615cbf8c Shrink DrawFunctionId (#6944)
# Objective
This includes one part of #4899. The aim is to improve CPU-side rendering performance by reducing the memory footprint and bandwidth required.

## Solution
Shrink `DrawFunctionId` to `u32`. Enforce that `u32 as usize` conversions are always safe by forbidding compilation on 16-bit platforms. This shouldn't be a breaking change since #4736 disabled compilation of `bevy_ecs` on those platforms.

Shrinking `DrawFunctionId` shrinks all of the `PhaseItem` types, which is integral to sort and render phase performance.

Testing against `many_cubes`, the sort phase improved by 22% (174.21us -> 141.76us per frame).

![image](https://user-images.githubusercontent.com/3137680/207345422-a512b4cf-1680-46e0-9973-ea72494ebdfe.png)

The main opaque pass also imrproved by 9% (5.49ms -> 5.03ms)

![image](https://user-images.githubusercontent.com/3137680/207346436-cbee7209-6450-4964-b566-0b64cfa4b4ea.png)

Overall frame time improved by 5% (14.85ms -> 14.09ms)

![image](https://user-images.githubusercontent.com/3137680/207346895-9de8676b-ef37-4cb9-8445-8493f5f90003.png)

There will be a followup PR that likewise shrinks `CachedRenderPipelineId` which should yield similar results on top of these improvements.
2022-12-20 15:40:42 +00:00
Zeenobit
f8e4b755ff Add EntityMap::iter() (#6935)
# Objective

There is currently no way to iterate over key/value pairs inside an `EntityMap`, which makes the usage of this struct very awkward. I couldn't think of a good reason why the `iter()` function should not be exposed, considering the interface already exposes `keys()` and `values()`, so I made this PR.

## Solution

Implement `iter()` for `EntityMap` in terms of its inner map type.
2022-12-16 20:14:13 +00:00
ira
00fa0d8cf2 Apply WindowDescriptor settings in all modes (#6934)
# Objective
Some settings were only applied in windowed mode.
Fix the issue in #6933 

# Solution
Always apply the settings.


Co-authored-by: devil-ira <justthecooldude@gmail.com>
2022-12-16 20:14:11 +00:00
ira
0d606030a2 Remove EntityCommands::add_children (#6942)
# Objective
Remove a method with an unfortunate name and questionable usefulness.
Added in #4708

It doesn't make sense to me for us to provide a method to work around a limitation of closures when we can simply, *not* use a closure.
The limitation in this case is not being able to initialize a variable from inside a closure:

```rust
let child_id;
commands.spawn_empty().with_children(|parent| {
    // Error: passing uninitalized variable to a closure.
    child_id = parent.spawn_empty().id();
});

// Do something with child_id
```
The docs for `add_children` suggest the following:
```rust
let child_id = commands
    .spawn_empty()
    .add_children(|parent| parent.spawn_empty().id());
```
I would instead suggest using the following snippet.
```rust
let parent_id = commands.spawn_empty().id();
let child_id = commands.spawn_empty().set_parent(parent_id).id();

// To be fair, at the time of #4708 this would have been a bit more cumbersome since `set_parent` did not exist.
```

Using `add_children` gets more unwieldy when you also want the `parent_id`.
```rust
let parent_commands = commands.spawn_empty();
let parent_id = parent_commands.id();
let child_id = parent_commands.add_children(|parent| parent.spawn_empty().id());
```
### The name
I see why `add_children` is named that way, it's the non-builder variant of `with_children` so it kinda makes sense,
but now the method name situation for `add_child`, `add_children` and `push_children` is *rather* unfortunate.

Removing `add_children` and renaming `push_children` to `add_children` in one go is kinda bleh, but that way we end up with the matching methods `add_child` and `add_children`. 

Another reason to rename `push_children` is that it's trying to mimick the `Vec` api naming but fails because `push` is for single elements. I guess it should have been `extend_children_from_slice`, but lets not name it that :)

### Questions
~~Should `push_children` be renamed in this PR? This would make the migration guide easier to deal with.~~
Let's do that later.

Does anyone know of a way to do a simple text/regex search through all the github repos for usage of `add_children`?
That way we can have a better idea of how this will affect users. My guess is that usage of `add_children` is quite rare.

## Migration Guide
The method `add_children` on `EntityCommands` was removed.
If you were using `add_children` over `with_children` to return data out of the closure you can use `set_parent` or `add_child` to avoid the closure instead.

Co-authored-by: devil-ira <justthecooldude@gmail.com>
2022-12-16 19:53:23 +00:00
Jonah Henriksson
38d567d2c5 Make AsBindGroup unsized (#6937)
# Objective

`AsBindGroup` can't be used as a trait object because of the constraint `Sized` and because of the associated function.

This is a problem for [`bevy_atmosphere`](https://github.com/JonahPlusPlus/bevy_atmosphere) because it needs to use a trait that depends on `AsBindGroup` as a trait object, for switching out different shaders at runtime. The current solution it employs is reimplementing the trait and derive macro into that trait, instead of constraining to `AsBindGroup`.

## Solution

Remove the `Sized` constraint from `AsBindGroup` and add the constraint `where Self: Sized` to the associated function `bind_group_layout`. Also change `PreparedBindGroup<T: AsBindGroup>` to `PreparedBindGroup<T>` and use it as `PreparedBindGroup<Self::Data>` instead of `PreparedBindGroup<Self>`.

This weakens the constraints, but increases the flexibility of `AsBindGroup`.
I'm not entirely sure why the `Sized` constraint was there, because it worked fine without it (maybe @cart wasn't aware of use cases for `AsBindGroup` as a trait object or this was just leftover from legacy code?).

---

## Changelog

- `AsBindGroup` can be used as a trait object.
2022-12-16 01:40:15 +00:00
Rob Parrett
ec0478d100 Fix clippy lints and failed test with Rust 1.66 (#6945)
# Objective

[Rust 1.66](https://blog.rust-lang.org/inside-rust/2022/12/12/1.66.0-prerelease.html) is coming in a few days, and bevy doesn't build with it.

Fix that.

## Solution

Replace output from a trybuild test, and fix a few new instances of `needless_borrow` and `unnecessary_cast` that are now caught.

## Note

Due to the trybuild test, this can't be merged until 1.66 is released.
2022-12-15 18:05:15 +00:00
François
bad3d57d0c update cargo deny config with latest list of duplicate crates in dependencies (#6947)
# Objective

- Get dependency check to succeed

## Solution

- Update the list
2022-12-13 22:54:27 +00:00
ira
b7d6ee8c68 Update concurrent-queue to 2.0 (#6538)
Co-authored-by: devil-ira <justthecooldude@gmail.com>
2022-12-13 21:00:43 +00:00
James Liu
79b9231b74 Move system_commands spans into apply_buffers (#6900)
# Objective
A separate `tracing` span for running a system's commands is created, even if the system doesn't have commands. This is adding extra measuring overhead (see #4892) where it's not needed.

## Solution
Move the span into `ParallelCommandState` and `CommandQueue`'s `SystemParamState::apply`. To get the right metadata for the span, a additional `&SystemMeta` parameter was added to `SystemParamState::apply`.

---

## Changelog
Added: `SystemMeta::name`
Changed: Systems without `Commands` and  `ParallelCommands` will no longer show a "system_commands" span when profiling.
Changed: `SystemParamState::apply` now takes a `&SystemMeta` parameter in addition to the provided `&mut World`.
2022-12-11 23:04:04 +00:00
Zoey
4820917af6 Add set_if_neq method to DetectChanges trait (Rebased) (#6853)
# Objective

Change detection can be spuriously triggered by setting a field to the same value as before. As a result, a common pattern is to write:

```rust
if *foo != value {
  *foo = value;
}
```

This is confusing to read, and heavy on boilerplate.

Adopted from #5373, but untangled and rebased to current `bevy/main`.

## Solution

    1. Add a method to the `DetectChanges` trait that implements this boilerplate when the appropriate trait bounds are met.

    2. Document this minor footgun, and point users to it.


## Changelog

    * added the `set_if_neq` method to avoid triggering change detection when the new and previous values are equal. This will work on both components and resources.


## Migration Guide

If you are manually checking if a component or resource's value is equal to its new value before setting it to avoid triggering change detection, migrate to the clearer and more convenient `set_if_neq` method.
## Context

Related to #2363 as it avoids triggering change detection, but not a complete solution (as it still requires triggering it when real changes are made).



Co-authored-by: Zoey <Dessix@Dessix.net>
2022-12-11 19:24:19 +00:00
Lixou
aeb2c4b917 Update linux_dependencies.md for Arch - Vulkan API not only for Intel GPUs (#6729)
fix note in arch's linux deps.
2022-12-11 19:24:18 +00:00
zxygentoo
68a7127a27 Update linux_dependencies.md (#6915)
Add a section about install `vulkan-loader` on Gentoo.

# Objective

- Clarify the dependency about install on Gentoo with NVIDIA GPU and using a proprietary driver.

## Solution

- Emerge `vulkan-loader` to help Bevy to find the correct ICD.
2022-12-11 18:46:48 +00:00
Tianlan Zhou
b1a634cade Fix alpha channel in RGB32F image texture format conversion (#6914)
# Objective

The following code:

```rs
use bevy::prelude::Image;
use image::{ DynamicImage, GenericImage, Rgba };

fn main() {
    let mut dynamic_image = DynamicImage::new_rgb32f(1, 1);
    dynamic_image.put_pixel(0, 0, Rgba([1, 1, 1, 1]));
    
    let image = Image::from_dynamic(dynamic_image, false); // Panic!
    println!("{image:?}");
}
```

Can cause an assertion failed:

```
thread 'main' panicked at 'assertion failed: `(left == right)`
  left: `16`,
 right: `14`: Pixel data, size and format have to match', .../bevy_render-0.9.1/src/texture/image.rs:209:9
stack backtrace:
...
   4: core::panicking::assert_failed<usize,usize>
             at /rustc/897e37553bba8b42751c67658967889d11ecd120/library/core/src/panicking.rs:181
   5: bevy_render::texture::image::Image::new
             at .../bevy_render-0.9.1/src/texture/image.rs:209
   6: bevy_render::texture::image::Image::from_dynamic
             at .../bevy_render-0.9.1/src/texture/image_texture_conversion.rs:159
   7: bevy_test::main
             at ./src/main.rs:8
...
```

It seems to be cause by a copypasta in `crates/bevy_render/src/texture/image_texture_conversion.rs`. Let's fix it.

## Solution

```diff
  // DynamicImage::ImageRgb32F(image) => {
- let a = u16::max_value();
+ let a = 1f32;
```

This will fix the conversion.

---

## Changelog

- Fixed the alpha channel of the `image::DynamicImage::ImageRgb32F` to `bevy_render::texture::Image` conversion in `bevy_render::texture::Image::from_dynamic()`.
2022-12-11 18:46:47 +00:00
Hennadii Chernyshchyk
544776831d Remove render feature group (#6912)
# Objective

The feature doesn't have any use case in libraries or applications and many users use this feature incorrectly. See the issue for details.
Closes #5753.

## Solution

Remove it.

---

## Changelog

### Removed

- `render` feature group. 

## Migration Guide

Instead of using `render` feature group use dependencies directly. This group consisted of `bevy_core_pipeline`, `bevy_pbr`, `bevy_gltf`, `bevy_render`, `bevy_sprite`, `bevy_text` and `bevy_ui`. You probably want to check if you need all of them.
2022-12-11 18:46:46 +00:00
IceSentry
36691769ba Document undocumented features of AsBindGroup derive (#6910)
# Objective

- https://github.com/bevyengine/bevy/pull/5364 Added a few features to the AsBindGroup derive, but if you don't know they exist they aren't documented anywhere.


## Solution

- Document the new arguments in the doc block for the derive.
2022-12-11 18:46:45 +00:00
James Liu
87bf0e2664 Remove unnecessary branching from bundle insertion (#6902)
# Objective
Speed up bundle insertion and spawning from a bundle.

## Solution
Use the same technique used in #6800 to remove the branch on storage type when writing components from a `Bundle` into storage.

 - Add a `StorageType` argument to the closure on `Bundle::get_components`.
 - Pass `C::Storage::STORAGE_TYPE` into that argument.
 - Match on that argument instead of reading from a `Vec<StorageType>` in `BundleInfo`.
 - Marked all implementations of `Bundle::get_components` as inline to encourage dead code elimination.

The `Vec<StorageType>` in `BundleInfo` was also removed as it's no longer needed. If users were reliant on this, they can either use the compile time constants or fetch the information from `Components`. Should save a rather negligible amount of memory.

## Performance
Microbenchmarks show a slight improvement to inserting components into existing entities, as well as spawning from a bundle. Ranging about 8-16% faster depending on the benchmark.

```
group                                          main                                    soft-constant-write-components
-----                                          ----                                    ------------------------------
add_remove/sparse_set                          1.08  1019.0±80.10µs        ? ?/sec     1.00   944.6±66.86µs        ? ?/sec
add_remove/table                               1.07  1343.3±20.37µs        ? ?/sec     1.00  1257.3±18.13µs        ? ?/sec
add_remove_big/sparse_set                      1.08  1132.4±263.10µs        ? ?/sec    1.00  1050.8±240.74µs        ? ?/sec
add_remove_big/table                           1.02      2.6±0.05ms        ? ?/sec     1.00      2.5±0.08ms        ? ?/sec
get_or_spawn/batched                           1.15   401.4±17.76µs        ? ?/sec     1.00   349.3±11.26µs        ? ?/sec
get_or_spawn/individual                        1.13   732.1±43.35µs        ? ?/sec     1.00   645.6±41.44µs        ? ?/sec
insert_commands/insert                         1.12   623.9±37.48µs        ? ?/sec     1.00   557.4±34.99µs        ? ?/sec
insert_commands/insert_batch                   1.16   401.4±17.00µs        ? ?/sec     1.00   347.4±12.87µs        ? ?/sec
insert_simple/base                             1.08    416.9±5.60µs        ? ?/sec     1.00    385.2±4.14µs        ? ?/sec
insert_simple/unbatched                        1.06   934.5±44.58µs        ? ?/sec     1.00   881.3±47.86µs        ? ?/sec
spawn_commands/2000_entities                   1.09   190.7±11.41µs        ? ?/sec     1.00    174.7±9.15µs        ? ?/sec
spawn_commands/4000_entities                   1.10   386.5±25.33µs        ? ?/sec     1.00   352.3±18.81µs        ? ?/sec
spawn_commands/6000_entities                   1.10   586.2±34.42µs        ? ?/sec     1.00   535.3±27.25µs        ? ?/sec
spawn_commands/8000_entities                   1.08   778.5±45.15µs        ? ?/sec     1.00   718.0±33.66µs        ? ?/sec
spawn_world/10000_entities                     1.04  1026.4±195.46µs        ? ?/sec    1.00  985.8±253.37µs        ? ?/sec
spawn_world/1000_entities                      1.06   103.8±20.23µs        ? ?/sec     1.00    97.6±18.22µs        ? ?/sec
spawn_world/100_entities                       1.15     11.4±4.25µs        ? ?/sec     1.00      9.9±1.87µs        ? ?/sec
spawn_world/10_entities                        1.05  1030.8±229.78ns        ? ?/sec    1.00  986.2±231.12ns        ? ?/sec
spawn_world/1_entities                         1.01   105.1±23.33ns        ? ?/sec     1.00   104.6±31.84ns        ? ?/sec
```

---

## Changelog
Changed: `Bundle::get_components` now takes a `FnMut(StorageType, OwningPtr)`. The provided storage type must be correct for the component being fetched.
2022-12-11 18:46:43 +00:00
James Liu
26d6145915 Document remaining members of bevy_utils (#6897)
# Objective
Partially address #3492. 

## Solution
Document the remaining undocumented members of `bevy_utils` and set `warn(missing_docs)` on the crate level. Also enabled `clippy::undocumented_unsafe_blocks` as a warning on the crate to keep it in sync with `bevy_ecs`'s warnings.
2022-12-11 18:46:42 +00:00
François
f4818bcd69 scene viewer: can select a scene from the asset path (#6859)
# Objective

- Fixes #6630, fixes #6679
- Improve scene viewer in cases where there are more than one scene in a gltf file

## Solution

- Can select which scene to display using `#SceneN`, defaults to scene 0 if not present
- Display the number of scenes available if there are more than one
2022-12-11 18:46:41 +00:00
ira
ea8f74692f Add with_a and friends to Color (#6899)
# Objective
```rust
// makes clippy complain about 'taking a mutable reference to a `const` item'
let color = *Color::RED.set_a(0.5);

// Now you can do
let color = Color::RED.with_a(0.5);
```

## Changelog
Added `with_r`, `with_g`, `with_b`, and `with_a` to `Color`.

Co-authored-by: devil-ira <justthecooldude@gmail.com>
2022-12-11 18:34:16 +00:00
Mike
75880a0b17 run clear trackers on render world (#6878)
# Objective

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

## Solution

- clear_trackers was not being called on the render world. This causes the removed components vecs to continuously grow. This PR adds clear trackers to the end of RenderStage::Cleanup

## Migration Guide

The call to `clear_trackers` in `App` has been moved from the schedule to App::update for the main world and calls to `clear_trackers` have been added for sub_apps in the same function. This was due to needing stronger guarantees. If clear_trackers isn't called on a world it can lead to memory leaks in `RemovedComponents`.
2022-12-11 18:34:15 +00:00
JoJoJet
1af73624fa Simplify trait hierarchy for SystemParam (#6865)
# Objective

* Implementing a custom `SystemParam` by hand requires implementing three traits -- four if it is read-only.
* The trait `SystemParamFetch<'w, 's>` is a workaround from before we had generic associated types, and is no longer necessary.

## Solution

* Combine the trait `SystemParamFetch` with `SystemParamState`.
    * I decided to remove the `Fetch` name and keep the `State` name, since the former was consistently conflated with the latter.
* Replace the trait `ReadOnlySystemParamFetch` with `ReadOnlySystemParam`, which simplifies trait bounds in generic code.

---

## Changelog

- Removed the trait `SystemParamFetch`, moving its functionality to `SystemParamState`.
- Replaced the trait `ReadOnlySystemParamFetch` with `ReadOnlySystemParam`.

## Migration Guide

The trait `SystemParamFetch` has been removed, and its functionality has been transferred to `SystemParamState`.

```rust
// Before
impl SystemParamState for MyParamState {
    fn init(world: &mut World, system_meta: &mut SystemMeta) -> Self { ... }
}
impl<'w, 's> SystemParamFetch<'w, 's> for MyParamState {
    type Item = MyParam<'w, 's>;
    fn get_param(...) -> Self::Item;
}

// After
impl SystemParamState for MyParamState {
    type Item<'w, 's> = MyParam<'w, 's>; // Generic associated types!
    fn init(world: &mut World, system_meta: &mut SystemMeta) -> Self { ... }
    fn get_param<'w, 's>(...) -> Self::Item<'w, 's>;
}
```

The trait `ReadOnlySystemParamFetch` has been replaced with `ReadOnlySystemParam`.

```rust
// Before
unsafe impl ReadOnlySystemParamFetch for MyParamState {}

// After
unsafe impl<'w, 's> ReadOnlySystemParam for MyParam<'w, 's> {}
```
2022-12-11 18:34:14 +00:00
James Liu
c16791ce67 Document options for !Sync types for Component and Resources (#6864)
# Objective
It's not clear to users how to handle `!Sync` types as components and resources in the absence of engine level support for them. 

## Solution
Added a section to `Component`'s and `Resource`'s type level docs on available options for making a type `Sync` when it holds `!Sync` fields, linking `bevy_utils::synccell::SyncCell` and the currently unstable `std::sync::Exclusive`.

Also added a compile_fail doctest that illustrates how to apply `SyncCell`. These will break when/if #6572 gets merged, at which point these docs should be updated.
2022-12-11 18:34:13 +00:00
Mike
ea80aca7ca unpin miri (#6863)
# Objective

- https://github.com/rust-lang/miri/pull/2713 was merged into miri. See if this fixes miri for bevy.
2022-12-11 18:22:11 +00:00
Alejandro Pascual
95c0d99e45 Sprite sheet example: specify animation indices (#6861)
# Objective

- Make running animation fluid skipping 'idle' frame.

## Solution

- Loop through the specified indices instead of through the whole sprite sheet.

The example is correct, is just the feeling that the animation loop is not seamless.

Based on the solution suggested by @mockersf in #5429.
2022-12-11 18:22:10 +00:00
James Liu
0d67c32153 Avoid triggering change detection for inputs (#6847)
# Objective
Fix #5292.

## Solution
Avoid derefencing when clearing to ensure that change detection is not triggered when there is nothing to clear.
2022-12-11 18:22:09 +00:00
James Liu
b37a6ca9a2 Add reflection support for VecDeque (#6831)
# Objective
This is an adoption of #5792. Fixes #5791.

## Solution
Implemented all the required reflection traits for `VecDeque`, taking from `Vec`'s impls.

---

## Changelog
Added: `std::collections::VecDeque` now implements `Reflect` and all relevant traits.

Co-authored-by: james7132 <contact@jamessliu.com>
2022-12-11 18:22:08 +00:00
Mike
6903a9411b get pixel size from wgpu (#6820)
# Objective

- Get rid of giant match statement to get PixelInfo. 
- This will allow for supporting any texture that is uncompressed, instead of people needing to PR in any textures that are supported in wgpu, but not bevy.

## Solution

- More conservative alternative to https://github.com/bevyengine/bevy/pull/6788, where we don't try to make some of the calculations correct for compressed types.
- Delete `PixelInfo` and get the pixel_size directly from wgpu. Data from wgpu is here: https://docs.rs/wgpu-types/0.14.0/src/wgpu_types/lib.rs.html#2359
- Panic if the texture is a compressed type. An integer byte size of a pixel is no longer a valid concept when talking about compressed textures.
- All internal usages use `pixel_size` and not `pixel_info` and are on uncompressed formats. Most of these usages are on either explicit texture formats or slightly indirectly through `TextureFormat::bevy_default()`. The other uses are in `TextureAtlas` and have other calculations that assumes the texture is uncompressed. 

## Changelog

- remove `PixelInfo` and get `pixel_size` from wgpu

## Migration Guide

`PixelInfo` has been removed. `PixelInfo::components` is equivalent to `texture_format.describe().components`. `PixelInfo::type_size` can be gotten from `texture_format.describe().block_size/ texture_format.describe().components`. But note this can yield incorrect results for some texture types like Rg11b10Float.
2022-12-11 18:22:07 +00:00
Jay Pavlina
2e7925d8d0 Add cylinder shape (#6809)
# Objective

Adds a cylinder shape. Fixes #2282.

## Solution

- I added a custom cylinder shape, taken from [here](https://github.com/rparrett/typey_birb/blob/main/src/cylinder.rs) with permission from @rparrett.
- I also added the cylinder shape to the `3d_shapes` example scene.

---

## Changelog

- Added cylinder shape

Co-Authored-By: Rob Parrett <robparrett@gmail.com>
Co-Authored-By: davidhof <7483215+davidhof@users.noreply.github.com>
2022-12-11 18:22:05 +00:00
Edvin Kjell
aea4c5b1a4 [Fixes #6224] Add logging variants of system piping (#6751)
# Objective

Fixes #6224, add ``dbg``, ``info``, ``warn`` and ``error`` system piping adapter variants to expand #5776, which call the corresponding re-exported [bevy_log macros](https://docs.rs/bevy/latest/bevy/log/macro.info.html) when the result is an error.

## Solution

* Added ``dbg``, ``info``, ``warn`` and ``error`` system piping adapter variants to ``system_piping.rs``. 
* Modified and added tests for these under examples in ``system_piping.rs``.
2022-12-11 18:10:03 +00:00
dis-da-moe
81153a8b0c document file formats for bytes field of AudioSource (#6619)
# Objective

Fixes #6299 

## Solution

Change one line of documentation.

Co-authored-by: dis-da-moe <84386186+dis-da-moe@users.noreply.github.com>
2022-12-11 18:10:02 +00:00
Jerome Humbert
07e7fa5a4d Document World::clear_trackers() (#6520)
# Objective

Document `World::clear_trackers()`.

## Solution

Document the `World::clear_trackers()` method, and briefly how it's related to change detection and `RemovedComponents`.

This is a follow-up from [this discussion](https://discord.com/channels/691052431525675048/749335865876021248/1039628807025479700) on Discord.
2022-12-11 18:10:01 +00:00
harudagondi
344a65313f Make AudioOutput a Resource (#6436)
# Objective

- Make `AudioOutput` a `Resource`.

## Solution

- Do not store `OutputStream` in the struct.
- `mem::forget` `OutputStream`.

---

## Changelog

### Added

- `AudioOutput` is now a `Resource`.

## Migration Guide

- Use `Res<AudioOutput<Source>>` instead of `NonSend<AudioOutput<Source>>`. Same for `Mut` variants.
2022-12-11 18:10:00 +00:00
Gino Valente
63f1a9dec8 bevy_reflect: Add ReflectFromReflect (v2) (#6245)
# Objective

Resolves #4597 (based on the work from #6056 and a refresh of #4147)

When using reflection, we may often end up in a scenario where we have a Dynamic representing a certain type. Unfortunately, we can't just call `MyType::from_reflect` as we do not have knowledge of the concrete type (`MyType`) at runtime.

Such scenarios happen when we call `Reflect::clone_value`, use the reflection deserializers, or create the Dynamic type ourselves.

## Solution

Add a `ReflectFromReflect` type data struct.

This struct allows us to easily convert Dynamic representations of our types into their respective concrete instances.

```rust
#[derive(Reflect, FromReflect)]
#[reflect(FromReflect)] // <- Register `ReflectFromReflect`
struct MyStruct(String);

let type_id = TypeId::of::<MyStruct>();

// Register our type
let mut registry = TypeRegistry::default();
registry.register::<MyStruct>();

// Create a concrete instance
let my_struct = MyStruct("Hello world".to_string());

// `Reflect::clone_value` will generate a `DynamicTupleStruct` for tuple struct types
let dynamic_value: Box<dyn Reflect> = my_struct.clone_value();
assert!(!dynamic_value.is::<MyStruct>());

// Get the `ReflectFromReflect` type data from the registry
let rfr: &ReflectFromReflect = registry
  .get_type_data::<ReflectFromReflect>(type_id)
  .unwrap();

// Call `FromReflect::from_reflect` on our Dynamic value
let concrete_value: Box<dyn Reflect> = rfr.from_reflect(&dynamic_value);
assert!(concrete_value.is::<MyStruct>());
```

### Why this PR?

###### Why now?

The three main reasons I closed #4147 were that:

1. Registering `ReflectFromReflect` is clunky (deriving `FromReflect` *and* registering `ReflectFromReflect`)
2. The ecosystem and Bevy itself didn't seem to pay much attention to deriving `FromReflect`
3. I didn't see a lot of desire from the community for such a feature

However, as time has passed it seems 2 and 3 are not really true anymore. Bevy is internally adding lots more `FromReflect` derives, which should make this feature all the more useful. Additionally, I have seen a growing number of people look for something like `ReflectFromReflect`.

I think 1 is still an issue, but not a horrible one. Plus it could be made much, much better using #6056. And I think splitting this feature out of #6056 could lead to #6056 being adopted sooner (or at least make the need more clear to users).

###### Why not just re-open #4147?

The main reason is so that this PR can garner more attention than simply re-opening the old one. This helps bring fresh eyes to the PR for potentially more perspectives/reviews.

---

## Changelog

* Added `ReflectFromReflect`

Co-authored-by: Gino Valente <49806985+MrGVSV@users.noreply.github.com>
2022-12-11 17:52:48 +00:00
James Liu
6308041772 Fix Sparse Change Detection (#6896)
# Objective
#6547 accidentally broke change detection for SparseSet components by using `Ticks::from_tick_cells` with the wrong argument order.

## Solution
Use the right argument order. Add a regression test.
2022-12-10 09:25:53 +00:00
TehPers
a5d70b8952 Derive Reflect + FromReflect for window event types (#6235)
# Objective

The window event types currently don't support reflection. This PR adds support to them (as requested [here](https://github.com/bevyengine/bevy/issues/6223#issuecomment-1273852329)).

## Solution

Implement `Reflect` + `FromReflect` for window event types. Relevant traits are also being reflected with `#[reflect(...)]` attributes.

Additionally, this PR derives `Reflect` + `FromReflect` for `WindowDescriptor` and the types it depends on so that `CreateWindow` events can be fully manipulated through reflection.

Finally, this PR adds `FromReflect` for `PathBuf` as a value type, which is needed for `FileDragAndDrop`.

This adds the "glam" feature to the `bevy_reflect` dependency for package `bevy_window`. Since `bevy_window` transitively depends on `glam` already, all this brings in are the reflection `impl`s.

## Open questions

Should `app.register_type::<PathBuf>();` be moved to `CorePlugin`? I added it to `WindowPlugin` because that's where it's used and `CorePlugin` doesn't seem to register all the missing std types, but it would also make sense in `CorePlugin` I believe since it's a commonly used type.

---

## Changelog

Added:
- Implemented `Reflect` + `FromReflect` for window events and related types. These types are automatically registered when adding the `WindowPlugin`.
2022-12-09 01:20:44 +00:00
Olivia Crain
b58ca8721a ci: Use Ubuntu 22.04 runner for run-examples, run-examples-on-wasm jobs (#6875)
# Objective

- The `run-examples-on-wasm` job fails on Ubuntu 22.04, when it was previously working on Ubuntu 20.04. Playwright 1.22.1 (the version currently pinned by us) fails trying to install system dependencies that were renamed between Ubuntu 20.04 and 22.04.
- The `run-examples` job previously failed on Ubuntu 22.04 with errors consistent with those listed in [this upstream mesa bug](https://gitlab.freedesktop.org/mesa/mesa/-/issues/7819).
- Fixes #6832

## Solution

- Upgrade `playwright` to the latest [v1.28.1](https://github.com/microsoft/playwright/releases/tag/v1.28.1) release. Ubuntu 22.04 support was [added](https://github.com/microsoft/playwright/pull/14588) in [v1.23.0](https://github.com/microsoft/playwright/releases/tag/v1.23.0). The [test now passes on 22.04](https://github.com/oliviacrain/bevy/actions/runs/3633583112/jobs/6130757397), and the output screenshots are unchanged from previous job outputs.
- Use `ubuntu-latest` for the `run-examples` job. No other modifications necessary. The [PPA we pull mesa from](https://launchpad.net/~oibaf/+archive/ubuntu/graphics-drivers) rebuilt the package for 22.04 with the [upstream fix](https://gitlab.freedesktop.org/mesa/mesa/-/merge_requests/20145/diffs?commit_id=b3d1ae19f2f4d93cf0a5f45a598149ac4e8e05aa).
2022-12-08 20:05:27 +00:00
François
8eedc8f69d ShaderDefVal: add an UInt option (#6881)
# Objective

- Fixes #6841 
- In some case, the number of maximum storage buffers is `u32::MAX` which doesn't fit in a `i32`

## Solution

- Add an option to have a `u32` in a `ShaderDefVal`
2022-12-07 23:10:27 +00:00
Boxy
bac0d89059 remove a doc(hidden) on read only version of derive(WorldQuery) (#6877)
having `doc(hidden)` on the read only version of a generated mutable world query leads to docs on the readonly item having a dead link. It also makes it annoying to have nice docs for libraries attempting to expose derived `WorldQuery` structs as re-exporting the read only item does not cause it to appear in docs even though it would be intended for users to know about the read only world query and use it.
2022-12-07 23:10:26 +00:00
Zhell
e08701307b Updated docs for `List Trait in bevy_reflect` (#6872)
# Objective

Fixes #6866.

## Solution

Docs now should describe what the _front_, _first_, _back_, and _last_ elements are for an implementor of the `bevy::reflect::list::List` Trait. Further, the docs should describe how `bevy::reflect::list::List::push` and `bevy::reflect::list::List::pop` should act on these elements.


Co-authored-by: Linus Käll <linus.kall.business@gmail.com>
2022-12-07 23:10:25 +00:00
James Liu
10898d1dc9 Docs: Show how to compare two different traces in Tracy (#6869)
# Objective
Fixes #5199.

## Solution
Mention how to compare two different saved tracy traces in the profiling section.
2022-12-07 22:57:27 +00:00
Olivia Crain
176d7df5db docs: Use correct cargo-flamegraph upstream repo URL (#6873)
# Objective

Links to `cargo-flamegraph`'s repo point to a [fork](https://github.com/killercup/cargo-flamegraph), not the actual upstream repo. We should point to the source of truth instead of a fork that hasn't been updated since 2019.

## Solution

Change links to point to the upstream repo at  [flamegraph-rs/flamegraph](https://github.com/flamegraph-rs/flamegraph).
2022-12-07 21:23:20 +00:00
James Liu
530be10e72 Newtype ArchetypeRow and TableRow (#4878)
# Objective
Prevent future unsoundness that was seen in #6623.

## Solution
Newtype both indexes in `Archetype` and `Table` as `ArchetypeRow` and `TableRow`. This avoids weird numerical manipulation on the indices, and can be stored and treated opaquely. Also enforces the source and destination of where these indices at a type level.

---

## Changelog
Changed: `Archetype` indices and `Table` rows have been newtyped as `ArchetypeRow` and `TableRow`.
2022-12-06 01:38:21 +00:00
James Liu
a3f203b504 Use T::Storage::STORAGE_TYPE to optimize out unused branches (#6800)
# Objective
`EntityRef::get` and friends all type erase calls to fetch the target components by using passing in the `TypeId` instead of using generics. This is forcing a lookup to `Components` to fetch the storage type. This adds an extra memory lookup and forces a runtime branch instead of allowing the compiler to optimize out the unused branch.

## Solution
Leverage `Component::Storage::STORAGE_TYPE` as a constant instead of fetching the metadata from `Components`.

## Performance
This has a near 2x speedup for all calls to `World::get`. Microbenchmark results from my local machine. `Query::get_component`, which uses `EntityRef::get` internally also show a slight speed up. This has closed the gap between `World::get` and `Query::get` for the same use case.

```
group                                                             entity-ref-generics                     main
-----                                                             -------------------                     ----
query_get_component/50000_entities_sparse                         1.00   890.6±40.42µs        ? ?/sec     1.10   980.6±28.22µs        ? ?/sec
query_get_component/50000_entities_table                          1.00   968.5±73.73µs        ? ?/sec     1.08  1048.8±31.76µs        ? ?/sec
query_get_component_simple/system                                 1.00    703.2±4.37µs        ? ?/sec     1.00    702.1±6.13µs        ? ?/sec
query_get_component_simple/unchecked                              1.02    855.8±8.98µs        ? ?/sec     1.00    843.1±8.19µs        ? ?/sec
world_get/50000_entities_sparse                                   1.00    202.3±3.15µs        ? ?/sec     1.85   374.0±20.96µs        ? ?/sec
world_get/50000_entities_table                                    1.00    193.0±1.78µs        ? ?/sec     2.02   389.2±26.55µs        ? ?/sec
world_query_get/50000_entities_sparse                             1.01    162.4±2.23µs        ? ?/sec     1.00    161.3±0.95µs        ? ?/sec
world_query_get/50000_entities_table                              1.00    199.9±0.63µs        ? ?/sec     1.00    200.2±0.74µs        ? ?/sec
```

This should also, by proxy, speed up the `ReflectComponent` APIs as most of those use `World::get` variants internally.
2022-12-05 23:56:33 +00:00
Elbert Ronnie
f9c52f98b9 Make proc macros hygienic in bevy_reflect_derive (#6752)
# Objective

- Fixes #3004 

## Solution

- Replaced all the types with their fully quallified names
- Replaced all trait methods and inherent methods on dyn traits with their fully qualified names
- Made a new file `fq_std.rs` that contains structs corresponding to commonly used Structs and Traits from `std`. These structs are replaced by their respective fully qualified names when used inside `quote!`
2022-12-05 23:39:44 +00:00
polygon
9f0c41f26d Adapt path type of dynamically_load_plugin (#6734)
# Objective

- Fixes #6711

## Solution

- Change the `path` function parameter of `dynamically_load_plugin` and `DynamicPluginExt::load_plugin` to a generic with `AsRef<OsStr>` bound
2022-12-05 23:39:43 +00:00