Skip to main content

ssruntime/context/
tracks.rs

1//! The track API: laying animations on tracks, crossfades, and each track's and source's settings.
2
3use super::Context;
4use crate::mix::{LayerState, NO_SOURCE, SourceState, TrackBlend, TrackFade, TrackState, TrackSync, count_attribute_capacities};
5use crate::resource::fnv1a_hash_str;
6use crate::{error, eval};
7
8impl<'a> Context<'a> {
9    /// Put `name` on `track`, replacing whatever it was playing.
10    ///
11    /// Tracks are addressed by index and grow on demand: setting track 3 creates
12    /// 0..=3, the new ones silent. Track 0 is the structure track — its animation
13    /// supplies every discrete attribute and drives events — so it must be set up
14    /// first (`setup_animation` does exactly that), and this errors with
15    /// `AnimationNotFound` until it has been.
16    ///
17    /// The animation must live in the currently bound `AnimationResource`
18    /// (same-SSAB constraint). Cancels any fade in flight on the track.
19    pub fn set_track_animation(&mut self, track: u32, name: &str) -> Result<(), error::SSRuntimeError> {
20        self.set_track_animation_by_hash(track, fnv1a_hash_str(name))
21    }
22
23    pub fn set_track_animation_by_hash(&mut self, track: u32, hash: u32) -> Result<(), error::SSRuntimeError> {
24        let index = self.resolve_animation(hash)?;
25        self.ensure_set_up()?;
26        self.ensure_track(track)?;
27        let handle = self.attach_source(track, index, 1.0)?;
28        self.replace_track_main(track, handle);
29        Ok(())
30    }
31
32    /// The strength of a track, i.e. how much of it survives onto the pose the
33    /// tracks below produced. **This is the knob that always means something**: a
34    /// source's `weight` only decides proportions among the sources sharing one
35    /// track, and is silent when a source is the only one animating an attribute.
36    ///
37    /// Alpha is not clamped: values above 1 extrapolate, which is occasionally
38    /// what an overlay wants. At `0` the track contributes nothing. Track 0 at
39    /// alpha 0 resolves to the setup pose, which is how an animation fades out to
40    /// rest.
41    pub fn set_track_alpha(&mut self, track: u32, alpha: f32) -> Result<(), error::SSRuntimeError> {
42        let t = self.instance.tracks.get_mut(track as usize).ok_or(error::SSRuntimeError::InvalidParameter)?;
43        if alpha.is_nan() {
44            return Err(error::SSRuntimeError::InvalidParameter);
45        }
46        t.alpha = alpha;
47        Ok(())
48    }
49
50    pub fn get_track_alpha(&self, track: u32) -> Option<f32> {
51        self.instance.tracks.get(track as usize).map(|t| t.alpha)
52    }
53
54    /// How the track folds onto what is below: [`TrackBlend::Mix`] lerps toward
55    /// the track's pose, [`TrackBlend::Additive`] adds the track's offset from the
56    /// setup pose. Additive is for overlays that displace a performance rather
57    /// than replace it.
58    pub fn set_track_blend(&mut self, track: u32, blend: TrackBlend) -> Result<(), error::SSRuntimeError> {
59        let t = self.instance.tracks.get_mut(track as usize).ok_or(error::SSRuntimeError::InvalidParameter)?;
60        t.blend = blend;
61        Ok(())
62    }
63
64    pub fn get_track_blend(&self, track: u32) -> Option<TrackBlend> {
65        self.instance.tracks.get(track as usize).map(|t| t.blend)
66    }
67
68    /// Where the animations laid on `track` start: [`TrackSync::Free`] from the
69    /// head of their section, [`TrackSync::Start`] at the phase track 0 stands
70    /// at. It applies to everything laid on the track from then on —
71    /// `set_track_animation`, `crossfade` and `add_track_source` — so set it
72    /// before laying, and a track with nothing on it yet is created for it.
73    /// Like the rest of a track it goes with the stack on the next setup.
74    pub fn set_track_sync(&mut self, track: u32, sync: TrackSync) -> Result<(), error::SSRuntimeError> {
75        self.ensure_track(track)?;
76        self.instance.tracks[track as usize].sync = sync;
77        Ok(())
78    }
79
80    pub fn get_track_sync(&self, track: u32) -> Option<TrackSync> {
81        self.instance.tracks.get(track as usize).map(|t| t.sync)
82    }
83
84    /// Number of tracks that exist, including silent ones. Always at least 1.
85    pub fn get_track_count(&self) -> u32 {
86        self.instance.tracks.len() as u32
87    }
88
89    /// Silence a track: every source on it is deactivated and its fade cancelled.
90    /// Track 0 cannot be cleared — it carries the structure, and an instance with
91    /// no structure has no pose to emit. Fade it to alpha 0 instead.
92    pub fn clear_track(&mut self, track: u32) -> Result<(), error::SSRuntimeError> {
93        if track == 0 {
94            return Err(error::SSRuntimeError::InvalidParameter);
95        }
96        let t = self.instance.tracks.get_mut(track as usize).ok_or(error::SSRuntimeError::InvalidParameter)?;
97        t.main = NO_SOURCE;
98        t.fade = None;
99        for source in self.instance.sources.iter_mut() {
100            if source.track as u32 == track {
101                source.deactivate();
102            }
103        }
104        Ok(())
105    }
106
107    /// Fade `track` to `name` over `duration_ms` (the same time unit as
108    /// [`Context::update`]'s `delta`). The fade starts from whatever the track is
109    /// already playing, so there are no handles to pair up and nothing to clean up
110    /// afterwards: on completion the outgoing sources are deactivated.
111    ///
112    /// **The incoming animation becomes the track's main one the moment the fade
113    /// begins**, at weight 0 — on track 0 that makes it the primary, so the
114    /// frame, `is_playing` / `is_finished` / `just_looped`, the playback settings,
115    /// the discrete attributes and the events all speak for it from the call on.
116    /// The host has said where the character is going, and the outgoing side is
117    /// only its pose fading away: it neither reports state nor fires events
118    /// (unless its event threshold is lowered). Handing over on completion would
119    /// let an outgoing animation that runs out mid-fade report the character
120    /// finished, and then playing again once the fade completes.
121    ///
122    /// **Everything the track carries fades out together**, in the proportions it
123    /// carries them: the main animation, any `add_track_source` sources, and
124    /// whatever a cancelled fade left behind. Their weights are normalised to sum
125    /// to 1 when the fade begins and scaled down by `1 - t` from there, so the
126    /// pose does not jump when the fade begins or when it completes.
127    ///
128    /// Starting a crossfade while one is running on the same track folds the one
129    /// in flight into the new outgoing side, at the weights it has reached. There
130    /// is never more than one outgoing side, so fades restarted faster than they
131    /// run do not pile up, and every outgoing source is released on completion.
132    pub fn crossfade(&mut self, track: u32, name: &str, duration_ms: f32) -> Result<(), error::SSRuntimeError> {
133        self.crossfade_by_hash(track, fnv1a_hash_str(name), duration_ms)
134    }
135
136    pub fn crossfade_by_hash(&mut self, track: u32, hash: u32, duration_ms: f32) -> Result<(), error::SSRuntimeError> {
137        if duration_ms.is_nan() || duration_ms <= 0.0 {
138            return Err(error::SSRuntimeError::InvalidParameter);
139        }
140        let index = self.resolve_animation(hash)?;
141        self.ensure_set_up()?;
142        self.ensure_track(track)?;
143
144        let to = self.attach_source(track, index, 0.0)?;
145        let outgoing: f32 = self.instance.sources.iter().enumerate().filter(|&(i, s)| i as u32 != to && s.track as u32 == track && s.has_real_animation()).map(|(_, s)| s.weight.max(0.0)).sum();
146        if outgoing <= 0.0 {
147            // Nothing audible to fade from — this is just "start playing".
148            self.instance.sources[to as usize].weight = 1.0;
149            self.replace_track_main(track, to);
150            return Ok(());
151        }
152
153        // Normalise the outgoing side once, here, so the fade only has to scale it.
154        // Left as they were, a cancelled fade's leftovers or a host's weights of 2
155        // would change their share of the pose the moment the incoming one rose.
156        for (i, source) in self.instance.sources.iter_mut().enumerate() {
157            if i as u32 != to && source.track as u32 == track && source.has_real_animation() {
158                source.outgoing_share = source.weight.max(0.0) / outgoing;
159                source.weight = source.outgoing_share;
160            }
161        }
162        let t = &mut self.instance.tracks[track as usize];
163        t.main = to;
164        t.fade = Some(TrackFade::Cross { to, elapsed: 0.0, duration: duration_ms });
165        if track == 0 {
166            self.instance.primary = to;
167        }
168        Ok(())
169    }
170
171    /// Drive a track's `alpha` to `target` over `duration_ms`. Fading track 0 to 0
172    /// resolves the instance to its setup pose, which is what "fade out to rest"
173    /// means here — no placeholder animation required.
174    pub fn fade_track(&mut self, track: u32, target: f32, duration_ms: f32) -> Result<(), error::SSRuntimeError> {
175        if duration_ms.is_nan() || duration_ms <= 0.0 || target.is_nan() {
176            return Err(error::SSRuntimeError::InvalidParameter);
177        }
178        let t = self.instance.tracks.get_mut(track as usize).ok_or(error::SSRuntimeError::InvalidParameter)?;
179        t.fade = Some(TrackFade::Alpha { start: t.alpha, target, elapsed: 0.0, duration: duration_ms });
180        Ok(())
181    }
182
183    /// Progress of the fade in flight on `track`, in `[0.0, 1.0]`; `None` when the
184    /// track is not fading.
185    pub fn get_track_fade_progress(&self, track: u32) -> Option<f32> {
186        self.instance.tracks.get(track as usize)?.fade.as_ref().map(TrackFade::progress)
187    }
188
189    /// Cancel the fade on `track`, leaving alpha and weights where they stand.
190    pub fn cancel_track_fade(&mut self, track: u32) -> Result<(), error::SSRuntimeError> {
191        let t = self.instance.tracks.get_mut(track as usize).ok_or(error::SSRuntimeError::InvalidParameter)?;
192        t.fade = None;
193        Ok(())
194    }
195
196    /// Seek the track's current animation. This is how a modulation axis is
197    /// driven: author the axis as an animation and scrub it with the tracked
198    /// value.
199    pub fn set_track_frame(&mut self, track: u32, frame: f32) -> Result<(), error::SSRuntimeError> {
200        let handle = self.track_main(track)?;
201        self.instance.sources[handle as usize].controller.set_frame_no(frame);
202        Ok(())
203    }
204
205    pub fn get_track_frame(&self, track: u32) -> Option<f32> {
206        let handle = self.instance.tracks.get(track as usize)?.main;
207        let source = self.instance.sources.get(handle as usize)?;
208        (source.animation_idx >= 0).then(|| source.controller.get_frame_no())
209    }
210
211    /// The speed of `track`, as a multiple of each animation's frame rate. Kept
212    /// by the track: it reaches every source on it now and every one laid on it
213    /// later, so a crossfade or a `set_track_animation` does not reset it.
214    /// Track 0's is [`Self::set_speed_scale`]. Like every track setting it goes
215    /// with the track when `setup_animation` collapses the stack, except on
216    /// track 0.
217    pub fn set_track_speed(&mut self, track: u32, speed: f32) -> Result<(), error::SSRuntimeError> {
218        self.ensure_track(track)?;
219        self.instance.set_track_policy(track, |p| p.set_speed_scale(speed), |c| c.set_speed_scale(speed));
220        Ok(())
221    }
222
223    /// What [`Self::set_track_speed`] stored: a negative speed reads back as 0.
224    pub fn get_track_speed(&self, track: u32) -> Option<f32> {
225        Some(self.instance.tracks.get(track as usize)?.policy.speed_scale)
226    }
227
228    /// The frame rate `track` plays its animations at instead of the rate they
229    /// were authored at; `0` or a negative rate clears it. Kept by the track,
230    /// as [`Self::set_track_speed`] is.
231    pub fn set_track_frame_rate(&mut self, track: u32, frame_rate: i32) -> Result<(), error::SSRuntimeError> {
232        self.ensure_track(track)?;
233        self.instance.set_track_policy(track, |p| p.set_frame_rate(frame_rate), |c| c.set_frame_rate(frame_rate));
234        Ok(())
235    }
236
237    /// The rate `track`'s animation plays at: the override when one is set,
238    /// otherwise the rate it was authored at. `None` for a track that does not
239    /// exist; `0` for one with no animation and no override.
240    pub fn get_track_frame_rate(&self, track: u32) -> Option<i32> {
241        let policy = self.instance.tracks.get(track as usize)?.policy;
242        Some(self.instance.track_main_controller(track).map_or(policy.frame_rate_override.unwrap_or(0), |c| c.get_frame_rate()))
243    }
244
245    /// Whether `track` skips frames to keep up. Kept by the track, as
246    /// [`Self::set_track_speed`] is.
247    pub fn set_track_skip_frames(&mut self, track: u32, skip: bool) -> Result<(), error::SSRuntimeError> {
248        self.ensure_track(track)?;
249        self.instance.set_track_policy(track, |p| p.is_skip_frames = skip, |c| c.set_skip_frames(skip));
250        Ok(())
251    }
252
253    pub fn get_track_skip_frames(&self, track: u32) -> Option<bool> {
254        Some(self.instance.tracks.get(track as usize)?.policy.is_skip_frames)
255    }
256
257    /// The direction and style `track` plays its animations in. Kept by the
258    /// track, as [`Self::set_track_speed`] is.
259    pub fn set_track_playback_direction(&mut self, track: u32, direction: eval::playback_controller::PlaybackDirection, style: eval::playback_controller::PlaybackStyle) -> Result<(), error::SSRuntimeError> {
260        self.ensure_track(track)?;
261        self.instance.set_track_policy(
262            track,
263            |p| {
264                p.playback_direction = direction;
265                p.playback_style = style;
266            },
267            |c| c.set_playback_direction(direction, style),
268        );
269        Ok(())
270    }
271
272    pub fn get_track_playback_direction(&self, track: u32) -> Option<eval::playback_controller::PlaybackDirection> {
273        Some(self.instance.tracks.get(track as usize)?.policy.playback_direction)
274    }
275
276    pub fn get_track_playback_style(&self, track: u32) -> Option<eval::playback_controller::PlaybackStyle> {
277        Some(self.instance.tracks.get(track as usize)?.policy.playback_style)
278    }
279
280    /// How many times `track`'s animation plays before it holds its last frame;
281    /// `0` or a negative count loops forever. Unlike the speed this belongs to
282    /// the animation on the track, not the track: laying another animation
283    /// there starts it looping forever again, so state the count after laying
284    /// it. Track 0's is [`Self::set_loop_count`].
285    pub fn set_track_loop_count(&mut self, track: u32, loop_count: i32) -> Result<(), error::SSRuntimeError> {
286        let handle = self.track_main(track)?;
287        self.instance.sources[handle as usize].controller.set_loop_count(loop_count);
288        Ok(())
289    }
290
291    /// `-1` for a track that loops forever; `None` for one with no animation.
292    pub fn get_track_loop_count(&self, track: u32) -> Option<i32> {
293        Some(self.instance.track_main_controller(track)?.get_loop_count())
294    }
295
296    /// `true` once `track`'s animation has played its loop count out and holds
297    /// its last frame, as [`Self::is_finished`] is for track 0. A finished track
298    /// keeps mixing that frame in until the host fades or clears it. `false` for
299    /// a track with no animation.
300    pub fn is_track_finished(&self, track: u32) -> bool {
301        self.instance.track_main_controller(track).is_some_and(|c| c.is_finished())
302    }
303
304    /// `true` for the update in which `track`'s animation wrapped back to its
305    /// start, as [`Self::just_looped`] is for track 0.
306    pub fn track_just_looped(&self, track: u32) -> bool {
307        self.instance.track_main_controller(track).is_some_and(|c| c.just_looped())
308    }
309
310    /// Handle of the source carrying `track`'s animation. Needed to give that
311    /// animation a weight of its own once a track holds several — the animation
312    /// put there by `set_track_animation` starts at weight 1.
313    pub fn get_track_main_source(&self, track: u32) -> Option<u32> {
314        let main = self.instance.tracks.get(track as usize)?.main;
315        (main != NO_SOURCE).then_some(main)
316    }
317
318    /// Add another weighted source to `track`, for the case a track needs several
319    /// animations blended by proportion (locomotion: walk + run). Returns a stable
320    /// handle for [`Self::set_source_weight`].
321    ///
322    /// Most tracks never need this — one animation plus the track's `alpha`
323    /// covers layering, and `crossfade` covers transitions.
324    pub fn add_track_source(&mut self, track: u32, name: &str, weight: f32) -> Result<u32, error::SSRuntimeError> {
325        self.add_track_source_by_hash(track, fnv1a_hash_str(name), weight)
326    }
327
328    pub fn add_track_source_by_hash(&mut self, track: u32, hash: u32, weight: f32) -> Result<u32, error::SSRuntimeError> {
329        let index = self.resolve_animation(hash)?;
330        self.ensure_set_up()?;
331        self.ensure_track(track)?;
332        let handle = self.attach_source(track, index, weight)?;
333        // The first animation to land on a track becomes its main one, so callers
334        // may build a track entirely out of `add_track_source` calls.
335        if self.instance.tracks[track as usize].main == NO_SOURCE {
336            self.replace_track_main(track, handle);
337        }
338        Ok(handle)
339    }
340
341    /// Proportion of one source **within its track**. See [`Self::set_track_alpha`]
342    /// for the strength of the track as a whole.
343    pub fn set_source_weight(&mut self, handle: u32, weight: f32) -> Result<(), error::SSRuntimeError> {
344        let source = self.instance.sources.get_mut(handle as usize).ok_or(error::SSRuntimeError::InvalidParameter)?;
345        if source.animation_idx < 0 {
346            return Err(error::SSRuntimeError::InvalidParameter);
347        }
348        source.weight = weight;
349        Ok(())
350    }
351
352    pub fn get_source_weight(&self, handle: u32) -> Option<f32> {
353        let source = self.instance.sources.get(handle as usize)?;
354        (source.animation_idx >= 0).then_some(source.weight)
355    }
356
357    pub fn set_source_frame(&mut self, handle: u32, frame: f32) -> Result<(), error::SSRuntimeError> {
358        let source = self.instance.sources.get_mut(handle as usize).ok_or(error::SSRuntimeError::InvalidParameter)?;
359        if source.animation_idx < 0 {
360            return Err(error::SSRuntimeError::InvalidParameter);
361        }
362        source.controller.set_frame_no(frame);
363        Ok(())
364    }
365
366    /// Which animation `handle` plays, as an index into the pack's animations:
367    /// the order of [`AnimationResource::get_animation_names`] and of the
368    /// ssab's `animations()`. `None` for a handle that names no source.
369    ///
370    /// An index from [`Self::get_passed_event_indices`] addresses the `events()`
371    /// of the animation of the source that fired it, so this is how a Player
372    /// decodes an event. Track 0's included: a crossfade on track 0 hands it to
373    /// another animation, and a table kept from `setup_animation` is then the
374    /// wrong one.
375    ///
376    /// [`AnimationResource::get_animation_names`]: crate::AnimationResource::get_animation_names
377    pub fn get_source_animation_index(&self, handle: u32) -> Option<u32> {
378        let source = self.instance.sources.get(handle as usize)?;
379        source.has_real_animation().then_some(source.animation_idx as u32)
380    }
381
382    /// Which animation track 0's main source plays, as an index into the pack's
383    /// animations: the one `setup_animation` set up, until a `crossfade` or a
384    /// `set_track_animation` on track 0 hands the track to another, from the
385    /// call on. `None` before anything is set up.
386    pub fn get_current_animation_index(&self) -> Option<u32> {
387        self.get_source_animation_index(self.instance.primary)
388    }
389
390    pub fn get_source_frame(&self, handle: u32) -> Option<f32> {
391        let source = self.instance.sources.get(handle as usize)?;
392        (source.animation_idx >= 0).then(|| source.controller.get_frame_no())
393    }
394
395    /// Per-source event firing threshold. A source fires events once its weight
396    /// reaches the threshold. The default is `+∞`, so by default no source
397    /// fires but track 0's main source, which always does regardless of this
398    /// setting. Distinguish sources with
399    /// [`Self::get_passed_event_source_handles`].
400    pub fn set_source_event_threshold(&mut self, handle: u32, threshold: f32) -> Result<(), error::SSRuntimeError> {
401        let source = self.instance.sources.get_mut(handle as usize).ok_or(error::SSRuntimeError::InvalidParameter)?;
402        if !source.has_real_animation() {
403            return Err(error::SSRuntimeError::InvalidParameter);
404        }
405        source.event_threshold = threshold;
406        Ok(())
407    }
408
409    pub fn get_source_event_threshold(&self, handle: u32) -> Option<f32> {
410        let source = self.instance.sources.get(handle as usize)?;
411        source.has_real_animation().then_some(source.event_threshold)
412    }
413
414    /// How far into a crossfade on `track` the outgoing side keeps firing
415    /// events. It fires while its share of the track, `1 - t`, is at least
416    /// `threshold`, however many sources it holds: `0.5` keeps it firing for the
417    /// first half of the fade. The default, `+∞`, keeps it silent from the moment
418    /// the fade begins, which is where the incoming animation starts firing.
419    /// The outgoing sources' own thresholds are not consulted while they fade.
420    ///
421    /// A setting of the track rather than of a source, since the outgoing side
422    /// can be several sources, released when the fade completes; it applies to
423    /// every crossfade on the track until it is changed. Track 0 keeps it
424    /// across `setup_animation`, as it keeps its playback settings.
425    pub fn set_track_outgoing_event_threshold(&mut self, track: u32, threshold: f32) -> Result<(), error::SSRuntimeError> {
426        self.ensure_track(track)?;
427        self.instance.tracks[track as usize].outgoing_event_threshold = threshold;
428        Ok(())
429    }
430
431    pub fn get_track_outgoing_event_threshold(&self, track: u32) -> Option<f32> {
432        Some(self.instance.tracks.get(track as usize)?.outgoing_event_threshold)
433    }
434
435    /// Build the part bases for this instance's coordinate setup now, not on the
436    /// first frame. Runs when the animation or a coordinate setting changes.
437    pub(super) fn prepare_part_bases(&mut self) {
438        let Some(resource) = self.eval.resource else {
439            return;
440        };
441        let anim_idx = self.instance.primary_source().animation_idx;
442        if anim_idx < 0 {
443            return;
444        }
445        resource.animations[anim_idx as usize].part_bases(self.instance.coordinate_system, self.instance.origin, self.instance.unit);
446    }
447
448    fn resolve_animation(&self, hash: u32) -> Result<usize, error::SSRuntimeError> {
449        let Some(resource) = self.eval.resource else {
450            return Err(error::SSRuntimeError::NotLoaded);
451        };
452        resource.find_animation_index_by_hash(hash).ok_or(error::SSRuntimeError::AnimationNotFound)
453    }
454
455    /// `setup_animation` sizes the frame's buffers, so nothing can be laid on any
456    /// track before it has run, track 0 included.
457    fn ensure_set_up(&self) -> Result<(), error::SSRuntimeError> {
458        if self.instance.primary_source().has_real_animation() { Ok(()) } else { Err(error::SSRuntimeError::AnimationNotFound) }
459    }
460
461    /// Grow the stack so `track` exists. Track 0 exists from construction, so its
462    /// settings can be stated before `setup_animation`; any other track reports
463    /// `AnimationNotFound` until then, with no structure to layer onto.
464    fn ensure_track(&mut self, track: u32) -> Result<(), error::SSRuntimeError> {
465        if track != 0 && !self.instance.primary_source().has_real_animation() {
466            return Err(error::SSRuntimeError::AnimationNotFound);
467        }
468        if track as usize >= self.instance.tracks.len() {
469            self.instance.tracks.resize(track as usize + 1, TrackState::new());
470        }
471        Ok(())
472    }
473
474    /// Park a new source on `track`, reusing a slot left behind by a finished
475    /// fade when one is free so a long-lived instance does not grow a slot per
476    /// transition. Handles stay stable: a slot is only reused once inactive.
477    fn attach_source(&mut self, track: u32, animation_idx: usize, weight: f32) -> Result<u32, error::SSRuntimeError> {
478        let Some(resource) = self.eval.resource else {
479            return Err(error::SSRuntimeError::NotLoaded);
480        };
481        let metadata = &resource.animations[animation_idx];
482        let num_parts = metadata.cached_parts().len();
483        let (cell_c, color_c, shader_c, deform_c) = count_attribute_capacities(metadata);
484        let cursor_c = crate::eval::framedata::cursor_count(metadata.cached_parts());
485
486        metadata.part_bases(self.instance.coordinate_system, self.instance.origin, self.instance.unit);
487        let mut source = SourceState::new();
488        // The track's policy, not the defaults: a laid animation is played the
489        // way the host plays that track. Before `setup`, which derives the
490        // heading and the frame interval from it.
491        source.controller.adopt_policy(&self.instance.tracks[track as usize].policy);
492        source.controller.setup(metadata.start_frame, metadata.end_frame, metadata.fps);
493        // A laid source plays from the moment it is attached; the character's
494        // clock decides whether it actually moves.
495        source.controller.play();
496        if self.instance.tracks[track as usize].sync == TrackSync::Start
497            && let Some(phase) = self.primary_phase()
498        {
499            let c = &mut source.controller;
500            let frame = c.get_start_frame() as f32 + phase * (c.get_end_frame() - c.get_start_frame() + 1) as f32;
501            c.set_frame_no(frame);
502        }
503        source.animation_idx = animation_idx as i32;
504        source.weight = weight;
505        source.track = track as u16;
506
507        let free = self.instance.sources.iter().position(|s| s.animation_idx < 0);
508        let handle = match free {
509            Some(i) => {
510                self.instance.sources[i] = source;
511                self.instance.layers[i].resize_for_parts(num_parts, cursor_c, cell_c, color_c, shader_c, deform_c);
512                i
513            }
514            None => {
515                self.instance.sources.push(source);
516                let mut layer = LayerState::new();
517                layer.resize_for_parts(num_parts, cursor_c, cell_c, color_c, shader_c, deform_c);
518                self.instance.layers.push(layer);
519                self.instance.sources.len() - 1
520            }
521        };
522        Ok(handle as u32)
523    }
524
525    /// How far through its section track 0's main animation stands, in
526    /// `[0.0, 1.0)`; `None` with nothing set up. Measured by position, not by
527    /// progress, so a backward or ping-pong return leg reads where it stands.
528    /// During a crossfade on track 0 this is the incoming animation, which takes
529    /// the main role when the fade begins; the source a crossfade is laying
530    /// is attached before that, so it reads the outgoing one it is replacing.
531    fn primary_phase(&self) -> Option<f32> {
532        let source = self.instance.primary_source();
533        if !source.has_real_animation() {
534            return None;
535        }
536        let c = &source.controller;
537        let length = (c.get_end_frame() - c.get_start_frame() + 1) as f32;
538        Some(((c.get_frame_no() - c.get_start_frame() as f32) / length).clamp(0.0, 1.0))
539    }
540
541    /// Make `handle` the track's animation, retiring whatever held that role.
542    pub(super) fn replace_track_main(&mut self, track: u32, handle: u32) {
543        let previous = self.instance.tracks[track as usize].main;
544        if previous != NO_SOURCE && previous != handle {
545            self.instance.sources[previous as usize].deactivate();
546        }
547        // Any other source on this track belonged to the animation being replaced.
548        for (i, source) in self.instance.sources.iter_mut().enumerate() {
549            if i as u32 != handle && source.track as u32 == track {
550                source.deactivate();
551            }
552        }
553        let t = &mut self.instance.tracks[track as usize];
554        t.main = handle;
555        t.fade = None;
556        if track == 0 {
557            self.instance.primary = handle;
558        }
559    }
560
561    fn track_main(&self, track: u32) -> Result<u32, error::SSRuntimeError> {
562        let t = self.instance.tracks.get(track as usize).ok_or(error::SSRuntimeError::InvalidParameter)?;
563        if t.main == NO_SOURCE {
564            return Err(error::SSRuntimeError::InvalidParameter);
565        }
566        Ok(t.main)
567    }
568}