Skip to main content

nadir/
animation.rs

1// Copyright 2026 Joseph Anthony Abbott III
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Sprite animation: [`Clip`]s of frames, kept in [`Clips`], and the
16//! [`Animator`] that plays one on its entity's [`Sprite`](crate::Sprite)
17//! (ADR-0024). A cooked atlas's clips, from Aseprite's tags, are added with
18//! [`Clips::add_atlas`], each frame placed as its trimmed pixels (ADR-0035).
19
20use std::collections::BTreeMap;
21use std::fmt;
22use std::time::Duration;
23
24use nadir_assets::Handle;
25use nadir_core::{GenArena, Rect, Vec2};
26use nadir_ecs::{Component, Entity};
27use nadir_render::{Atlas, AtlasSprite, Texture};
28
29/// One frame of a [`Clip`]: a region of a texture, shown for `duration`,
30/// and maybe the size and pivot of its quad.
31///
32/// Made with [`ClipFrame::new`] or [`ClipFrame::from_atlas`] outside this
33/// crate, so that fields can be added later.
34#[derive(Clone, Copy, Debug, PartialEq)]
35#[non_exhaustive]
36pub struct ClipFrame {
37    /// The texture, usually an atlas page.
38    pub texture: Handle<Texture>,
39    /// The region of the texture, normalized, as [`Sprite::uv`](crate::Sprite::uv).
40    pub uv: Rect,
41    /// How long the frame shows: more than zero.
42    pub duration: Duration,
43    /// The quad the frame is drawn as, which `nadir::animate` writes into
44    /// the Sprite with the texture and uv: a trimmed frame's own size and
45    /// pivot. `None` leaves the Sprite's size and pivot as they are, which
46    /// may be those that a frame of another clip wrote.
47    pub placement: Option<Placement>,
48}
49
50/// The size and pivot of a frame's quad, as [`Sprite::size`](crate::Sprite::size)
51/// and [`Sprite::pivot`](crate::Sprite::pivot) hold them.
52#[derive(Clone, Copy, Debug, PartialEq)]
53pub struct Placement {
54    /// The size in world units.
55    pub size: Vec2,
56    /// The point of the quad at the entity's position, normalized.
57    pub pivot: Vec2,
58}
59
60impl ClipFrame {
61    /// The region `uv` of `texture`, shown for `duration`, in the quad the
62    /// Sprite already has.
63    pub const fn new(texture: Handle<Texture>, uv: Rect, duration: Duration) -> Self {
64        Self {
65            texture,
66            uv,
67            duration,
68            placement: None,
69        }
70    }
71
72    /// Frame `frame` of `sprite`, from a cooked [`Atlas`], in `texture`,
73    /// which must be the frame's page, shown for `duration`: placed as
74    /// [`Sprite::from_atlas`](crate::Sprite::from_atlas) places it, its
75    /// trimmed size at one world unit a pixel, with the sprite's pivot where
76    /// the untrimmed cell has it. So the frames of a clip, trimmed each to
77    /// its own pixels, show where the sheet drew them, and mirror about the
78    /// pivot. `None` if `sprite` has no such frame, or is a tile set.
79    pub fn from_atlas(
80        texture: Handle<Texture>,
81        sprite: &AtlasSprite,
82        frame: usize,
83        duration: Duration,
84    ) -> Option<Self> {
85        let pivot = sprite.pivot()?;
86        let frame = sprite.frame(frame)?;
87        Some(Self {
88            texture,
89            uv: frame.uv(),
90            duration,
91            placement: Some(Placement {
92                size: frame.size().as_vec2(),
93                pivot: frame.pivot_in(pivot),
94            }),
95        })
96    }
97}
98
99/// Why a clip could not be made or added.
100#[derive(Clone, Debug, PartialEq, Eq)]
101#[non_exhaustive]
102pub enum ClipError {
103    /// The clip has no frame.
104    NoFrames,
105    /// A frame lasts zero.
106    FrameLastsZero {
107        /// The frame, from 0.
108        index: usize,
109    },
110    /// The frames together last longer than a `Duration` holds.
111    TooLong,
112    /// [`Clips`] has a clip of this name already.
113    NameTaken(String),
114    /// The textures given for an atlas's pages are not one for each.
115    WrongPages {
116        /// The atlas's pages.
117        needed: usize,
118        /// The textures given.
119        given: usize,
120    },
121}
122
123impl fmt::Display for ClipError {
124    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
125        match self {
126            Self::NoFrames => write!(f, "a clip needs a frame"),
127            Self::FrameLastsZero { index } => write!(f, "frame {index} of a clip lasts zero"),
128            Self::TooLong => write!(f, "a clip's frames last longer than a Duration holds"),
129            Self::NameTaken(name) => write!(f, "there is a clip named `{name}` already"),
130            Self::WrongPages { needed, given } => write!(
131                f,
132                "the atlas has {needed} pages, and {given} textures were given for them"
133            ),
134        }
135    }
136}
137
138impl std::error::Error for ClipError {}
139
140/// What a [`Clip`] does at its end.
141#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
142pub enum Playback {
143    /// It starts again from its first frame, for as long as it plays.
144    #[default]
145    Loop,
146    /// It stops on its last frame, and its animator sends
147    /// [`AnimationFinished`].
148    Once,
149}
150
151/// An animation: frames shown one after another, looping or once.
152#[derive(Clone, Debug, PartialEq)]
153pub struct Clip {
154    frames: Vec<ClipFrame>,
155    /// Where each frame ends, from the clip's start.
156    ends: Vec<Duration>,
157    playback: Playback,
158}
159
160impl Clip {
161    /// A clip of `frames`, in order.
162    ///
163    /// # Panics
164    ///
165    /// If there are no frames, if a frame lasts zero, or if the frames
166    /// together last longer than a `Duration` can hold: see
167    /// [`Clip::try_new`].
168    pub fn new(frames: Vec<ClipFrame>, playback: Playback) -> Self {
169        match Self::try_new(frames, playback) {
170            Ok(clip) => clip,
171            Err(error) => panic!("{error}"),
172        }
173    }
174
175    /// A clip of `frames`, in order, as [`Clip::new`] makes it.
176    ///
177    /// # Errors
178    ///
179    /// [`ClipError::NoFrames`], [`ClipError::FrameLastsZero`] or
180    /// [`ClipError::TooLong`].
181    pub fn try_new(frames: Vec<ClipFrame>, playback: Playback) -> Result<Self, ClipError> {
182        if frames.is_empty() {
183            return Err(ClipError::NoFrames);
184        }
185        let mut ends = Vec::with_capacity(frames.len());
186        let mut end = Duration::ZERO;
187        for (index, frame) in frames.iter().enumerate() {
188            if frame.duration.is_zero() {
189                return Err(ClipError::FrameLastsZero { index });
190            }
191            end = end.checked_add(frame.duration).ok_or(ClipError::TooLong)?;
192            ends.push(end);
193        }
194        Ok(Self {
195            frames,
196            ends,
197            playback,
198        })
199    }
200
201    /// The frames, in order.
202    pub fn frames(&self) -> &[ClipFrame] {
203        &self.frames
204    }
205
206    /// What the clip does at its end.
207    pub fn playback(&self) -> Playback {
208        self.playback
209    }
210
211    /// How long the clip lasts, once through: its frames' durations added.
212    pub fn duration(&self) -> Duration {
213        *self.ends.last().expect("a clip has a frame")
214    }
215
216    /// The index of the frame shown `elapsed` after the clip started. A
217    /// frame shows from where the one before it ends, up to but not at its
218    /// own end. A looping clip starts again at each multiple of its
219    /// duration; a clip that plays once shows its last frame from its end
220    /// on.
221    pub fn frame_at(&self, elapsed: Duration) -> usize {
222        let at = match self.playback {
223            Playback::Loop => from_nanos(elapsed.as_nanos() % self.duration().as_nanos()),
224            Playback::Once if elapsed >= self.duration() => return self.frames.len() - 1,
225            Playback::Once => elapsed,
226        };
227        self.ends.partition_point(|&end| end <= at)
228    }
229}
230
231/// `nanos` nanoseconds, which are fewer than a `Duration` holds.
232fn from_nanos(nanos: u128) -> Duration {
233    let seconds = u64::try_from(nanos / 1_000_000_000).expect("less than a Duration holds");
234    Duration::new(seconds, (nanos % 1_000_000_000) as u32)
235}
236
237/// The clips, by handle, and by name for those that have one: a resource
238/// that the engine adds. An [`Animator`] names its clip by the handle that
239/// [`Clips::add`], [`Clips::add_named`] or [`Clips::add_atlas`] gives.
240///
241/// It is the only place `Handle<Clip>`s come from: a clip is not an asset
242/// of the `AssetServer` (ADR-0024).
243pub struct Clips {
244    clips: GenArena<Named>,
245    names: BTreeMap<String, Handle<Clip>>,
246    /// The atlases added, each by its pages' textures, with the clips added
247    /// of it that are still here.
248    atlases: Vec<AtlasClips>,
249}
250
251/// An atlas that gave clips, known by its pages, the clips it gave that
252/// are still there, and how many adds hold them.
253struct AtlasClips {
254    pages: Vec<Handle<Texture>>,
255    clips: Vec<Handle<Clip>>,
256    holds: u32,
257}
258
259/// A clip, and its name if it has one.
260struct Named {
261    clip: Clip,
262    name: Option<String>,
263}
264
265impl Clips {
266    /// No clips.
267    pub fn new() -> Self {
268        Self {
269            clips: GenArena::new(),
270            names: BTreeMap::new(),
271            atlases: Vec::new(),
272        }
273    }
274
275    /// Adds `clip`, with no name, and returns its handle.
276    pub fn add(&mut self, clip: Clip) -> Handle<Clip> {
277        Handle::new(self.clips.insert(Named { clip, name: None }))
278    }
279
280    /// Adds `clip` named `name`, and returns its handle.
281    ///
282    /// # Errors
283    ///
284    /// [`ClipError::NameTaken`] if a clip has that name: none is added.
285    pub fn add_named(
286        &mut self,
287        name: impl Into<String>,
288        clip: Clip,
289    ) -> Result<Handle<Clip>, ClipError> {
290        let name = name.into();
291        if self.names.contains_key(&name) {
292            return Err(ClipError::NameTaken(name));
293        }
294        let handle = Handle::new(self.clips.insert(Named {
295            clip,
296            name: Some(name.clone()),
297        }));
298        self.names.insert(name, handle);
299        Ok(handle)
300    }
301
302    /// Adds every clip of every sprite of `atlas`, each named by its sprite
303    /// and its own name, as `sprites/person/walk`, with its frames placed
304    /// by [`ClipFrame::from_atlas`] in `pages`, the textures of the atlas's
305    /// pages ([`Atlas::load_pages`]). Returns their handles sprite by sprite,
306    /// in the atlas's order, and each sprite's clips by name. A looping clip
307    /// is [`Playback::Loop`]; the others [`Playback::Once`].
308    ///
309    /// An atlas is known by its pages. One added before with the same
310    /// `pages`, whose clips are not all removed, is not added again: the
311    /// result is the handles it gave, and the atlas is held once more, as
312    /// [`Clips::release_atlas`] lets go. So a level and the game can each
313    /// add an atlas they share, in either order, and the clips stay until
314    /// the last lets go of it (ADR-0038).
315    ///
316    /// # Errors
317    ///
318    /// [`ClipError::WrongPages`] if `pages` is not one texture a page, and
319    /// [`ClipError::NameTaken`] if a clip has one of their names, as when
320    /// two atlases have a sprite of one name. Then none is added.
321    pub fn add_atlas(
322        &mut self,
323        atlas: &Atlas,
324        pages: &[Handle<Texture>],
325    ) -> Result<Vec<Handle<Clip>>, ClipError> {
326        if pages.len() != atlas.pages().len() {
327            return Err(ClipError::WrongPages {
328                needed: atlas.pages().len(),
329                given: pages.len(),
330            });
331        }
332        if let Some(known) = self.atlases.iter_mut().find(|known| known.pages == pages) {
333            known.holds = known.holds.saturating_add(1);
334            return Ok(known.clips.clone());
335        }
336        let mut made = Vec::new();
337        for (name, clip) in atlas_clips(atlas, pages) {
338            if self.names.contains_key(&name) {
339                return Err(ClipError::NameTaken(name));
340            }
341            made.push((name, clip?));
342        }
343        let handles: Vec<Handle<Clip>> = made
344            .into_iter()
345            .map(|(name, clip)| {
346                self.add_named(name, clip)
347                    .expect("each name was checked as free, and they differ")
348            })
349            .collect();
350        if !handles.is_empty() {
351            self.atlases.push(AtlasClips {
352                pages: pages.to_vec(),
353                clips: handles.clone(),
354                holds: 1,
355            });
356        }
357        Ok(handles)
358    }
359
360    /// Finds the clips of an atlas added before again, by name, in `atlas`
361    /// as a reload made it, with `pages` its pages' textures: the hot
362    /// reload's, under `dev` (M5.8). The atlas added before is the one of
363    /// `pages`, or else the one with a page among them, as when the
364    /// atlas gains a page or loses one; `None` if there is none, as for an
365    /// atlas whose clips were never added, and nothing changes.
366    ///
367    /// Each clip of `atlas` replaces the one of its name in place, under
368    /// the handle it had, so that animators play it on from their time:
369    /// a looping one wraps it by its new duration, and a finished one
370    /// holds its new last frame ([`Animator`]). A clip new to the atlas is
371    /// added, as [`Clips::add_atlas`] adds one. A clip the atlas no longer
372    /// has stays as it was, so that its handle stays good, and one that
373    /// cannot be made, or whose name another atlas's clip has, is not
374    /// changed: the result names each. The atlas keeps its holds, now known
375    /// by `pages`.
376    #[cfg(feature = "dev")]
377    pub(crate) fn reload_atlas(
378        &mut self,
379        atlas: &Atlas,
380        pages: &[Handle<Texture>],
381    ) -> Option<AtlasReload> {
382        let index = self
383            .atlases
384            .iter()
385            .position(|known| known.pages == pages)
386            .or_else(|| {
387                self.atlases
388                    .iter()
389                    .position(|known| known.pages.iter().any(|page| pages.contains(page)))
390            })?;
391        let made = atlas_clips(atlas, pages);
392        let names: Vec<String> = made.iter().map(|(name, _)| name.clone()).collect();
393        let mut reload = AtlasReload {
394            old_pages: Vec::new(),
395            replaced: 0,
396            added: 0,
397            kept: Vec::new(),
398            refused: Vec::new(),
399        };
400        for (name, clip) in made {
401            let clip = match clip {
402                Ok(clip) => clip,
403                Err(error) => {
404                    reload.refused.push((name, error));
405                    continue;
406                }
407            };
408            match self.names.get(&name).copied() {
409                Some(handle) if self.atlases[index].clips.contains(&handle) => {
410                    if let Some(named) = self.clips.get_mut(handle.id()) {
411                        named.clip = clip;
412                        reload.replaced += 1;
413                    }
414                }
415                Some(_) => reload
416                    .refused
417                    .push((name.clone(), ClipError::NameTaken(name))),
418                None => {
419                    let handle = self
420                        .add_named(name, clip)
421                        .expect("the name was checked as free");
422                    self.atlases[index].clips.push(handle);
423                    reload.added += 1;
424                }
425            }
426        }
427        let known = &mut self.atlases[index];
428        for &handle in &known.clips {
429            if let Some(name) = self.clips.get(handle.id()).and_then(|it| it.name.as_ref())
430                && !names.contains(name)
431            {
432                reload.kept.push(name.clone());
433            }
434        }
435        reload.old_pages = std::mem::replace(&mut known.pages, pages.to_vec());
436        Some(reload)
437    }
438
439    /// Lets go of one hold of the atlas of `pages`, which
440    /// [`Clips::add_atlas`] took, and returns whether that was the last:
441    /// then the clips it gave that are still here are removed, as
442    /// [`Clips::remove`] removes one. An atlas that gave no clip, or whose
443    /// clips are all gone, is not held: nothing happens.
444    pub fn release_atlas(&mut self, pages: &[Handle<Texture>]) -> bool {
445        let Some(index) = self.atlases.iter().position(|known| known.pages == pages) else {
446            return false;
447        };
448        let known = &mut self.atlases[index];
449        known.holds -= 1;
450        if known.holds > 0 {
451            return false;
452        }
453        let atlas = self.atlases.remove(index);
454        for handle in atlas.clips {
455            if let Some(named) = self.clips.remove(handle.id())
456                && let Some(name) = &named.name
457            {
458                self.names.remove(name);
459            }
460        }
461        true
462    }
463
464    /// The clip of `handle`, or `None` if it was removed.
465    pub fn get(&self, handle: Handle<Clip>) -> Option<&Clip> {
466        self.clips.get(handle.id()).map(|named| &named.clip)
467    }
468
469    /// The clip named `name`, such as `sprites/person/walk`.
470    pub fn find(&self, name: &str) -> Option<Handle<Clip>> {
471        self.names.get(name).copied()
472    }
473
474    /// The name of the clip of `handle`, if it has one and was not removed.
475    pub fn name(&self, handle: Handle<Clip>) -> Option<&str> {
476        self.clips.get(handle.id())?.name.as_deref()
477    }
478
479    /// Removes the clip of `handle`, and its name, and returns it.
480    /// Animators that still play it stop where they are; the first such
481    /// animator in the process logs a warning.
482    pub fn remove(&mut self, handle: Handle<Clip>) -> Option<Clip> {
483        let named = self.clips.remove(handle.id())?;
484        if let Some(name) = &named.name {
485            self.names.remove(name);
486            // An atlas whose clips are all gone may be added again.
487            for atlas in &mut self.atlases {
488                atlas.clips.retain(|&clip| clip != handle);
489            }
490            self.atlases.retain(|atlas| !atlas.clips.is_empty());
491        }
492        Some(named.clip)
493    }
494
495    /// How many clips there are.
496    pub fn len(&self) -> usize {
497        self.clips.len()
498    }
499
500    /// Whether there are none.
501    pub fn is_empty(&self) -> bool {
502        self.clips.is_empty()
503    }
504}
505
506impl Default for Clips {
507    fn default() -> Self {
508        Self::new()
509    }
510}
511
512impl fmt::Debug for Clips {
513    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
514        f.debug_struct("Clips").field("len", &self.len()).finish()
515    }
516}
517
518/// What [`Clips::reload_atlas`] did.
519#[cfg(feature = "dev")]
520#[derive(Debug, PartialEq)]
521pub(crate) struct AtlasReload {
522    /// The pages the atlas was known by before.
523    pub(crate) old_pages: Vec<Handle<Texture>>,
524    /// How many clips were replaced in place.
525    pub(crate) replaced: usize,
526    /// How many were new to the atlas, and added.
527    pub(crate) added: usize,
528    /// The clips the atlas no longer has, which stay as they were.
529    pub(crate) kept: Vec<String>,
530    /// The clips that could not be made, or whose name another atlas's
531    /// clip has, which were not changed.
532    pub(crate) refused: Vec<(String, ClipError)>,
533}
534
535/// Every clip of every sprite of `atlas`, named `<sprite>/<clip>`, in the
536/// atlas's order, its frames placed by [`ClipFrame::from_atlas`] in
537/// `pages`, the textures of its pages: as [`Clips::add_atlas`] makes them.
538fn atlas_clips(atlas: &Atlas, pages: &[Handle<Texture>]) -> Vec<(String, Result<Clip, ClipError>)> {
539    let mut made = Vec::new();
540    for sprite in atlas.sprites() {
541        for clip in sprite.clips() {
542            let name = format!("{}/{}", sprite.name(), clip.name());
543            // The atlas reader checked that each step shows a frame of the
544            // sprite, which is on one of the pages.
545            let frames = clip
546                .frames()
547                .iter()
548                .filter_map(|step| {
549                    let page = sprite.frame(step.frame())?.page();
550                    ClipFrame::from_atlas(*pages.get(page)?, sprite, step.frame(), step.duration())
551                })
552                .collect();
553            let playback = if clip.is_looping() {
554                Playback::Loop
555            } else {
556                Playback::Once
557            };
558            made.push((name, Clip::try_new(frames, playback)));
559        }
560    }
561    made
562}
563
564/// Plays a [`Clip`] on its entity's [`Sprite`](crate::Sprite).
565///
566/// The system `nadir::animate`, first in the frame stage `Animate`,
567/// advances it by how long the simulation ran since the last frame (the
568/// change in `RenderFrame::time`), so clips slow and stop with the clock,
569/// as animated tiles do. It then writes the texture and the uv of the frame
570/// it shows into the Sprite, and its size and pivot if the frame has a
571/// [`Placement`], which `nadir::extract_sprites` draws.
572///
573/// Its time is frame state. It moves once a frame, by however the ticks
574/// fell into frames, so a fixed system may call [`Animator::play`] and
575/// [`Animator::restart`], but must not decide anything by
576/// [`Animator::elapsed`], [`Animator::is_finished`] or what it writes into
577/// the Sprite: to wait for a clip, count ticks (roadmap M4.7).
578///
579/// An animator that starts (new, played or restarted) is advanced on its
580/// first frame by that frame's whole step, so it is first drawn up to one
581/// frame into its clip: after a hitch (frames are at most 250 ms), early
582/// frames can be skipped, and a clip that plays once and is no longer than
583/// the step ends on its first frame.
584///
585/// A clip replaced under its handle, as the hot reload replaces an
586/// atlas's under `dev`, plays on from the animator's time: a looping one
587/// wraps it by its new duration, and one that plays once and finished
588/// holds its new last frame, with no second [`AnimationFinished`].
589///
590/// It is reflected by hand as its clip's name in the [`Clips`], and a read
591/// one starts its clip: its time and finished flag are left out (ADR-0024,
592/// ADR-0038).
593#[derive(Clone, Copy, Debug, PartialEq, Eq)]
594pub struct Animator {
595    clip: Handle<Clip>,
596    /// How far into the clip: a looping clip's wraps, and the clip of one
597    /// that plays once stops at its end.
598    elapsed: Duration,
599    /// A clip that plays once reached its end, and its event was sent.
600    finished: bool,
601}
602
603impl Animator {
604    /// Plays `clip` from its start.
605    pub const fn new(clip: Handle<Clip>) -> Self {
606        Self::starting_at(clip, Duration::ZERO)
607    }
608
609    /// Plays `clip` as if it had started `elapsed` ago: a looping clip from
610    /// `elapsed` past its last start, and a clip that plays once at most
611    /// from its end, which it then reaches on its first frame.
612    ///
613    /// Started at `RenderFrame::time`, from a system in a tick or in a frame,
614    /// or before the first frame, a looping clip keeps in step with the
615    /// animated tiles of the same frame lengths, to within the millisecond
616    /// that the tiles' time is rounded to.
617    pub const fn starting_at(clip: Handle<Clip>, elapsed: Duration) -> Self {
618        Self {
619            clip,
620            elapsed,
621            finished: false,
622        }
623    }
624
625    /// The clip it plays.
626    pub fn clip(&self) -> Handle<Clip> {
627        self.clip
628    }
629
630    /// How far into its clip it is: as of the last frame, or as set since
631    /// by [`Animator::starting_at`], [`Animator::play`] or
632    /// [`Animator::restart`], which a looping clip wraps at its next frame.
633    /// Frame state (see [`Animator`]).
634    pub fn elapsed(&self) -> Duration {
635        self.elapsed
636    }
637
638    /// Whether its clip plays once and reached its end by the last frame:
639    /// frame state (see [`Animator`]).
640    pub fn is_finished(&self) -> bool {
641        self.finished
642    }
643
644    /// Plays `clip` from its start, unless it is the clip playing already,
645    /// which goes on: a system may call this every tick. A clip that played
646    /// once and finished stays finished: [`Animator::restart`] plays it
647    /// again.
648    pub fn play(&mut self, clip: Handle<Clip>) {
649        if clip != self.clip {
650            *self = Self::new(clip);
651        }
652    }
653
654    /// Plays its clip from the start again.
655    pub fn restart(&mut self) {
656        *self = Self::new(self.clip);
657    }
658
659    /// Advances it by `by` along `clip`, its clip. Returns the index of the
660    /// frame it then shows, and whether a clip that plays once reached its
661    /// end in this step.
662    pub(crate) fn advance(&mut self, clip: &Clip, by: Duration) -> (usize, bool) {
663        let duration = clip.duration();
664        let ended = match clip.playback() {
665            Playback::Loop => {
666                // Each is less than a Duration holds, so the sum fits.
667                let nanos = self.elapsed.as_nanos() + by.as_nanos();
668                self.elapsed = from_nanos(nanos % duration.as_nanos());
669                false
670            }
671            Playback::Once => {
672                // A finished one holds its clip's last frame, as it does
673                // when a reload makes the clip longer.
674                self.elapsed = if self.finished {
675                    duration
676                } else {
677                    self.elapsed.saturating_add(by).min(duration)
678                };
679                let ended = !self.finished && self.elapsed == duration;
680                self.finished |= ended;
681                ended
682            }
683        };
684        (clip.frame_at(self.elapsed), ended)
685    }
686}
687
688/// A clip that plays once reached its end in this frame: `nadir::animate`
689/// sends it, first in the frame stage `Animate`.
690///
691/// Frame systems after it read it with `Events::frame_events`. Fixed
692/// systems never see it: the next tick clears its tick buffer before they
693/// run. Its readers run in frames, so whatever they spawn, despawn, add or
694/// remove lands at a tick that depends on frame timing: change gameplay
695/// state (what replays and the world hash reproduce, roadmap M4.7) by tick
696/// counts in fixed systems instead.
697#[derive(Clone, Copy, Debug, PartialEq, Eq)]
698pub struct AnimationFinished {
699    /// The entity whose animator finished.
700    pub entity: Entity,
701    /// The clip that finished.
702    pub clip: Handle<Clip>,
703}
704
705/// The `RenderFrame::time` that the last frame animated to: the engine's
706/// own resource, which `nadir::animate` keeps.
707#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
708pub(crate) struct AnimationClock(pub(crate) Duration);
709
710impl Component for Animator {}
711
712#[cfg(test)]
713mod tests {
714    use std::num::NonZeroU32;
715
716    use nadir_core::{GenIndex, Vec2};
717
718    use super::*;
719
720    const MS: Duration = Duration::from_millis(1);
721    const NS: Duration = Duration::from_nanos(1);
722
723    fn texture(index: u32) -> Handle<Texture> {
724        Handle::new(GenIndex::new(index, NonZeroU32::MIN))
725    }
726
727    /// Frames of `ms` milliseconds each, the i-th at uv (i, 0) to (i + 1, 1).
728    fn clip(ms: &[u64], playback: Playback) -> Clip {
729        let frames = (0..)
730            .zip(ms)
731            .map(|(i, &ms)| {
732                let uv = Rect::new(Vec2::new(i as f32, 0.0), Vec2::new(i as f32 + 1.0, 1.0));
733                ClipFrame::new(texture(0), uv, Duration::from_millis(ms))
734            })
735            .collect();
736        Clip::new(frames, playback)
737    }
738
739    /// A handle for an animator under test, whose clip is passed by hand.
740    fn handle() -> Handle<Clip> {
741        Handle::new(GenIndex::new(0, NonZeroU32::MIN))
742    }
743
744    // -- frame_at ------------------------------------------------------------
745
746    #[test]
747    fn a_looping_clip_shows_each_frame_from_its_start_up_to_its_end() {
748        // Frames of 30, 50 and 20 ms: ends at 30, 80 and 100 ms.
749        let clip = clip(&[30, 50, 20], Playback::Loop);
750        assert_eq!(clip.duration(), 100 * MS);
751        let cases = [
752            (Duration::ZERO, 0),
753            (30 * MS - NS, 0),
754            (30 * MS, 1),
755            (80 * MS - NS, 1),
756            (80 * MS, 2),
757            (100 * MS - NS, 2),
758            (100 * MS, 0),
759            (130 * MS, 1),
760            (1_000_080 * MS, 2),
761            // 99,999,999 ns past the last multiple of 100 ms.
762            (Duration::MAX, 2),
763        ];
764        for (elapsed, frame) in cases {
765            assert_eq!(clip.frame_at(elapsed), frame, "at {elapsed:?}");
766        }
767    }
768
769    #[test]
770    fn a_clip_that_plays_once_holds_its_last_frame_from_its_end() {
771        let clip = clip(&[30, 50, 20], Playback::Once);
772        let cases = [
773            (Duration::ZERO, 0),
774            (30 * MS, 1),
775            (100 * MS - NS, 2),
776            (100 * MS, 2),
777            (100 * MS + NS, 2),
778            (130 * MS, 2),
779            (Duration::MAX, 2),
780        ];
781        for (elapsed, frame) in cases {
782            assert_eq!(clip.frame_at(elapsed), frame, "at {elapsed:?}");
783        }
784    }
785
786    #[test]
787    fn a_clip_needs_frames_that_last() {
788        let empty = std::panic::catch_unwind(|| Clip::new(Vec::new(), Playback::Loop));
789        assert!(empty.is_err(), "no frames");
790        let zero = std::panic::catch_unwind(|| clip(&[30, 0], Playback::Loop));
791        assert!(zero.is_err(), "a frame of zero");
792        let frame =
793            |duration| ClipFrame::new(texture(0), Rect::new(Vec2::ZERO, Vec2::ONE), duration);
794        let long = std::panic::catch_unwind(|| {
795            Clip::new(vec![frame(Duration::MAX), frame(NS)], Playback::Loop)
796        });
797        assert!(long.is_err(), "longer than a Duration");
798        // The same, as errors.
799        assert_eq!(
800            Clip::try_new(Vec::new(), Playback::Loop),
801            Err(ClipError::NoFrames)
802        );
803        assert_eq!(
804            Clip::try_new(vec![frame(MS), frame(Duration::ZERO)], Playback::Once),
805            Err(ClipError::FrameLastsZero { index: 1 })
806        );
807        assert_eq!(
808            Clip::try_new(vec![frame(Duration::MAX), frame(NS)], Playback::Loop),
809            Err(ClipError::TooLong)
810        );
811        assert_eq!(
812            ClipError::FrameLastsZero { index: 1 }.to_string(),
813            "frame 1 of a clip lasts zero"
814        );
815        // As long as a Duration holds is long enough.
816        let longest = Clip::new(vec![frame(Duration::MAX - NS), frame(NS)], Playback::Loop);
817        assert_eq!(longest.duration(), Duration::MAX);
818        assert_eq!(longest.frame_at(Duration::MAX - NS), 1);
819    }
820
821    // -- advance -------------------------------------------------------------
822
823    #[test]
824    fn a_looping_clip_wraps_whole_cycles_and_never_ends() {
825        let clip = clip(&[30, 50, 20], Playback::Loop);
826        let mut animator = Animator::new(handle());
827        assert_eq!(animator.advance(&clip, Duration::ZERO), (0, false));
828        assert_eq!(animator.elapsed(), Duration::ZERO);
829        assert_eq!(animator.advance(&clip, 30 * MS), (1, false));
830        assert_eq!(animator.elapsed(), 30 * MS);
831        // 280 ms: twice round, and on the start of the last frame.
832        assert_eq!(animator.advance(&clip, 250 * MS), (2, false));
833        assert_eq!(animator.elapsed(), 80 * MS);
834        // Whole cycles change nothing.
835        assert_eq!(animator.advance(&clip, 200 * MS), (2, false));
836        assert_eq!(animator.elapsed(), 80 * MS);
837        // Onto the end: the start again.
838        assert_eq!(animator.advance(&clip, 20 * MS), (0, false));
839        assert_eq!(animator.elapsed(), Duration::ZERO);
840        // The longest step there is.
841        assert_eq!(animator.advance(&clip, Duration::MAX), (2, false));
842        assert_eq!(animator.elapsed(), 100 * MS - NS);
843        assert!(!animator.is_finished());
844    }
845
846    #[test]
847    fn a_clip_that_plays_once_ends_once_on_the_step_that_reaches_its_end() {
848        let clip = clip(&[30, 50, 20], Playback::Once);
849        let mut animator = Animator::new(handle());
850        assert_eq!(animator.advance(&clip, 100 * MS - NS), (2, false));
851        assert!(!animator.is_finished());
852        // Exactly onto the end.
853        assert_eq!(animator.advance(&clip, NS), (2, true));
854        assert_eq!(animator.elapsed(), 100 * MS);
855        assert!(animator.is_finished());
856        // And not again.
857        assert_eq!(animator.advance(&clip, Duration::ZERO), (2, false));
858        assert_eq!(animator.advance(&clip, 250 * MS), (2, false));
859        assert_eq!(animator.elapsed(), 100 * MS);
860        assert_eq!(animator.advance(&clip, Duration::MAX), (2, false));
861    }
862
863    #[test]
864    fn a_step_past_the_end_of_a_clip_that_plays_once_ends_it_there() {
865        // A hitch of 250 ms over a new animator: it ends on its first step,
866        // and only its last frame is drawn.
867        let clip = clip(&[80, 80, 80], Playback::Once);
868        let mut animator = Animator::new(handle());
869        assert_eq!(animator.advance(&clip, 250 * MS), (2, true));
870        assert_eq!(animator.elapsed(), 240 * MS);
871        // A single frame.
872        let flash = clip_of_one(16);
873        let mut animator = Animator::new(handle());
874        assert_eq!(animator.advance(&flash, 16 * MS), (0, true));
875    }
876
877    fn clip_of_one(ms: u64) -> Clip {
878        clip(&[ms], Playback::Once)
879    }
880
881    #[test]
882    fn restart_plays_a_finished_clip_again_and_play_switches_only_to_another() {
883        let once = clip(&[30, 50, 20], Playback::Once);
884        let mut animator = Animator::new(handle());
885        assert_eq!(animator.advance(&once, 100 * MS), (2, true));
886        // The same clip again: still finished.
887        animator.play(handle());
888        assert!(animator.is_finished());
889        assert_eq!(animator.advance(&once, 16 * MS), (2, false));
890        // Restarted: from its start, and it ends again.
891        animator.restart();
892        assert_eq!(
893            (animator.elapsed(), animator.is_finished()),
894            (Duration::ZERO, false)
895        );
896        assert_eq!(animator.advance(&once, 50 * MS), (1, false));
897        assert_eq!(animator.advance(&once, 50 * MS), (2, true));
898        // Another clip: from its start.
899        let other = Handle::new(GenIndex::new(1, NonZeroU32::MIN));
900        animator.play(other);
901        assert_eq!(animator.clip(), other);
902        assert_eq!(
903            (animator.elapsed(), animator.is_finished()),
904            (Duration::ZERO, false)
905        );
906
907        // Mid-clip, playing the same clip goes on from where it is.
908        let looping = clip(&[30, 50, 20], Playback::Loop);
909        let mut animator = Animator::new(handle());
910        animator.advance(&looping, 50 * MS);
911        animator.play(handle());
912        assert_eq!(animator.elapsed(), 50 * MS);
913        assert_eq!(animator.advance(&looping, 30 * MS), (2, false));
914    }
915
916    #[test]
917    fn an_animator_can_start_partway_through_its_clip() {
918        let looping = clip(&[100, 100, 100], Playback::Loop);
919        let mut animator = Animator::starting_at(handle(), 250 * MS);
920        assert_eq!(animator.advance(&looping, Duration::ZERO), (2, false));
921        // Past the clip's end: wrapped.
922        let mut animator = Animator::starting_at(handle(), 37_310 * MS);
923        assert_eq!(animator.advance(&looping, Duration::ZERO), (1, false));
924        assert_eq!(animator.elapsed(), 110 * MS);
925        // A clip that plays once, started past its end, ends on its first
926        // step.
927        let once = clip(&[30, 50, 20], Playback::Once);
928        let mut animator = Animator::starting_at(handle(), 130 * MS);
929        assert_eq!(animator.advance(&once, Duration::ZERO), (2, true));
930        assert_eq!(animator.elapsed(), 100 * MS);
931    }
932
933    // -- Clips ---------------------------------------------------------------
934
935    #[test]
936    fn clips_are_found_by_handle_until_removed() {
937        let mut clips = Clips::new();
938        assert!(clips.is_empty());
939        let walk = clips.add(clip(&[100, 100], Playback::Loop));
940        let jump = clips.add(clip(&[50], Playback::Once));
941        assert_eq!(clips.len(), 2);
942        assert_eq!(clips.get(walk).map(Clip::playback), Some(Playback::Loop));
943        assert_eq!(clips.get(jump).map(Clip::duration), Some(50 * MS));
944        assert_eq!(clips.remove(walk).map(|clip| clip.frames().len()), Some(2));
945        assert_eq!(clips.get(walk), None);
946        assert_eq!(clips.remove(walk), None);
947        // A new clip in the old one's slot is not found by the old handle.
948        let fall = clips.add(clip(&[10], Playback::Once));
949        assert_ne!(fall, walk);
950        assert_eq!(clips.get(walk), None);
951        assert_eq!(format!("{clips:?}"), "Clips { len: 2 }");
952    }
953
954    #[test]
955    fn a_named_clip_is_found_by_its_name_until_removed() {
956        let mut clips = Clips::new();
957        let walk = clips
958            .add_named("sprites/person/walk", clip(&[100], Playback::Loop))
959            .expect("a free name");
960        let unnamed = clips.add(clip(&[10], Playback::Once));
961        assert_eq!(clips.find("sprites/person/walk"), Some(walk));
962        assert_eq!(clips.name(walk), Some("sprites/person/walk"));
963        assert_eq!(clips.name(unnamed), None);
964        assert_eq!(clips.find("sprites/person"), None);
965        assert_eq!(
966            clips.add_named("sprites/person/walk", clip(&[5], Playback::Loop)),
967            Err(ClipError::NameTaken("sprites/person/walk".to_string()))
968        );
969        assert_eq!(clips.len(), 2);
970        clips.remove(walk);
971        assert_eq!(clips.find("sprites/person/walk"), None);
972        assert_eq!(clips.name(walk), None);
973        // The name is free again.
974        let again = clips
975            .add_named("sprites/person/walk", clip(&[5], Playback::Loop))
976            .expect("a free name");
977        assert_ne!(again, walk);
978    }
979
980    /// An atlas of two pages: a person whose two frames are trimmed apart,
981    /// with two clips, and a tree with none.
982    fn atlas() -> Atlas {
983        atlas_of(
984            r#"{ "version": 2,
985            "pages": [ { "path": "atlas/sprites_0.qoi", "w": 64, "h": 64 },
986                       { "path": "atlas/sprites_1.qoi", "w": 64, "h": 64 } ],
987            "sprites": [
988              { "name": "sprites/person",
989                "frames": [ { "page": 0, "x": 1, "y": 1, "w": 10, "h": 20, "ox": 1, "oy": 0, "sw": 12, "sh": 20 },
990                            { "page": 1, "x": 1, "y": 1, "w": 9, "h": 18, "ox": 2, "oy": 2, "sw": 12, "sh": 20 } ],
991                "pivot": [6.0, 20.0],
992                "clips": [ { "name": "stand", "loop": true, "frames": [[0, 100]] },
993                           { "name": "wave", "loop": false, "frames": [[1, 40], [0, 60]] } ] },
994              { "name": "sprites/tree",
995                "frames": [ { "page": 0, "x": 20, "y": 1, "w": 24, "h": 44, "ox": 0, "oy": 4, "sw": 24, "sh": 48 } ],
996                "pivot": [12.0, 48.0] } ] }"#,
997        )
998    }
999
1000    /// The atlas of `text`, as its reader reads it.
1001    fn atlas_of(text: &str) -> Atlas {
1002        use nadir_assets::{Asset, DecodeCtx};
1003        use nadir_codec::{Limits, json, kbj};
1004        let value = json::parse(text, Limits::default()).expect("the test's JSON");
1005        let bytes = kbj::encode(&value, Limits::default()).expect("encodable");
1006        Atlas::decode(
1007            &bytes,
1008            &DecodeCtx::new("atlas/sprites.kbj", Limits::default()),
1009        )
1010        .expect("an atlas")
1011    }
1012
1013    #[test]
1014    fn an_atlas_s_clips_are_added_by_name_each_frame_placed_on_its_page() {
1015        let atlas = atlas();
1016        let pages = [texture(7), texture(8)];
1017        let mut clips = Clips::new();
1018        let added = clips.add_atlas(&atlas, &pages).expect("the clips");
1019        let stand = clips.find("sprites/person/stand").expect("stand");
1020        let wave = clips.find("sprites/person/wave").expect("wave");
1021        assert_eq!(added, [stand, wave]);
1022        assert_eq!(clips.len(), 2);
1023
1024        let stand = clips.get(stand).expect("a clip");
1025        assert_eq!(stand.playback(), Playback::Loop);
1026        assert_eq!(stand.duration(), 100 * MS);
1027        let wave = clips.get(wave).expect("a clip");
1028        assert_eq!(wave.playback(), Playback::Once);
1029        let person = atlas.sprite("sprites/person").expect("the person");
1030        let shown: Vec<(Handle<Texture>, Rect, Duration)> = wave
1031            .frames()
1032            .iter()
1033            .map(|frame| (frame.texture, frame.uv, frame.duration))
1034            .collect();
1035        assert_eq!(
1036            shown,
1037            [
1038                (pages[1], person.frames()[1].uv(), 40 * MS),
1039                (pages[0], person.frames()[0].uv(), 60 * MS),
1040            ]
1041        );
1042        // Each frame its own quad, with the pivot where the cell has it: a
1043        // frame 2 pixels in from the left, 9 wide, has the pivot 6 - 2 = 4
1044        // pixels in.
1045        assert_eq!(
1046            wave.frames()[0].placement,
1047            Some(Placement {
1048                size: Vec2::new(9.0, 18.0),
1049                pivot: Vec2::new(4.0 / 9.0, 18.0 / 18.0),
1050            })
1051        );
1052        assert_eq!(
1053            wave.frames()[1].placement,
1054            Some(Placement {
1055                size: Vec2::new(10.0, 20.0),
1056                pivot: Vec2::new(0.5, 1.0),
1057            })
1058        );
1059    }
1060
1061    #[test]
1062    fn an_atlas_s_clips_are_added_all_or_none() {
1063        let atlas = atlas();
1064        let mut clips = Clips::new();
1065        assert_eq!(
1066            clips.add_atlas(&atlas, &[texture(7)]),
1067            Err(ClipError::WrongPages {
1068                needed: 2,
1069                given: 1
1070            })
1071        );
1072        assert!(clips.is_empty());
1073        // One name already taken: none is added.
1074        clips
1075            .add_named("sprites/person/wave", clip(&[5], Playback::Loop))
1076            .expect("a free name");
1077        assert_eq!(
1078            clips.add_atlas(&atlas, &[texture(7), texture(8)]),
1079            Err(ClipError::NameTaken("sprites/person/wave".to_string()))
1080        );
1081        assert_eq!(clips.len(), 1);
1082        assert_eq!(clips.find("sprites/person/stand"), None);
1083    }
1084
1085    #[test]
1086    fn an_atlas_added_again_is_held_again_until_its_clips_are_removed() {
1087        let atlas = atlas();
1088        let pages = [texture(7), texture(8)];
1089        let mut clips = Clips::new();
1090        let added = clips.add_atlas(&atlas, &pages).expect("the clips");
1091        assert!(!added.is_empty());
1092        let count = clips.len();
1093        // Again, by the same pages: the same clips, held twice.
1094        assert_eq!(clips.add_atlas(&atlas, &pages), Ok(added.clone()));
1095        assert_eq!(clips.len(), count);
1096        // Let go once, they stay; let go again, they go, and it is not held.
1097        assert!(!clips.release_atlas(&pages));
1098        assert_eq!(clips.len(), count);
1099        assert!(clips.release_atlas(&pages));
1100        assert!(clips.is_empty());
1101        assert_eq!(clips.find("sprites/person/stand"), None);
1102        assert!(!clips.release_atlas(&pages));
1103        let added = clips.add_atlas(&atlas, &pages).expect("the clips");
1104        // By other pages, another load of it: its names are taken.
1105        assert!(matches!(
1106            clips.add_atlas(&atlas, &[texture(9), texture(10)]),
1107            Err(ClipError::NameTaken(_))
1108        ));
1109        // Once its clips are gone, it is added anew.
1110        for handle in added {
1111            clips.remove(handle);
1112        }
1113        assert!(clips.is_empty());
1114        let again = clips.add_atlas(&atlas, &pages).expect("the clips");
1115        assert_eq!(again.len(), count);
1116    }
1117
1118    #[test]
1119    fn a_frame_of_an_atlas_is_placed_as_a_sprite_of_it_would_be() {
1120        let atlas = atlas();
1121        let person = atlas.sprite("sprites/person").expect("the person");
1122        let frame = ClipFrame::from_atlas(texture(8), person, 1, 40 * MS).expect("a frame");
1123        let sprite = crate::Sprite::from_atlas(texture(8), person, 1).expect("a sprite");
1124        let placement = frame.placement.expect("placed");
1125        assert_eq!(
1126            (frame.uv, placement.size, placement.pivot),
1127            (sprite.uv, sprite.size, sprite.pivot)
1128        );
1129        assert!(ClipFrame::from_atlas(texture(8), person, 2, MS).is_none());
1130    }
1131
1132    /// An atlas reloaded under `dev` (M5.8).
1133    #[cfg(feature = "dev")]
1134    mod reloaded {
1135        use super::*;
1136
1137        /// The atlas of [`atlas`] as a reload makes it: the person's wave is
1138        /// now three steps long, and on the other page first, its stand gone,
1139        /// and a sit new; the tree has a clip of its own.
1140        const RELOADED: &str = r#"{ "version": 2,
1141            "pages": [ { "path": "atlas/sprites_0.qoi", "w": 64, "h": 64 },
1142                       { "path": "atlas/sprites_1.qoi", "w": 64, "h": 64 } ],
1143            "sprites": [
1144              { "name": "sprites/person",
1145                "frames": [ { "page": 1, "x": 30, "y": 1, "w": 10, "h": 20, "ox": 1, "oy": 0, "sw": 12, "sh": 20 },
1146                            { "page": 0, "x": 40, "y": 1, "w": 9, "h": 18, "ox": 2, "oy": 2, "sw": 12, "sh": 20 } ],
1147                "pivot": [6.0, 20.0],
1148                "clips": [ { "name": "sit", "loop": true, "frames": [[0, 50]] },
1149                           { "name": "wave", "loop": false, "frames": [[1, 40], [0, 60], [1, 100]] } ] },
1150              { "name": "sprites/tree",
1151                "frames": [ { "page": 0, "x": 20, "y": 1, "w": 24, "h": 44, "ox": 0, "oy": 4, "sw": 24, "sh": 48 } ],
1152                "pivot": [12.0, 48.0],
1153                "clips": [ { "name": "sway", "loop": true, "frames": [[0, 80]] } ] } ] }"#;
1154
1155        #[test]
1156        fn a_reloaded_atlas_replaces_its_clips_by_name_under_their_handles() {
1157            let pages = [texture(7), texture(8)];
1158            let mut clips = Clips::new();
1159            clips.add_atlas(&atlas(), &pages).expect("the clips");
1160            let stand = clips.find("sprites/person/stand").expect("stand");
1161            let wave = clips.find("sprites/person/wave").expect("wave");
1162
1163            let reloaded = atlas_of(RELOADED);
1164            let reload = clips
1165                .reload_atlas(&reloaded, &pages)
1166                .expect("the atlas was added");
1167            assert_eq!(reload.old_pages, pages);
1168            assert_eq!((reload.replaced, reload.added), (1, 2));
1169            assert_eq!(reload.kept, ["sprites/person/stand"]);
1170            assert!(reload.refused.is_empty());
1171
1172            // The wave, under its handle, as the reloaded atlas has it.
1173            assert_eq!(clips.find("sprites/person/wave"), Some(wave));
1174            let person = reloaded.sprite("sprites/person").expect("the person");
1175            let shown: Vec<(Handle<Texture>, Rect, Duration)> = clips
1176                .get(wave)
1177                .expect("the wave")
1178                .frames()
1179                .iter()
1180                .map(|frame| (frame.texture, frame.uv, frame.duration))
1181                .collect();
1182            assert_eq!(
1183                shown,
1184                [
1185                    (pages[0], person.frames()[1].uv(), 40 * MS),
1186                    (pages[1], person.frames()[0].uv(), 60 * MS),
1187                    (pages[0], person.frames()[1].uv(), 100 * MS),
1188                ]
1189            );
1190            // The stand is kept as it was; the sit and the sway are new.
1191            assert_eq!(clips.find("sprites/person/stand"), Some(stand));
1192            assert_eq!(clips.get(stand).map(Clip::duration), Some(100 * MS));
1193            let sit = clips.find("sprites/person/sit").expect("the sit");
1194            assert_eq!(clips.get(sit).map(Clip::playback), Some(Playback::Loop));
1195            assert!(clips.find("sprites/tree/sway").is_some());
1196
1197            // They are all the atlas's: its last hold lets go of every one.
1198            assert!(clips.release_atlas(&pages));
1199            assert!(clips.is_empty());
1200        }
1201
1202        #[test]
1203        fn a_reloaded_atlas_on_other_pages_is_known_by_them_from_then_on() {
1204            let mut clips = Clips::new();
1205            let pages = [texture(7), texture(8)];
1206            clips.add_atlas(&atlas(), &pages).expect("the clips");
1207            clips.add_atlas(&atlas(), &pages).expect("held twice");
1208            let wave = clips.find("sprites/person/wave").expect("wave");
1209
1210            // A page more: known by the names of its clips.
1211            let three = RELOADED.replace(
1212                r#"{ "path": "atlas/sprites_1.qoi", "w": 64, "h": 64 } ],"#,
1213                r#"{ "path": "atlas/sprites_1.qoi", "w": 64, "h": 64 },
1214                   { "path": "atlas/sprites_2.qoi", "w": 64, "h": 64 } ],"#,
1215            );
1216            let more = [texture(7), texture(8), texture(9)];
1217            let reload = clips
1218                .reload_atlas(&atlas_of(&three), &more)
1219                .expect("found by name");
1220            assert_eq!(reload.old_pages, pages);
1221            assert_eq!(clips.find("sprites/person/wave"), Some(wave));
1222
1223            // Its two holds stay, under its new pages.
1224            assert!(!clips.release_atlas(&pages));
1225            assert!(!clips.release_atlas(&more));
1226            assert!(!clips.is_empty());
1227            assert_eq!(
1228                clips.add_atlas(&atlas_of(&three), &more).map(|it| it.len()),
1229                Ok(4)
1230            );
1231            assert!(!clips.release_atlas(&more));
1232            assert!(clips.release_atlas(&more));
1233            assert!(clips.is_empty());
1234        }
1235
1236        #[test]
1237        fn an_atlas_whose_clips_were_never_added_is_not_reloaded() {
1238            let mut clips = Clips::new();
1239            let pages = [texture(7), texture(8)];
1240            assert_eq!(clips.reload_atlas(&atlas(), &pages), None);
1241            assert!(clips.is_empty());
1242
1243            // Another atlas, of no page of this one's, with clips of its
1244            // names, is not taken for it.
1245            clips.add_atlas(&atlas(), &pages).expect("the clips");
1246            let wave = clips.find("sprites/person/wave").expect("wave");
1247            let other = [texture(9), texture(10)];
1248            assert_eq!(clips.reload_atlas(&atlas_of(RELOADED), &other), None);
1249            assert_eq!(clips.get(wave).map(Clip::duration), Some(100 * MS));
1250            assert!(clips.release_atlas(&pages));
1251            assert!(clips.is_empty());
1252
1253            // Another atlas's clip of one of its names is left as it is.
1254            let theirs = clips
1255                .add_named("sprites/tree/sway", clip(&[5], Playback::Once))
1256                .expect("a free name");
1257            clips.add_atlas(&atlas(), &pages).expect("the clips");
1258            let reload = clips
1259                .reload_atlas(&atlas_of(RELOADED), &pages)
1260                .expect("the atlas was added");
1261            assert_eq!(
1262                reload.refused,
1263                [(
1264                    "sprites/tree/sway".to_string(),
1265                    ClipError::NameTaken("sprites/tree/sway".to_string())
1266                )]
1267            );
1268            assert_eq!(clips.find("sprites/tree/sway"), Some(theirs));
1269            assert_eq!(clips.get(theirs).map(Clip::duration), Some(5 * MS));
1270            // It stays when the atlas goes, with the stand the atlas kept.
1271            assert!(clips.release_atlas(&pages));
1272            assert_eq!(clips.len(), 1);
1273            assert_eq!(clips.find("sprites/tree/sway"), Some(theirs));
1274        }
1275    }
1276
1277    #[test]
1278    fn an_animator_plays_on_through_a_clip_replaced_under_its_handle() {
1279        // A looping clip of 300 ms, 200 ms in, replaced by one of 150 ms:
1280        // it wraps by the new duration.
1281        let mut looping = Animator::new(handle());
1282        looping.advance(&clip(&[100, 100, 100], Playback::Loop), 200 * MS);
1283        let (frame, ended) = looping.advance(&clip(&[50, 100], Playback::Loop), 10 * MS);
1284        assert_eq!((looping.elapsed(), frame, ended), (60 * MS, 1, false));
1285
1286        // A finished clip of 100 ms replaced by a longer one holds its new
1287        // last frame, and does not end again.
1288        let mut once = Animator::new(handle());
1289        let (_, ended) = once.advance(&clip(&[100], Playback::Once), 150 * MS);
1290        assert!(ended && once.is_finished());
1291        let longer = clip(&[100, 100, 100], Playback::Once);
1292        let (frame, ended) = once.advance(&longer, 10 * MS);
1293        assert_eq!((once.elapsed(), frame, ended), (300 * MS, 2, false));
1294        assert!(once.is_finished());
1295        // Replaced by a shorter one, it holds that one's last frame.
1296        let (frame, ended) = once.advance(&clip(&[20, 20], Playback::Once), 10 * MS);
1297        assert_eq!((once.elapsed(), frame, ended), (40 * MS, 1, false));
1298
1299        // One not finished plays on into the longer clip, and ends at its
1300        // end.
1301        let mut playing = Animator::new(handle());
1302        playing.advance(&clip(&[100], Playback::Once), 50 * MS);
1303        let (frame, ended) = playing.advance(&longer, 100 * MS);
1304        assert_eq!((playing.elapsed(), frame, ended), (150 * MS, 1, false));
1305        let (_, ended) = playing.advance(&longer, 200 * MS);
1306        assert!(ended && playing.is_finished());
1307    }
1308}