Skip to main content

ssruntime/context/
playback.rs

1//! The playhead, the playback state and settings, and the controls that drive the character's clock.
2
3use super::{CharacterClock, Context};
4use crate::error::SSRuntimeError;
5use crate::eval;
6use crate::mix::TrackFade;
7
8impl<'a> Context<'a> {
9    pub fn get_frame_no(&self) -> f32 {
10        self.instance.primary_source().controller.get_frame_no()
11    }
12
13    /// `true` once the configured loops have completed, and sticky until the
14    /// next `play` / `setup_animation`. Never `true` under an infinite loop
15    /// count, and never raised by `stop`.
16    ///
17    /// This is a *state*, not a pulse: to notify once, take its rising edge.
18    pub fn is_finished(&self) -> bool {
19        self.instance.primary_source().controller.is_finished()
20    }
21
22    pub fn just_looped(&self) -> bool {
23        self.instance.primary_source().controller.just_looped()
24    }
25
26    /// `true` while the clock runs and track 0 has not finished. A held
27    /// character is still playing.
28    pub fn is_playing(&self) -> bool {
29        self.instance.clock.playing && self.instance.primary_source().controller.is_playing()
30    }
31
32    pub fn is_playing_forward(&self) -> bool {
33        self.instance.primary_source().controller.is_playing_forward()
34    }
35
36    /// `true` while a playing character is held. Implies [`Self::is_playing`],
37    /// so the pair reads as three states. Once track 0 has finished, a pause
38    /// still holds the other tracks and the fades, but this reads `false`
39    /// along with `is_playing`.
40    pub fn is_pausing(&self) -> bool {
41        self.instance.clock.pausing && self.is_playing()
42    }
43
44    /// `true` from `play` until `stop` or the next setup: the character's
45    /// clock, which [`Self::is_playing`] reads only while track 0 has not
46    /// finished. A host that stops ticking a character with nothing to move
47    /// reads this, since the other tracks and the fades run on after track 0
48    /// ends. A held clock is still playing.
49    pub fn is_clock_playing(&self) -> bool {
50        self.instance.clock.playing
51    }
52
53    /// `true` while [`Self::pause`] holds a playing clock. Implies
54    /// [`Self::is_clock_playing`], so the pair reads as three states, as
55    /// [`Self::is_playing`] and [`Self::is_pausing`] do; unlike `is_pausing`,
56    /// it still reads the hold after track 0 has finished.
57    pub fn is_clock_pausing(&self) -> bool {
58        self.instance.clock.pausing
59    }
60
61    /// `true` while the track stack would move the pose on a running clock for a
62    /// reason other than track 0's own animation stepping: a fade on any track,
63    /// or a source — other than track 0's main one — that plays, at a speed above
64    /// 0 and a weight above 0, on a track that is heard. A cleared, finished or
65    /// silenced track does not count, nor does one at speed 0 moved by hand, nor
66    /// a source a crossfade has retired; one a cancelled crossfade left behind
67    /// does.
68    ///
69    /// It does not read the clock: a Player that skips ticks while nothing moves
70    /// still runs one while the clock runs unheld ([`Self::is_clock_playing`]
71    /// and not [`Self::is_clock_pausing`]) and either track 0 plays
72    /// ([`Self::is_playing`]) or this holds. Read it before `update`: the
73    /// update a fade ends on clears the fade, so a read after it skips the
74    /// fade's last frame. With this, a Player keeps no copy of which tracks and
75    /// sources it has laid, which goes wrong the moment one is released inside
76    /// the runtime.
77    pub fn is_stack_in_motion(&self) -> bool {
78        let instance = &self.instance;
79        if instance.tracks.iter().any(|t| t.fade.is_some()) {
80            return true;
81        }
82        let primary = instance.primary_idx();
83        instance
84            .sources
85            .iter()
86            .enumerate()
87            .any(|(i, source)| i != primary && source.has_real_animation() && source.weight > 0.0 && source.controller.is_playing() && instance.tracks.get(source.track as usize).is_some_and(|t| t.is_audible() && t.policy.speed_scale > 0.0))
88    }
89
90    // The track 0 settings below read the track, which their setters write:
91    // set before an animation is laid, there is no controller holding them yet.
92
93    /// Track 0's [`Self::get_track_skip_frames`].
94    pub fn get_skip_frames(&self) -> bool {
95        self.instance.tracks[0].policy.is_skip_frames
96    }
97
98    /// Track 0's [`Self::get_track_playback_direction`].
99    pub fn get_playback_direction(&self) -> eval::playback_controller::PlaybackDirection {
100        self.instance.tracks[0].policy.playback_direction
101    }
102
103    /// Track 0's [`Self::get_track_playback_style`].
104    pub fn get_playback_style(&self) -> eval::playback_controller::PlaybackStyle {
105        self.instance.tracks[0].policy.playback_style
106    }
107
108    pub fn get_loop_count(&self) -> i32 {
109        self.instance.primary_source().controller.get_loop_count()
110    }
111
112    pub fn get_remaining_loops(&self) -> i32 {
113        self.instance.primary_source().controller.get_remaining_loops()
114    }
115
116    pub fn get_start_frame(&self) -> i32 {
117        self.instance.primary_source().controller.get_start_frame()
118    }
119
120    pub fn get_end_frame(&self) -> i32 {
121        self.instance.primary_source().controller.get_end_frame()
122    }
123
124    pub fn get_anime_data_start_frame(&self) -> i32 {
125        self.instance.primary_source().controller.get_anime_data_start_frame()
126    }
127
128    pub fn get_anime_data_end_frame(&self) -> i32 {
129        self.instance.primary_source().controller.get_anime_data_end_frame()
130    }
131
132    /// Track 0's [`Self::get_track_frame_rate`].
133    pub fn get_frame_rate(&self) -> i32 {
134        let policy = &self.instance.tracks[0].policy;
135        self.instance.track_main_controller(0).map_or(policy.frame_rate_override.unwrap_or(0), |c| c.get_frame_rate())
136    }
137
138    /// Track 0's [`Self::get_track_speed`].
139    pub fn get_speed_scale(&self) -> f32 {
140        self.instance.tracks[0].policy.speed_scale
141    }
142
143    /// Track 0's [`Self::set_track_skip_frames`].
144    pub fn set_skip_frames(&mut self, skip: bool) {
145        self.instance.set_track_policy(0, |p| p.is_skip_frames = skip, |c| c.set_skip_frames(skip));
146    }
147
148    pub fn set_loop_count(&mut self, loop_count: i32) {
149        self.instance.primary_source_mut().controller.set_loop_count(loop_count);
150    }
151
152    /// Track 0's [`Self::set_track_frame_rate`].
153    pub fn set_frame_rate(&mut self, frame_rate: i32) {
154        self.instance.set_track_policy(0, |p| p.set_frame_rate(frame_rate), |c| c.set_frame_rate(frame_rate));
155    }
156
157    /// Track 0's [`Self::set_track_playback_direction`].
158    pub fn set_playback_direction(&mut self, direction: eval::playback_controller::PlaybackDirection, style: eval::playback_controller::PlaybackStyle) {
159        self.instance.set_track_policy(
160            0,
161            |p| {
162                p.playback_direction = direction;
163                p.playback_style = style;
164            },
165            |c| c.set_playback_direction(direction, style),
166        );
167    }
168
169    /// Track 0's [`Self::set_track_speed`].
170    pub fn set_speed_scale(&mut self, speed_scale: f32) {
171        self.instance.set_track_policy(0, |p| p.set_speed_scale(speed_scale), |c| c.set_speed_scale(speed_scale));
172    }
173
174    /// Track 0's playback section, as
175    /// [`eval::playback_controller::PlaybackController::set_animation_section`]
176    /// sets it. An end before the start, both in range, is refused with
177    /// [`SSRuntimeError::InvalidParameter`], and the section and the playhead
178    /// stay as they were.
179    pub fn set_animation_section(&mut self, start_frame: i32, end_frame: i32) -> Result<(), SSRuntimeError> {
180        if self.instance.primary_source_mut().controller.set_animation_section(start_frame, end_frame) { Ok(()) } else { Err(SSRuntimeError::InvalidParameter) }
181    }
182
183    pub fn set_coordinate_system(&mut self, coordinate_system: crate::eval::SsCoordinateSystem) {
184        self.instance.coordinate_system = coordinate_system;
185        // The part bases live in this space, so they have to move with it.
186        self.prepare_part_bases();
187    }
188
189    pub fn get_coordinate_system(&self) -> crate::eval::SsCoordinateSystem {
190        self.instance.coordinate_system
191    }
192
193    pub fn set_origin(&mut self, origin: crate::eval::SsOrigin) {
194        self.instance.origin = origin;
195        // The part bases live in this space, so they have to move with it.
196        self.prepare_part_bases();
197    }
198
199    pub fn get_origin(&self) -> crate::eval::SsOrigin {
200        self.instance.origin
201    }
202
203    pub fn set_unit(&mut self, unit: crate::eval::SsUnit) {
204        self.instance.unit = unit;
205        // The part bases live in this space, so they have to move with it.
206        self.prepare_part_bases();
207    }
208
209    pub fn get_unit(&self) -> crate::eval::SsUnit {
210        self.instance.unit
211    }
212
213    /// Advance every source's controller by `delta` milliseconds and return the
214    /// frame to hand to [`Self::get_frame_data`]: that of track 0's main
215    /// animation, which `get_frame_data` validates against. A crossfade on
216    /// track 0 hands that role over when it begins, so across one this is the
217    /// incoming animation's frame.
218    ///
219    /// Nothing moves while the character's clock is stopped or held, fades
220    /// included. The controllers are still updated with no elapsed time, which
221    /// is what reports a frame a seek has just landed on.
222    pub fn update(&mut self, delta: f32) -> f32 {
223        self.instance.updates += 1;
224        let running = self.instance.clock.is_running();
225        let elapsed = if running { delta } else { 0.0 };
226        for source in self.instance.sources.iter_mut() {
227            if !source.has_real_animation() {
228                continue;
229            }
230            source.controller.update(elapsed);
231        }
232
233        if running {
234            self.advance_track_fades(delta);
235        }
236        self.collect_events();
237
238        self.get_frame_no()
239    }
240
241    /// Advance every track's fade by `delta`.
242    ///
243    /// A crossfade raises the incoming source's weight linearly while the
244    /// outgoing side sinks by the same amount, and on completion releases every
245    /// source on the track but the incoming one, which has been its main one
246    /// since the fade began. An alpha fade drives the track's `alpha` to its
247    /// target. A crossfade whose incoming source was released elsewhere cancels
248    /// itself.
249    fn advance_track_fades(&mut self, delta: f32) {
250        for track in 0..self.instance.tracks.len() {
251            let Some(fade) = self.instance.tracks[track].fade else {
252                continue;
253            };
254            match fade {
255                TrackFade::Cross { to, mut elapsed, duration } => {
256                    if self.instance.sources.get(to as usize).is_none_or(|s| !s.has_real_animation()) {
257                        self.instance.tracks[track].fade = None;
258                        continue;
259                    }
260                    elapsed += delta;
261                    let t = (elapsed / duration).clamp(0.0, 1.0);
262                    for (i, source) in self.instance.sources.iter_mut().enumerate() {
263                        // A source added to the track after the fade began has no
264                        // share, keeps the weight it was given, and is released with
265                        // the rest on completion.
266                        if i as u32 != to && source.track as usize == track && source.has_real_animation() && source.outgoing_share > 0.0 {
267                            source.weight = source.outgoing_share * (1.0 - t);
268                        }
269                    }
270                    self.instance.sources[to as usize].weight = t;
271                    if elapsed >= duration {
272                        self.replace_track_main(track as u32, to);
273                    } else {
274                        self.instance.tracks[track].fade = Some(TrackFade::Cross { to, elapsed, duration });
275                    }
276                }
277                TrackFade::Alpha { start, target, mut elapsed, duration } => {
278                    elapsed += delta;
279                    let t = (elapsed / duration).clamp(0.0, 1.0);
280                    self.instance.tracks[track].alpha = start + (target - start) * t;
281                    if elapsed >= duration {
282                        self.instance.tracks[track].alpha = target;
283                        self.instance.tracks[track].fade = None;
284                    } else {
285                        self.instance.tracks[track].fade = Some(TrackFade::Alpha { start, target, elapsed, duration });
286                    }
287                }
288            }
289        }
290    }
291
292    /// Heads track 0 out — back to its section start, loop count re-armed — and
293    /// starts the character's clock. The other tracks keep their playheads, as
294    /// they do when track 0 loops or ends on its own.
295    pub fn play(&mut self) {
296        self.instance.primary_source_mut().controller.play();
297        self.start_clock();
298    }
299
300    pub fn play_with_start_frame(&mut self, frame_no: f32) {
301        self.instance.primary_source_mut().controller.play_with_start_frame(frame_no);
302        self.start_clock();
303    }
304
305    fn start_clock(&mut self) {
306        self.instance.clock = CharacterClock { playing: true, pausing: false };
307    }
308
309    /// Holds the whole character in place: every track and every fade.
310    /// Idempotent, and ignored while the clock is stopped; `is_playing` stays
311    /// `true`.
312    pub fn pause(&mut self) {
313        if self.instance.clock.playing {
314            self.instance.clock.pausing = true;
315        }
316    }
317
318    /// Lifts a [`Self::pause`]. Idempotent, and not a way to start a stopped
319    /// animation — `play` rewinds, so it cannot serve as a resume.
320    pub fn resume(&mut self) {
321        self.instance.clock.pausing = false;
322    }
323
324    /// Stops the whole character where it stands: every track and every fade.
325    /// Nothing rewinds; only `play` starts it again.
326    pub fn stop(&mut self) {
327        self.instance.clock = CharacterClock::default();
328    }
329
330    pub fn set_frame_no(&mut self, frame: f32) {
331        self.instance.primary_source_mut().controller.set_frame_no(frame);
332    }
333
334    /// Sets the playback position based on `diff` (frames elapsed since
335    /// playback started, with per-instance speed already applied), applying
336    /// the configured section / loops / style / direction. Used by parent
337    /// Players to drive child Instance Players deterministically
338    /// across reverse, seek, and frame-skip operations.
339    pub fn set_frame_relative(&mut self, diff: f32) {
340        self.instance.primary_source_mut().controller.set_frame_relative(diff);
341    }
342
343    pub fn next_frame(&mut self) {
344        self.instance.primary_source_mut().controller.next_frame();
345    }
346
347    pub fn prev_frame(&mut self) {
348        self.instance.primary_source_mut().controller.prev_frame();
349    }
350}