Commit graph

1482 commits

Author SHA1 Message Date
François Mockers
4a4d73ef55
make example font_atlas_debug deterministic with a seeded random (#12519)
# Objective

- Make example font_atlas_debug deterministic so that it's easier to
check for regression

## Solution

- Use a seeded random
2024-03-17 21:11:25 +00:00
François Mockers
1e1e11c4a6
make alien_cake_addict deterministic with a seeded random (#12515)
# Objective

- Make example alien_cake_addict deterministic so that it's easier to
check for regression

## Solution

- Use a seeded random

---------

Co-authored-by: Rob Parrett <robparrett@gmail.com>
2024-03-17 18:42:44 +00:00
François Mockers
17c3faff07
make align deterministic with a seeded random (#12518)
# Objective

- Make example align deterministic so that it's easier to check for
regression

## Solution

- Use a seeded random
2024-03-17 18:36:43 +00:00
François Mockers
1073c49f96
order systems in axes example (#12486)
# Objective

- in example `axes`, the axes are sometime one frame late to follow
their mesh

## Solution

- System `move_cubes` modify the transforms, and `draw_axes` query them
for the axes
- if their order is not specified, it will be random and sometimes axes
are drawn before transforms are updated
- order systems
2024-03-15 00:54:42 +00:00
Tolki
d3d9cab30c
Breakout refactor (#12477)
# Objective

- Improve the code quality of the breakout example
- As a newcomer to `bevy` I was pointed to the breakout example after
the "Getting Started" tutorial
- I'm making this PR because it had a few wrong comments + some
inconsistency in used patterns

## Solution

- Remove references to `wall` in all the collision code as it also
handles bricks and the paddle
- Use the newtype pattern with `bevy::prelude::Deref` for resources
    -  It was already used for `Velocity` before this PR
- `Scoreboard` is a resource only containing `score`, so it's simpler as
a newtype `Score` resource
- `CollisionSound` is already a newtype, so might as well unify the
access pattern for it
- Added docstrings for `WallLocation::position` and `WallLocation::size`
to explain what they represent
2024-03-14 17:32:05 +00:00
Matty
325f0fd982
Alignment API for Transforms (#12187)
# Objective

- Closes #11793 
- Introduces a general API for aligning local coordinates of Transforms
with given vectors.

## Solution

- We introduce `Transform::align`, which allows a rotation to be
specified by four pieces of alignment data, as explained by the
documentation:
````rust
/// Rotates this [`Transform`] so that the `main_axis` vector, reinterpreted in local coordinates, points
/// in the given `main_direction`, while `secondary_axis` points towards `secondary_direction`.
///
/// For example, if a spaceship model has its nose pointing in the X-direction in its own local coordinates
/// and its dorsal fin pointing in the Y-direction, then `align(Vec3::X, v, Vec3::Y, w)` will make the spaceship's
/// nose point in the direction of `v`, while the dorsal fin does its best to point in the direction `w`.
///
/// More precisely, the [`Transform::rotation`] produced will be such that:
/// * applying it to `main_axis` results in `main_direction`
/// * applying it to `secondary_axis` produces a vector that lies in the half-plane generated by `main_direction` and
/// `secondary_direction` (with positive contribution by `secondary_direction`)
///
/// [`Transform::look_to`] is recovered, for instance, when `main_axis` is `Vec3::NEG_Z` (the [`Transform::forward`]
/// direction in the default orientation) and `secondary_axis` is `Vec3::Y` (the [`Transform::up`] direction in the default
/// orientation). (Failure cases may differ somewhat.)
///
/// In some cases a rotation cannot be constructed. Another axis will be picked in those cases:
/// * if `main_axis` or `main_direction` is zero, `Vec3::X` takes its place
/// * if `secondary_axis` or `secondary_direction` is zero, `Vec3::Y` takes its place
/// * if `main_axis` is parallel with `secondary_axis` or `main_direction` is parallel with `secondary_direction`,
/// a rotation is constructed which takes `main_axis` to `main_direction` along a great circle, ignoring the secondary
/// counterparts
/// 
/// Example
/// ```
/// # use bevy_math::{Vec3, Quat};
/// # use bevy_transform::components::Transform;
/// let mut t1 = Transform::IDENTITY;
/// let mut t2 = Transform::IDENTITY;
/// t1.align(Vec3::ZERO, Vec3::Z, Vec3::ZERO, Vec3::X);
/// t2.align(Vec3::X, Vec3::Z, Vec3::Y, Vec3::X);
/// assert_eq!(t1.rotation, t2.rotation);
/// 
/// t1.align(Vec3::X, Vec3::Z, Vec3::X, Vec3::Y);
/// assert_eq!(t1.rotation, Quat::from_rotation_arc(Vec3::X, Vec3::Z));
/// ```
pub fn align(
    &mut self,
    main_axis: Vec3,
    main_direction: Vec3,
    secondary_axis: Vec3,
    secondary_direction: Vec3,
) { //... }
````

- We introduce `Transform::aligned_by`, the returning-Self version of
`align`:
````rust
pub fn aligned_by(
    mut self,
    main_axis: Vec3,
    main_direction: Vec3,
    secondary_axis: Vec3,
    secondary_direction: Vec3,
) -> Self { //... }
````

- We introduce an example (examples/transforms/align.rs) that shows the
usage of this API. It is likely to be mathier than most other
`Transform` APIs, so when run, the example demonstrates what the API
does in space:
<img width="1440" alt="Screenshot 2024-03-12 at 11 01 19 AM"
src="https://github.com/bevyengine/bevy/assets/2975848/884b3cc3-cbd9-48ae-8f8c-49a677c59dfe">

---

## Changelog

- Added methods `align`, `aligned_by` to `Transform`.
- Added transforms/align.rs to examples.

---

## Discussion

### On the form of `align`

The original issue linked above suggests an API similar to that of the
existing `Transform::look_to` method:
````rust
pub fn align_to(&mut self, direction: Vec3, up: Vec3) { //... }
````
Not allowing an input axis of some sort that is to be aligned with
`direction` would not really solve the problem in the issue, since the
user could easily be in a scenario where they have to compose with
another rotation on their own (undesirable). This leads to something
like:
````rust
pub fn align_to(&mut self, axis: Vec3, direction: Vec3, up: Vec3) { //... }
````
However, this still has two problems:
- If the vector that the user wants to align is parallel to the Y-axis,
then the API basically does not work (we cannot fully specify a
rotation)
- More generally, it does not give the user the freedom to specify which
direction is to be treated as the local "up" direction, so it fails as a
general alignment API

Specifying both leads us to the present situation, with two local axis
inputs (`main_axis` and `secondary_axis`) and two target directions
(`main_direction` and `secondary_direction`). This might seem a little
cumbersome for general use, but for the time being I stand by the
decision not to expand further without prompting from users. I'll expand
on this below.

### Additional APIs?

Presently, this PR introduces only `align` and `aligned_by`. Other
potentially useful bundles of API surface arrange into a few different
categories:

1. Inferring direction from position, a la `Transform::look_at`, which
might look something like this:
````rust
pub fn align_at(&mut self, axis: Vec3, target: Vec3, up: Vec3) {
    self.align(axis, target - self.translation, Vec3::Y, up);
}
````
(This is simple but still runs into issues when the user wants to point
the local Y-axis somewhere.)

2. Filling in some data for the user for common use-cases; e.g.:
````rust
pub fn align_x(&mut self, direction: Vec3, up: Vec3) {
    self.align(Vec3::X, direction, Vec3::Y, up);
}
````
(Here, use of the `up` vector doesn't lose any generality, but it might
be less convenient to specify than something else. This does naturally
leave open the question of what `align_y` would look like if we provided
it.)

Morally speaking, I do think that the `up` business is more pertinent
when the intention is to work with cameras, which the `look_at` and
`look_to` APIs seem to cover pretty well. If that's the case, then I'm
not sure what the ideal shape for these API functions would be, since it
seems like a lot of input would have to be baked into the function
definitions. For some cases, this might not be the end of the world:
````rust
pub fn align_x_z(&mut self, direction: Vec3, weak_direction: Vec3) {
    self.align(Vec3::X, direction, Vec3::Z, weak_direction);
}
````
(However, this is not symmetrical in x and z, so you'd still need six
API functions just to support the standard positive coordinate axes, and
if you support negative axes then things really start to balloon.)

The reasons that these are not actually produced in this PR are as
follows:
1. Without prompting from actual users in the wild, it is unknown to me
whether these additional APIs would actually see a lot of use. Extending
these to our users in the future would be trivial if we see there is a
demand for something specific from the above-mentioned categories.
2. As discussed above, there are so many permutations of these that
could be provided that trying to do so looks like it risks unduly
ballooning the API surface for this feature.
3. Finally, and most importantly, creating these helper functions in
user-space is trivial, since they all just involve specializing `align`
to particular inputs; e.g.:
````rust
fn align_ship(ship_transform: &mut Transform, nose_direction: Vec3, dorsal_direction: Vec3) {
    ship_transform.align(Ship::NOSE, nose_direction, Ship::DORSAL, dorsal_direction);
}
````

With that in mind, I would prefer instead to focus on making the
documentation and examples for a thin API as clear as possible, so that
users can get a grip on the tool and specialize it for their own needs
when they feel the desire to do so.

### `Dir3`?

As in the case of `Transform::look_to` and `Transform::look_at`, the
inputs to this function are, morally speaking, *directions* rather than
vectors (actually, if we're being pedantic, the input is *really really*
a pair of orthonormal frames), so it's worth asking whether we should
really be using `Dir3` as inputs instead of `Vec3`. I opted for `Vec3`
for the following reasons:
1. Specifying a `Dir3` in user-space is just more annoying than
providing a `Vec3`. Even in the most basic cases (e.g. providing a
vector literal), you still have to do error handling or call an unsafe
unwrap in your function invocations.
2. The existing API mentioned above uses `Vec3`, so we are just adhering
to the same thing.

Of course, the use of `Vec3` has its own downsides; it can be argued
that the replacement of zero-vectors with fixed ones (which we do in
`Transform::align` as well as `Transform::look_to`) more-or-less amounts
to failing silently.

### Future steps

The question of additional APIs was addressed above. For me, the main
thing here to handle more immediately is actually just upstreaming this
API (or something similar and slightly mathier) to `glam::Quat`. The
reason that this would be desirable for users is that this API currently
only works with `Transform`s even though all it's actually doing is
specifying a rotation. Upstreaming to `glam::Quat`, properly done, could
buy a lot basically for free, since a number of `Transform` methods take
a rotation as an input. Using these together would require a little bit
of mathematical savvy, but it opens up some good things (e.g.
`Transform::rotate_around`).
2024-03-14 14:55:55 +00:00
Lynn
ee0fa7d1c2
Gizmo 3d grids (#12430)
# Objective

- Adds 3d grids, suggestion of #9400

## Solution

- Added 3d grids (grids spanning all three dimensions, not flat grids)
to bevy_gizmos

---

## Changelog

- `gizmos.grid(...)` and `gizmos.grid_2d(...)` now return a
`GridBuilder2d`.
- Added `gizmos.grid_3d(...)` which returns a `GridBuilder3d`.
- The difference between them is basically only that `GridBuilder3d`
exposes some methods for configuring the z axis while the 2d version
doesn't.
- Allowed for drawing the outer edges along a specific axis by calling
`.outer_edges_x()`, etc. on the builder.

## Additional information
Please note that I have not added the 3d grid to any example as not to
clutter them.
Here is an image of what the 3d grid looks like:
<img width="1440" alt="Screenshot 2024-03-12 at 02 19 55"
src="https://github.com/bevyengine/bevy/assets/62256001/4cd3b7de-cf2c-4f05-8a79-920a4dd804b8">

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
2024-03-13 18:51:53 +00:00
Rob Parrett
a9ca8491aa
Fix z scale being 0.0 in breakout example (#12439)
# Objective

Scaling `z` by anything but `1.0` in 2d can only lead to bugs and
confusion. See #4149.

## Solution

Use a `Vec2` for the paddle size const, and add a scale of `1.0` later.
This matches the way `BRICK_SIZE` is defined.
2024-03-13 01:30:43 +00:00
Andrew
3f6300dc81
low_power example: pick nits (#12437)
# Objective

- no-longer-extant type `WinitConfig` referenced in comments
- `mouse_button_input` refers to `KeyCode` input
- "spacebar" flagged as a typo by RustRover IDE

## Solution

- replace `WinitConfig` with `WinitSettings` in comments
- rename `mouse_button_input` to just `button_input`
- change "spacebar" to "space bar"
2024-03-12 22:03:41 +00:00
Mateusz Wachowiak
2d29954034
Fps overlay (#12382)
# Objective

- Part of #12351
- Add fps overlay

## Solution

- Create `FpsOverlayPlugin`
- Allow for configuration through resource `FpsOverlayConfig`
- Allow for configuration during runtime

### Preview on default settings

![20240308_22h23m25s_grim](https://github.com/bevyengine/bevy/assets/62356462/33d3d7a9-435e-4e0b-9814-d3274e779a69)

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
2024-03-11 19:26:14 +00:00
Lynn
27215b79b0
Gizmo line joints (#12252)
# Objective

- Adds gizmo line joints, suggestion of #9400

## Solution

- Adds `line_joints: GizmoLineJoint` to `GizmoConfig`. Currently the
following values are supported:
- `GizmoLineJoint::None`: does not draw line joints, same behaviour as
previously
  - `GizmoLineJoint::Bevel`: draws a single triangle between the lines
- `GizmoLineJoint::Miter` / 'spiky joints': draws two triangles between
the lines extending them until they meet at a (miter) point.
- NOTE: for very small angles between the lines, which happens
frequently in 3d, the miter point will be very far away from the point
at which the lines meet.
- `GizmoLineJoint::Round(resolution)`: Draw a circle arc between the
lines. The circle is a triangle fan of `resolution` triangles.

---

## Changelog

- Added `GizmoLineJoint`, use that in `GizmoConfig` and added necessary
pipelines and draw commands.
- Added a new `line_joints.wgsl` shader containing three vertex shaders
`vertex_bevel`, `vertex_miter` and `vertex_round` as well as a basic
`fragment` shader.

## Migration Guide

Any manually created `GizmoConfig`s must now set the `.line_joints`
field.

## Known issues

- The way we currently create basic closed shapes like rectangles,
circles, triangles or really any closed 2d shape means that one of the
corners will not be drawn with joints, although that would probably be
expected. (see the triangle in the 2d image)
- This could be somewhat mitigated by introducing line caps or fixed by
adding another segment overlapping the first of the strip. (Maybe in a
followup PR?)
- 3d shapes can look 'off' with line joints (especially bevel) because
wherever 3 or more lines meet one of them may stick out beyond the joint
drawn between the other 2.
- Adding additional lines so that there is a joint between every line at
a corner would fix this but would probably be too computationally
expensive.
- Miter joints are 'unreasonably long' for very small angles between the
lines (the angle is the angle between the lines in screen space). This
is technically correct but distracting and does not feel right,
especially in 3d contexts. I think limiting the length of the miter to
the point at which the lines meet might be a good idea.
- The joints may be drawn with a different gizmo in-between them and
their corresponding lines in 2d. Some sort of z-ordering would probably
be good here, but I believe this may be out of scope for this PR.

## Additional information

Some pretty images :)


<img width="1175" alt="Screenshot 2024-03-02 at 04 53 50"
src="https://github.com/bevyengine/bevy/assets/62256001/58df7e63-9376-4430-8871-32adba0cb53b">

- Note that the top vertex does not have a joint drawn.

<img width="1440" alt="Screenshot 2024-03-02 at 05 03 55"
src="https://github.com/bevyengine/bevy/assets/62256001/137a00cf-cbd4-48c2-a46f-4b47492d4fd9">


Now for a weird video: 


https://github.com/bevyengine/bevy/assets/62256001/93026f48-f1d6-46fe-9163-5ab548a3fce4

- The black lines shooting out from the cube are miter joints that get
very long because the lines between which they are drawn are (almost)
collinear in screen space.

---------

Co-authored-by: Pablo Reinhardt <126117294+pablo-lua@users.noreply.github.com>
2024-03-11 19:21:32 +00:00
François Mockers
40732148da
correctly set up background color in mobile example (#12384)
# Objective

- Since #11165, the button in the mobile example doesn't visually react
to touches

## Solution

- Correctly set up the background color
2024-03-11 18:36:52 +00:00
François
7546624471
Improve gizmo axes example (#12335)
# Objective

- Improve example from #12299 
- Make it frame rate independent
- Make it not randomly random

## Solution

- Transitions between transforms will take 2 seconds instead of 100
frames
- Random is seeded
2024-03-08 23:05:11 +00:00
andristarr
432a4f1d85
Fix dim emissive values in lighting example (#12343)
# Objective

- Fixes #12330 

## Solution

- Increasing the emissive of the objects representing the lights.
2024-03-07 22:12:57 +00:00
Patrick Walton
dfdf2b9ea4
Implement the AnimationGraph, allowing for multiple animations to be blended together. (#11989)
This is an implementation of RFC #51:
https://github.com/bevyengine/rfcs/blob/main/rfcs/51-animation-composition.md

Note that the implementation strategy is different from the one outlined
in that RFC, because two-phase animation has now landed.

# Objective

Bevy needs animation blending. The RFC for this is [RFC 51].

## Solution

This is an implementation of the RFC. Note that the implementation
strategy is different from the one outlined there, because two-phase
animation has now landed.

This is just a draft to get the conversation started. Currently we're
missing a few things:

- [x] A fully-fleshed-out mechanism for transitions
- [x] A serialization format for `AnimationGraph`s
- [x] Examples are broken, other than `animated_fox`
- [x] Documentation

---

## Changelog

### Added

* The `AnimationPlayer` has been reworked to support blending multiple
animations together through an `AnimationGraph`, and as such will no
longer function unless a `Handle<AnimationGraph>` has been added to the
entity containing the player. See [RFC 51] for more details.

* Transition functionality has moved from the `AnimationPlayer` to a new
component, `AnimationTransitions`, which works in tandem with the
`AnimationGraph`.

## Migration Guide

* `AnimationPlayer`s can no longer play animations by themselves and
need to be paired with a `Handle<AnimationGraph>`. Code that was using
`AnimationPlayer` to play animations will need to create an
`AnimationGraph` asset first, add a node for the clip (or clips) you
want to play, and then supply the index of that node to the
`AnimationPlayer`'s `play` method.

* The `AnimationPlayer::play_with_transition()` method has been removed
and replaced with the `AnimationTransitions` component. If you were
previously using `AnimationPlayer::play_with_transition()`, add all
animations that you were playing to the `AnimationGraph`, and create an
`AnimationTransitions` component to manage the blending between them.

[RFC 51]:
https://github.com/bevyengine/rfcs/blob/main/rfcs/51-animation-composition.md

---------

Co-authored-by: Rob Parrett <robparrett@gmail.com>
2024-03-07 20:22:42 +00:00
BD103
713d91b721
Improve Bloom 3D lighting (#11981)
# Objective

- With the recent lighting changes, the default configuration in the
`bloom_3d` example is less clear what bloom actually does
- See [this
screenshot](4fdb1455d5 (r1494648414))
for a comparison.
- `bloom_3d` additionally uses a for-loop to spawn the spheres, which
can be turned into `commands::spawn_batch` call.
- The text is black, which is difficult to see on the gray background.

## Solution

- Increase emmisive values of materials.
- Set text to white.

## Showcase

Before:

<img width="1392" alt="before"
src="https://github.com/bevyengine/bevy/assets/59022059/757057ad-ed9f-4eed-b135-8e2032fcdeb5">

After:

<img width="1392" alt="image"
src="https://github.com/bevyengine/bevy/assets/59022059/3f9dc7a8-94b2-44b9-8ac3-deef1905221b">

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
2024-03-07 15:20:38 +00:00
Antony
f67b17d80d
Use .register_asset_source() in extra_asset_source example (#12350)
# Objective

Fixes #12347.

## Solution

Use `.register_asset_source()` in `extra_asset_source` example instead
of writing part of the app state.
2024-03-07 05:44:52 +00:00
James Liu
512b7463a3
Disentangle bevy_utils/bevy_core's reexported dependencies (#12313)
# Objective
Make bevy_utils less of a compilation bottleneck. Tackle #11478.

## Solution
* Move all of the directly reexported dependencies and move them to
where they're actually used.
* Remove the UUID utilities that have gone unused since `TypePath` took
over for `TypeUuid`.
* There was also a extraneous bytemuck dependency on `bevy_core` that
has not been used for a long time (since `encase` became the primary way
to prepare GPU buffers).
* Remove the `all_tuples` macro reexport from bevy_ecs since it's
accessible from `bevy_utils`.

---

## Changelog
Removed: Many of the reexports from bevy_utils (petgraph, uuid, nonmax,
smallvec, and thiserror).
Removed: bevy_core's reexports of bytemuck.

## Migration Guide
bevy_utils' reexports of petgraph, uuid, nonmax, smallvec, and thiserror
have been removed.

bevy_core' reexports of bytemuck's types has been removed. 

Add them as dependencies in your own crate instead.
2024-03-07 02:30:15 +00:00
Turki Al-Marri
6f2ecdf822
We must have googly eyes (new Game example) (#12331)
# Objective

- We must have googly eyes.
- Also it would be nice if there was an example of a desk toy
application (like the old NEKO.EXE).

## Solution

- Created an example with googly eyed Bevy logo under
examples/games/desktoy.rs.

---

## Changelog
- Added "Desk Toy" game example showcasing window transparency and hit
test.

---------

Co-authored-by: Rob Parrett <robparrett@gmail.com>
2024-03-06 22:21:41 +00:00
François
f9e70abcac
Fix ios simulator support (#12339)
# Objective

- #12103 broke iOS simulator support, it doesn't even compile anymore

## Solution

- Fix the feature
2024-03-06 17:48:17 +00:00
James Liu
9e5db9abc7
Clean up type registrations (#12314)
# Objective
Fix #12304. Remove unnecessary type registrations thanks to #4154.

## Solution
Conservatively remove type registrations. Keeping the top level
components, resources, and events, but dropping everything else that is
a type of a member of those types.
2024-03-06 16:05:53 +00:00
NiseVoid
e3b318f599
Add extra_asset_source example (#11824)
# Objective

- Make it easier to figure out how to add asset sources

## Solution

- Add an example that adds an asset source, it functions almost
identical to the embedded_asset example
- Move the file from the embedded_asset example into a `files/` folder
2024-03-06 16:00:03 +00:00
Rob Parrett
d56e16754c
Fix "dark grey" colors becoming lighter in various examples (#12333)
# Objective

Fixes #12226

Prior to the `bevy_color` port, `DARK GRAY` used to mean "dark grey."
But it is now lighter than `GRAY`, matching the css4 spec.

## Solution

Change usages of `css::DARK_GRAY` to `Color::srgb(0.25, 0.25, 0.25)` to
restore the examples to their former colors.

With one exception: `display_and_visibility`. I think the new color is
an improvement.

## Note

A lot of these examples could use nicer colors. I'm not trying to revamp
everything here.

The css4 palette is truly a horror. See #12176 and #12080 for some
discussion about alternatives.
2024-03-06 05:19:59 +00:00
Rob Parrett
0746b8eb4c
Fix green colors becoming darker in various examples (#12328)
# Objective

Fixes #12225

Prior to the `bevy_color` port, `GREEN` used to mean "full green." But
it is now a much darker color matching the css1 spec.

## Solution

Change usages of `basic::GREEN` or `css::GREEN` to `LIME` to restore the
examples to their former colors.

This also removes the duplicate definition of `GREEN` from `css`. (it
was already re-exported from `basic`)

## Note

A lot of these examples could use nicer colors. I'm not trying to do
that here.

"Dark Grey" will be tackled separately and has its own tracking issue.
2024-03-05 23:42:03 +00:00
Rob Parrett
fea6f9d915
Use floats mathed from 8-bit values in basic color palette (#12323)
# Objective

Addresses one of the side-notes in #12225.

Colors in the `basic` palette are inconsistent in a few ways:
- `CYAN` was named `AQUA` in the referenced spec. (an alias was added in
a later spec)
- Colors are defined with e.g. "half green" having a `g` value of `0.5`.
But any spec would have been based on 8-bit color, so `0x80 / 0xFF` or
`128 / 255` or ~`0.502`. This precision is likely meaningful when doing
color math/rounding.

## Solution

Regenerate the colors from
https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=37563bedc8858033bd8b8380328c5230
2024-03-05 18:05:27 +00:00
Félix Lescaudey de Maneville
fc202f2e3d
Slicing support for texture atlas (#12059)
# Objective

Follow up to #11600 and #10588 
https://github.com/bevyengine/bevy/issues/11944 made clear that some
people want to use slicing with texture atlases

## Changelog

* Added support for `TextureAtlas` slicing and tiling.
`SpriteSheetBundle` and `AtlasImageBundle` can now use `ImageScaleMode`
* Added new `ui_texture_atlas_slice` example using a texture sheet

<img width="798" alt="Screenshot 2024-02-23 at 11 58 35"
src="https://github.com/bevyengine/bevy/assets/26703856/47a8b764-127c-4a06-893f-181703777501">

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
Co-authored-by: Pablo Reinhardt <126117294+pablo-lua@users.noreply.github.com>
2024-03-05 16:05:39 +00:00
James Liu
dc40cd134f
Remove ComponentStorage and associated types (#12311)
# Objective
When doing a final pass for #3362, it appeared that `ComponentStorage`
as a trait, the two types implementing it, and the associated type on
`Component` aren't really necessary anymore. This likely was due to an
earlier constraint on the use of consts in traits, but that definitely
doesn't seem to be a problem in Rust 1.76.

## Solution
Remove them.

---

## Changelog
Changed: `Component::Storage` has been replaced with
`Component::STORAGE_TYPE` as a const.
Removed: `bevy::ecs::component::ComponentStorage` trait
Removed: `bevy::ecs::component::TableStorage` struct
Removed: `bevy::ecs::component::SparseSetStorage` struct

## Migration Guide
If you were manually implementing `Component` instead of using the
derive macro, replace the associated `Storage` associated type with the
`STORAGE_TYPE` const:

```rust
// in Bevy 0.13
impl Component for MyComponent {
    type Storage = TableStorage;
}
// in Bevy 0.14
impl Component for MyComponent {
    const STORAGE_TYPE: StorageType = StorageType::Table;
}
```

Component is no longer object safe. If you were relying on `&dyn
Component`, `Box<dyn Component>`, etc. please [file an issue
](https://github.com/bevyengine/bevy/issues) to get [this
change](https://github.com/bevyengine/bevy/pull/12311) reverted.

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
2024-03-05 15:54:52 +00:00
François
9a6fc76148
remove background color from UI example image (#12306)
# Objective

- After https://github.com/bevyengine/bevy/pull/11165, example `ui` is
not pretty as it displays the Bevy logo on a white background, with a
comment that is now wrong

## Solution

- Remove the background color
2024-03-04 23:41:51 +00:00
Afonso Lage
15db61a1f8
Improve components hooks docs (#12295)
# Objective

- Closes #12256 

## Solution

- Improved component hooks docs.
- Improved component hooks example docs.

---------

Co-authored-by: James Liu <contact@jamessliu.com>
Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
2024-03-04 19:31:10 +00:00
Matty
4673fb3e57
Example for axes gizmos (#12299)
# Objective

- Follow-up to #12211 
- Introduces an example project that demonstrates the implementation and
behavior of `Gizmos::axes` for an entity with a `Transform` component.

## Solution

In order to demonstrate how `Gizmo::axes` can be used and behaves in
practice, we introduce an example of a simple scene containing a pair of
cuboids locked in a grotesque, inscrutable dance: the two are repeatedly
given random `Transform`s which they interpolate to, showing how the
axes move with objects as they translate, rotate, and scale.

<img width="1023" alt="Screenshot 2024-03-04 at 1 16 33 PM"
src="https://github.com/bevyengine/bevy/assets/2975848/c1ff4794-6722-491c-8522-f59801645139">



On the implementation side, we demonstrate how to draw axes for
entities, automatically sizing them according to their bounding boxes
(so that the axes will be visible):
````rust
fn draw_axes(mut gizmos: Gizmos, query: Query<(&Transform, &Aabb), With<ShowAxes>>) {
    for (&transform, &aabb) in &query {
        let length = aabb.half_extents.length();
        gizmos.axes(transform, length);
    }
}
````

---

## Changelog

- Created examples/gizmos/axes.rs.
- Added 'axes' example to Cargo.toml.
2024-03-04 19:30:39 +00:00
Gino Valente
ccb9d0500f
bevy_reflect: Recursive registration (#5781)
# Objective

Resolves #4154

Currently, registration must all be done manually:

```rust
#[derive(Reflect)]
struct Foo(Bar);

#[derive(Reflect)]
struct Bar(Baz);

#[derive(Reflect)]
struct Baz(usize);

fn main() {
  // ...
  app
    .register_type::<Foo>()
    .register_type::<Bar>()
    .register_type::<Baz>()
    // .register_type::<usize>() <- This one is handled by Bevy, thankfully
  // ...
}
```

This can grow really quickly and become very annoying to add, remove,
and update as types change. It would be great if we could help reduce
the number of types that a user must manually implement themselves.

## Solution

As suggested in #4154, this PR adds automatic recursive registration.
Essentially, when a type is registered, it may now also choose to
register additional types along with it using the new
`GetTypeRegistration::register_type_dependencies` trait method.

The `Reflect` derive macro now automatically does this for all fields in
structs, tuple structs, struct variants, and tuple variants. This is
also done for tuples, arrays, `Vec<T>`, `HashMap<K, V>`, and
`Option<T>`.

This allows us to simplify the code above like:

```rust
#[derive(Reflect)]
struct Foo(Bar);

#[derive(Reflect)]
struct Bar(Baz);

#[derive(Reflect)]
struct Baz(usize);

fn main() {
  // ...
  app.register_type::<Foo>()
  // ...
}
```

This automatic registration only occurs if the type has not yet been
registered. If it has been registered, we simply skip it and move to the
next one. This reduces the cost of registration and prevents overwriting
customized registrations.

## Considerations

While this does improve ergonomics on one front, it's important to look
at some of the arguments against adopting a PR like this.

#### Generic Bounds

~~Since we need to be able to register the fields individually, we need
those fields to implement `GetTypeRegistration`. This forces users to
then add this trait as a bound on their generic arguments. This
annoyance could be relieved with something like #5772.~~

This is no longer a major issue as the `Reflect` derive now adds the
`GetTypeRegistration` bound by default. This should technically be okay,
since we already add the `Reflect` bound.

However, this can also be considered a breaking change for manual
implementations that left out a `GetTypeRegistration` impl ~~or for
items that contain dynamic types (e.g. `DynamicStruct`) since those also
do not implement `GetTypeRegistration`~~.

#### Registration Assumptions

By automatically registering fields, users might inadvertently be
relying on certain types to be automatically registered. If `Foo`
auto-registers `Bar`, but `Foo` is later removed from the code, then
anywhere that previously used or relied on `Bar`'s registration would
now fail.

---

## Changelog

- Added recursive type registration to structs, tuple structs, struct
variants, tuple variants, tuples, arrays, `Vec<T>`, `HashMap<K, V>`, and
`Option<T>`
- Added a new trait in the hidden `bevy_reflect::__macro_exports` module
called `RegisterForReflection`
- Added `GetTypeRegistration` impl for
`bevy_render::render_asset::RenderAssetUsages`

## Migration Guide

All types that derive `Reflect` will now automatically add
`GetTypeRegistration` as a bound on all (unignored) fields. This means
that all reflected fields will need to also implement
`GetTypeRegistration`.

If all fields **derive** `Reflect` or are implemented in `bevy_reflect`,
this should not cause any issues. However, manual implementations of
`Reflect` that excluded a `GetTypeRegistration` impl for their type will
need to add one.

```rust
#[derive(Reflect)]
struct Foo<T: FromReflect> {
  data: MyCustomType<T>
}

// OLD
impl<T: FromReflect> Reflect for MyCustomType<T> {/* ... */}

// NEW
impl<T: FromReflect + GetTypeRegistration> Reflect for MyCustomType<T> {/* ... */}
impl<T: FromReflect + GetTypeRegistration> GetTypeRegistration for MyCustomType<T> {/* ... */}
```

---------

Co-authored-by: James Liu <contact@jamessliu.com>
Co-authored-by: radiish <cb.setho@gmail.com>
Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2024-03-04 19:04:10 +00:00
François
b1a5aabce9
Fix failures of typos and check-cfg (#12293)
# Objective

- CI is green

## Solution

- Fix typos (#12045)
- Correctly declare features (#12100)
2024-03-04 07:48:09 +00:00
Doonv
14c20a6c9c
Add access to App within LogPlugin::update_subscriber (#12045)
# Objective

In my library,
[`bevy_dev_console`](https://github.com/doonv/bevy_dev_console) I need
access to `App` within `LogPlugin::update_subscriber` in order to
communicate with the `App` from my custom `Layer`.

## Solution

Give access to `App`.

---

## Changelog

- Added access to `App` within `LogPlugin::update_subscriber`

## Migration Guide

`LogPlugin::update_subscriber` now has a `&mut App` parameter. If you
don't need access to `App`, you can ignore the parameter with an
underscore (`_`).

```diff,rust
- fn update_subscriber(subscriber: BoxedSubscriber) -> BoxedSubscriber {
+ fn update_subscriber(_: &mut App, subscriber: BoxedSubscriber) -> BoxedSubscriber {
      Box::new(subscriber.with(CustomLayer))
  }
```
2024-03-04 00:01:05 +00:00
François
faa2ce4d55
fix example lightmaps after color migration (#12265)
# Objective

- Since #12163 example lightmaps is more dull
<img width="1280" alt="Screenshot 2024-03-02 at 23 04 36"
src="https://github.com/bevyengine/bevy/assets/8672791/7736f420-b9c5-4870-93f6-b5b992c4768a">


## Solution

- Use a srgba color, as it was before:

b24ab2e9fb/examples/3d/lightmaps.rs (L39)

b24ab2e9fb/crates/bevy_render/src/color/mod.rs (L132)

<img width="1280" alt="Screenshot 2024-03-02 at 23 05 09"
src="https://github.com/bevyengine/bevy/assets/8672791/451187ed-8612-456f-ad25-180d5f774188">
2024-03-03 21:36:11 +00:00
Ben Frankel
e8ae0d6c49
Decouple BackgroundColor from UiImage (#11165)
# Objective

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

## Solution

Stop using `BackgroundColor` as a color tint for `UiImage`. Add a
`UiImage::color` field for color tint instead. Allow a UI node to
simultaneously include a solid-color background and an image, with the
image rendered on top of the background (this is already how it works
for e.g. text).


![2024-02-29_1709239666_563x520](https://github.com/bevyengine/bevy/assets/12173779/ec50c9ef-4c7f-4ab8-a457-d086ce5b3425)

---

## Changelog

- The `BackgroundColor` component now renders a solid-color background
behind `UiImage` instead of tinting its color.
- Removed `BackgroundColor` from `ImageBundle`, `AtlasImageBundle`, and
`ButtonBundle`.
- Added `UiImage::color`.
- Expanded `RenderUiSystem` variants.
- Renamed `bevy_ui::extract_text_uinodes` to `extract_uinodes_text` for
consistency.

## Migration Guide

- `BackgroundColor` no longer tints the color of UI images. Use
`UiImage::color` for that instead.
- For solid color buttons, replace `ButtonBundle { background_color:
my_color.into(), ... }` with `ButtonBundle { image:
UiImage::default().with_color(my_color), ... }`, and update button
interaction systems to use `UiImage::color` instead of `BackgroundColor`
as well.
- `bevy_ui::RenderUiSystem::ExtractNode` has been split into
`ExtractBackgrounds`, `ExtractImages`, `ExtractBorders`, and
`ExtractText`.
- `bevy_ui::extract_uinodes` has been split into
`bevy_ui::extract_uinode_background_colors` and
`bevy_ui::extract_uinode_images`.
- `bevy_ui::extract_text_uinodes` has been renamed to
`extract_uinode_text`.
2024-03-03 21:35:50 +00:00
Ben Frankel
6e83439a06
Deprecate SpriteSheetBundle and AtlasImageBundle (#12218)
# Objective

After the `TextureAtlas` changes that landed in 0.13,
`SpriteSheetBundle` is equivalent to `TextureAtlas` + `SpriteBundle` and
`AtlasImageBundle` is equivalent to `TextureAtlas` + `ImageBundle`. As
such, the atlas bundles aren't particularly useful / necessary additions
to the API anymore.

In addition, atlas bundles are inconsistent with `ImageScaleMode` (also
introduced in 0.13) which doesn't have its own version of each image
bundle.

## Solution

Deprecate `SpriteSheetBundle` and `AtlasImageBundle` in favor of
including `TextureAtlas` as a separate component alongside
`SpriteBundle` and `ImageBundle`, respectively.

---

## Changelog

- Deprecated `SpriteSheetBundle` and `AtlasImageBundle`.

## Migration Guide

- `SpriteSheetBundle` has been deprecated. Use `TextureAtlas` alongside
a `SpriteBundle` instead.
- `AtlasImageBundle` has been deprecated. Use `TextureAtlas` alongside
an `ImageBundle` instead.
2024-03-03 20:11:15 +00:00
Kanabenki
de0ed293fa
Add basic light gizmos (#12228)
# Objective

- Part of #9400.
- Add light gizmos for `SpotLight`, `PointLight` and `DirectionalLight`.

## Solution

- Add a `ShowLightGizmo` and its related gizmo group and plugin, that
shows a gizmo for all lights of an entities when inserted on it. Light
display can also be toggled globally through the gizmo config in the
same way it can already be done for `Aabb`s.
- Add distinct segment setters for height and base one `Cone3dBuilder`.
This allow having a properly rounded base without too much edges along
the height. The doc comments explain how to ensure height and base
connect when setting different values.

Gizmo for the three light types without radius with the depth bias set
to -1:

![without-radius](https://github.com/bevyengine/bevy/assets/18357657/699d0154-f367-4727-9b09-8b458d96a0e2)

With Radius:

![with-radius](https://github.com/bevyengine/bevy/assets/18357657/f3af003e-dbba-427a-a305-c5cc1676e340)

Possible future improvements:
- Add a billboarded sprite with a distinct sprite for each light type.
- Display the intensity of the light somehow (no idea how to represent
that apart from some text).

---

## Changelog

### Added

- The new `ShowLightGizmo`, part of the `LightGizmoPlugin` and
configurable globally with `LightGizmoConfigGroup`, allows drawing gizmo
for `PointLight`, `SpotLight` and `DirectionalLight`. The gizmos color
behavior can be controlled with the `LightGizmoColor` member of
`ShowLightGizmo` and `LightGizmoConfigGroup`.
- The cone gizmo builder (`Cone3dBuilder`) now allows setting a
differing number of segments for the base and height.

---------

Co-authored-by: Gino Valente <49806985+MrGVSV@users.noreply.github.com>
2024-03-03 18:50:46 +00:00
Thierry Berger
8cf5fbbf94
Fix fit_canvas_to_parent (#11278)
Follow up to #11057

Implemented suggestions from reviewers from: a simpler
fit_canvas_to_parent leads to an explicit CSS setting to the canvas.

From my understanding, it has do be set after wgpu creation due to wgpu
overriding the canvas width/height:
4400a58470/examples/src/utils.rs (L68-L74)


# Changelog

- Re-enable a `fit_canvas_to_parent`, it's removal from
https://github.com/bevyengine/bevy/pull/11057 was problematic. Still,
its inner working is more simple than before: bevy doesn't handle its
resizing, winit does.

## Migration Guide

- Cancels the migration from
https://github.com/bevyengine/bevy/pull/11057
2024-03-03 14:33:30 +00:00
geekvest
d5c32bdc23
remove repetitive code (#12270)
Signed-off-by: geekvest <cuimoman@sohu.com>
2024-03-03 07:58:22 +00:00
targrub
13cbb9cf10
Move commands module into bevy::ecs::world (#12234)
# Objective

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

## Migration Guide

`Command` and `CommandQueue` have migrated from `bevy_ecs::system` to
`bevy_ecs::world`, so `use bevy_ecs::world::{Command, CommandQueue};`
when necessary.
2024-03-02 23:13:45 +00:00
James O'Brien
bacd5e873b
Replace init_component_info with register_component_hooks (#12244)
# Objective

- Fix mismatch between the `Component` trait method and the `World`
method.

## Solution

- Replace init_component_info with register_component_hooks.
2024-03-02 05:27:48 +00:00
Kaur Kuut
165c360070
Update wgpu to v0.19.3 and unpin web-sys. (#12247)
# Objective

This PR unpins `web-sys` so that unrelated projects that have
`bevy_render` in their workspace can finally update their `web-sys`.
More details in and fixes #12246.

## Solution

* Update `wgpu` from 0.19.1 to 0.19.3.
* Remove the `web-sys` pin.
* Update docs and wasm helper to remove the now-stale
`--cfg=web_sys_unstable_apis` Rust flag.

---

## Changelog

Updated `wgpu` to v0.19.3 and removed `web-sys` pin.
2024-03-02 00:44:51 +00:00
Natalie Soltis
cc32610543
Add size and physical_size to window (#12238)
This is an implementation within `bevy_window::window` that fixes
#12229.

# Objective

Fixes #12229, allow users to retrieve the window's size and physical
size as Vectors without having to manually construct them using
`height()` and `width()` or `physical_height()` and `physical_width()`

## Solution

As suggested in #12229, created two public functions within `window`:
`size() -> Vec` and `physical_size() -> UVec` that return the needed
Vectors ready-to-go.

### Discussion

My first FOSS PRQ ever, so bear with me a bit. I'm new to this.

- I replaced instances of ```Vec2::new(window.width(),
window.height());``` or `UVec2::new(window.physical_width(),
window.physical_height());` within bevy examples be replaced with their
`size()`/`physical_size()` counterparts?
- Discussion within #12229 still holds: should these also be added to
WindowResolution?
2024-03-01 22:28:37 +00:00
Patrick Walton
f9cc91d5a1
Intern mesh vertex buffer layouts so that we don't have to compare them over and over. (#12216)
Although we cached hashes of `MeshVertexBufferLayout`, we were paying
the cost of `PartialEq` on `InnerMeshVertexBufferLayout` for every
entity, every frame. This patch changes that logic to place
`MeshVertexBufferLayout`s in `Arc`s so that they can be compared and
hashed by pointer. This results in a 28% speedup in the
`queue_material_meshes` phase of `many_cubes`, with frustum culling
disabled.

Additionally, this patch contains two minor changes:

1. This commit flattens the specialized mesh pipeline cache to one level
of hash tables instead of two. This saves a hash lookup.

2. The example `many_cubes` has been given a `--no-frustum-culling`
flag, to aid in benchmarking.

See the Tracy profile:

<img width="1064" alt="Screenshot 2024-02-29 144406"
src="https://github.com/bevyengine/bevy/assets/157897/18632f1d-1fdd-4ac7-90ed-2d10306b2a1e">

## Migration guide

* Duplicate `MeshVertexBufferLayout`s are now combined into a single
object, `MeshVertexBufferLayoutRef`, which contains an
atomically-reference-counted pointer to the layout. Code that was using
`MeshVertexBufferLayout` may need to be updated to use
`MeshVertexBufferLayoutRef` instead.
2024-03-01 20:56:21 +00:00
James O'Brien
94ff123d7f
Component Lifecycle Hooks and a Deferred World (#10756)
# Objective

- Provide a reliable and performant mechanism to allows users to keep
components synchronized with external sources: closing/opening sockets,
updating indexes, debugging etc.
- Implement a generic mechanism to provide mutable access to the world
without allowing structural changes; this will not only be used here but
is a foundational piece for observers, which are key for a performant
implementation of relations.

## Solution

- Implement a new type `DeferredWorld` (naming is not important,
`StaticWorld` is also suitable) that wraps a world pointer and prevents
user code from making any structural changes to the ECS; spawning
entities, creating components, initializing resources etc.
- Add component lifecycle hooks `on_add`, `on_insert` and `on_remove`
that can be assigned callbacks in user code.

---

## Changelog
- Add new `DeferredWorld` type.
- Add new world methods: `register_component::<T>` and
`register_component_with_descriptor`. These differ from `init_component`
in that they provide mutable access to the created `ComponentInfo` but
will panic if the component is already in any archetypes. These
restrictions serve two purposes:
1. Prevent users from defining hooks for components that may already
have associated hooks provided in another plugin. (a use case better
served by observers)
2. Ensure that when an `Archetype` is created it gets the appropriate
flags to early-out when triggering hooks.
- Add methods to `ComponentInfo`: `on_add`, `on_insert` and `on_remove`
to be used to register hooks of the form `fn(DeferredWorld, Entity,
ComponentId)`
- Modify `BundleInserter`, `BundleSpawner` and `EntityWorldMut` to
trigger component hooks when appropriate.
- Add bit flags to `Archetype` indicating whether or not any contained
components have each type of hook, this can be expanded for other flags
as needed.
- Add `component_hooks` example to illustrate usage. Try it out! It's
fun to mash keys.

## Safety
The changes to component insertion, removal and deletion involve a large
amount of unsafe code and it's fair for that to raise some concern. I
have attempted to document it as clearly as possible and have confirmed
that all the hooks examples are accepted by `cargo miri` as not causing
any undefined behavior. The largest issue is in ensuring there are no
outstanding references when passing a `DeferredWorld` to the hooks which
requires some use of raw pointers (as was already happening to some
degree in those places) and I have taken some time to ensure that is the
case but feel free to let me know if I've missed anything.

## Performance
These changes come with a small but measurable performance cost of
between 1-5% on `add_remove` benchmarks and between 1-3% on `insert`
benchmarks. One consideration to be made is the existence of the current
`RemovedComponents` which is on average more costly than the addition of
`on_remove` hooks due to the early-out, however hooks doesn't completely
remove the need for `RemovedComponents` as there is a chance you want to
respond to the removal of a component that already has an `on_remove`
hook defined in another plugin, so I have not removed it here. I do
intend to deprecate it with the introduction of observers in a follow up
PR.

## Discussion Questions
- Currently `DeferredWorld` implements `Deref` to `&World` which makes
sense conceptually, however it does cause some issues with rust-analyzer
providing autocomplete for `&mut World` references which is annoying.
There are alternative implementations that may address this but involve
more code churn so I have attempted them here. The other alternative is
to not implement `Deref` at all but that leads to a large amount of API
duplication.
- `DeferredWorld`, `StaticWorld`, something else?
- In adding support for hooks to `EntityWorldMut` I encountered some
unfortunate difficulties with my desired API. If commands are flushed
after each call i.e. `world.spawn() // flush commands .insert(A) //
flush commands` the entity may be despawned while `EntityWorldMut` still
exists which is invalid. An alternative was then to add
`self.world.flush_commands()` to the drop implementation for
`EntityWorldMut` but that runs into other problems for implementing
functions like `into_unsafe_entity_cell`. For now I have implemented a
`.flush()` which will flush the commands and consume `EntityWorldMut` or
users can manually run `world.flush_commands()` after using
`EntityWorldMut`.
- In order to allowing querying on a deferred world we need
implementations of `WorldQuery` to not break our guarantees of no
structural changes through their `UnsafeWorldCell`. All our
implementations do this, but there isn't currently any safety
documentation specifying what is or isn't allowed for an implementation,
just for the caller, (they also shouldn't be aliasing components they
didn't specify access for etc.) is that something we should start doing?
(see 10752)

Please check out the example `component_hooks` or the tests in
`bundle.rs` for usage examples. I will continue to expand this
description as I go.

See #10839 for a more ergonomic API built on top of this one that isn't
subject to the same restrictions and supports `SystemParam` dependency
injection.
2024-03-01 14:59:22 +00:00
Rob Parrett
bcdca068ad
Various improvements to the contributors example (#12217)
# Objective / Solution

- Use `Hsla` for the color constants (Fixes #12203)

And a few other improvements:

- Make contributor colors persistent between runs
- Move text to top left where the birbs can't reach and add padding
- Remove `Contributor:` text. It's obvious what is being shown from
context, and then we can remove `has_triggered`.
- Show the number of commits authored
- Some system names were postfixed with `_system` and some weren't.
Removed `_system` for consistency.
- Clean up collision code slightly with a bounding volume
- Someone accidentally typed "bird" instead of "birb" in one comment.
- Other misc. cleanup

## Before

<img width="1280" alt="image"
src="https://github.com/bevyengine/bevy/assets/200550/9c6229d6-313a-464d-8a97-0220aa16901f">

## After

<img width="1280" alt="image"
src="https://github.com/bevyengine/bevy/assets/200550/0c00e95b-2f50-4f50-b177-def4ca405313">
2024-03-01 14:53:48 +00:00
Alice Cecile
599e5e4e76
Migrate from LegacyColor to bevy_color::Color (#12163)
# Objective

- As part of the migration process we need to a) see the end effect of
the migration on user ergonomics b) check for serious perf regressions
c) actually migrate the code
- To accomplish this, I'm going to attempt to migrate all of the
remaining user-facing usages of `LegacyColor` in one PR, being careful
to keep a clean commit history.
- Fixes #12056.

## Solution

I've chosen to use the polymorphic `Color` type as our standard
user-facing API.

- [x] Migrate `bevy_gizmos`.
- [x] Take `impl Into<Color>` in all `bevy_gizmos` APIs
- [x] Migrate sprites
- [x] Migrate UI
- [x] Migrate `ColorMaterial`
- [x] Migrate `MaterialMesh2D`
- [x] Migrate fog
- [x] Migrate lights
- [x] Migrate StandardMaterial
- [x] Migrate wireframes
- [x] Migrate clear color
- [x] Migrate text
- [x] Migrate gltf loader
- [x] Register color types for reflection
- [x] Remove `LegacyColor`
- [x] Make sure CI passes

Incidental improvements to ease migration:

- added `Color::srgba_u8`, `Color::srgba_from_array` and friends
- added `set_alpha`, `is_fully_transparent` and `is_fully_opaque` to the
`Alpha` trait
- add and immediately deprecate (lol) `Color::rgb` and friends in favor
of more explicit and consistent `Color::srgb`
- standardized on white and black for most example text colors
- added vector field traits to `LinearRgba`: ~~`Add`, `Sub`,
`AddAssign`, `SubAssign`,~~ `Mul<f32>` and `Div<f32>`. Multiplications
and divisions do not scale alpha. `Add` and `Sub` have been cut from
this PR.
- added `LinearRgba` and `Srgba` `RED/GREEN/BLUE`
- added `LinearRgba_to_f32_array` and `LinearRgba::to_u32`

## Migration Guide

Bevy's color types have changed! Wherever you used a
`bevy::render::Color`, a `bevy::color::Color` is used instead.

These are quite similar! Both are enums storing a color in a specific
color space (or to be more precise, using a specific color model).
However, each of the different color models now has its own type.

TODO...

- `Color::rgba`, `Color::rgb`, `Color::rbga_u8`, `Color::rgb_u8`,
`Color::rgb_from_array` are now `Color::srgba`, `Color::srgb`,
`Color::srgba_u8`, `Color::srgb_u8` and `Color::srgb_from_array`.
- `Color::set_a` and `Color::a` is now `Color::set_alpha` and
`Color::alpha`. These are part of the `Alpha` trait in `bevy_color`.
- `Color::is_fully_transparent` is now part of the `Alpha` trait in
`bevy_color`
- `Color::r`, `Color::set_r`, `Color::with_r` and the equivalents for
`g`, `b` `h`, `s` and `l` have been removed due to causing silent
relatively expensive conversions. Convert your `Color` into the desired
color space, perform your operations there, and then convert it back
into a polymorphic `Color` enum.
- `Color::hex` is now `Srgba::hex`. Call `.into` or construct a
`Color::Srgba` variant manually to convert it.
- `WireframeMaterial`, `ExtractedUiNode`, `ExtractedDirectionalLight`,
`ExtractedPointLight`, `ExtractedSpotLight` and `ExtractedSprite` now
store a `LinearRgba`, rather than a polymorphic `Color`
- `Color::rgb_linear` and `Color::rgba_linear` are now
`Color::linear_rgb` and `Color::linear_rgba`
- The various CSS color constants are no longer stored directly on
`Color`. Instead, they're defined in the `Srgba` color space, and
accessed via `bevy::color::palettes::css`. Call `.into()` on them to
convert them into a `Color` for quick debugging use, and consider using
the much prettier `tailwind` palette for prototyping.
- The `LIME_GREEN` color has been renamed to `LIMEGREEN` to comply with
the standard naming.
- Vector field arithmetic operations on `Color` (add, subtract, multiply
and divide by a f32) have been removed. Instead, convert your colors
into `LinearRgba` space, and perform your operations explicitly there.
This is particularly relevant when working with emissive or HDR colors,
whose color channel values are routinely outside of the ordinary 0 to 1
range.
- `Color::as_linear_rgba_f32` has been removed. Call
`LinearRgba::to_f32_array` instead, converting if needed.
- `Color::as_linear_rgba_u32` has been removed. Call
`LinearRgba::to_u32` instead, converting if needed.
- Several other color conversion methods to transform LCH or HSL colors
into float arrays or `Vec` types have been removed. Please reimplement
these externally or open a PR to re-add them if you found them
particularly useful.
- Various methods on `Color` such as `rgb` or `hsl` to convert the color
into a specific color space have been removed. Convert into
`LinearRgba`, then to the color space of your choice.
- Various implicitly-converting color value methods on `Color` such as
`r`, `g`, `b` or `h` have been removed. Please convert it into the color
space of your choice, then check these properties.
- `Color` no longer implements `AsBindGroup`. Store a `LinearRgba`
internally instead to avoid conversion costs.

---------

Co-authored-by: Alice Cecile <alice.i.cecil@gmail.com>
Co-authored-by: Afonso Lage <lage.afonso@gmail.com>
Co-authored-by: Rob Parrett <robparrett@gmail.com>
Co-authored-by: Zachary Harrold <zac@harrold.com.au>
2024-02-29 19:35:12 +00:00
Joona Aalto
f418de8eb6
Rename Direction2d/3d to Dir2/3 (#12189)
# Objective

Split up from #12017, rename Bevy's direction types.

Currently, Bevy has the `Direction2d`, `Direction3d`, and `Direction3dA`
types, which provide a type-level guarantee that their contained vectors
remain normalized. They can be very useful for a lot of APIs for safety,
explicitness, and in some cases performance, as they can sometimes avoid
unnecessary normalizations.

However, many consider them to be inconvenient to use, and opt for
standard vector types like `Vec3` because of this. One reason is that
the direction type names are a bit long and can be annoying to write (of
course you can use autocomplete, but just typing `Vec3` is still nicer),
and in some intances, the extra characters can make formatting worse.
The naming is also inconsistent with Glam's shorter type names, and
results in names like `Direction3dA`, which (in my opinion) are
difficult to read and even a bit ugly.

This PR proposes renaming the types to `Dir2`, `Dir3`, and `Dir3A`.
These names are nice and easy to write, consistent with Glam, and work
well for variants like the SIMD aligned `Dir3A`. As a bonus, it can also
result in nicer formatting in a lot of cases, which can be seen from the
diff of this PR.

Some examples of what it looks like: (copied from #12017)

```rust
// Before
let ray_cast = RayCast2d::new(Vec2::ZERO, Direction2d::X, 5.0);

// After
let ray_cast = RayCast2d::new(Vec2::ZERO, Dir2::X, 5.0);
```

```rust
// Before (an example using Bevy XPBD)
let hit = spatial_query.cast_ray(
    Vec3::ZERO,
    Direction3d::X,
    f32::MAX,
    true,
    SpatialQueryFilter::default(),
);

// After
let hit = spatial_query.cast_ray(
    Vec3::ZERO,
    Dir3::X,
    f32::MAX,
    true,
    SpatialQueryFilter::default(),
);
```

```rust
// Before
self.circle(
    Vec3::new(0.0, -2.0, 0.0),
    Direction3d::Y,
    5.0,
    Color::TURQUOISE,
);

// After (formatting is collapsed in this case)
self.circle(Vec3::new(0.0, -2.0, 0.0), Dir3::Y, 5.0, Color::TURQUOISE);
```

## Solution

Rename `Direction2d`, `Direction3d`, and `Direction3dA` to `Dir2`,
`Dir3`, and `Dir3A`.

---

## Migration Guide

The `Direction2d` and `Direction3d` types have been renamed to `Dir2`
and `Dir3`.

## Additional Context

This has been brought up on the Discord a few times, and we had a small
[poll](https://discord.com/channels/691052431525675048/1203087353850364004/1212465038711984158)
on this. `Dir2`/`Dir3`/`Dir3A` was quite unanimously chosen as the best
option, but of course it was a very small poll and inconclusive, so
other opinions are certainly welcome too.

---------

Co-authored-by: IceSentry <c.giguere42@gmail.com>
2024-02-28 22:48:43 +00:00
Rob Parrett
315e637bf5
Add tinting to the border in ui_texture_slice example (#11901)
# Objective

This is just a cool property of the full-white border texture we added
for this example that I think would be nice to show off.

## Solution

Add a tint to the border on hover / click.


![screenshot-100](https://github.com/bevyengine/bevy/assets/200550/a436c383-2cda-4578-999d-b89d244c993d)
2024-02-28 17:21:09 +00:00
Lynn
35cec8bd3a
Add Grid gizmos (#11988)
# Objective

- Implement grid gizmos, suggestion of #9400 

## Solution

- Added `gizmos.grid(...) ` and `gizmos.grid_2d(...)`
- The grids may be configured using `.outer_edges(...)` to specify
whether to draw the outer border/edges of the grid and `.skew(...)`to
specify the skew of the grid along the x or y directions.

---

## Changelog

- Added a `grid` module to `bevy_gizmos` containing `gizmos.grid(...) `
and `gizmos.grid_2d(...)` as well as assorted items.
- Updated the `2d_gizmos` and `3d_gizmos` examples to use grids.

## Additional

The 2D and 3D examples now look like this:
<img width="1440" alt="Screenshot 2024-02-20 at 15 09 40"
src="https://github.com/bevyengine/bevy/assets/62256001/ce04191e-d839-4faf-a6e3-49b6bb4b922b">
<img width="1440" alt="Screenshot 2024-02-20 at 15 10 07"
src="https://github.com/bevyengine/bevy/assets/62256001/317459ba-d452-42eb-ae95-7c84cdbd569b">
2024-02-28 00:18:26 +00:00