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