Skip to content

Commit 887bc27

Browse files
lynn-lumenalice-i-cecilebushrat011899
authored
Animatable for colors (#12614)
# Objective - Fixes #12202 ## Solution - Implements `Animatable` for all color types implementing arithmetic operations. - the colors returned by `Animatable`s methods are already clamped. - Adds a `color_animation.rs` example. - Implements the `*Assign` operators for color types that already had the corresponding operators. This is just a 'nice to have' and I am happy to remove this if it's not wanted. --- ## Changelog - `bevy_animation` now depends on `bevy_color`. - `LinearRgba`, `Laba`, `Oklaba` and `Xyza` implement `Animatable`. --------- Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com> Co-authored-by: Zachary Harrold <zac@harrold.com.au>
1 parent fcf01a7 commit 887bc27

File tree

6 files changed

+204
-0
lines changed

6 files changed

+204
-0
lines changed

Cargo.toml

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1013,6 +1013,17 @@ description = "Create and play an animation defined by code that operates on the
10131013
category = "Animation"
10141014
wasm = true
10151015

1016+
[[example]]
1017+
name = "color_animation"
1018+
path = "examples/animation/color_animation.rs"
1019+
doc-scrape-examples = true
1020+
1021+
[package.metadata.example.color_animation]
1022+
name = "Color animation"
1023+
description = "Demonstrates how to animate colors using mixing and splines in different color spaces"
1024+
category = "Animation"
1025+
wasm = true
1026+
10161027
[[example]]
10171028
name = "cubic_curve"
10181029
path = "examples/animation/cubic_curve.rs"

crates/bevy_animation/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ keywords = ["bevy"]
1212
# bevy
1313
bevy_app = { path = "../bevy_app", version = "0.14.0-dev" }
1414
bevy_asset = { path = "../bevy_asset", version = "0.14.0-dev" }
15+
bevy_color = { path = "../bevy_color", version = "0.14.0-dev" }
1516
bevy_core = { path = "../bevy_core", version = "0.14.0-dev" }
1617
bevy_derive = { path = "../bevy_derive", version = "0.14.0-dev" }
1718
bevy_log = { path = "../bevy_log", version = "0.14.0-dev" }

crates/bevy_animation/src/animatable.rs

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
use crate::util;
2+
use bevy_color::{ClampColor, Laba, LinearRgba, Oklaba, Xyza};
23
use bevy_ecs::world::World;
34
use bevy_math::*;
45
use bevy_reflect::Reflect;
@@ -57,6 +58,31 @@ macro_rules! impl_float_animatable {
5758
};
5859
}
5960

61+
macro_rules! impl_color_animatable {
62+
($ty: ident) => {
63+
impl Animatable for $ty {
64+
#[inline]
65+
fn interpolate(a: &Self, b: &Self, t: f32) -> Self {
66+
let value = *a * (1. - t) + *b * t;
67+
value.clamped()
68+
}
69+
70+
#[inline]
71+
fn blend(inputs: impl Iterator<Item = BlendInput<Self>>) -> Self {
72+
let mut value = Default::default();
73+
for input in inputs {
74+
if input.additive {
75+
value += input.weight * input.value;
76+
} else {
77+
value = Self::interpolate(&value, &input.value, input.weight);
78+
}
79+
}
80+
value.clamped()
81+
}
82+
}
83+
};
84+
}
85+
6086
impl_float_animatable!(f32, f32);
6187
impl_float_animatable!(Vec2, f32);
6288
impl_float_animatable!(Vec3A, f32);
@@ -67,6 +93,11 @@ impl_float_animatable!(DVec2, f64);
6793
impl_float_animatable!(DVec3, f64);
6894
impl_float_animatable!(DVec4, f64);
6995

96+
impl_color_animatable!(LinearRgba);
97+
impl_color_animatable!(Laba);
98+
impl_color_animatable!(Oklaba);
99+
impl_color_animatable!(Xyza);
100+
70101
// Vec3 is special cased to use Vec3A internally for blending
71102
impl Animatable for Vec3 {
72103
#[inline]

crates/bevy_color/src/lib.rs

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -170,6 +170,12 @@ macro_rules! impl_componentwise_point {
170170
}
171171
}
172172

