Skip to main content

ssruntime/
mix.rs

1//! The track stack: its sources and tracks, the pose buffers each source is extracted into, and the mix that folds them into one pose.
2
3use alloc::vec::Vec;
4
5use crate::resource::AnimationMetadata;
6use crate::{eval, runtime};
7
8/// Per-layer pose buffers — the immediate output of `extract_pose`,
9/// before any cross-layer composition. SRT / Color / Cell ID / Vertex /
10/// Deform / Cursor live here, as do the pose-derived per-part buffers
11/// (`cell_meta_per_part`, `cell_texture_hashes`, `local_vertices`) that
12/// are written in lockstep with the pose evaluation.
13///
14/// An instance has one per source, and the resolved one the mix writes
15/// (`InstanceState::resolved_layer`). While one source plays alone, its pose
16/// is extracted straight into the resolved layer, and its own layer stays
17/// unallocated until a mix needs it.
18pub(crate) struct LayerState<'a> {
19    pub(crate) parts_vec: Vec<crate::runtime::framedata::ss::runtime::PartState>,
20    pub(crate) cell_vec: Vec<crate::runtime::framedata::ss::runtime::PartAttributeCell>,
21    pub(crate) parts_color_vec: Vec<crate::runtime::framedata::ss::runtime::PartAttributePartColor>,
22    pub(crate) shader_vec: Vec<crate::runtime::framedata::ss::runtime::PartAttributeShader>,
23    pub(crate) vertex_vec: Vec<crate::runtime::framedata::ss::runtime::PartAttributeVertex>,
24    pub(crate) deform_vec: Vec<flatbuffers::WIPOffset<crate::runtime::framedata::ss::runtime::PartAttributeDeform<'a>>>,
25    pub(crate) cursors: Vec<u32>,
26    pub(crate) cell_meta_per_part: Vec<f32>,
27    pub(crate) cell_texture_hashes: Vec<u32>,
28    /// Each part's cell, as an index for `KeyColumns::cell`: the one its UVs sample.
29    pub(crate) cell_ids: Vec<Option<u32>>,
30    pub(crate) local_vertices: Vec<f32>,
31    /// Per-part mesh deform retained from Phase 1 for the Phase 2 skinning pass.
32    pub(crate) mesh_deform: Vec<crate::eval::framedata::DeformSlot<crate::eval::framedata::PartDeformFrame>>,
33    pub(crate) raw_vertex_deform: Vec<crate::eval::framedata::DeformSlot<crate::eval::framedata::RawVertexDeform>>,
34    /// Per-part attribute coverage of the animation this layer was extracted
35    /// from (`CachedPartData::coverage`), consulted by [`mix_tracks`]. Copied in
36    /// after pose extraction; empty means none was recorded (`layer_coverage`).
37    pub(crate) coverage_vec: Vec<crate::runtime::framedata::ss::runtime::UpdateAttributeFlags>,
38}
39
40impl<'a> LayerState<'a> {
41    pub(crate) fn new() -> Self {
42        Self {
43            parts_vec: Vec::new(),
44            cell_vec: Vec::new(),
45            parts_color_vec: Vec::new(),
46            shader_vec: Vec::new(),
47            vertex_vec: Vec::new(),
48            deform_vec: Vec::new(),
49            cursors: Vec::new(),
50            cell_meta_per_part: Vec::new(),
51            cell_texture_hashes: Vec::new(),
52            cell_ids: Vec::new(),
53            local_vertices: Vec::new(),
54            mesh_deform: Vec::new(),
55            raw_vertex_deform: Vec::new(),
56            coverage_vec: Vec::new(),
57        }
58    }
59
60    pub(crate) fn resize_for_parts(&mut self, num_parts: usize, cursor_c: usize, cell_c: usize, color_c: usize, shader_c: usize, deform_c: usize) {
61        self.parts_vec.clear();
62        self.parts_vec.reserve(num_parts);
63        self.cell_vec.clear();
64        self.cell_vec.reserve(cell_c);
65        self.parts_color_vec.clear();
66        self.parts_color_vec.reserve(color_c);
67        self.shader_vec.clear();
68        self.shader_vec.reserve(shader_c);
69        self.deform_vec.clear();
70        self.deform_vec.reserve(deform_c);
71
72        self.cursors.clear();
73        self.cursors.resize(cursor_c, 0);
74        self.cell_meta_per_part.clear();
75        self.cell_meta_per_part.resize(num_parts * 6, 0.0);
76        self.cell_texture_hashes.clear();
77        self.cell_texture_hashes.resize(num_parts, 0);
78        self.cell_ids.clear();
79        self.cell_ids.reserve(num_parts);
80        self.local_vertices.clear();
81        self.local_vertices.resize(num_parts * crate::eval::framedata::LOCAL_VERTICES_STRIDE, 0.0);
82        self.raw_vertex_deform.clear();
83        self.raw_vertex_deform.resize_with(num_parts, || None);
84    }
85
86    /// Size the buffers for `metadata`'s animation unless they already are: the
87    /// first time a source's own layer is extracted into, or after the layer
88    /// last held a different part count.
89    pub(crate) fn fit(&mut self, metadata: &AnimationMetadata<'_>) {
90        let num_parts = metadata.cached_parts().len();
91        let sized = self.raw_vertex_deform.len() == num_parts && self.cell_texture_hashes.len() == num_parts && self.cell_meta_per_part.len() == num_parts * 6 && self.local_vertices.len() == num_parts * crate::eval::framedata::LOCAL_VERTICES_STRIDE;
92        if !sized {
93            let (cell_c, color_c, shader_c, deform_c) = count_attribute_capacities(metadata);
94            self.resize_for_parts(num_parts, crate::eval::framedata::cursor_count(metadata.cached_parts()), cell_c, color_c, shader_c, deform_c);
95        }
96    }
97}
98
99pub(crate) struct SourceState {
100    pub(crate) animation_idx: i32,
101    pub(crate) controller: eval::playback_controller::PlaybackController,
102    /// Which track this source plays on. Sources sharing a track are mixed by
103    /// weight; tracks fold onto each other by `TrackState::alpha`.
104    pub(crate) track: u16,
105    pub(crate) weight: f32,
106    /// Minimum weight at which this source's events should fire (only meaningful
107    /// for non-primary sources). The default, [`NO_EVENT_THRESHOLD`], keeps
108    /// "track 0's animation fires events; other sources never do" — the caller
109    /// opts a source in by lowering the threshold to <= its current weight.
110    pub(crate) event_threshold: f32,
111    /// This source's part of the outgoing side while its track crossfades: its
112    /// weight when the fade began, normalised against every source the track
113    /// carried then. The fade scales it by `1 - t`, so the outgoing side keeps
114    /// its proportions and the track's weights sum to 1 throughout. Only read
115    /// while the track's crossfade runs; the next crossfade overwrites it.
116    pub(crate) outgoing_share: f32,
117}
118
119/// The default event threshold: no weight reaches it, so a source fires only
120/// once the host lowers it.
121pub(crate) const NO_EVENT_THRESHOLD: f32 = f32::INFINITY;
122
123impl SourceState {
124    pub(crate) fn new() -> Self {
125        Self { animation_idx: -1, controller: eval::playback_controller::PlaybackController::new(), track: 0, weight: 1.0, event_threshold: NO_EVENT_THRESHOLD, outgoing_share: 0.0 }
126    }
127
128    pub(crate) fn is_active(&self) -> bool {
129        self.animation_idx != -1 && self.weight > 0.0
130    }
131
132    /// Release the slot. It keeps its position so live handles never shift, and
133    /// `attach_source` may hand it out again.
134    pub(crate) fn deactivate(&mut self) {
135        self.controller.reset_setup();
136        self.animation_idx = -1;
137        self.weight = 0.0;
138        self.event_threshold = NO_EVENT_THRESHOLD;
139        self.outgoing_share = 0.0;
140    }
141
142    /// True for slots that carry an animation, not the released `-1`. Use this
143    /// whenever a method needs a valid `metadata`/`controller`-backed source.
144    pub(crate) fn has_real_animation(&self) -> bool {
145        self.animation_idx >= 0
146    }
147}
148
149/// How a track folds onto the pose the tracks below it produced.
150#[derive(Debug, Clone, Copy, PartialEq, Eq)]
151pub enum TrackBlend {
152    /// `resolved = lerp(below, track_pose, alpha)`. The default.
153    Mix,
154    /// `resolved = below + alpha * (track_pose - setup_pose)`. For overlays that
155    /// offset what is underneath instead of replacing it.
156    Additive,
157}
158
159/// How the animation laid on a track keeps time with track 0. Sync means the
160/// normalised phase: how far through its section an animation stands, from
161/// `0.0` at the section start towards `1.0` at its end, so animations of
162/// different lengths line up by proportion rather than by frame.
163#[derive(Debug, Clone, Copy, PartialEq, Eq)]
164pub enum TrackSync {
165    /// The animation starts from the head of its section and keeps its own
166    /// time. The default; right for one-off motions such as a blink.
167    Free,
168    /// The animation starts at the phase track 0's main animation stands at
169    /// when it is laid on, then runs on the shared clock. Aligned once, not
170    /// held: lengths or speeds that differ drift apart again.
171    Start,
172}
173
174/// One track of the stack. Tracks fold in ascending index order onto the setup
175/// pose; `alpha` is the strength knob (unlike a source's `weight`, which only
176/// decides proportions *within* a track).
177#[derive(Debug, Clone, Copy)]
178pub(crate) struct TrackState {
179    pub(crate) alpha: f32,
180    pub(crate) blend: TrackBlend,
181    /// Where the animations laid on this track start.
182    pub(crate) sync: TrackSync,
183    /// How the animations laid on this track are played: the speed, the
184    /// frame-rate override, the frame skip, the direction and style. Every source
185    /// laid on the track takes it, and changing it reaches the sources already
186    /// there, so it survives a crossfade or a `set_track_animation`.
187    pub(crate) policy: eval::playback_controller::PlaybackPolicy,
188    /// How far into a crossfade the outgoing side keeps firing events: it fires
189    /// while its share of the track, `1 - t`, is at least this. The default,
190    /// [`NO_EVENT_THRESHOLD`], keeps it silent from the moment the fade begins.
191    pub(crate) outgoing_event_threshold: f32,
192    /// Handle of the source carrying this track's animation, or [`NO_SOURCE`].
193    /// Extra sources added for weighted blending sit alongside it.
194    pub(crate) main: u32,
195    pub(crate) fade: Option<TrackFade>,
196}
197
198/// `TrackState::main` when a track has no animation on it.
199pub(crate) const NO_SOURCE: u32 = u32::MAX;
200
201impl TrackState {
202    pub(crate) fn new() -> Self {
203        Self { alpha: 1.0, blend: TrackBlend::Mix, sync: TrackSync::Free, policy: eval::playback_controller::PlaybackPolicy::DEFAULT, outgoing_event_threshold: NO_EVENT_THRESHOLD, main: NO_SOURCE, fade: None }
204    }
205
206    /// A track contributes nothing at alpha 0 — `Mix` returns the pose below and
207    /// `Additive` adds a zero-scaled delta.
208    pub(crate) fn is_audible(&self) -> bool {
209        self.alpha > 0.0
210    }
211}
212
213/// A fade in flight on one track. Advanced by [`Context::update`](crate::Context::update).
214#[derive(Debug, Clone, Copy)]
215pub(crate) enum TrackFade {
216    /// Raise `to` from weight 0 to 1 while every other source the track carried
217    /// when the fade began sinks from its `outgoing_share` to 0, then retire them.
218    Cross { to: u32, elapsed: f32, duration: f32 },
219    /// Drive the track's `alpha` from `start` to `target`.
220    Alpha { start: f32, target: f32, elapsed: f32, duration: f32 },
221}
222
223impl TrackFade {
224    pub(crate) fn progress(&self) -> f32 {
225        let (elapsed, duration) = match self {
226            TrackFade::Cross { elapsed, duration, .. } | TrackFade::Alpha { elapsed, duration, .. } => (*elapsed, *duration),
227        };
228        (elapsed / duration).clamp(0.0, 1.0)
229    }
230}
231
232pub(crate) fn count_attribute_capacities(metadata: &AnimationMetadata<'_>) -> (usize, usize, usize, usize) {
233    let mut cell_c = 0;
234    let mut color_c = 0;
235    let mut shader_c = 0;
236    let mut deform_c = 0;
237    for p in metadata.cached_parts() {
238        if p.run(crate::eval::framedata::IDX_ATTRIBUTECELL).is_some() {
239            cell_c += 1;
240        }
241        if p.run(crate::eval::framedata::IDX_ATTRIBUTEPARTCOLOR).is_some() {
242            color_c += 1;
243        }
244        if p.run(crate::eval::framedata::IDX_ATTRIBUTESHADER).is_some() {
245            shader_c += 1;
246        }
247        if p.run(crate::eval::framedata::IDX_ATTRIBUTEDEFORM).is_some() {
248            deform_c += 1;
249        }
250    }
251    (cell_c, color_c, shader_c, deform_c)
252}
253
254/// Make room for `total` elements in all, whatever `v` holds now.
255pub(crate) fn reserve_total<T>(v: &mut Vec<T>, total: usize) {
256    v.reserve(total.saturating_sub(v.len()));
257}
258
259// Indices into the mix's per-attribute weight / accumulator arrays. One entry
260// per continuous value the mix blends; `MIX_ATTR_FLAGS` maps each to the
261// coverage bit that decides whether a source votes on it.
262const MIX_POS_X: usize = 0;
263const MIX_POS_Y: usize = 1;
264const MIX_POS_Z: usize = 2;
265const MIX_ROT_X: usize = 3;
266const MIX_ROT_Y: usize = 4;
267const MIX_ROT_Z: usize = 5;
268const MIX_SCL_X: usize = 6;
269const MIX_SCL_Y: usize = 7;
270const MIX_LOSCL_X: usize = 8;
271const MIX_LOSCL_Y: usize = 9;
272const MIX_ALPHA: usize = 10;
273const MIX_LOCAL_ALPHA: usize = 11;
274const MIX_PIVOT_X: usize = 12;
275const MIX_PIVOT_Y: usize = 13;
276const MIX_ANCHOR_X: usize = 14;
277const MIX_ANCHOR_Y: usize = 15;
278const MIX_SIZE_X: usize = 16;
279const MIX_SIZE_Y: usize = 17;
280const MIX_UV_TX: usize = 18;
281const MIX_UV_TY: usize = 19;
282const MIX_UV_RZ: usize = 20;
283const MIX_UV_SX: usize = 21;
284const MIX_UV_SY: usize = 22;
285const MIX_BOUND_R: usize = 23;
286const MIX_MASK: usize = 24;
287const MIX_SKEW_X: usize = 25;
288const MIX_SKEW_Y: usize = 26;
289const MIX_ATTR_COUNT: usize = 27;
290
291/// Coverage bit gating each mixed attribute, in `MIX_*` index order.
292/// `skew_x` / `skew_y` come from one source array and therefore share one bit.
293pub(crate) const MIX_ATTR_FLAGS: [runtime::framedata::ss::runtime::UpdateAttributeFlags; MIX_ATTR_COUNT] = {
294    use runtime::framedata::ss::runtime::UpdateAttributeFlags as F;
295    [
296        F::AttributePosX,
297        F::AttributePosY,
298        F::AttributePosZ,
299        F::AttributeRotX,
300        F::AttributeRotY,
301        F::AttributeRotZ,
302        F::AttributeSclX,
303        F::AttributeSclY,
304        F::AttributeLosclX,
305        F::AttributeLosclY,
306        F::AttributeAlpha,
307        F::AttributeLoAlpha,
308        F::AttributePivotX,
309        F::AttributePivotY,
310        F::AttributeAnchorX,
311        F::AttributeAnchorY,
312        F::AttributeSizeX,
313        F::AttributeSizeY,
314        F::AttributeUvtX,
315        F::AttributeUvtY,
316        F::AttributeUvrZ,
317        F::AttributeUvsX,
318        F::AttributeUvsY,
319        F::AttributeBoundr,
320        F::AttributeMask,
321        F::AttributeSkew,
322        F::AttributeSkew,
323    ]
324};
325
326/// Which attributes `layer`'s source animates on `part`.
327///
328/// An empty `coverage_vec` means no coverage was recorded for this layer, which
329/// reads as "covers everything": that keeps hand-built layers (unit tests)
330/// working, and an unrecorded layer contributes rather than silently dropping out
331/// of the mix.
332#[inline]
333fn layer_coverage(layer: &LayerState<'_>, part: usize) -> runtime::framedata::ss::runtime::UpdateAttributeFlags {
334    layer.coverage_vec.get(part).copied().unwrap_or(runtime::framedata::ss::runtime::UpdateAttributeFlags::all())
335}
336
337/// Read a `PartState`'s mixed attributes into `out`, in `MIX_*` index order.
338#[inline]
339fn read_attrs(s: &runtime::framedata::ss::runtime::PartState, out: &mut [f32; MIX_ATTR_COUNT]) {
340    out[MIX_POS_X] = s.position_x();
341    out[MIX_POS_Y] = s.position_y();
342    out[MIX_POS_Z] = s.position_z();
343    out[MIX_ROT_X] = s.rotation_x();
344    out[MIX_ROT_Y] = s.rotation_y();
345    out[MIX_ROT_Z] = s.rotation_z();
346    out[MIX_SCL_X] = s.scale_x();
347    out[MIX_SCL_Y] = s.scale_y();
348    out[MIX_LOSCL_X] = s.local_scale_x();
349    out[MIX_LOSCL_Y] = s.local_scale_y();
350    out[MIX_ALPHA] = s.alpha();
351    out[MIX_LOCAL_ALPHA] = s.local_alpha();
352    out[MIX_PIVOT_X] = s.pivot_x();
353    out[MIX_PIVOT_Y] = s.pivot_y();
354    out[MIX_ANCHOR_X] = s.anchor_x();
355    out[MIX_ANCHOR_Y] = s.anchor_y();
356    out[MIX_SIZE_X] = s.size_x();
357    out[MIX_SIZE_Y] = s.size_y();
358    out[MIX_UV_TX] = s.uv_translation_x();
359    out[MIX_UV_TY] = s.uv_translation_y();
360    out[MIX_UV_RZ] = s.uv_rotation_z();
361    out[MIX_UV_SX] = s.uv_scale_x();
362    out[MIX_UV_SY] = s.uv_scale_y();
363    out[MIX_BOUND_R] = s.bounding_radius();
364    out[MIX_MASK] = s.mask();
365    out[MIX_SKEW_X] = s.skew_x();
366    out[MIX_SKEW_Y] = s.skew_y();
367}
368
369/// Write back the attributes some track spoke for; the rest keep what the
370/// primary's extracted pose already held.
371#[inline]
372fn write_attrs(s: &mut runtime::framedata::ss::runtime::PartState, v: &[f32; MIX_ATTR_COUNT], touched: &[bool; MIX_ATTR_COUNT]) {
373    macro_rules! w {
374        ($idx:expr, $setter:ident) => {
375            if touched[$idx] {
376                s.$setter(v[$idx]);
377            }
378        };
379    }
380    w!(MIX_POS_X, set_position_x);
381    w!(MIX_POS_Y, set_position_y);
382    w!(MIX_POS_Z, set_position_z);
383    w!(MIX_ROT_X, set_rotation_x);
384    w!(MIX_ROT_Y, set_rotation_y);
385    w!(MIX_ROT_Z, set_rotation_z);
386    w!(MIX_SCL_X, set_scale_x);
387    w!(MIX_SCL_Y, set_scale_y);
388    w!(MIX_LOSCL_X, set_local_scale_x);
389    w!(MIX_LOSCL_Y, set_local_scale_y);
390    w!(MIX_ALPHA, set_alpha);
391    w!(MIX_LOCAL_ALPHA, set_local_alpha);
392    w!(MIX_PIVOT_X, set_pivot_x);
393    w!(MIX_PIVOT_Y, set_pivot_y);
394    w!(MIX_ANCHOR_X, set_anchor_x);
395    w!(MIX_ANCHOR_Y, set_anchor_y);
396    w!(MIX_SIZE_X, set_size_x);
397    w!(MIX_SIZE_Y, set_size_y);
398    w!(MIX_UV_TX, set_uv_translation_x);
399    w!(MIX_UV_TY, set_uv_translation_y);
400    w!(MIX_UV_RZ, set_uv_rotation_z);
401    w!(MIX_UV_SX, set_uv_scale_x);
402    w!(MIX_UV_SY, set_uv_scale_y);
403    w!(MIX_BOUND_R, set_bounding_radius);
404    w!(MIX_MASK, set_mask);
405    w!(MIX_SKEW_X, set_skew_x);
406    w!(MIX_SKEW_Y, set_skew_y);
407}
408
409/// Resolve every track onto one pose in `resolved_layer`.
410///
411/// Two levels. **Within a track**, its sources are weighted-summed, normalized
412/// **per attribute** so a source that does not animate an attribute neither
413/// contributes to it nor dilutes the sources that do (the coverage rule).
414/// **Between tracks**, each track folds onto the pose below it in ascending
415/// order — `Mix` lerps by the track's `alpha`, `Additive` adds `alpha` times the
416/// track's offset from the setup pose. The stack's floor is the setup pose, so a
417/// track's `alpha` always means something even where nothing below it has an
418/// opinion; a source's `weight`, by contrast, only decides proportions among the
419/// sources of one track.
420///
421/// Attributes no track speaks for keep `layers[primary_idx]`'s value, and every
422/// discrete attribute (cell / part_color / shader / vertex / deform indices, flip
423/// flags, hide, priority, texture, cell_meta, mesh_deform) is copied from there
424/// verbatim — tracks never blend those. `update_flag` is OR-merged across every
425/// contributing source so Stage B sees each attribute that took part.
426///
427/// A source is "active" when `animation_idx >= 0 && weight > 0.0`; a track is
428/// audible when `alpha > 0.0`. With neither, the resolved pose equals
429/// `layers[primary_idx]`.
430pub(crate) fn mix_tracks<'b>(sources: &[SourceState], layers: &[LayerState<'b>], tracks: &[TrackState], primary_idx: usize, setup_pose: &[runtime::framedata::ss::runtime::PartState], resolved_layer: &mut LayerState<'b>) {
431    let primary = &layers[primary_idx];
432    let num_parts = primary.parts_vec.len();
433
434    // Discrete structure: copied from primary verbatim.
435    resolved_layer.cell_vec.clone_from(&primary.cell_vec);
436    resolved_layer.parts_color_vec.clone_from(&primary.parts_color_vec);
437    resolved_layer.shader_vec.clone_from(&primary.shader_vec);
438    resolved_layer.deform_vec.clone_from(&primary.deform_vec);
439    resolved_layer.cell_meta_per_part.clone_from(&primary.cell_meta_per_part);
440    resolved_layer.cell_texture_hashes.clone_from(&primary.cell_texture_hashes);
441    // The cell each part shows is the primary's; the UVs sample it.
442    resolved_layer.cell_ids.clone_from(&primary.cell_ids);
443
444    // mesh_deform holds variable-size per-part deltas; deep-copy from primary.
445    if resolved_layer.mesh_deform.len() != num_parts {
446        resolved_layer.mesh_deform.resize_with(num_parts, || None);
447    }
448    for (dst, src) in resolved_layer.mesh_deform.iter_mut().zip(primary.mesh_deform.iter()) {
449        match src.as_deref() {
450            Some(src) => {
451                let dst = dst.get_or_insert_with(Default::default);
452                dst.indices.clear();
453                dst.indices.extend_from_slice(&src.indices);
454                dst.dx.clear();
455                dst.dx.extend_from_slice(&src.dx);
456                dst.dy.clear();
457                dst.dy.extend_from_slice(&src.dy);
458            }
459            None => {
460                if let Some(dst) = dst.as_deref_mut() {
461                    dst.clear();
462                }
463            }
464        }
465    }
466
467    // Stage B fills these; clear them so stale post-mix data is never read.
468    resolved_layer.vertex_vec.clear();
469    for v in resolved_layer.local_vertices.iter_mut() {
470        *v = 0.0;
471    }
472
473    resolved_layer.parts_vec.clear();
474    resolved_layer.parts_vec.reserve(num_parts);
475    if resolved_layer.raw_vertex_deform.len() != num_parts {
476        resolved_layer.raw_vertex_deform.clear();
477        resolved_layer.raw_vertex_deform.resize_with(num_parts, || None);
478    } else {
479        for slot in resolved_layer.raw_vertex_deform.iter_mut().flatten() {
480            slot.present = false;
481        }
482    }
483
484    for i in 0..num_parts {
485        let primary_state = primary.parts_vec[i];
486        let mut mixed = primary_state;
487
488        // The stack starts at the setup pose and each track folds onto it in
489        // ascending order. `cur` carries the running resolved value per attribute;
490        // `touched` records which ones any track actually spoke for, so the rest
491        // keep the primary's value.
492        let floor = setup_pose.get(i).copied().unwrap_or(primary_state);
493        let mut cur = [0.0f32; MIX_ATTR_COUNT];
494        let mut base = [0.0f32; MIX_ATTR_COUNT];
495        read_attrs(&floor, &mut cur);
496        base.copy_from_slice(&cur);
497        let mut touched = [false; MIX_ATTR_COUNT];
498
499        let mut cur_dx = wide::f32x4::splat(0.0);
500        let mut cur_dy = wide::f32x4::splat(0.0);
501        let mut deform_present = false;
502        let mut flag = runtime::framedata::ss::runtime::UpdateAttributeFlags::empty();
503
504        for (t, track) in tracks.iter().enumerate() {
505            // A silent track is not skipped: its sources still decide which
506            // attributes the stack speaks for, and folding at `alpha == 0` is a
507            // no-op that leaves the floor showing. That is what makes fading a
508            // track to 0 resolve to the setup pose instead of freezing the pose
509            // the source last produced.
510
511            // Level 1: weighted mix of this track's own sources, per attribute
512            // (the coverage rule). Without it, a source that carries no keyframe
513            // array for an attribute would vote `evaluate_part`'s hardcoded default
514            // and drag the result toward a number that means nothing — up to
515            // thousands of pixels on real assets. Coverage is per animation
516            // (`CachedPartData::coverage`), never per frame.
517            let mut wsum = [0.0f32; MIX_ATTR_COUNT];
518            let mut acc = [0.0f32; MIX_ATTR_COUNT];
519            let mut deform_weight = 0.0_f32;
520            let mut dx_acc = wide::f32x4::splat(0.0);
521            let mut dy_acc = wide::f32x4::splat(0.0);
522
523            for (j, src) in sources.iter().enumerate() {
524                if src.track as usize != t || !src.is_active() {
525                    continue;
526                }
527                // A source whose layer is shorter than the primary's part list does
528                // not cover the trailing indices at all (mismatched part counts,
529                // parts correlated positionally). Skipping it here instead of
530                // indexing out of bounds is what keeps such a blend from panicking
531                // and aborting the host.
532                let Some(state) = layers[j].parts_vec.get(i) else {
533                    continue;
534                };
535
536                // Per-attribute weights: `w` where this source covers the attribute,
537                // 0 where it does not. Materializing them keeps the accumulation
538                // branch-free and straight-line, which is what lets LLVM keep
539                // vectorizing it.
540                //
541                // Two cheaper forms measured no faster: a "coverage is uniform across
542                // sources" fast path, which almost never fires, and a branch-free
543                // bit-mask form, since the cost is the stores. Single-source playback
544                // does not reach here at all.
545                let w = src.weight;
546                let cov = layer_coverage(&layers[j], i);
547                let mut wk = [0.0f32; MIX_ATTR_COUNT];
548                for (k, f) in MIX_ATTR_FLAGS.iter().enumerate() {
549                    if cov.contains(*f) {
550                        wk[k] = w;
551                        wsum[k] += w;
552                    }
553                }
554
555                let mut v = [0.0f32; MIX_ATTR_COUNT];
556                read_attrs(state, &mut v);
557                for k in 0..MIX_ATTR_COUNT {
558                    acc[k] += wk[k] * v[k];
559                }
560                flag |= state.update_flag();
561
562                // `raw_vertex_deform` carries its own presence flag, which is the
563                // same signal as coverage for the other attributes: normalize over
564                // the sources that actually have a deform, so a source without one
565                // does not pull the deltas toward zero.
566                if let Some(rvd) = crate::eval::framedata::vertex_deform_at(&layers[j].raw_vertex_deform, i) {
567                    deform_weight += w;
568                    let w_v = wide::f32x4::splat(w);
569                    dx_acc = w_v.mul_add(wide::f32x4::from(rvd.dx), dx_acc);
570                    dy_acc = w_v.mul_add(wide::f32x4::from(rvd.dy), dy_acc);
571                }
572            }
573
574            // Level 2: fold this track's pose onto everything below it. Attributes
575            // the track says nothing about pass through untouched — that is what
576            // lets a track that only animates part of the rig act as an overlay
577            // without an explicit mask.
578            let alpha = track.alpha;
579            for k in 0..MIX_ATTR_COUNT {
580                if wsum[k] <= 0.0 {
581                    continue;
582                }
583                let v = acc[k] / wsum[k];
584                cur[k] = match track.blend {
585                    TrackBlend::Mix => cur[k] + (v - cur[k]) * alpha,
586                    TrackBlend::Additive => cur[k] + (v - base[k]) * alpha,
587                };
588                touched[k] = true;
589            }
590
591            if deform_weight > 0.0 {
592                let inv = wide::f32x4::splat(1.0 / deform_weight);
593                let (dx, dy) = (dx_acc * inv, dy_acc * inv);
594                let a = wide::f32x4::splat(alpha);
595                match track.blend {
596                    TrackBlend::Mix => {
597                        cur_dx += (dx - cur_dx) * a;
598                        cur_dy += (dy - cur_dy) * a;
599                    }
600                    // The setup pose carries no deform, so the additive reference is zero.
601                    TrackBlend::Additive => {
602                        cur_dx += dx * a;
603                        cur_dy += dy * a;
604                    }
605                }
606                deform_present = true;
607            }
608        }
609
610        if touched.iter().any(|t| *t) {
611            write_attrs(&mut mixed, &cur, &touched);
612            mixed.set_update_flag(flag);
613        }
614        if deform_present {
615            **resolved_layer.raw_vertex_deform[i].get_or_insert_with(Default::default) = crate::eval::framedata::RawVertexDeform { present: true, dx: cur_dx.to_array(), dy: cur_dy.to_array() };
616        }
617
618        resolved_layer.parts_vec.push(mixed);
619    }
620}