1use crate::{Image, ImageAsset, ImageFormat, LoadedAnimation, Node, Property};
2use std::{
3 collections::BTreeMap,
4 fmt,
5 rc::Rc,
6 time::{Duration, Instant},
7};
8
9#[derive(Debug, PartialEq, Eq)]
11pub struct ImageAnimationFrame {
12 pub end_ms: u32,
13 pub png: &'static [u8],
14}
15
16#[derive(Debug)]
18pub struct ImageAnimation {
19 size: [u32; 2],
20 frames: &'static [ImageAnimationFrame],
21 plays: u32,
22}
23
24impl ImageAnimation {
25 #[doc(hidden)]
26 pub const fn new(size: [u32; 2], frames: &'static [ImageAnimationFrame], plays: u32) -> Self {
27 Self {
28 size,
29 frames,
30 plays,
31 }
32 }
33
34 pub fn frame_count(&self) -> usize {
35 self.frames.len()
36 }
37
38 pub fn frame(&self, index: usize) -> Image {
39 self.frames
40 .get(index)
41 .or_else(|| self.frames.first())
42 .map_or(Image::Empty, |frame| Image::Embedded {
43 format: ImageFormat::Png,
44 bytes: frame.png,
45 size: self.size,
46 })
47 }
48
49 pub fn size(&self) -> [u32; 2] {
50 self.size
51 }
52
53 pub(crate) fn matches_loaded(&self, other: &LoadedAnimation) -> bool {
54 self.size == other.size
55 && self.plays == other.plays
56 && self
57 .frames
58 .iter()
59 .map(|frame| (frame.end_ms, frame.png))
60 .eq(other
61 .frames
62 .iter()
63 .map(|(end, frame)| (*end, frame.bytes())))
64 }
65}
66
67impl PartialEq for ImageAnimation {
68 fn eq(&self, other: &Self) -> bool {
69 std::ptr::eq(self, other)
70 || (self.size == other.size && self.plays == other.plays && self.frames == other.frames)
71 }
72}
73
74impl Eq for ImageAnimation {}
75
76enum Timeline<'a> {
77 Embedded(&'a ImageAnimation),
78 Loaded(&'a LoadedAnimation),
79}
80
81impl<'a> Timeline<'a> {
82 fn for_image(image: &'a ImageAsset) -> Option<Self> {
83 match image {
84 ImageAsset::Embedded(Image::Animated(animation)) => Some(Self::Embedded(animation)),
85 ImageAsset::Animated(animation) => Some(Self::Loaded(animation)),
86 _ => None,
87 }
88 }
89
90 fn plays(&self) -> u32 {
91 match self {
92 Self::Embedded(animation) => animation.plays,
93 Self::Loaded(animation) => animation.plays,
94 }
95 }
96
97 fn end(&self, frame: usize) -> f64 {
98 f64::from(match self {
99 Self::Embedded(animation) => animation.frames[frame].end_ms,
100 Self::Loaded(animation) => animation.frames[frame].0,
101 })
102 }
103
104 fn frame_at(&self, position: f64) -> usize {
105 match self {
106 Self::Embedded(animation) => animation
107 .frames
108 .partition_point(|frame| f64::from(frame.end_ms) <= position),
109 Self::Loaded(animation) => animation
110 .frames
111 .partition_point(|(end, _)| f64::from(*end) <= position),
112 }
113 }
114}
115
116#[derive(Clone, Debug, Default, PartialEq, Eq)]
117struct Sample {
118 source: ImageAsset,
119 frame: usize,
120}
121
122#[derive(Clone, Debug, PartialEq)]
123struct Playback {
124 source: ImageAsset,
125 playing: bool,
126 paused: bool,
127 speed: f64,
128 loops: i64,
129}
130
131impl Playback {
132 fn from_node(node: &Node) -> Self {
133 let speed = node.number("speed").unwrap_or(1.0);
134 Self {
135 source: node.image_asset("source").unwrap_or_default(),
136 playing: node.boolean("playing", true),
137 paused: node.boolean("paused", false),
138 speed: if speed.is_finite() {
139 speed.clamp(0.0, 16.0)
140 } else {
141 0.0
142 },
143 loops: node.int("loops").unwrap_or(0),
144 }
145 }
146
147 fn active(&self) -> bool {
148 self.playing && !self.paused && self.speed > 0.0
149 }
150
151 fn plays(&self, animation: &Timeline<'_>) -> u32 {
152 match self.loops {
153 i64::MIN..=-1 => 0,
154 0 => animation.plays(),
155 count => count.min(i64::from(u32::MAX)) as u32,
156 }
157 }
158}
159
160#[doc(hidden)]
161#[derive(Default)]
162pub struct ImagePlaybackSlot(Rc<Property<Sample>>);
163
164impl ImagePlaybackSlot {
165 pub fn current_frame(&self) -> i64 {
166 self.0.get(Sample::default).frame as i64
167 }
168
169 pub fn frame_count(&self) -> i64 {
170 self.0.get(Sample::default).source.frame_count() as i64
171 }
172
173 pub fn populate(&self, node: &mut Node, finished: impl Fn() -> bool + 'static) {
174 let config = Playback::from_node(node);
175 let sample = self.0.get(Sample::default);
176 let frame = if config.playing && sample.source == config.source {
177 sample.frame
178 } else {
179 0
180 };
181 node.properties
182 .insert("current-frame", (frame as i64).into());
183 node.image_playback = Some(Rc::new(ImagePlaybackRegistration {
184 sample: self.0.clone(),
185 config,
186 finished: Rc::new(finished),
187 }));
188 }
189}
190
191#[doc(hidden)]
192pub struct ImagePlaybackRegistration {
193 sample: Rc<Property<Sample>>,
194 config: Playback,
195 finished: Rc<dyn Fn() -> bool>,
196}
197
198impl ImagePlaybackRegistration {
199 fn key(&self) -> usize {
200 Rc::as_ptr(&self.sample) as usize
201 }
202
203 pub fn finish(&self) -> bool {
204 (self.finished)()
205 }
206}
207
208impl PartialEq for ImagePlaybackRegistration {
209 fn eq(&self, other: &Self) -> bool {
210 Rc::ptr_eq(&self.sample, &other.sample) && self.config == other.config
211 }
212}
213
214impl fmt::Debug for ImagePlaybackRegistration {
215 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
216 f.debug_struct("ImagePlaybackRegistration")
217 .field("key", &self.key())
218 .field("config", &self.config)
219 .finish_non_exhaustive()
220 }
221}
222
223struct Entry {
224 registration: Rc<ImagePlaybackRegistration>,
225 anchor: Instant,
226 presented: bool,
227 position_ms: f64,
228 next: Option<Instant>,
229 ended: bool,
230 pending_finished: bool,
231}
232
233impl Entry {
234 fn integrate(&mut self, now: Instant) {
235 let config = &self.registration.config;
236 if self.next.is_some() {
237 let elapsed_ms =
238 now.saturating_duration_since(self.anchor).as_nanos() as f64 / 1_000_000.0;
239 self.position_ms += elapsed_ms * config.speed;
240 }
241 self.anchor = now;
242 }
243
244 fn sample(&mut self) -> bool {
245 let config = &self.registration.config;
246 let mut frame = 0;
247 let mut ended = false;
248 self.next = None;
249 if config.playing
250 && let Some(animation) = Timeline::for_image(&config.source)
251 && config.source.frame_count() >= 2
252 {
253 let count = config.source.frame_count();
254 let duration = animation.end(count - 1);
255 if duration > 0.0 {
256 let plays = config.plays(&animation);
257 ended = plays != 0 && self.position_ms >= duration * f64::from(plays);
258 if ended {
259 frame = count - 1;
260 } else {
261 let within = self.position_ms % duration;
262 frame = animation.frame_at(within);
263 if self.presented && config.active() {
264 let remaining_ms = animation.end(frame) - within;
265 self.next = Duration::try_from_secs_f64(
266 (remaining_ms / config.speed / 1000.0).max(0.001),
267 )
268 .ok()
269 .and_then(|delay| self.anchor.checked_add(delay));
270 }
271 }
272 }
273 }
274 self.pending_finished |= ended && !self.ended;
275 self.ended = ended;
276 let sample = Sample {
277 source: config.source.clone(),
278 frame,
279 };
280 if self.registration.sample.get(Sample::default) == sample {
281 return false;
282 }
283 self.registration.sample.set(sample);
284 true
285 }
286}
287
288#[doc(hidden)]
290#[derive(Default)]
291pub struct ImagePlaybackQueue {
292 entries: BTreeMap<usize, Entry>,
293}
294
295impl ImagePlaybackQueue {
296 pub fn sync<'a>(
297 &mut self,
298 now: Instant,
299 registrations: impl IntoIterator<Item = (&'a Rc<ImagePlaybackRegistration>, bool)>,
300 ) -> bool {
301 let mut changed = false;
302 let mut previous = std::mem::take(&mut self.entries);
303 for (registration, presented) in registrations {
304 let key = registration.key();
305 if self.entries.contains_key(&key) {
306 continue;
307 }
308 let mut entry = if let Some(mut entry) = previous.remove(&key) {
309 let old = &entry.registration.config;
310 let next = ®istration.config;
311 if old == next && entry.presented == presented {
312 entry.registration = registration.clone();
313 self.entries.insert(key, entry);
314 continue;
315 }
316 let reset = old.source != next.source || !next.playing || !old.playing;
317 entry.integrate(now);
318 if reset {
319 entry.position_ms = 0.0;
320 entry.ended = false;
321 entry.pending_finished = false;
322 }
323 entry.registration = registration.clone();
324 entry.presented = presented;
325 entry
326 } else {
327 Entry {
328 registration: registration.clone(),
329 anchor: now,
330 presented,
331 position_ms: 0.0,
332 next: None,
333 ended: false,
334 pending_finished: false,
335 }
336 };
337 changed |= entry.sample();
338 self.entries.insert(key, entry);
339 }
340 for entry in previous.into_values() {
341 let sample = &entry.registration.sample;
342 let empty = Sample::default();
343 if sample.get(Sample::default) != empty {
344 sample.set(empty);
345 changed = true;
346 }
347 }
348 changed
349 }
350
351 pub fn deadline(&self) -> Option<Instant> {
352 self.entries
353 .values()
354 .filter_map(|entry| {
355 if entry.pending_finished {
356 Some(entry.anchor)
357 } else {
358 entry.next
359 }
360 })
361 .min()
362 }
363
364 pub fn advance(&mut self, now: Instant) -> bool {
366 let mut changed = false;
367 for entry in self
368 .entries
369 .values_mut()
370 .filter(|entry| entry.next.is_some_and(|next| next <= now))
371 {
372 entry.integrate(now);
373 changed |= entry.sample();
374 }
375 changed
376 }
377
378 pub fn next_finished(&mut self) -> Option<Rc<ImagePlaybackRegistration>> {
379 let entry = self
380 .entries
381 .values_mut()
382 .find(|entry| entry.pending_finished)?;
383 entry.pending_finished = false;
384 Some(entry.registration.clone())
385 }
386}