bevy/examples/stress_tests/many_foxes.rs
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

316 lines
9.1 KiB
Rust

//! Loads animations from a skinned glTF, spawns many of them, and plays the
//! animation to stress test skinned meshes.
use std::f32::consts::PI;
use std::time::Duration;
use argh::FromArgs;
use bevy::{
diagnostic::{FrameTimeDiagnosticsPlugin, LogDiagnosticsPlugin},
pbr::CascadeShadowConfigBuilder,
prelude::*,
window::{PresentMode, WindowPlugin, WindowResolution},
winit::{UpdateMode, WinitSettings},
};
#[derive(FromArgs, Resource)]
/// `many_foxes` stress test
struct Args {
/// whether all foxes run in sync.
#[argh(switch)]
sync: bool,
/// total number of foxes.
#[argh(option, default = "1000")]
count: usize,
}
#[derive(Resource)]
struct Foxes {
count: usize,
speed: f32,
moving: bool,
sync: bool,
}
fn main() {
// `from_env` panics on the web
#[cfg(not(target_arch = "wasm32"))]
let args: Args = argh::from_env();
#[cfg(target_arch = "wasm32")]
let args = Args::from_args(&[], &[]).unwrap();
App::new()
.add_plugins((
DefaultPlugins.set(WindowPlugin {
primary_window: Some(Window {
title: "🦊🦊🦊 Many Foxes! 🦊🦊🦊".into(),
present_mode: PresentMode::AutoNoVsync,
resolution: WindowResolution::new(1920.0, 1080.0)
.with_scale_factor_override(1.0),
..default()
}),
..default()
}),
FrameTimeDiagnosticsPlugin,
LogDiagnosticsPlugin::default(),
))
.insert_resource(WinitSettings {
focused_mode: UpdateMode::Continuous,
unfocused_mode: UpdateMode::Continuous,
})
.insert_resource(Foxes {
count: args.count,
speed: 2.0,
moving: true,
sync: args.sync,
})
.add_systems(Startup, setup)
.add_systems(
Update,
(
setup_scene_once_loaded,
keyboard_animation_control,
update_fox_rings.after(keyboard_animation_control),
),
)
.run();
}
#[derive(Resource)]
struct Animations(Vec<Handle<AnimationClip>>);
const RING_SPACING: f32 = 2.0;
const FOX_SPACING: f32 = 2.0;
#[derive(Component, Clone, Copy)]
enum RotationDirection {
CounterClockwise,
Clockwise,
}
impl RotationDirection {
fn sign(&self) -> f32 {
match self {
RotationDirection::CounterClockwise => 1.0,
RotationDirection::Clockwise => -1.0,
}
}
}
#[derive(Component)]
struct Ring {
radius: f32,
}
fn setup(
mut commands: Commands,
asset_server: Res<AssetServer>,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
foxes: Res<Foxes>,
) {
warn!(include_str!("warning_string.txt"));
// Insert a resource with the current scene information
commands.insert_resource(Animations(vec![
asset_server.load("models/animated/Fox.glb#Animation2"),
asset_server.load("models/animated/Fox.glb#Animation1"),
asset_server.load("models/animated/Fox.glb#Animation0"),
]));
// Foxes
// Concentric rings of foxes, running in opposite directions. The rings are spaced at 2m radius intervals.
// The foxes in each ring are spaced at least 2m apart around its circumference.'
// NOTE: This fox model faces +z
let fox_handle = asset_server.load("models/animated/Fox.glb#Scene0");
let ring_directions = [
(
Quat::from_rotation_y(PI),
RotationDirection::CounterClockwise,
),
(Quat::IDENTITY, RotationDirection::Clockwise),
];
let mut ring_index = 0;
let mut radius = RING_SPACING;
let mut foxes_remaining = foxes.count;
info!("Spawning {} foxes...", foxes.count);
while foxes_remaining > 0 {
let (base_rotation, ring_direction) = ring_directions[ring_index % 2];
let ring_parent = commands
.spawn((
SpatialBundle::INHERITED_IDENTITY,
ring_direction,
Ring { radius },
))
.id();
let circumference = PI * 2. * radius;
let foxes_in_ring = ((circumference / FOX_SPACING) as usize).min(foxes_remaining);
let fox_spacing_angle = circumference / (foxes_in_ring as f32 * radius);
for fox_i in 0..foxes_in_ring {
let fox_angle = fox_i as f32 * fox_spacing_angle;
let (s, c) = fox_angle.sin_cos();
let (x, z) = (radius * c, radius * s);
commands.entity(ring_parent).with_children(|builder| {
builder.spawn(SceneBundle {
scene: fox_handle.clone(),
transform: Transform::from_xyz(x, 0.0, z)
.with_scale(Vec3::splat(0.01))
.with_rotation(base_rotation * Quat::from_rotation_y(-fox_angle)),
..default()
});
});
}
foxes_remaining -= foxes_in_ring;
radius += RING_SPACING;
ring_index += 1;
}
// Camera
let zoom = 0.8;
let translation = Vec3::new(
radius * 1.25 * zoom,
radius * 0.5 * zoom,
radius * 1.5 * zoom,
);
commands.spawn(Camera3dBundle {
transform: Transform::from_translation(translation)
.looking_at(0.2 * Vec3::new(translation.x, 0.0, translation.z), Vec3::Y),
..default()
});
// Plane
commands.spawn(PbrBundle {
mesh: meshes.add(Plane3d::default().mesh().size(5000.0, 5000.0)),
material: materials.add(Color::srgb(0.3, 0.5, 0.3)),
..default()
});
// Light
commands.spawn(DirectionalLightBundle {
transform: Transform::from_rotation(Quat::from_euler(EulerRot::ZYX, 0.0, 1.0, -PI / 4.)),
directional_light: DirectionalLight {
shadows_enabled: true,
..default()
},
cascade_shadow_config: CascadeShadowConfigBuilder {
first_cascade_far_bound: 0.9 * radius,
maximum_distance: 2.8 * radius,
..default()
}
.into(),
..default()
});
println!("Animation controls:");
println!(" - spacebar: play / pause");
println!(" - arrow up / down: speed up / slow down animation playback");
println!(" - arrow left / right: seek backward / forward");
println!(" - return: change animation");
}
// Once the scene is loaded, start the animation
fn setup_scene_once_loaded(
animations: Res<Animations>,
foxes: Res<Foxes>,
mut player: Query<(Entity, &mut AnimationPlayer)>,
mut done: Local<bool>,
) {
if !*done && player.iter().len() == foxes.count {
for (entity, mut player) in &mut player {
player.play(animations.0[0].clone_weak()).repeat();
if !foxes.sync {
player.seek_to(entity.index() as f32 / 10.0);
}
}
*done = true;
}
}
fn update_fox_rings(
time: Res<Time>,
foxes: Res<Foxes>,
mut rings: Query<(&Ring, &RotationDirection, &mut Transform)>,
) {
if !foxes.moving {
return;
}
let dt = time.delta_seconds();
for (ring, rotation_direction, mut transform) in &mut rings {
let angular_velocity = foxes.speed / ring.radius;
transform.rotate_y(rotation_direction.sign() * angular_velocity * dt);
}
}
fn keyboard_animation_control(
keyboard_input: Res<ButtonInput<KeyCode>>,
mut animation_player: Query<&mut AnimationPlayer>,
animations: Res<Animations>,
mut current_animation: Local<usize>,
mut foxes: ResMut<Foxes>,
) {
if keyboard_input.just_pressed(KeyCode::Space) {
foxes.moving = !foxes.moving;
}
if keyboard_input.just_pressed(KeyCode::ArrowUp) {
foxes.speed *= 1.25;
}
if keyboard_input.just_pressed(KeyCode::ArrowDown) {
foxes.speed *= 0.8;
}
if keyboard_input.just_pressed(KeyCode::Enter) {
*current_animation = (*current_animation + 1) % animations.0.len();
}
for mut player in &mut animation_player {
if keyboard_input.just_pressed(KeyCode::Space) {
if player.is_paused() {
player.resume();
} else {
player.pause();
}
}
if keyboard_input.just_pressed(KeyCode::ArrowUp) {
let speed = player.speed();
player.set_speed(speed * 1.25);
}
if keyboard_input.just_pressed(KeyCode::ArrowDown) {
let speed = player.speed();
player.set_speed(speed * 0.8);
}
if keyboard_input.just_pressed(KeyCode::ArrowLeft) {
let elapsed = player.seek_time();
player.seek_to(elapsed - 0.1);
}
if keyboard_input.just_pressed(KeyCode::ArrowRight) {
let elapsed = player.seek_time();
player.seek_to(elapsed + 0.1);
}
if keyboard_input.just_pressed(KeyCode::Enter) {
player
.play_with_transition(
animations.0[*current_animation].clone_weak(),
Duration::from_millis(250),
)
.repeat();
}
}
}