173+
impl std::ops::AddAssign<Self> for $ty {
174+
fn add_assign(&mut self, rhs: Self) {
175+
*self = *self + rhs;
176+
}
177+
}
178+
173179
impl std::ops::Sub<Self> for $ty {
174180
type Output = Self;
175181

@@ -180,6 +186,12 @@ macro_rules! impl_componentwise_point {
180186
}
181187
}
182188

189+
impl std::ops::SubAssign<Self> for $ty {
190+
fn sub_assign(&mut self, rhs: Self) {
191+
*self = *self - rhs;
192+
}
193+
}
194+
183195
impl std::ops::Mul<f32> for $ty {
184196
type Output = Self;
185197

@@ -200,6 +212,12 @@ macro_rules! impl_componentwise_point {
200212
}
201213
}
202214

215+
impl std::ops::MulAssign<f32> for $ty {
216+
fn mul_assign(&mut self, rhs: f32) {
217+
*self = *self * rhs;
218+
}
219+
}
220+
203221
impl std::ops::Div<f32> for $ty {
204222
type Output = Self;
205223

@@ -210,6 +228,12 @@ macro_rules! impl_componentwise_point {
210228
}
211229
}
212230

231+
impl std::ops::DivAssign<f32> for $ty {
232+
fn div_assign(&mut self, rhs: f32) {
233+
*self = *self / rhs;
234+
}
235+
}
236+
213237
impl bevy_math::cubic_splines::Point for $ty {}
214238
};
215239
}

