1pub use sui_animation::*;
2
3use sui_core::{InvalidationKind, InvalidationRequest, InvalidationTarget};
4use sui_runtime::EventCtx;
5
6#[derive(Debug, Clone, PartialEq)]
7pub struct AnimationBindingInvalidation {
8 pub binding: AnimationBinding,
9 pub kind: InvalidationKind,
10}
11
12#[derive(Debug, Clone, Copy, PartialEq)]
13pub struct TimelineTick<'a> {
14 pub samples: &'a [SampledAnimationValue],
15 pub invalidations: &'a [AnimationBindingInvalidation],
16 pub should_continue: bool,
17}
18
19impl TimelineTick<'_> {
20 pub fn request_current_widget_invalidations(&self, ctx: &mut EventCtx) {
21 for invalidation in self.invalidations {
22 request_invalidation_kind(ctx, invalidation.kind);
23 }
24 if self.should_continue {
25 ctx.request_animation_frame();
26 }
27 }
28}
29
30pub trait TimelineBindingSink {
31 fn apply_animation_value(&mut self, binding: &AnimationBinding, value: AnimationValue) -> bool;
32}
33
34#[derive(Debug, Clone, Copy, PartialEq)]
35pub struct MotionScalar {
36 pub value: f32,
37 pub target: f32,
38 transition: Option<Transition<f32>>,
39}
40
41impl MotionScalar {
42 pub const EPSILON: f32 = 1e-4;
43
44 pub const fn new(value: f32) -> Self {
45 Self {
46 value,
47 target: value,
48 transition: None,
49 }
50 }
51
52 pub fn current(&self, time: f64) -> f32 {
53 self.transition
54 .map(|transition| transition.sample(time))
55 .unwrap_or(self.value)
56 }
57
58 pub fn set_target(&mut self, target: f32, time: f64, duration: f64, easing: Easing) -> bool {
59 let target = target.clamp(0.0, 1.0);
60 let current = self.current(time);
61 if (current - target).abs() < Self::EPSILON {
62 self.value = target;
63 self.target = target;
64 self.transition = None;
65 return false;
66 }
67
68 self.value = current;
69 self.target = target;
70 self.transition = Some(Transition::new(current, target, time, duration, easing));
71 true
72 }
73
74 pub fn set_target_event(
75 &mut self,
76 target: f32,
77 duration: f64,
78 easing: Easing,
79 ctx: &mut EventCtx,
80 ) -> bool {
81 let should_animate = self.set_target(target, ctx.current_time(), duration, easing);
82 if should_animate {
83 ctx.request_animation_frame();
84 }
85 should_animate
86 }
87
88 pub fn advance(&mut self, time: f64) -> bool {
89 let Some(transition) = self.transition else {
90 return false;
91 };
92
93 self.value = transition.sample(time);
94 if transition.is_complete(time) {
95 self.value = self.target;
96 self.transition = None;
97 return false;
98 }
99
100 true
101 }
102
103 pub fn changed_since(&self, previous: f32) -> bool {
104 (self.value - previous).abs() > Self::EPSILON
105 }
106
107 pub fn is_presented(&self) -> bool {
108 self.value > Self::EPSILON || self.target > Self::EPSILON || self.transition.is_some()
109 }
110}
111
112#[derive(Debug, Clone, PartialEq)]
113pub struct TimelinePlayer {
114 timeline: Timeline,
115 compiled: CompiledTimeline,
116 compiled_dirty: bool,
117 playback: PlaybackState,
118 samples: SampleBuffer,
119 invalidations: Vec<AnimationBindingInvalidation>,
120}
121
122impl TimelinePlayer {
123 pub fn new(timeline: Timeline) -> Self {
124 let compiled = timeline.compile();
125 let sample_capacity = compiled.sample_capacity();
126 Self {
127 timeline,
128 compiled,
129 compiled_dirty: false,
130 playback: PlaybackState::default(),
131 samples: SampleBuffer::with_capacity(sample_capacity),
132 invalidations: Vec::with_capacity(sample_capacity),
133 }
134 }
135
136 pub fn timeline(&self) -> &Timeline {
137 &self.timeline
138 }
139
140 pub fn timeline_mut(&mut self) -> &mut Timeline {
141 self.compiled_dirty = true;
142 &mut self.timeline
143 }
144
145 pub fn set_timeline(&mut self, timeline: Timeline) {
146 self.timeline = timeline;
147 self.recompile_timeline();
148 }
149
150 pub fn playback(&self) -> PlaybackState {
151 self.playback
152 }
153
154 pub fn playback_mut(&mut self) -> &mut PlaybackState {
155 &mut self.playback
156 }
157
158 pub fn play(&mut self) {
159 self.playback.play();
160 }
161
162 pub fn pause(&mut self) {
163 self.playback.pause();
164 }
165
166 pub fn stop(&mut self) {
167 self.playback.stop();
168 }
169
170 pub fn seek(&mut self, time: f64) {
171 self.playback.seek(time, self.timeline.duration);
172 }
173
174 pub fn sample(&self) -> Vec<SampledAnimationValue> {
175 self.timeline.sample(self.playback.playhead)
176 }
177
178 pub fn sample_reusing_scratch(&mut self) -> &[SampledAnimationValue] {
179 self.ensure_compiled_timeline();
180 self.compiled
181 .sample_into(self.playback.playhead, &mut self.samples);
182 self.samples.samples()
183 }
184
185 pub fn tick<S>(&mut self, delta_seconds: f64, sink: &mut S) -> TimelineTick<'_>
186 where
187 S: TimelineBindingSink,
188 {
189 self.ensure_compiled_timeline();
190 self.playback.tick(delta_seconds, self.compiled.duration());
191 self.compiled
192 .sample_into(self.playback.playhead, &mut self.samples);
193 self.invalidations.clear();
194 self.invalidations
195 .reserve(self.samples.len().saturating_sub(self.invalidations.len()));
196
197 for sample in self.samples.samples() {
198 if sink.apply_animation_value(&sample.binding, sample.value) {
199 self.invalidations.push(AnimationBindingInvalidation {
200 binding: sample.binding.clone(),
201 kind: invalidation_for_animation_property(&sample.binding.property),
202 });
203 }
204 }
205
206 TimelineTick {
207 samples: self.samples.samples(),
208 invalidations: &self.invalidations,
209 should_continue: self.playback.playing,
210 }
211 }
212
213 pub fn tick_event<S>(
214 &mut self,
215 delta_seconds: f64,
216 sink: &mut S,
217 ctx: &mut EventCtx,
218 ) -> TimelineTick<'_>
219 where
220 S: TimelineBindingSink,
221 {
222 let tick = self.tick(delta_seconds, sink);
223 tick.request_current_widget_invalidations(ctx);
224 tick
225 }
226
227 fn ensure_compiled_timeline(&mut self) {
228 if self.compiled_dirty {
229 self.recompile_timeline();
230 }
231 }
232
233 fn recompile_timeline(&mut self) {
234 self.compiled = self.timeline.compile();
235 self.compiled_dirty = false;
236 let sample_capacity = self.compiled.sample_capacity();
237 self.samples.reserve_capacity(sample_capacity);
238 self.invalidations
239 .reserve(sample_capacity.saturating_sub(self.invalidations.len()));
240 }
241}
242
243pub fn invalidation_for_animation_property(property: &AnimationProperty) -> InvalidationKind {
244 match property {
245 AnimationProperty::LayerOpacity => InvalidationKind::Effect,
246 AnimationProperty::LayerTranslation => InvalidationKind::Transform,
247 AnimationProperty::Bounds => InvalidationKind::Measure,
248 AnimationProperty::FillColor | AnimationProperty::Custom(_) => InvalidationKind::Paint,
249 }
250}
251
252fn request_invalidation_kind(ctx: &mut EventCtx, kind: InvalidationKind) {
253 match kind {
254 InvalidationKind::Measure => ctx.request_measure(),
255 InvalidationKind::Arrange => ctx.request_arrange(),
256 InvalidationKind::Ordering => ctx.request_ordering(),
257 InvalidationKind::Transform => ctx.request_transform(),
258 InvalidationKind::Clip => ctx.request(InvalidationRequest::new(
259 InvalidationTarget::Widget(ctx.widget_id()),
260 InvalidationKind::Clip,
261 )),
262 InvalidationKind::Effect => ctx.request_effect(),
263 InvalidationKind::Visibility => ctx.request_visibility(),
264 InvalidationKind::Paint => ctx.request_paint(),
265 InvalidationKind::HitTest => ctx.request_hit_test(),
266 InvalidationKind::Text => ctx.request_text(),
267 InvalidationKind::Semantics => ctx.request_semantics(),
268 InvalidationKind::Resources => ctx.request_resources(),
269 }
270}
271
272#[cfg(test)]
273mod tests {
274 use super::{
275 AnimationBinding, AnimationProperty, AnimationTargetId, AnimationValue, Clip, Easing,
276 Keyframe, Timeline, TimelineBindingSink, TimelinePlayer, Track,
277 invalidation_for_animation_property,
278 };
279 use sui_core::{Color, InvalidationKind, Vector};
280
281 #[derive(Default)]
282 struct DemoSink {
283 opacity: f32,
284 translation: Vector,
285 fill: Color,
286 }
287
288 impl TimelineBindingSink for DemoSink {
289 fn apply_animation_value(
290 &mut self,
291 binding: &AnimationBinding,
292 value: AnimationValue,
293 ) -> bool {
294 match (&binding.property, value) {
295 (AnimationProperty::LayerOpacity, AnimationValue::Scalar(value)) => {
296 let changed = (self.opacity - value).abs() > f32::EPSILON;
297 self.opacity = value;
298 changed
299 }
300 (AnimationProperty::LayerTranslation, AnimationValue::Vector(value)) => {
301 let changed = self.translation != value;
302 self.translation = value;
303 changed
304 }
305 (AnimationProperty::FillColor, AnimationValue::Color(value)) => {
306 let changed = self.fill != value;
307 self.fill = value;
308 changed
309 }
310 _ => false,
311 }
312 }
313 }
314
315 fn binding(property: AnimationProperty) -> AnimationBinding {
316 AnimationBinding::new(AnimationTargetId::new("preview"), property)
317 }
318
319 #[test]
320 fn animation_property_maps_to_retained_invalidation_kinds() {
321 assert_eq!(
322 invalidation_for_animation_property(&AnimationProperty::LayerOpacity),
323 InvalidationKind::Effect
324 );
325 assert_eq!(
326 invalidation_for_animation_property(&AnimationProperty::LayerTranslation),
327 InvalidationKind::Transform
328 );
329 assert_eq!(
330 invalidation_for_animation_property(&AnimationProperty::FillColor),
331 InvalidationKind::Paint
332 );
333 }
334
335 #[test]
336 fn timeline_player_applies_samples_and_reports_invalidations() {
337 let timeline = Timeline::new(1.0).with_clip(
338 Clip::new("intro", 0.0, 1.0)
339 .with_track(
340 Track::new(binding(AnimationProperty::LayerOpacity)).with_keyframes([
341 Keyframe::new(0.0, AnimationValue::Scalar(0.0)).with_easing(Easing::Linear),
342 Keyframe::new(1.0, AnimationValue::Scalar(1.0)),
343 ]),
344 )
345 .with_track(
346 Track::new(binding(AnimationProperty::LayerTranslation)).with_keyframes([
347 Keyframe::new(0.0, AnimationValue::Vector(Vector::ZERO))
348 .with_easing(Easing::Linear),
349 Keyframe::new(1.0, AnimationValue::Vector(Vector::new(10.0, 0.0))),
350 ]),
351 ),
352 );
353 let mut player = TimelinePlayer::new(timeline);
354 let mut sink = DemoSink::default();
355 player.play();
356
357 let tick = player.tick(0.5, &mut sink);
358
359 assert!(tick.should_continue);
360 assert_eq!(tick.samples.len(), 2);
361 assert_eq!(tick.invalidations.len(), 2);
362 assert!((sink.opacity - 0.5).abs() < 1e-6);
363 assert_eq!(sink.translation, Vector::new(5.0, 0.0));
364 }
365}