Commit graph

3075 commits

Author SHA1 Message Date
JoJoJet
5472ea4a14
Improve encapsulation for commands and add docs (#8725)
# Objective

Several of our built-in `Command` types are too public:
- `GetOrSpawn` is public, even though it only makes sense to call it
from within `Commands::get_or_spawn`.
- `Remove` and `RemoveResource` contain public `PhantomData` marker
fields.

## Solution

Remove `GetOrSpawn` and use an anonymous command. Make the marker fields
private.

---

## Migration Guide

The `Command` types `Remove` and `RemoveResource` may no longer be
constructed manually.

```rust
// Before:
commands.add(Remove::<T> {
    entity: id,
    phantom: PhantomData,
});

// After:
commands.add(Remove::<T>::new(id));

// Before:
commands.add(RemoveResource::<T> { phantom: PhantomData });

// After:
commands.add(RemoveResource::<T>::new());
```

The command type `GetOrSpawn` has been removed. It was not possible to
use this type outside of `bevy_ecs`.
2023-05-31 16:45:46 +00:00
Nicola Papale
c8167c1276
Add CubicCurve::segment_count + iter_samples adjustment (#8711)
## Objective

- Provide a way to use `CubicCurve` non-iter methods
- Accept a `FnMut` over a `fn` pointer on `iter_samples`
- Improve `build_*_cubic_100_points` benchmark by -45% (this means they
are twice as fast)

### Solution

Previously, the only way to iterate over an evenly spaced set of points
on a `CubicCurve` was to use one of the `iter_*` methods.

The return value of those methods were bound by `&self` lifetime, making
them unusable in certain contexts.

Furthermore, other `CubicCurve` methods (`position`, `velocity`,
`acceleration`) required normalizing `t` over the `CubicCurve`'s
internal segment count.

There were no way to access this segment count, making those methods
pretty much unusable.

The newly added `segment_count` allows accessing the segment count.

`iter_samples` used to accept a `fn`, a function pointer. This is
surprising and contrary to the rust stdlib APIs, which accept `Fn`
traits for `Iterator` combinators.

`iter_samples` now accepts a `FnMut`.

I don't trust a bit the bevy benchmark suit, but according to it, this
doubles (-45%) the performance on the `build_pos_cubic_100_points` and
`build_accel_cubic_100_points` benchmarks.

---

## Changelog

- Added the `CubicCurve::segments` method to access the underlying
segments of a cubic curve
- Allow closures as `CubicCurve::iter_samples` `sample_function`
argument.
2023-05-31 14:57:37 +00:00
Sélène Amanita
ca81d3e435
Document query errors (#8692)
# Objective

Add documentation to `Query` and `QueryState` errors in bevy_ecs
(`QuerySingleError`, `QueryEntityError`, `QueryComponentError`)

## Solution

- Change display message for `QueryEntityError::QueryDoesNotMatch`: this
error can also happen when the entity has a component which is filtered
out (with `Without<C>`)
- Fix wrong reference in the documentation of `Query::get_component` and
`Query::get_component_mut` from `QueryEntityError` to
`QueryComponentError`
- Complete the documentation of the three error enum variants.
- Add examples for `QueryComponentError::MissingReadAccess` and
`QueryComponentError::MissingWriteAccess`
- Add reference to `QueryState` in `QueryEntityError`'s documentation.

---

## Migration Guide

Expect `QueryEntityError::QueryDoesNotMatch`'s display message to
change? Not sure that counts.

---------

Co-authored-by: harudagondi <giogdeasis@gmail.com>
2023-05-30 14:41:14 +00:00
Marco Buono
292e069bb5
Apply codebase changes in preparation for StandardMaterial transmission (#8704)
# Objective

- Make #8015 easier to review;

## Solution

- This commit contains changes not directly related to transmission
required by #8015, in easier-to-review, one-change-per-commit form.

---

## Changelog

### Fixed

- Clear motion vector prepass using `0.0` instead of `1.0`, to avoid TAA
artifacts on transparent objects against the background;

### Added

- The `E` mathematical constant is now available for use in shaders,
exposed under `bevy_pbr::utils`;
- A new `TAA` shader def is now available, for conditionally enabling
shader logic via `#ifdef` when TAA is enabled; (e.g. for jittering
texture samples)
- A new `FallbackImageZero` resource is introduced, for when a fallback
image filled with zeroes is required;
- A new `RenderPhase<I>::render_range()` method is introduced, for
render phases that need to render their items in multiple parceled out
“steps”;

### Changed

- The `MainTargetTextures` struct now holds both `Texture` and
`TextureViews` for the main textures;
- The fog shader functions under `bevy_pbr::fog` now take the a `Fog`
structure as their first argument, instead of relying on the global
`fog` uniform;
- The main textures can now be used as copy sources;

## Migration Guide

- `ViewTarget::main_texture()` and `ViewTarget::main_texture_other()`
now return `&Texture` instead of `&TextureView`. If you were relying on
these methods, replace your usage with
`ViewTarget::main_texture_view()`and
`ViewTarget::main_texture_other_view()`, respectively;
- `ViewTarget::sampled_main_texture()` now returns `Option<&Texture>`
instead of a `Option<&TextureView>`. If you were relying on this method,
replace your usage with `ViewTarget::sampled_main_texture_view()`;
- The `apply_fog()`, `linear_fog()`, `exponential_fog()`,
`exponential_squared_fog()` and `atmospheric_fog()` functions now take a
configurable `Fog` struct. If you were relying on them, update your
usage by adding the global `fog` uniform as their first argument;
2023-05-30 14:21:53 +00:00
JMS55
c8deedb0e1
Change default tonemapping method (#8685)
Change the default tonemapping method from ReinhardLuminance to
TonyMcMapface, which generally looks nicer and works out of the box with
bloom.

---

## Changelog

- TonyMcMapface is now the default tonemapper, instead of
ReinhardLuminance.

## Migration Guide

- The default tonemapper has been changed from ReinhardLuminance to
TonyMcMapface. Explicitly set ReinhardLuminance on your cameras to get
back the previous look.
2023-05-29 15:36:21 +00:00
Gino Valente
6b292d4263
bevy_reflect: Allow #[reflect(default)] on enum variant fields (#8514)
# Objective

When using `FromReflect`, fields can be optionally left out if they are
marked with `#[reflect(default)]`. This is very handy for working with
serialized data as giant structs only need to list a subset of defined
fields in order to be constructed.

<details>
<summary>Example</summary>

Take the following struct:
```rust
#[derive(Reflect, FromReflect)]
struct Foo {
  #[reflect(default)]
  a: usize,
  #[reflect(default)]
  b: usize,
  #[reflect(default)]
  c: usize,
  #[reflect(default)]
  d: usize,
}
```

Since all the fields are default-able, we can successfully call
`FromReflect` on deserialized data like:

```rust
(
  "foo::Foo": (
    // Only set `b` and default the rest
    b: 123
  )
)
```

</details>

Unfortunately, this does not work with fields in enum variants. Marking
a variant field as `#[reflect(default)]` does nothing when calling
`FromReflect`.

## Solution

Allow enum variant fields to define a default value using
`#[reflect(default)]`.

### `#[reflect(Default)]`

One thing that structs and tuple structs can do is use their `Default`
implementation when calling `FromReflect`. Adding `#[reflect(Default)]`
to the struct or tuple struct both registers `ReflectDefault` and alters
the `FromReflect` implementation to use `Default` to generate any
missing fields.

This works well enough for structs and tuple structs, but for enums it's
not as simple. Since the `Default` implementation for an enum only
covers a single variant, it's not as intuitive as to what the behavior
will be. And (imo) it feels weird that we would be able to specify
default values in this way for one variant but not the others.

Because of this, I chose to not implement that behavior here. However,
I'm open to adding it in if anyone feels otherwise.

---

## Changelog

- Allow enum variant fields to define a default value using
`#[reflect(default)]`
2023-05-29 15:29:29 +00:00
JoJoJet
85a918a8dd
Improve safety for the multi-threaded executor using UnsafeWorldCell (#8292)
# Objective

Fix #7833.

Safety comments in the multi-threaded executor don't really talk about
system world accesses, which makes it unclear if the code is actually
valid.

## Solution

Update the `System` trait to use `UnsafeWorldCell`. This type's API is
written in a way that makes it much easier to cleanly maintain safety
invariants. Use this type throughout the multi-threaded executor, with a
liberal use of safety comments.

---

## Migration Guide

The `System` trait now uses `UnsafeWorldCell` instead of `&World`. This
type provides a robust API for interior mutable world access.
- The method `run_unsafe` uses this type to manage world mutations
across multiple threads.
- The method `update_archetype_component_access` uses this type to
ensure that only world metadata can be used.

```rust
let mut system = IntoSystem::into_system(my_system);
system.initialize(&mut world);

// Before:
system.update_archetype_component_access(&world);
unsafe { system.run_unsafe(&world) }

// After:
system.update_archetype_component_access(world.as_unsafe_world_cell_readonly());
unsafe { system.run_unsafe(world.as_unsafe_world_cell()) }
```

---------

Co-authored-by: James Liu <contact@jamessliu.com>
2023-05-29 15:22:10 +00:00
Marco Buono
4465f256eb
Add MAY_DISCARD shader def, enabling early depth tests for most cases (#6697)
# Objective

- Right now we can't really benefit from [early depth
testing](https://www.khronos.org/opengl/wiki/Early_Fragment_Test) in our
PBR shader because it includes codepaths with `discard`, even for
situations where they are not necessary.

## Solution

- This PR introduces a new `MeshPipelineKey` and shader def,
`MAY_DISCARD`;
- All possible material/mesh options that that may result in `discard`s
being needed must set `MAY_DISCARD` ahead of time:
- Right now, this is only `AlphaMode::Mask(f32)`, but in the future
might include other options/effects; (e.g. one effect I'm personally
interested in is bayer dither pseudo-transparency for LOD transitions of
opaque meshes)
- Shader codepaths that can `discard` are guarded by an `#ifdef
MAY_DISCARD` preprocessor directive:
  - Right now, this is just one branch in `alpha_discard()`;
- If `MAY_DISCARD` is _not_ set, the `@early_depth_test` attribute is
added to the PBR fragment shader. This is a not yet documented, possibly
non-standard WGSL extension I found browsing Naga's source code. [I
opened a PR to document it
there](https://github.com/gfx-rs/naga/pull/2132). My understanding is
that for backends where this attribute is supported, it will force an
explicit opt-in to early depth test. (e.g. via
`layout(early_fragment_tests) in;` in GLSL)

## Caveats

- I included `@early_depth_test` for the sake of us being explicit, and
avoiding the need for the driver to be “smart” about enabling this
feature. That way, if we make a mistake and include a `discard`
unguarded by `MAY_DISCARD`, it will either produce errors or noticeable
visual artifacts so that we'll catch early, instead of causing a
performance regression.
- I'm not sure explicit early depth test is supported on the naga Metal
backend, which is what I'm currently using, so I can't really test the
explicit early depth test enable, I would like others with Vulkan/GL
hardware to test it if possible;
- I would like some guidance on how to measure/verify the performance
benefits of this;
- If I understand it correctly, this, or _something like this_ is needed
to fully reap the performance gains enabled by #6284;
- This will _most definitely_ conflict with #6284 and #6644. I can fix
the conflicts as needed, depending on whether/the order they end up
being merging in.

---

## Changelog

### Changed

- Early depth tests are now enabled whenever possible for meshes using
`StandardMaterial`, reducing the number of fragments evaluated for
scenes with lots of occlusions.
2023-05-29 15:15:01 +00:00
ira
5e3ae770ac
Fix screenshots on Wayland + Nvidia (#8701)
# Objective

Fix #8604

## Solution

Use `.add_srgb_suffix()` when creating the screenshot texture.
Allow converting `Bgra8Unorm` images.

Only a two line change for the fix, the `screenshot.rs` changes are just
a bit of cleanup.
2023-05-29 07:22:13 +00:00
JoJoJet
d628ae808f
Add documentation to UnsafeWorldCell::increment_change_tick (#8697)
# Objective

This function does not have documentation.

## Solution

Copy the docs from `World::increment_change_tick`.
2023-05-28 12:46:24 +00:00
Ame
a21bc41cca
fix warning: variable does not need to be mutable (#8688)
# Objective

Fix warnings:

```rs
warning: variable does not need to be mutable
   --> /bevy/crates/bevy_app/src/plugin_group.rs:147:13
    |
147 |         let mut plugin_entry = self
    |             ----^^^^^^^^^^^^
    |             |
    |             help: remove this `mut`
    |
    = note: `#[warn(unused_mut)]` on by default

warning: variable does not need to be mutable
   --> /bevy/crates/bevy_app/src/plugin_group.rs:161:13
    |
161 |         let mut plugin_entry = self
    |             ----^^^^^^^^^^^^
    |             |
    |             help: remove this `mut`

warning: `bevy_app` (lib) generated 2 warnings (run `cargo fix --lib -p bevy_app` to apply 2 suggestions)
warning: variable does not need to be mutable
   --> /bevy/crates/bevy_render/src/view/window.rs:126:13
    |
126 | ...   let mut extracted_window = extracted_windows.entry(entity).or_insert(Extracte...
    |           ----^^^^^^^^^^^^^^^^
    |
    = note: `#[warn(unused_mut)]` on by default

warning: `bevy_render` (lib) generated 1 warning (run `cargo fix --lib -p bevy_render` to apply 1 suggestion)
```
## Solution

- Remove the mut keyword in those variables.
2023-05-27 20:50:40 +00:00
Martin Lysell
735f9b6024
Allow missing docs on wasm implementation of BoxedFuture (#8674)
# Objective

Reduce missing docs warning noise when building examples for wasm

## Solution

Added "#[allow(missing_docs)]" on the wasm specific version of
BoxedFuture
2023-05-26 00:29:26 +00:00
bird
bc9144bcd6
implement Deref for State<S> (#8668)
# Objective

- Allow for directly call methods on states without first calling
`state.get().my_method()`

## Solution

- Implement `Deref` for `State<S>` with `Target = S`
---
*I did not implement `DerefMut` because states hold no data and should
only be changed via `NextState::set()`*
2023-05-25 10:40:43 +00:00
张林伟
a9ca40506e
Hide naga info logs & Derive PartialEq on Timer and Stopwatch (#8664)
# Objective

- Fixes https://github.com/bevyengine/bevy/issues/8662
- Fixes https://github.com/bevyengine/bevy/issues/8663

---------

Co-authored-by: Andres O. Vela <andresovela@users.noreply.github.com>
2023-05-24 15:16:15 +00:00
Nolan Darilek
897daa0ad6
Move bevy_ui accessibility systems to PostUpdate. (#8653)
# Objective

`bevy_ui` accessibility updates are probably more correctly done in
`PostUpdate`.

## Solution

Move `bevy_ui` accessibility updates to `PostUpdate`.

---------

Co-authored-by: ickshonpe <david.curthoys@googlemail.com>
2023-05-23 23:50:48 +00:00
张林伟
df3e81c1fb
Fix look_to variable naming (#8627)
# Objective

- If I understand correctly, forward points in `direction`, so the
negative of `direction` should be back.

## Migration Guide

- `Transform::look_to` method changed default value of
`direction.try_normalize()` from `Vec3::Z` to `Vec3::NEG_Z`
2023-05-23 02:17:33 +00:00
François
ebac7e8268
update ahash and hashbrown (#8623)
# Objective

- Update `ahash` and `hashbrown`
- Alternative to #5700 and #7420

## Solution

- Update the dependencies

This is a breaking change because we were creating two fixed hashers
with
[`AHasher::new_with_keys`](https://docs.rs/ahash/0.7.6/ahash/struct.AHasher.html#method.new_with_keys),
which was a method that existed only for testing purpose and has been
removed from public.

I replaced it with
[`RandomState::with_seeds`](https://docs.rs/ahash/0.8.3/ahash/random_state/struct.RandomState.html#method.with_seeds)
which is the proper way to get a fixed hasher (see [this
table](https://docs.rs/ahash/0.8.3/ahash/random_state/struct.RandomState.html)).
This means that hashes won't be the same across versions

---

## Migration Guide

- If you were using hashes to an asset or using one of the fixed hasher
exposed by Bevy with a previous version, you will have to update the
hashes
2023-05-23 02:17:07 +00:00
lelo
c475a2a954
Correct RequestRedraw documentation (#8640)
# Objective

- Since the `RequestRedraw` event triggers the bevy app to run `update`
in `bevy_app::app::App`, the documentation should state that all the
windows in the application and its sub-apps are going to get redrawn,
rather than a single window.

## Solution

- Change `RequestRedraw` documentation in `bevy_window` to mention every
window.
2023-05-23 02:16:56 +00:00
Tin Rabzelj
335afbf77a
Make Material2d pipeline systems public (#8642)
# Objective

Make `Material2dPipeline` reusable. This was already done for PBR
materials in #7548.

## Solution

Expose `extract_materials_2d`, `prepare_materials_2d` and
`ExtractedMaterials2d`.

---

## Changelog

- bevy_sprite: Make `prepare_materials_2d`, `extract_materials_2d` and
`ExtractedMaterials2d` public.
2023-05-23 02:16:39 +00:00
dependabot[bot]
f0b1e1d32b
Update libloading requirement from 0.7 to 0.8 (#8649)
Updates the requirements on
[libloading](https://github.com/nagisa/rust_libloading) to permit the
latest version.
<details>
<summary>Commits</summary>
<ul>
<li><a
href="83b1037f21"><code>83b1037</code></a>
Release 0.8.0</li>
<li><a
href="a6a394a7ef"><code>a6a394a</code></a>
bump MSRV to 1.48</li>
<li><a
href="c7955a761e"><code>c7955a7</code></a>
Replace winapi with windows-sys</li>
<li><a
href="95d03a1ddf"><code>95d03a1</code></a>
Add support for QNX Neutrino</li>
<li><a
href="6e284984ae"><code>6e28498</code></a>
Fix CI</li>
<li><a
href="95a0f62e8f"><code>95a0f62</code></a>
Placate clippy</li>
<li><a
href="224a3def35"><code>224a3de</code></a>
Release 0.7.4</li>
<li><a
href="bd17713dcc"><code>bd17713</code></a>
Support AIX dyld constants</li>
<li><a
href="6e07929736"><code>6e07929</code></a>
fix typo</li>
<li><a
href="6b33651a90"><code>6b33651</code></a>
Construct a PathBuf</li>
<li>Additional commits viewable in <a
href="https://github.com/nagisa/rust_libloading/compare/0.7.0...0.8.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>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-05-22 20:04:15 +00:00
dependabot[bot]
e8779c09e9
Update sysinfo requirement from 0.28.1 to 0.29.0 (#8650)
Updates the requirements on
[sysinfo](https://github.com/GuillaumeGomez/sysinfo) to permit the
latest version.
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a
href="https://github.com/GuillaumeGomez/sysinfo/blob/master/CHANGELOG.md">sysinfo's
changelog</a>.</em></p>
<blockquote>
<h1>0.29.0</h1>
<ul>
<li>Add <code>ProcessExt::effective_user_id</code> and
<code>ProcessExt::effective_group_id</code>.</li>
<li>Rename <code>DiskType</code> into <code>DiskKind</code>.</li>
<li>Rename <code>DiskExt::type_</code> into
<code>DiskExt::kind</code>.</li>
<li>macOS: Correctly handle <code>ProcessStatus</code> and remove public
<code>ThreadStatus</code> field.</li>
<li>Windows 11: Fix CPU core usage.</li>
</ul>
<h1>0.28.4</h1>
<ul>
<li>macOS: Improve CPU computation.</li>
<li>Strengthen a process test (needed for debian).</li>
</ul>
<h1>0.28.3</h1>
<ul>
<li>FreeBSD/Windows: Add missing frequency for global CPU.</li>
<li>macOS: Fix used memory computation.</li>
<li>macOS: Improve available memory computation.</li>
<li>Windows: Fix potential panic when getting process data.</li>
</ul>
<h1>0.28.2</h1>
<ul>
<li>Linux: Improve CPU usage computation.</li>
</ul>
<h1>0.28.1</h1>
<ul>
<li>macOS: Fix overflow when computing CPU usage.</li>
</ul>
<h1>0.28.0</h1>
<ul>
<li>Linux: Fix name and CPU usage for processes tasks.</li>
<li>unix: Keep all users, even &quot;not real&quot; accounts.</li>
<li>Windows: Use SID for Users ID.</li>
<li>Fix C API.</li>
<li>Disable default cdylib compilation.</li>
<li>Add <code>serde</code> feature to enable serialization.</li>
<li>Linux: Handle <code>Idle</code> state in
<code>ProcessStatus</code>.</li>
<li>Linux: Add brand and name of ARM CPUs.</li>
</ul>
<h1>0.27.8</h1>
<ul>
<li>macOS: Fix overflow when computing CPU usage.</li>
</ul>
<h1>0.27.7</h1>
<ul>
<li>macOS: Fix process CPU usage computation</li>
<li>Linux: Improve ARM CPU <code>brand</code> and <code>name</code>
information.</li>
<li>Windows: Fix resource leak.</li>
<li>Documentation improvements.</li>
</ul>
<!-- raw HTML omitted -->
</blockquote>
<p>... (truncated)</p>
</details>
<details>
<summary>Commits</summary>
<ul>
<li>See full diff in <a
href="https://github.com/GuillaumeGomez/sysinfo/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>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-05-22 18:11:33 +00:00
Alex Tennant
fdec72b860
Make TextureAtlas::texture_handles pub instead of pub(crate) (#8633) (#8643)
# Objective

- Fixes bevyengine#8633

## Solution

Make `TextureAtlas::texture_handles` `pub` instead of `pub(crate)`.
2023-05-21 23:20:36 +00:00
Wilhelm Vallrand
f76b3c4230
Fix bloom wasm support (#8631)
# Objective

- Fixes #7352 

## Solution

GLES doesn't support binding specific mip levels for sampling. Fallback
to using separate textures instead.
-
[wgpu-hal/src/gles/device.rs](628a95cd1c/wgpu-hal/src/gles/device.rs (L1038))

---

---------

Co-authored-by: Wilhelm Vallrand <>
2023-05-19 20:11:41 +00:00
JMS55
a75634ddc7
Update Camera::hdr docs (#8634)
Updates/removes an outdated doc comment. It seems to work without issue
now.

We could also consider making hdr the default at this point.
2023-05-19 20:09:12 +00:00
lelo
e8a694fc35
Remove unused field in FontAtlasSet (#8639)
# Objective

- Fulfill TODO about unused member from `FontAtlasSet`

## Solution

- Removed field `queue: Vec<FontSizeKey>` from `FontAtlasSet`
2023-05-19 18:55:12 +00:00
JoJoJet
b4e7f0899a
Add documentation to last_change_tick (#8598)
# Objective

This method has no documentation and it's extremely unclear what it
does, or what the returned tick represents.

## Solution

Write documentation.
2023-05-19 18:24:11 +00:00
François
ad8875958d
Update ruzstd and basis universal (#8622)
# Objective

- Update dependencies `ruzstd` and `basis-universal`
- Alternative to #5278 and #8133

## Solution

- Update the dependencies, fix the code
- Bevy now also depend on `syn@2` so it's not a blocker to update
`ruzstd` anymore
2023-05-17 23:29:31 +00:00
Nicola Papale
dce472222f
Fix outdated doc in bevy_render (#8578)
# Objective

Fix an out-of-date doc string.

The old doc string says "returns None if …" and "for a given
descriptor",
but this method neither takes an argument or returns an `Option`.
2023-05-17 19:46:18 +00:00
Luca Della Vedova
a47f1ab4be
Add support for pnm textures (#8601)
# Objective

Add support for the [Netpbm](https://en.wikipedia.org/wiki/Netpbm) image
formats, behind a `pnm` feature flag.

My personal use case for this was robotics applications, with `pgm`
being a popular format used in the field to represent world maps in
robots.
I chose the formats and feature name by checking the logic in
[image.rs](a35ed552fa/crates/bevy_render/src/texture/image.rs (L76))

## Solution

Quite straightforward, the `pnm` feature flag already exists in the
`image` crate so it's just creating and exposing a `pnm` feature flag in
the root `Cargo.toml` and forwarding it through `bevy_internal` and
`bevy_render` all the way to the `image` crate.

---

## Changelog

### Added

`pnm` feature to add support for `pam`, `pbm`, `pgm` and `ppm` image
formats.

---------

Signed-off-by: Luca Della Vedova <lucadv@intrinsic.ai>
2023-05-16 23:51:47 +00:00
François
e0b18091b5
fix missed examples in WebGPU update (#8553)
# Objective

- I missed a few examples in #8336 
- fixes #8556 
- fixes #8620

## Solution

- Update them
2023-05-16 20:31:30 +00:00
Gino Valente
56686a8962
bevy_derive: Add #[deref] attribute (#8552)
# Objective

Bevy code tends to make heavy use of the [newtype](
https://doc.rust-lang.org/rust-by-example/generics/new_types.html)
pattern, which is why we have a dedicated derive for
[`Deref`](https://doc.rust-lang.org/std/ops/trait.Deref.html) and
[`DerefMut`](https://doc.rust-lang.org/std/ops/trait.DerefMut.html).
This derive works for any struct with a single field:

```rust
#[derive(Component, Deref, DerefMut)]
struct MyNewtype(usize);
```

One reason for the single-field limitation is to prevent confusion and
footguns related that would arise from allowing multi-field structs:

<table align="center">
<tr>
<th colspan="2">
Similar structs, different derefs
</th>
</tr>
<tr>
<td>

```rust
#[derive(Deref, DerefMut)]
struct MyStruct {
  foo: usize, // <- Derefs usize
  bar: String,
}
```

</td>
<td>

```rust
#[derive(Deref, DerefMut)]
struct MyStruct {
  bar: String, // <- Derefs String
  foo: usize,
}
```

</td>
</tr>
<tr>
<th colspan="2">
Why `.1`?
</th>
</tr>
<tr>
<td colspan="2">

```rust
#[derive(Deref, DerefMut)]
struct MyStruct(Vec<usize>, Vec<f32>);

let mut foo = MyStruct(vec![123], vec![1.23]);

// Why can we skip the `.0` here?
foo.push(456);
// But not here?
foo.1.push(4.56);
```

</td>
</tr>
</table>

However, there are certainly cases where it's useful to allow for
structs with multiple fields. Such as for structs with one "real" field
and one `PhantomData` to allow for generics:

```rust
#[derive(Deref, DerefMut)]
struct MyStruct<T>(
  // We want use this field for the `Deref`/`DerefMut` impls
  String,
  // But we need this field so that we can make this struct generic
  PhantomData<T>
);

// ERROR: Deref can only be derived for structs with a single field
// ERROR: DerefMut can only be derived for structs with a single field
```

Additionally, the possible confusion and footguns are mainly an issue
for newer Rust/Bevy users. Those familiar with `Deref` and `DerefMut`
understand what adding the derive really means and can anticipate its
behavior.

## Solution

Allow users to opt into multi-field `Deref`/`DerefMut` derives using a
`#[deref]` attribute:

```rust
#[derive(Deref, DerefMut)]
struct MyStruct<T>(
  // Use this field for the `Deref`/`DerefMut` impls
  #[deref] String,
  // We can freely include any other field without a compile error
  PhantomData<T>
);
```

This prevents the footgun pointed out in the first issue described in
the previous section, but it still leaves the possible confusion
surrounding `.0`-vs-`.#`. However, the idea is that by making this
behavior explicit with an attribute, users will be more aware of it and
can adapt appropriately.

---

## Changelog

- Added `#[deref]` attribute to `Deref` and `DerefMut` derives
2023-05-16 18:29:09 +00:00
JoJoJet
1da726e046
Fix a change detection test (#8605)
# Objective

The unit test `chang_tick_wraparound` is meant to ensure that change
ticks correctly deal with wrapping by setting the world's
`last_change_tick` to `u32::MAX`. However, since systems don't use* the
value of `World::last_change_tick`, this test doesn't actually involve
any wrapping behavior.

*exclusive systems do use `World::last_change_tick`; however it gets
overwritten by the system's own last tick in `System::run`.

## Solution

Use `QueryState` instead of systems in the unit test. This approach
actually uses `World::last_change_tick`, so it properly tests that
change ticks deal with wrapping correctly.
2023-05-16 01:41:24 +00:00
Nico Burns
08bf1a6c2e
Flatten UI Style properties that use Size + remove Size (#8548)
# Objective

- Simplify API and make authoring styles easier

See:
https://github.com/bevyengine/bevy/issues/8540#issuecomment-1536177102

## Solution

- The `size`, `min_size`, `max_size`, and `gap` properties have been
replaced by `width`, `height`, `min_width`, `min_height`, `max_width`,
`max_height`, `row_gap`, and `column_gap` properties

---

## Changelog

- Flattened `Style` properties that have a `Size` value directly into
`Style`

## Migration Guide

- The `size`, `min_size`, `max_size`, and `gap` properties have been
replaced by the `width`, `height`, `min_width`, `min_height`,
`max_width`, `max_height`, `row_gap`, and `column_gap` properties. Use
the new properties instead.

---------

Co-authored-by: ickshonpe <david.curthoys@googlemail.com>
2023-05-16 01:36:32 +00:00
JMS55
17f045e2a0
Delay asset hot reloading (#8503)
# Objective

- Fix #5631 

## Solution

- Wait 50ms (configurable) after the last modification event before
reloading an asset.

---

## Changelog

- `AssetPlugin::watch_for_changes` is now a `ChangeWatcher` instead of a
`bool`
- Fixed https://github.com/bevyengine/bevy/issues/5631

## Migration Guide
- Replace `AssetPlugin::watch_for_changes: true` with e.g.
`ChangeWatcher::with_delay(Duration::from_millis(200))`

---------

Co-authored-by: François <mockersf@gmail.com>
2023-05-16 01:26:11 +00:00
François
0736195a1e
update syn, encase, glam and hexasphere (#8573)
# Objective

- Fixes #8282 
- Update `syn` to 2.0, `encase` to 0.6, `glam` to 0.24 and `hexasphere`
to 9.0


Blocked ~~on https://github.com/teoxoy/encase/pull/42~~ and ~~on
https://github.com/OptimisticPeach/hexasphere/pull/17~~

---------

Co-authored-by: Nicola Papale <nicopap@users.noreply.github.com>
Co-authored-by: JoJoJet <21144246+JoJoJet@users.noreply.github.com>
2023-05-16 01:24:17 +00:00
ickshonpe
a35ed552fa
Fix Node::physical_rect and add a physical_size method (#8551)
# Objective

* `Node::physical_rect` divides the logical size of the node by the
scale factor, when it should multiply.
* Add a `physical_size` method to `Node` that calculates the physical
size of a node.

---

## Changelog

* Added a method `physical_size` to `Node` that calculates the physical
size of the `Node` based on the given scale factor.
* Fixed the `Node::physical_rect` method, the logical size should be
multiplied by the scale factor to get the physical size.
* Removed the `scale_value` function from the `text` widget module and
replaced its usage with `Node::physical_size`.
* Derived `Copy` for `Node` (since it's only a wrapped `Vec2`).
* Made `Node::size` const.
2023-05-11 18:38:01 +00:00
JoJoJet
1644426761
Simplify the way run conditions are stored in the schedule (#8594)
# Objective

`ScheduleGraph` currently stores run conditions in a
`Option<Vec<BoxedCondition>>`. The `Option` is unnecessary, since we can
just use an empty vector instead of `None`.
2023-05-11 17:17:15 +00:00
Ame
636f711d26
Remove a repeated phrase in UnsafeWorldCell docs (#8590)
I just found a typo while reading the docs.

# Objective

- Fix `UnsafeWorldCell` docs 

## Solution

- Remove the repeated phrase
2023-05-11 05:35:27 +00:00
JoJoJet
76fe2b40c6
Improve documentation for UnsafeWorldCell::world_mut (#8587)
# Objective

The method `UnsafeWorldCell::world_mut` is a special case, since its
safety contract is more difficult to satisfy than the other methods on
`UnsafeWorldCell`. Rewrite its documentation to be specific about when
it can and cannot be used. Provide examples and emphasize that it is
unsound to call in most cases.
2023-05-11 00:31:26 +00:00
JoJoJet
35240fe4f8
Rename UnsafeWorldCell::read_change_tick (#8588)
# Objective

The method `UnsafeWorldCell::read_change_tick` is longer than it needs
to be. `World` only has a method called this because it has two methods
for getting a change tick: one that takes `&self` and one that takes
`&mut self`. Since this distinction is not applicable to
`UnsafeWorldCell`, we should just call this method `change_tick`.

## Solution

Deprecate the current method and add a new one called `change_tick`.

---

## Changelog

- Renamed `UnsafeWorldCell::read_change_tick` to `change_tick`.

## Migration Guide

The `UnsafeWorldCell` method `read_change_tick` has been renamed to
`change_tick`.
2023-05-10 23:59:04 +00:00
SpecificProtagonist
86aaad743b
Merge ScheduleRunnerSettings into ScheduleRunnerPlugin (#8585)
# Objective

`ScheduleRunnerPlugin` was still configured via a resource, meaning
users would be able to change the settings while the app is running, but
the changes wouldn't have an effect.

## Solution

Configure plugin directly

---

## Changelog

- Changed: merged `ScheduleRunnerSettings` into `ScheduleRunnerPlugin` 

## Migration Guide

- instead of inserting the `ScheduleRunnerSettings` resource, configure
the `ScheduleRunnerPlugin`
2023-05-10 16:46:21 +00:00
Connor McMillin
f786ad4906
Added Vec append to BufferVec - Issue #3531 (#8575)
# Objective

- Fixes #3531 

## Solution

- Added an append wrapper to BufferVec based on the function signature
for vec.append()

---

First PR to Bevy. I didn't see any tests for other BufferVec methods
(could have missed them) and currently this method is not used anywhere
in the project. Let me know if there are tests to add or if I should
find somewhere to use append so it is not dead code. The issue mentions
implementing `truncate` and `extend` which were already implemented and
merged
[here](https://github.com/bevyengine/bevy/pull/6833/files#diff-c8fb332382379e383f1811e30c31991b1e0feb38ca436c357971755368012ced)
2023-05-09 17:25:50 +00:00
ickshonpe
8581f607f8
Replace remaining uses of &T, Changed<T> with Ref in UI system queries (#8567)
# Objective

Replace `Query<&T, Changed<T>>` style queries with the more efficient
`Query<Ref<T>>` form in two of the UI systems.

---

## Changelog

Replaced use of `Changed` with `Ref` in queries in the
`ui_layout_system` and `calc_bounds` UI systems.
2023-05-08 20:49:55 +00:00
IceSentry
613b5a69ae
Add ViewNode to simplify render node management (#8118)
# Objective

- When writing render nodes that need a view, you always need to define
a `Query` on the associated view and make sure to update it manually and
query it manually. This is verbose and error prone.

## Solution

- Introduce a new `ViewNode` trait and `ViewNodeRunner` `Node` that will
take care of managing the associated view query automatically.
- The trait is currently a passthrough of the `Node` trait. So it still
has the update/run with all the same data passed in.
- The `ViewNodeRunner` is the actual node that is added to the render
graph and it contains the custom node. This is necessary because it's
the one that takes care of updating the node.

---

## Changelog

- Add `ViewNode`
- Add `ViewNodeRunner`

## Notes

Currently, this only handles the view query, but it could probably have
a ReadOnlySystemState that would also simplify querying all the readonly
resources that most render nodes currently query manually. The issue is
that I don't know how to do that without a `&mut self`.

At first, I tried making this a default feature of all `Node`, but I
kept hitting errors related to traits and generics and stuff I'm not
super comfortable with. This implementations is much simpler and keeps
the default Node behaviour so isn't a breaking change

## Reviewer Notes

The PR looks quite big, but the core of the PR is the changes in
`render_graph/node.rs`. Every other change is simply updating existing
nodes to use this new feature.

## Open questions

~~- Naming is not final, I'm opened to anything. I named it
ViewQueryNode because it's a node with a managed Query on a View.~~
~~- What to do when the query fails? All nodes using this pattern
currently just `return Ok(())` when it fails, so I chose that, but
should it be more flexible?~~
~~- Is the ViewQueryFilter actually necessary? All view queries run on
the entity that is already guaranteed to be a view. Filtering won't do
much, but maybe someone wants to control an effect with the presence of
a component instead of a flag.~~
~~- What to do with Nodes that are empty struct? Implementing
`FromWorld` is pretty verbose but not implementing it means there's 2
ways to create a `ViewNodeRunner` which seems less ideal. This is an
issue now because most node simply existed to hold the query, but now
that they don't hold the query state we are left with a bunch of empty
structs.~~
- Should we have a `RenderGraphApp::add_render_graph_view_node()`, this
isn't necessary, but it could make the code a bit shorter.

---------

Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2023-05-08 19:42:23 +00:00
Mincho Paskalev
fe57b9f744
Add Reflect and FromReflect for AssetPath (#8531)
# Objective

- Add Reflect and FromReflect for AssetPath
- Fixes #8458

## Solution

- Straightforward derive of `Reflect` and `FromReflect` for `AssetPath`
- Implement `Reflect` and `FromReflect` for `Cow<'static, Path>` as to
satisfy the 'static lifetime requierments of bevy_reflect.
Implementation is a direct copy of that for `Cow<'static, str>` so maybe
it begs the question that was already asked in #7429 - maybe it would be
benefitial to write a general implementation for `Reflect` for
`Cow<'static, T>`.
2023-05-08 19:19:19 +00:00
Zhixing Zhang
44a365d540
Allow custom depth texture usage (#6815)
# Objective
Sometimes we might want to read from the depth texture in some custom
rendering features. We must then add `STORAGE_BINDING` or
`TEXTURE_BINDING` to the texture usage flags when creating them.

## Solution

This PR allows one to customize the usage flags in the `Camera3d`
component.
2023-05-08 18:20:06 +00:00
bird
8930cfcdd4
conversions between [u8; 4] and Color (#8564)
# Objective

- Fixes #8563

## Solution

~~- Implement From<Color> for [u8; 4]~~
~~- also implement From<[u8; 4]> for Color because why not.~~
- implement method `as_rgba_u8` in Color

---------

Co-authored-by: Gino Valente <49806985+MrGVSV@users.noreply.github.com>
2023-05-08 16:36:46 +00:00
ickshonpe
e0a94abf1c
Replace the local text queues in the text systems with flags stored in a component (#8549)
# Objective

`text_system` and `measure_text_system` both keep local queues to keep
track of text node entities that need recomputations/remeasurement,
which scales very badly with large numbers of text entities (O(n^2)) and
makes the code quite difficult to understand.

Also `text_system` filters for `Changed<Text>`, this isn't something
that it should do. When a text node entity fails to be processed by
`measure_text_system` because a font can't be found, the text node will
still be added to `text_system`'s local queue for recomputation. `Text`
should only ever be queued by `text_system` when a text node's geometry
is modified or a new measure is added.

## Solution

Remove the local text queues and use a component `TextFlags` to schedule
remeasurements and recomputations.

## Changelog
* Created a component `TextFlags` with fields `remeasure` and
`recompute`, which can be used to schedule a text `remeasure` or
`recomputation` respectively and added it to `TextBundle`.
* Removed the local text queues from `measure_text_system` and
`text_system` and instead use the `TextFlags` component to schedule
remeasurements and recomputations.

## Migration Guide

The component `TextFlags` has been added to `TextBundle`.
2023-05-08 13:57:52 +00:00
ickshonpe
845f027ac2
UI layout tree debug print (#8521)
# Objective

Copy the `debug::print_tree` function from Taffy except display entity
ids instead of Taffy's node ids and indicate which ui nodes have a
measure func.
2023-05-08 13:56:19 +00:00
konsti219
1530f63756
Use cmp of Self in implementaions of partial_cmp (#8559)
# Objective

Ensure future consistency between the two compare functions for all
types with manual `Ord` and `PartialOrd` implementations.

## Solution

Use `Self::cpm` in the implementation of `partial_cpm` for types
`Handle` and `Name`.
2023-05-06 22:31:25 +00:00