Skip to main content

ssruntime/context/
frame.rs

1//! [`Context::get_frame_data`]: the frame pipeline that evaluates the pose and builds the frame data.
2
3use super::{Context, InstanceState, NO_MESH_LAYOUT};
4use crate::mix::mix_tracks;
5use crate::resource::AnimationMetadata;
6use crate::{error, eval};
7
8impl<'a> Context<'a> {
9    /// Build the FrameData of `frame_no`, which is in
10    /// `[first frame, last frame + 1)` of the animation. See `SCHEMA.md` for how to
11    /// read it. Fails with `NotLoaded` with no resource bound, `AnimationNotFound`
12    /// with no animation set up, and `InvalidParameter` for a `frame_no` out of
13    /// range.
14    pub fn get_frame_data(&mut self, frame_no: f32) -> Result<&[u8], error::SSRuntimeError> {
15        let Some(resource) = self.eval.resource else {
16            return Err(error::SSRuntimeError::NotLoaded);
17        };
18
19        let primary_anim_idx = self.instance.primary_source().animation_idx;
20        if primary_anim_idx < 0 {
21            return Err(error::SSRuntimeError::AnimationNotFound);
22        }
23
24        let primary_metadata = &resource.animations[primary_anim_idx as usize];
25        if !((primary_metadata.start_frame as f32) <= frame_no && frame_no < (primary_metadata.end_frame as f32 + 1.0)) {
26            return Err(error::SSRuntimeError::InvalidParameter);
27        }
28
29        if self.eval.fb_need > self.eval.fb_capacity {
30            // The last frame outgrew the builder, which doubled. Size it to the
31            // largest frame so far, with a sixteenth to spare for frames that
32            // carry a little more; the old buffer is released. The builder
33            // writes back to front from the end of its buffer, so the size sets
34            // where the frame data starts: a multiple of 8 keeps it on the
35            // boundary `PartState` needs, as the doubled sizes did.
36            self.eval.fb_capacity = (self.eval.fb_need + self.eval.fb_need / 16).next_multiple_of(8);
37            self.eval.fb = flatbuffers::FlatBufferBuilder::with_capacity(self.eval.fb_capacity);
38        }
39        self.eval.fb.reset();
40        self.eval.frame_data_ready = false;
41
42        let coordinate_system = self.instance.coordinate_system;
43        let origin = self.instance.origin;
44        let unit = self.instance.unit;
45
46        // Stage A: per-source pose extraction. Each source uses its own
47        // controller-driven frame; track 0's main source uses the explicit
48        // `frame_no` argument to preserve single-animation behavior. That source
49        // is always extracted regardless of its weight — `mix_tracks` uses it as
50        // the discrete-attribute / structure source even when its continuous
51        // contribution is zero.
52        let primary_idx = self.instance.primary_idx();
53        let primary_num_parts = primary_metadata.cached_parts().len();
54        let num_sources = self.instance.sources.len();
55        // One audible source at full alpha resolves to its own pose verbatim, so
56        // it is extracted straight into the resolved layer and the two-level fold
57        // is skipped. The floor is unobservable here: an attribute nothing keys
58        // reads the same from the setup pose as from the extracted pose.
59        let single = self.instance.is_single_full_track();
60        for i in 0..num_sources {
61            let source_anim_idx = self.instance.sources[i].animation_idx;
62            if source_anim_idx < 0 {
63                continue;
64            }
65            if i != primary_idx && self.instance.sources[i].weight <= 0.0 {
66                continue;
67            }
68            let frame_for_source = if i == primary_idx { frame_no } else { self.instance.sources[i].controller.get_frame_no() };
69            let metadata = &resource.animations[source_anim_idx as usize];
70            let into_resolved = single && i == primary_idx;
71            let layer = if into_resolved { &mut self.instance.resolved_layer } else { &mut self.instance.layers[i] };
72            layer.fit(metadata);
73            eval::framedata::extract_pose(
74                &mut self.eval.fb,
75                metadata.cached_parts(),
76                &resource.source.keys,
77                frame_for_source,
78                &mut layer.parts_vec,
79                &mut layer.cell_vec,
80                &mut layer.parts_color_vec,
81                &mut layer.shader_vec,
82                &mut layer.deform_vec,
83                &mut layer.raw_vertex_deform,
84                &mut layer.cursors,
85                Some(metadata.part_bases(coordinate_system, origin, unit)),
86                &mut layer.cell_meta_per_part,
87                &mut layer.cell_texture_hashes,
88                &mut layer.cell_ids,
89                &mut layer.mesh_deform,
90                coordinate_system,
91                origin,
92                unit,
93                metadata.canvas_width,
94                metadata.canvas_height,
95                &mut self.eval.deform_interpolation_start_workspace,
96                &mut self.eval.deform_interpolation_end_workspace,
97                &mut self.eval.deform_interpolation_out_workspace,
98                &mut self.eval.deform_result_coordinate_workspace,
99                &mut self.eval.deform_result_index_workspace,
100                &mut self.eval.inheritance_alphas_workspace,
101            );
102
103            // Record which attributes this animation actually carries, per part,
104            // for the mix's coverage rule. Animation-level and therefore constant
105            // for the source's lifetime; copied per frame because a source can be
106            // repointed at another animation at any time. The resolved layer is
107            // never mixed from, so it needs none.
108            if !into_resolved {
109                layer.coverage_vec.clear();
110                layer.coverage_vec.extend(metadata.cached_parts().iter().map(|p| p.coverage));
111            }
112        }
113
114        if !single {
115            mix_tracks(&self.instance.sources, &self.instance.layers, &self.instance.tracks, primary_idx, primary_metadata.setup_pose(coordinate_system, origin, unit), &mut self.instance.resolved_layer);
116        }
117
118        // ⟵ SEAM: apply the per-part runtime Override Layer on the resolved
119        // pose — after the mix, before compose — so overrides win over both
120        // keyframe values and blend results.
121        if self.instance.has_any_override() {
122            // (Re)size + clear the cell-UV meta so the seam records only the
123            // parts it overrides this frame; compute_local_uvs consults it.
124            if self.instance.override_cell_uv_meta.len() != primary_num_parts {
125                self.instance.override_cell_uv_meta.resize(primary_num_parts, None);
126            }
127            for slot in self.instance.override_cell_uv_meta.iter_mut() {
128                *slot = None;
129            }
130            // OverwriteOnNextKeyframe handover is decided from the frames the primary actually
131            // traversed this update (section / loop / reverse / ping-pong
132            // correct). Copy them out before the mutable borrows below so the
133            // controller borrow is released.
134            self.eval.override_passed_frames_workspace.clear();
135            self.eval.override_passed_frames_workspace.extend_from_slice(self.instance.primary_source().controller.get_passed_frames());
136            crate::eval::override_layer::apply_part_overrides(
137                &mut self.instance.part_overrides,
138                primary_metadata.cached_parts(),
139                &resource.source.keys,
140                &mut self.instance.resolved_layer.parts_vec,
141                &mut self.instance.resolved_layer.parts_color_vec,
142                &mut self.instance.resolved_layer.cell_vec,
143                &mut self.instance.resolved_layer.cell_meta_per_part,
144                &mut self.instance.resolved_layer.cell_texture_hashes,
145                &mut self.instance.override_cell_uv_meta,
146                &mut self.eval.override_hide_workspace,
147                &self.eval.override_passed_frames_workspace,
148                self.instance.updates,
149            );
150        } else {
151            // No overrides active: leave the buffer empty so compute_local_uvs
152            // falls back to the keyframe cell for every part.
153            self.instance.override_cell_uv_meta.clear();
154        }
155
156        // Stage B (`compute_local_vertices_for_parts`), Stage C
157        // (`serialize_pose_to_fb`) and the draw plan, on the resolved pose.
158        let nines = &mut self.instance.globals.nines;
159        let resolved = &mut self.instance.resolved_layer;
160        // A track-0 change can hand the primary role to another animation.
161        self.instance.z_order.fit(primary_anim_idx, primary_metadata.cached_parts());
162        let offset = eval::framedata::compose_frame_data(
163            &mut self.eval.fb,
164            primary_metadata.cached_parts(),
165            &mut self.instance.z_order,
166            &mut resolved.parts_vec,
167            &resolved.cell_vec,
168            &resolved.parts_color_vec,
169            &resolved.shader_vec,
170            &mut resolved.vertex_vec,
171            &resolved.deform_vec,
172            &resolved.raw_vertex_deform,
173            &resolved.cell_meta_per_part,
174            &resolved.cell_texture_hashes,
175            &mut resolved.local_vertices,
176            nines,
177            coordinate_system,
178            self.instance.render_mode,
179            &mut self.eval.draw_order_workspace,
180            &mut self.eval.batches_workspace,
181            &mut self.eval.mask_indices_workspace,
182        );
183
184        // Phase 2: resolve global state (matrices / UVs / shape vertices)
185        // from the (post-mix) local pose.
186        Self::resolve_global_state(&mut self.instance, primary_metadata);
187
188        self.eval.fb.finish_minimal(offset);
189        self.eval.frame_data_ready = true;
190        self.eval.fb_need = self.eval.fb_need.max(self.eval.fb.finished_data().len());
191        Ok(self.eval.fb.finished_data())
192    }
193
194    /// Phase 2 of the frame pipeline. Consumes the (post-mix) local pose
195    /// in `instance.resolved_layer` and writes per-instance global outputs
196    /// in `instance.globals` — world / inheritance matrices, local UVs,
197    /// and shape vertex buffers.
198    fn resolve_global_state(instance: &mut InstanceState<'a>, metadata: &AnimationMetadata<'a>) {
199        if instance.render_mode == crate::eval::RenderMode::Direct {
200            Self::compute_matrices(instance, metadata.cached_parts());
201            // Skinned mesh skinning depends on world matrices, so it lives in the
202            // Direct path. Mesh parts in SceneGraph mode get empty per-part ranges.
203            Self::compute_mesh_vertices(instance, metadata);
204        } else {
205            Self::clear_mesh_vertices(instance, metadata.cached_parts().len());
206        }
207        Self::compute_local_uvs(instance, metadata);
208        Self::compute_shape_vertices(instance, metadata.cached_parts());
209    }
210
211    /// Writes per-part mesh world-space vertex positions to
212    /// `globals.mesh_vertices_x` / `_y` for the current frame — skeletal
213    /// (bone-weighted) and Deform-only meshes alike, with the frame's deform
214    /// deltas applied.
215    ///
216    /// Layout: x/y are SoA, sliced per part by `mesh_vertex_offsets` (a CSR
217    /// prefix sum of length `num_parts + 1`; non-mesh parts get an empty
218    /// range). The CSR offsets and the static UV / index buffers are the
219    /// animation's (`StaticMeshBuffers`); only the vertex positions are
220    /// recomputed each frame.
221    #[allow(clippy::needless_range_loop)]
222    fn compute_mesh_vertices(instance: &mut InstanceState<'a>, metadata: &AnimationMetadata<'a>) {
223        let num_parts = instance.resolved_layer.parts_vec.len();
224        let cached_parts = metadata.cached_parts();
225
226        // The CSR offsets and the static UV / index buffers depend only on the
227        // animation's per-part Cells (fixed by the SS mesh spec). Take the
228        // offsets and size the SoA position buffers once per layout;
229        // `setup_animation` resets `mesh_layout` so a new animation sets up again.
230        if instance.globals.mesh_layout != metadata.mesh_layout {
231            Self::setup_static_mesh_buffers(instance, metadata);
232        }
233
234        let layer = &instance.resolved_layer;
235        // SSAB bind coordinates are authored Y-up; flip when the instance
236        // (hence the bone world matrices) runs Y-down.
237        let flip_y = instance.coordinate_system == crate::eval::SsCoordinateSystem::YDown;
238        // The Deform-only mesh rest comes from the cell's `table_coord_x` /
239        // `table_coord_y`, which ssconverter copies verbatim from the `.ssce`
240        // meshPointList — texture-pixel space, i.e. already Y-down. So it must be
241        // flipped for a Y-up target, the OPPOSITE of the Y-up-native bind
242        // coordinates above.
243        let flip_rest = instance.coordinate_system == crate::eval::SsCoordinateSystem::YUp;
244        let globals = &mut instance.globals;
245
246        let total_vertices = globals.mesh_vertices_x.len();
247        if total_vertices == 0 {
248            return;
249        }
250
251        for i in 0..num_parts {
252            let Some(cached) = cached_parts.get(i) else {
253                continue;
254            };
255            let start = globals.mesh_vertex_offsets[i] as usize;
256            let end = globals.mesh_vertex_offsets[i + 1] as usize;
257            if end <= start {
258                continue; // not a mesh part
259            }
260
261            // Skeletal mesh: a bone-weighted binding drives the vertices.
262            let skeletal = cached.mesh_binding.as_ref().map(|b| !b.bone_indices.is_empty()).unwrap_or(false);
263            if skeletal {
264                let binding = cached.mesh_binding.as_ref().unwrap();
265                // The SpriteStudio `.ssae` meshList carries the N rendered mesh vertices
266                // followed by 4 trailing placeholder entries (the cell-quad
267                // corners, bound to no bone), so a well-formed binding has
268                // `cell_count + 4` vertices. `compute_skinned_mesh_vertices`
269                // skins exactly `out_x.len()` (= cell count) vertices from the
270                // front of the binding, so a longer binding is fine — the
271                // trailing extras are simply never read. Only a binding with
272                // *fewer* vertices than the cell is unusable.
273                if binding.num_vertices() < end - start {
274                    continue; // bind has fewer vertices than the cell — cannot skin
275                }
276                let deform = layer.mesh_deform.get(i).and_then(|d| d.as_deref()).filter(|d| !d.indices.is_empty()).map(|d| (d.indices.as_slice(), d.dx.as_slice(), d.dy.as_slice(), &globals.world_matrices[i]));
277                let (out_x, out_y) = (&mut globals.mesh_vertices_x[start..end], &mut globals.mesh_vertices_y[start..end]);
278                crate::eval::geometry::compute_skinned_mesh_vertices(&binding.influence_offsets, &binding.bone_indices, &binding.weights, &binding.coords_x, &binding.coords_y, &globals.world_matrices, deform, flip_y, out_x, out_y);
279                continue;
280            }
281
282            // Deform-only mesh: no bones — rigidly transform the cell's rest
283            // mesh by the part's own world matrix.
284            let Some(mesh_cell) = cached.mesh_cell.as_ref() else {
285                continue;
286            };
287            if mesh_cell.rest_x.len() != (end - start) || i >= globals.world_matrices.len() {
288                continue;
289            }
290            // Rest transform (W · rest) — SIMD over 4 vertices at a time.
291            {
292                let (out_x, out_y) = (&mut globals.mesh_vertices_x[start..end], &mut globals.mesh_vertices_y[start..end]);
293                crate::eval::geometry::compute_rigid_mesh_vertices(&mesh_cell.rest_x, &mesh_cell.rest_y, &globals.world_matrices[i], flip_rest, out_x, out_y);
294            }
295            // Apply deform deltas as-is — evaluate_part has already applied any
296            // coordinate-system Y conversion. Sparse scatter, kept scalar.
297            if let Some(deform) = layer.mesh_deform.get(i).and_then(|d| d.as_deref()) {
298                let vert_count = end - start;
299                let mat = &globals.world_matrices[i];
300                let (m0, m1, m4, m5) = (mat.m[0], mat.m[1], mat.m[4], mat.m[5]);
301                for k in 0..deform.indices.len() {
302                    let v = deform.indices[k] as usize;
303                    if v < vert_count {
304                        globals.mesh_vertices_x[start + v] += m0 * deform.dx[k] + m4 * deform.dy[k];
305                        globals.mesh_vertices_y[start + v] += m1 * deform.dx[k] + m5 * deform.dy[k];
306                    }
307                }
308            }
309        }
310    }
311
312    /// Points the instance at the animation's static mesh buffers: copies their
313    /// vertex offsets, and sizes and zeroes the SoA position buffers. A
314    /// statically malformed mesh part keeps the zeros written here, so the
315    /// per-frame pass needs no clear.
316    fn setup_static_mesh_buffers(instance: &mut InstanceState<'a>, metadata: &AnimationMetadata<'a>) {
317        let globals = &mut instance.globals;
318        let mesh = metadata.static_mesh();
319        globals.mesh_vertex_offsets.clone_from(&mesh.vertex_offsets);
320        let total_vertices = *mesh.vertex_offsets.last().unwrap_or(&0) as usize;
321        globals.mesh_vertices_x.clear();
322        globals.mesh_vertices_x.resize(total_vertices, 0.0);
323        globals.mesh_vertices_y.clear();
324        globals.mesh_vertices_y.resize(total_vertices, 0.0);
325        globals.mesh_layout = metadata.mesh_layout;
326    }
327
328    fn clear_mesh_vertices(instance: &mut InstanceState<'a>, num_parts: usize) {
329        let globals = &mut instance.globals;
330        if globals.mesh_vertex_offsets.len() != num_parts + 1 {
331            globals.mesh_vertex_offsets.resize(num_parts + 1, 0);
332        }
333        for slot in globals.mesh_vertex_offsets.iter_mut() {
334            *slot = 0;
335        }
336        globals.mesh_vertices_x.clear();
337        globals.mesh_vertices_y.clear();
338        globals.mesh_layout = NO_MESH_LAYOUT;
339    }
340
341    #[allow(clippy::needless_range_loop)]
342    fn compute_matrices(instance: &mut InstanceState<'a>, cached_parts: &[crate::eval::framedata::CachedPartData]) {
343        let layer = &instance.resolved_layer;
344        let globals = &mut instance.globals;
345        for i in 0..layer.parts_vec.len() {
346            let parent_idx = cached_parts[i].parent_index;
347            let valid_parent_idx = (parent_idx >= 0 && (parent_idx as usize) < i).then_some(parent_idx as usize);
348
349            let parent_world = valid_parent_idx.map(|p_idx| &globals.inheritance_matrices[p_idx]);
350            let parent_size = valid_parent_idx.map(|p_idx| {
351                let p_state = &layer.parts_vec[p_idx];
352                (p_state.size_x(), p_state.size_y())
353            });
354
355            let part_state = &layer.parts_vec[i];
356            let (inh_m, draw_m) = crate::eval::SsMatrix4x4::compute_world_matrix(part_state, parent_world, parent_size);
357            globals.inheritance_matrices[i] = inh_m;
358            globals.world_matrices[i] = draw_m;
359        }
360    }
361
362    #[allow(clippy::needless_range_loop)]
363    fn compute_local_uvs(instance: &mut InstanceState<'a>, metadata: &AnimationMetadata<'a>) {
364        let keys = &metadata.source.keys;
365        let layer = &instance.resolved_layer;
366        let override_cell_uv_meta = &instance.override_cell_uv_meta;
367        let globals = &mut instance.globals;
368        let num_parts = layer.parts_vec.len();
369        if globals.local_uvs.len() != num_parts * 10 {
370            globals.local_uvs.resize(num_parts * 10, 0.0);
371        }
372        for slot in globals.local_uvs.iter_mut() {
373            *slot = 0.0;
374        }
375
376        for i in 0..num_parts {
377            let state = &layer.parts_vec[i];
378            if state.cell() < 0 {
379                continue;
380            }
381            // A cell override recorded at the seam wins for UVs too, so the
382            // sampled image (not just the quad size/texture) reflects the swap.
383            let meta = match override_cell_uv_meta.get(i).and_then(|m| m.as_ref()) {
384                Some(m) => m,
385                None => match layer.cell_ids.get(i).copied().flatten() {
386                    Some(cell) => &keys.cell(cell).meta,
387                    None => continue,
388                },
389            };
390            if meta.size_w == 0.0 && meta.size_h == 0.0 {
391                continue;
392            }
393
394            let rect_right = meta.rect_left + meta.size_w;
395            let rect_bottom = meta.rect_top + meta.size_h;
396
397            let (tu, tv, rot_deg, su, sv, fh, fv, ifh, ifv) =
398                (state.uv_translation_x() * meta.tex_w, state.uv_translation_y() * meta.tex_h, state.uv_rotation_z(), state.uv_scale_x(), state.uv_scale_y(), state.flip_h(), state.flip_v(), state.img_flip_h(), state.img_flip_v());
399
400            let (us, vs) = crate::eval::geometry::compute_local_uvs((meta.rect_left, meta.rect_top, rect_right, rect_bottom), (tu, tv, rot_deg, su, sv), (fh, fv), (ifh, ifv), meta.rotated);
401
402            let offset = i * 10;
403            for k in 0..5 {
404                globals.local_uvs[offset + k * 2] = us[k];
405                globals.local_uvs[offset + k * 2 + 1] = vs[k];
406            }
407        }
408    }
409
410    #[allow(clippy::needless_range_loop)]
411    fn compute_shape_vertices(instance: &mut InstanceState<'a>, cached_parts: &[crate::eval::framedata::CachedPartData]) {
412        let coordinate_system = instance.coordinate_system;
413        let layer = &instance.resolved_layer;
414        let globals = &mut instance.globals;
415        let num_parts = layer.parts_vec.len();
416        let stride = crate::eval::framedata::SHAPE_VERTICES_STRIDE;
417        if globals.shape_vertex_counts.len() != num_parts {
418            globals.shape_vertex_counts.resize(num_parts, 0);
419        }
420        globals.shape_vertex_counts.fill(0);
421        // `setup_animation` leaves the vertex buffers empty when no part is a shape.
422        if globals.shape_vertices.len() != num_parts * stride {
423            return;
424        }
425        globals.shape_vertices.fill(0.0);
426        globals.shape_vertex_box_coords.fill(0.0);
427
428        for i in 0..num_parts {
429            let Some(shape_kind) = cached_parts[i].shape_kind else { continue };
430            let state = &layer.parts_vec[i];
431            let size_x = state.size_x();
432            let size_y = state.size_y();
433            if size_x <= 0.0 || size_y <= 0.0 {
434                continue;
435            }
436
437            let (count, vx, vy) = crate::eval::geometry::compute_shape_vertices(shape_kind, (size_x, size_y));
438            if count < 3 {
439                continue;
440            }
441
442            let mut effective_pivot_y = state.pivot_y();
443            if coordinate_system == crate::eval::SsCoordinateSystem::YDown {
444                effective_pivot_y = -effective_pivot_y;
445            }
446            let tx = -state.pivot_x() * size_x;
447            let ty = -effective_pivot_y * size_y;
448            let hw = size_x * 0.5;
449            let hh = size_y * 0.5;
450
451            // Vertex deform: the 4 box-corner offsets ([LT, RT, LB, RB], in the
452            // part's Y-up local space) are spread across every shape vertex by
453            // bilinear interpolation over its box coordinates (fx, fy) — the same
454            // weighting the renderer uses for per-corner PartColor. Offsets are
455            // added in Y-up space, before the YDown negation, so the dy sign
456            // matches the 4-corner deform path in `compute_local_vertices`.
457            let deform = crate::eval::framedata::vertex_deform_at(&layer.raw_vertex_deform, i);
458            // Skew shares the Vertex-deform slot; applied as a shear about the
459            // pivot origin in Y-up, before the Y-down flip, like the deform.
460            let skew = crate::eval::geometry::skew_local_tans(state.skew_x(), state.skew_y());
461
462            let offset = i * stride;
463            for v in 0..count {
464                let fx = (vx[v] + hw) / size_x;
465                let fy = (hh - vy[v]) / size_y;
466
467                let (mut dvx, mut dvy) = (vx[v] + tx, vy[v] + ty);
468                if let Some(d) = deform {
469                    let (ddx, ddy) = crate::eval::geometry::bilinear_box_deform(&d.dx, &d.dy, fx, fy);
470                    dvx += ddx;
471                    dvy += ddy;
472                }
473                if let Some((tan_x, tan_y)) = skew {
474                    let (nx, ny) = crate::eval::geometry::skew_point_yup(dvx, dvy, tan_x, tan_y);
475                    dvx = nx;
476                    dvy = ny;
477                }
478
479                let mut y = dvy;
480                if coordinate_system == crate::eval::SsCoordinateSystem::YDown {
481                    y = -y;
482                }
483                globals.shape_vertices[offset + 2 * v] = dvx;
484                globals.shape_vertices[offset + 2 * v + 1] = y;
485
486                globals.shape_vertex_box_coords[offset + 2 * v] = fx;
487                globals.shape_vertex_box_coords[offset + 2 * v + 1] = fy;
488            }
489            globals.shape_vertex_counts[i] = count as i32;
490        }
491    }
492}