examples/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -165,6 +165,7 @@ Example | Description
165165
[Animated Fox](../examples/animation/animated_fox.rs) | Plays an animation from a skinned glTF
166166
[Animated Transform](../examples/animation/animated_transform.rs) | Create and play an animation defined by code that operates on the `Transform` component
167167
[Animation Graph](../examples/animation/animation_graph.rs) | Blends multiple animations together with a graph
168+
[Color animation](../examples/animation/color_animation.rs) | Demonstrates how to animate colors using mixing and splines in different color spaces
168169
[Cubic Curve](../examples/animation/cubic_curve.rs) | Bezier curve example showing a cube following a cubic curve
169170
[Custom Skinned Mesh](../examples/animation/custom_skinned_mesh.rs) | Skinned mesh example with mesh and joints data defined in code
170171
[Morph Targets](../examples/animation/morph_targets.rs) | Plays an animation from a glTF file with meshes with morph targets
Lines changed: 136 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,136 @@
1+
//! Demonstrates how to animate colors in different color spaces using mixing and splines.
2+
3+
use bevy::{math::cubic_splines::Point, prelude::*};
4+
5+
// We define this trait so we can reuse the same code for multiple color types that may be implemented using curves.
6+
trait CurveColor: Point + Into<Color> + Send + Sync + 'static {}
7+
impl<T: Point + Into<Color> + Send + Sync + 'static> CurveColor for T {}
8+
9+
// We define this trait so we can reuse the same code for multiple color types that may be implemented using mixing.
10+
trait MixedColor: Mix + Into<Color> + Send + Sync + 'static {}
11+
impl<T: Mix + Into<Color> + Send + Sync + 'static> MixedColor for T {}
12+
13+
#[derive(Debug, Component)]
14+
struct Curve<T: CurveColor>(CubicCurve<T>);
15+
16+
#[derive(Debug, Component)]
17+
struct Mixed<T: MixedColor>([T; 4]);
18+
19+
fn main() {
20+
App::new()
21+
.add_plugins(DefaultPlugins)
22+
.add_systems(Startup, setup)
23+
.add_systems(
24+
Update,
25+
(
26+
animate_curve::<LinearRgba>,
27+
animate_curve::<Oklaba>,
28+
animate_curve::<Xyza>,
29+
animate_mixed::<Hsla>,
30+
animate_mixed::<Srgba>,
31+
animate_mixed::<Oklcha>,
32+
),
33+
)
34+
.run();
35+
}
36+
37+
fn setup(mut commands: Commands) {
38+
commands.spawn(Camera2dBundle::default());
39+
40+
// The color spaces `Oklaba`, `Laba`, `LinearRgba` and `Xyza` all are either perceptually or physically linear.
41+
// This property allows us to define curves, e.g. bezier curves through these spaces.
42+
43+
// Define the control points for the curve.
44+
// For more information, please see the cubic curve example.
45+
let colors = [
46+
LinearRgba::WHITE,
47+
LinearRgba::rgb(1., 1., 0.), // Yellow
48+
LinearRgba::RED,
49+
LinearRgba::BLACK,
50+
];
51+
// Spawn a sprite using the provided colors as control points.
52+
spawn_curve_sprite(&mut commands, 275., colors);
53+
54+
// Spawn another sprite using the provided colors as control points after converting them to the `Xyza` color space.
55+
spawn_curve_sprite(&mut commands, 175., colors.map(Xyza::from));
56+
57+
spawn_curve_sprite(&mut commands, 75., colors.map(Oklaba::from));
58+
59+
// Other color spaces like `Srgba` or `Hsva` are neither perceptually nor physically linear.
60+
// As such, we cannot use curves in these spaces.
61+
// However, we can still mix these colours and animate that way. In fact, mixing colors works in any color space.
62+
63+
// Spawn a spritre using the provided colors for mixing.
64+
spawn_mixed_sprite(&mut commands, -75., colors.map(Hsla::from));
65+
66+
spawn_mixed_sprite(&mut commands, -175., colors.map(Srgba::from));
67+
68+
spawn_mixed_sprite(&mut commands, -275., colors.map(Oklcha::from));
69+
}
70+
71+
fn spawn_curve_sprite<T: CurveColor>(commands: &mut Commands, y: f32, points: [T; 4]) {
72+
commands.spawn((
73+
SpriteBundle {
74+
transform: Transform::from_xyz(0., y, 0.),
75+
sprite: Sprite {
76+
custom_size: Some(Vec2::new(75., 75.)),
77+
..Default::default()
78+
},
79+
..Default::default()
80+
},
81+
Curve(CubicBezier::new([points]).to_curve()),
82+
));
83+
}
84+
85+
fn spawn_mixed_sprite<T: MixedColor>(commands: &mut Commands, y: f32, colors: [T; 4]) {
86+
commands.spawn((
87+
SpriteBundle {
88+
transform: Transform::from_xyz(0., y, 0.),
89+
sprite: Sprite {
90+
custom_size: Some(Vec2::new(75., 75.)),
91+
..Default::default()
92+
},
93+
..Default::default()
94+
},
95+
Mixed(colors),
96+
));
97+
}
98+
99+
fn animate_curve<T: CurveColor>(
100+
time: Res<Time>,
101+
mut query: Query<(&mut Transform, &mut Sprite, &Curve<T>)>,
102+
) {
103+
let t = (time.elapsed_seconds().sin() + 1.) / 2.;
104+
105+
for (mut transform, mut sprite, cubic_curve) in &mut query {
106+
// position takes a point from the curve where 0 is the initial point
107+
// and 1 is the last point
108+
sprite.color = cubic_curve.0.position(t).into();
109+
transform.translation.x = 600. * (t - 0.5);
110+
}
111+
}
112+
113+
fn animate_mixed<T: MixedColor>(
114+
time: Res<Time>,
115+
mut query: Query<(&mut Transform, &mut Sprite, &Mixed<T>)>,
116+
) {
117+
let t = (time.elapsed_seconds().sin() + 1.) / 2.;
118+
119+
for (mut transform, mut sprite, mixed) in &mut query {
120+
sprite.color = {
121+
// First, we determine the amount of intervals between colors.
122+
// For four colors, there are three intervals between those colors;
123+
let intervals = (mixed.0.len() - 1) as f32;
124+
125+
// Next we determine the index of the first of the two colorts to mix.
126+
let start_i = (t * intervals).floor().min(intervals - 1.);
127+
128+
// Lastly we determine the 'local' value of t in this interval.
129+
let local_t = (t * intervals) - start_i;
130+
131+
let color = mixed.0[start_i as usize].mix(&mixed.0[start_i as usize + 1], local_t);
132+
color.into()
133+
};
134+
transform.translation.x = 600. * (t - 0.5);
135+
}
136+
}

0 commit comments

Comments
 (0)