Skip to main content

clairlune_render/
clock.rs

1//! Which moment of the character's life a frame shows.
2//!
3//! - `Clock::Live`: the seeded state machine plays freely (PLAN.md section 4.4);
4//!   live mode never repeats exactly.
5//! - `Clock::Loop(loop_ms)`: a seamless loop for GIF export. The character follows
6//!   the activity's `gif.loop_script`, its first looping state repeated to fill
7//!   the loop, then time-scaled so the script ends exactly at `loop_ms`; pacing
8//!   is snapped to a period that divides the loop. Frame `t = loop_ms` equals
9//!   frame `t = 0`.
10
11use clairlune_scene::activity::Activity;
12use clairlune_scene::anim::DEFAULT_ONE_SHOT_MS;
13use clairlune_scene::{CharacterTrack, Motion};
14use clairlune_sprites::Character;
15
16#[derive(Clone, Copy, Debug, PartialEq, Eq)]
17pub enum Clock {
18    Live,
19    Loop(u64),
20}
21
22/// One state of the loop script, placed on the loop's timeline.
23#[derive(Clone, Debug, PartialEq, Eq)]
24struct Segment {
25    state: String,
26    start: u64,
27    len: u64,
28    /// The state's own animation length (one cycle), in animation time.
29    cycle: u64,
30}
31
32/// The character's timeline for one seamless loop.
33#[derive(Clone, Debug, PartialEq, Eq)]
34pub struct LoopScript {
35    loop_ms: u64,
36    segments: Vec<Segment>,
37}
38
39impl LoopScript {
40    pub fn new(activity: &Activity, character: &dyn Character, loop_ms: u64) -> Self {
41        let script: Vec<String> = activity
42            .gif
43            .as_ref()
44            .map(|g| g.loop_script.clone())
45            .filter(|s| !s.is_empty())
46            .unwrap_or_else(|| vec![activity.animation.start.clone()]);
47        let cycle = |s: &str| {
48            character
49                .animation(&activity.id, s)
50                .map(|a| a.duration_ms())
51                .unwrap_or(DEFAULT_ONE_SHOT_MS)
52                .max(1)
53        };
54        let looping = |s: &str| activity.animation.states.get(s).is_some_and(|d| d.looping);
55
56        // Repeat the first looping state's cycle while it still fits in the loop.
57        let base: u64 = script.iter().map(|s| cycle(s)).sum();
58        let rep = script.iter().position(|s| looping(s)).unwrap_or(0);
59        let rep_cycle = cycle(&script[rep]);
60        let mut extra = 0;
61        while base + (extra + 1) * rep_cycle <= loop_ms {
62            extra += 1;
63        }
64        let mut natural: Vec<(String, u64)> = Vec::new();
65        for (i, s) in script.iter().enumerate() {
66            let n = if i == rep { 1 + extra } else { 1 };
67            for _ in 0..n {
68                natural.push((s.clone(), cycle(s)));
69            }
70        }
71
72        // Time-scale onto [0, loop_ms) with integer boundaries.
73        let total: u64 = natural.iter().map(|(_, c)| c).sum::<u64>().max(1);
74        let mut segments = Vec::with_capacity(natural.len());
75        let mut cum = 0u64;
76        for (state, c) in natural {
77            let start = cum * loop_ms / total;
78            cum += c;
79            let end = cum * loop_ms / total;
80            if end > start {
81                segments.push(Segment {
82                    state,
83                    start,
84                    len: end - start,
85                    cycle: c,
86                });
87            }
88        }
89        Self { loop_ms, segments }
90    }
91
92    /// State and elapsed animation time at `t` (wraps every `loop_ms`).
93    pub fn at(&self, t_ms: u64) -> (&str, u64) {
94        let t = t_ms % self.loop_ms.max(1);
95        let seg = self
96            .segments
97            .iter()
98            .rev()
99            .find(|s| s.start <= t)
100            .unwrap_or(&self.segments[0]);
101        let elapsed = (t - seg.start) * seg.cycle / seg.len.max(1);
102        (&seg.state, elapsed.min(seg.cycle - 1))
103    }
104}
105
106/// The character track with pacing snapped to a period that divides the loop.
107pub fn loop_track(track: CharacterTrack, loop_ms: u64) -> CharacterTrack {
108    match track.motion {
109        Motion::Pace {
110            x_min,
111            x_max,
112            period_ms,
113        } => {
114            // Whole round trips per loop, nearest to the natural speed, dividing the loop.
115            let target = (loop_ms as f64 / period_ms.max(1) as f64).round().max(1.0) as u64;
116            let n = (1..=loop_ms)
117                .filter(|n| loop_ms.is_multiple_of(*n))
118                .min_by_key(|n| n.abs_diff(target))
119                .unwrap_or(1);
120            CharacterTrack {
121                motion: Motion::Pace {
122                    x_min,
123                    x_max,
124                    period_ms: loop_ms / n,
125                },
126                ..track
127            }
128        }
129        Motion::Stationary { .. } => track,
130    }
131}
132
133#[cfg(test)]
134mod tests {
135    use super::*;
136    use clairlune_scene::activity::builtin_catalog;
137    use clairlune_sprites::builtin_character;
138
139    #[test]
140    fn script_fills_the_loop_and_wraps() {
141        for a in &builtin_catalog().activities {
142            for loop_ms in [6000, 12000] {
143                let s = LoopScript::new(a, builtin_character(), loop_ms);
144                assert_eq!(s.segments.first().unwrap().start, 0, "{}", a.id);
145                let last = s.segments.last().unwrap();
146                assert_eq!(last.start + last.len, loop_ms, "{}", a.id);
147                assert_eq!(s.at(0), s.at(loop_ms));
148                // Starts on the first frame of the script's first state.
149                assert_eq!(s.at(0).1, 0);
150            }
151        }
152    }
153
154    #[test]
155    fn pacing_divides_the_loop() {
156        let track = CharacterTrack {
157            y: 0,
158            scale: 1,
159            face_left: false,
160            motion: Motion::Pace {
161                x_min: 0,
162                x_max: 100,
163                period_ms: 4700,
164            },
165        };
166        let t = loop_track(track, 6000);
167        let Motion::Pace { period_ms, .. } = t.motion else {
168            panic!()
169        };
170        assert!(6000u64.is_multiple_of(period_ms));
171        assert_eq!(t.at(0), t.at(6000));
172    }
173}