Skip to main content

ssruntime/eval/
keyframes.rs

1//! Read side of `SsAnimeBinary.keyframes`: every key of the pack, one column per
2//! field, and the tables its compound values live in.
3
4use crate::eval::framedata::ResolvedCellMeta;
5use crate::runtime;
6use flatbuffers::{ForwardsUOffset, Vector};
7use ssab::ssab::ss::format::{CellMap, InterpolationType, KeyCurve, Keyframes, PartAttributeCell, PartAttributeDeform};
8
9use ssab::{NO_CURVE, NO_KEYS};
10
11/// One attribute's keys on one part in one animation: `count` keys from `first`.
12#[derive(Clone, Copy, Debug, PartialEq, Eq)]
13pub struct KeyRun {
14    first: u32,
15    count: u32,
16}
17
18impl KeyRun {
19    pub const fn new(first: u32, count: u32) -> Self {
20        Self { first, count }
21    }
22
23    #[inline]
24    pub fn first(&self) -> u32 {
25        self.first
26    }
27
28    #[inline]
29    pub fn count(&self) -> u32 {
30        self.count
31    }
32}
33
34/// A cell a key shows, with what it resolves to in the pack's cellmaps.
35#[derive(Clone, Copy)]
36pub struct CellValue {
37    pub cell: runtime::framedata::ss::runtime::PartAttributeCell,
38    /// All zeros when the pack's cellmaps do not hold the cell.
39    pub meta: ResolvedCellMeta,
40}
41
42/// The pack's keyframe columns, looked up once when the pack is loaded. The
43/// fixed-size compound values its keys share are decoded then too, cells
44/// resolved against the cellmaps, so every animation reads a key's value by
45/// index instead of decoding it again. Deforms vary in length and are read
46/// from the pack as they are.
47pub struct KeyColumns<'a> {
48    // The columns every frame reads, as the little-endian bytes FlatBuffers
49    // stores them as: indexing one is a slice access, where `Vector::get` reads
50    // the length back out of the buffer on every call.
51    runs: &'a [U32Bytes],
52    frame: &'a [U16Bytes],
53    interpolation: &'a [u8],
54    curve: &'a [U16Bytes],
55    value: &'a [U32Bytes],
56    curves: Vector<'a, KeyCurve>,
57    easing_rates: Vector<'a, f32>,
58    cells: alloc::boxed::Box<[CellValue]>,
59    part_colors: alloc::boxed::Box<[runtime::framedata::ss::runtime::PartAttributePartColor]>,
60    shaders: alloc::boxed::Box<[runtime::framedata::ss::runtime::PartAttributeShader]>,
61    vertices: alloc::boxed::Box<[runtime::framedata::ss::runtime::PartAttributeVertex]>,
62    /// `(x, y)`.
63    skews: alloc::boxed::Box<[(f32, f32)]>,
64    deforms: Vector<'a, ForwardsUOffset<PartAttributeDeform<'a>>>,
65}
66
67impl<'a> KeyColumns<'a> {
68    /// `cellmaps` are the pack's, which its cells resolve against.
69    pub fn new(keyframes: Keyframes<'a>, cellmaps: Option<Vector<'a, ForwardsUOffset<CellMap<'a>>>>) -> Self {
70        let cell = |c: PartAttributeCell| CellValue {
71            cell: runtime::framedata::ss::runtime::PartAttributeCell::new(c.cellmap_name_hash(), c.name_hash()),
72            meta: cellmaps.as_ref().and_then(|maps| crate::eval::framedata::resolve_cell(maps, c.cellmap_name_hash(), c.name_hash())).unwrap_or_default(),
73        };
74        Self {
75            runs: u32s(keyframes.runs()),
76            frame: u16s(keyframes.frame()),
77            interpolation: keyframes.interpolation().bytes(),
78            curve: u16s(keyframes.curve()),
79            value: u32s(keyframes.value()),
80            curves: keyframes.curves(),
81            easing_rates: keyframes.easing_rates(),
82            cells: keyframes.cells().iter().map(cell).collect(),
83            part_colors: keyframes.part_colors().iter().map(|c| transfer_partcolor(&c)).collect(),
84            shaders: keyframes.shaders().iter().map(|s| transfer_shader(&s)).collect(),
85            vertices: keyframes.vertices().iter().map(|v| transfer_vertex(&v)).collect(),
86            skews: keyframes.skews().iter().map(|s| (s.v1(), s.v2())).collect(),
87            deforms: keyframes.deforms(),
88        }
89    }
90
91    /// The keys of run `r` — a `PartAnimationData` field — or `None` for
92    /// [`NO_KEYS`].
93    #[inline]
94    pub fn run(&self, r: u32) -> Option<KeyRun> {
95        if r == NO_KEYS {
96            return None;
97        }
98        let at = |i: usize| u32::from_le_bytes(self.runs[i]);
99        let first = at(r as usize);
100        Some(KeyRun::new(first, at(r as usize + 1) - first))
101    }
102
103    /// The frames `run`'s keys sit on.
104    #[inline]
105    pub fn frames(&self, run: &KeyRun) -> Frames<'a> {
106        Frames(&self.frame[run.first() as usize..][..run.count() as usize])
107    }
108
109    /// Key `k` of the pack.
110    #[inline]
111    pub fn key(&self, k: usize) -> Key<'_, 'a> {
112        Key { columns: self, k }
113    }
114
115    /// The cell a cell key's [`Key::cell`] names.
116    #[inline]
117    pub fn cell(&self, cell: u32) -> &CellValue {
118        &self.cells[cell as usize]
119    }
120}
121
122/// One key of a [`KeyColumns`]. Which value accessor applies is the attribute's
123/// to say: the run a key belongs to is read as one type throughout.
124#[derive(Clone, Copy)]
125pub struct Key<'c, 'a> {
126    columns: &'c KeyColumns<'a>,
127    k: usize,
128}
129
130impl<'c, 'a> Key<'c, 'a> {
131    /// The frame the key sits on.
132    #[inline]
133    pub fn index(&self) -> u16 {
134        u16::from_le_bytes(self.columns.frame[self.k])
135    }
136
137    #[inline]
138    pub fn interpolation(&self) -> InterpolationType {
139        InterpolationType(self.columns.interpolation[self.k])
140    }
141
142    /// The control values of a Hermite or Bezier key; `None` for any other.
143    #[inline]
144    pub fn curve(&self) -> Option<&'a KeyCurve> {
145        match self.interpolation() {
146            InterpolationType::Hermite | InterpolationType::Bezier => self.slot().map(|i| self.columns.curves.get(i)),
147            _ => None,
148        }
149    }
150
151    /// The rate of an ease that takes one; `0.0` for any other key.
152    #[inline]
153    pub fn easing_rate(&self) -> f32 {
154        match self.interpolation() {
155            InterpolationType::EaseIn | InterpolationType::EaseOut | InterpolationType::EaseInOut | InterpolationType::EaseElasticIn | InterpolationType::EaseElasticOut | InterpolationType::EaseElasticInOut => {
156                self.slot().map_or(0.0, |i| self.columns.easing_rates.get(i))
157            }
158            _ => 0.0,
159        }
160    }
161
162    #[inline]
163    fn slot(&self) -> Option<usize> {
164        let slot = u16::from_le_bytes(self.columns.curve[self.k]);
165        (slot != NO_CURVE).then_some(slot as usize)
166    }
167
168    #[inline]
169    fn bits(&self) -> u32 {
170        u32::from_le_bytes(self.columns.value[self.k])
171    }
172
173    #[inline]
174    pub fn float(&self) -> f32 {
175        f32::from_bits(self.bits())
176    }
177
178    #[inline]
179    pub fn int(&self) -> i32 {
180        self.bits() as i32
181    }
182
183    #[inline]
184    pub fn bool(&self) -> bool {
185        self.bits() != 0
186    }
187
188    #[inline]
189    pub fn uint(&self) -> u32 {
190        self.bits()
191    }
192
193    /// The cell the key shows, as an index for [`KeyColumns::cell`].
194    #[inline]
195    pub fn cell(&self) -> u32 {
196        self.bits()
197    }
198
199    #[inline]
200    pub fn part_color(&self) -> &'c runtime::framedata::ss::runtime::PartAttributePartColor {
201        &self.columns.part_colors[self.bits() as usize]
202    }
203
204    #[inline]
205    pub fn shader(&self) -> &'c runtime::framedata::ss::runtime::PartAttributeShader {
206        &self.columns.shaders[self.bits() as usize]
207    }
208
209    #[inline]
210    pub fn vertex(&self) -> &'c runtime::framedata::ss::runtime::PartAttributeVertex {
211        &self.columns.vertices[self.bits() as usize]
212    }
213
214    #[inline]
215    pub fn skew(&self) -> (f32, f32) {
216        self.columns.skews[self.bits() as usize]
217    }
218
219    #[inline]
220    pub fn deform(&self) -> PartAttributeDeform<'a> {
221        self.columns.deforms.get(self.bits() as usize)
222    }
223}
224
225/// The frames a run's keys sit on, in order, as [`KeyColumns::frames`] gives
226/// them: what a key search looks through.
227#[derive(Clone, Copy)]
228pub struct Frames<'a>(&'a [U16Bytes]);
229
230impl Frames<'_> {
231    /// How many keys [`locate`](Self::locate) steps from the hint, either way,
232    /// before it searches instead.
233    const NEAR: usize = 4;
234
235    #[inline]
236    pub fn len(&self) -> usize {
237        self.0.len()
238    }
239
240    #[inline]
241    pub fn is_empty(&self) -> bool {
242        self.0.is_empty()
243    }
244
245    #[inline]
246    fn at(&self, i: usize) -> f32 {
247        u16::from_le_bytes(self.0[i]) as f32
248    }
249
250    /// Where `frame_no` falls: the position of the last key at or before it, or
251    /// `None` before the first. The answer depends on `frame_no` alone, never on
252    /// `hint`, which is only where to look first, counted from the run's first
253    /// key. It is left on the position found, so playback that moves a few keys
254    /// either way settles within a few steps of it, and a longer seek falls back
255    /// to a binary search.
256    #[inline]
257    pub fn locate(&self, frame_no: f32, hint: &mut u32) -> Option<usize> {
258        let found = self.near(frame_no, *hint as usize).unwrap_or_else(|| self.0.partition_point(|f| u16::from_le_bytes(*f) as f32 <= frame_no).checked_sub(1));
259        *hint = found.unwrap_or(0) as u32;
260        found
261    }
262
263    /// [`locate`](Self::locate)'s answer when it lies within a few keys of
264    /// `hint`, or `None` to search for it.
265    #[inline]
266    fn near(&self, frame_no: f32, hint: usize) -> Option<Option<usize>> {
267        let last = self.len().checked_sub(1)?;
268        let mut i = hint.min(last);
269        if self.at(i) <= frame_no {
270            // Forward playback: the key is the hint's or a few after it.
271            for _ in 0..=Self::NEAR {
272                if i == last || frame_no < self.at(i + 1) {
273                    return Some(Some(i));
274                }
275                i += 1;
276            }
277        } else {
278            // Reverse playback, or a loop back to the start.
279            for _ in 0..Self::NEAR {
280                if i == 0 {
281                    return Some(None);
282                }
283                i -= 1;
284                if self.at(i) <= frame_no {
285                    return Some(Some(i));
286                }
287            }
288        }
289        None
290    }
291}
292
293/// A `u16` as FlatBuffers stores it.
294type U16Bytes = [u8; size_of::<u16>()];
295
296/// A `u32` as FlatBuffers stores it.
297type U32Bytes = [u8; size_of::<u32>()];
298
299// A column's element type is spelled in each of these, so a schema change to it
300// stops the build here rather than misreading the bytes.
301
302fn u16s(column: Vector<'_, u16>) -> &[U16Bytes] {
303    column.bytes().as_chunks().0
304}
305
306fn u32s(column: Vector<'_, u32>) -> &[U32Bytes] {
307    column.bytes().as_chunks().0
308}
309
310// The runtime form of each compound value, which `KeyColumns::new` decodes the
311// pack's into once. A corner the pack leaves out reads as zeros.
312
313#[inline]
314fn transfer_blend_type(bt: ssab::ssab::ss::format::BlendType) -> runtime::framedata::ss::runtime::BlendType {
315    match bt {
316        ssab::ssab::ss::format::BlendType::Mix => runtime::framedata::ss::runtime::BlendType::Mix,
317        ssab::ssab::ss::format::BlendType::Mul => runtime::framedata::ss::runtime::BlendType::Mul,
318        ssab::ssab::ss::format::BlendType::Add => runtime::framedata::ss::runtime::BlendType::Add,
319        ssab::ssab::ss::format::BlendType::Sub => runtime::framedata::ss::runtime::BlendType::Sub,
320        ssab::ssab::ss::format::BlendType::Mulalpha => runtime::framedata::ss::runtime::BlendType::Mulalpha,
321        ssab::ssab::ss::format::BlendType::Screen => runtime::framedata::ss::runtime::BlendType::Screen,
322        ssab::ssab::ss::format::BlendType::Exclusion => runtime::framedata::ss::runtime::BlendType::Exclusion,
323        ssab::ssab::ss::format::BlendType::Invert => runtime::framedata::ss::runtime::BlendType::Invert,
324        ssab::ssab::ss::format::BlendType::Mul2 => runtime::framedata::ss::runtime::BlendType::Mul2,
325        ssab::ssab::ss::format::BlendType::Div2 => runtime::framedata::ss::runtime::BlendType::Div2,
326        ssab::ssab::ss::format::BlendType::Screen2 => runtime::framedata::ss::runtime::BlendType::Screen2,
327        ssab::ssab::ss::format::BlendType::Overlay2 => runtime::framedata::ss::runtime::BlendType::Overlay2,
328        _ => runtime::framedata::ss::runtime::BlendType::Mix,
329    }
330}
331
332#[inline]
333fn transfer_partcolor(source: &ssab::ssab::ss::format::PartAttributePartColor) -> runtime::framedata::ss::runtime::PartAttributePartColor {
334    let mut destination = runtime::framedata::ss::runtime::PartAttributePartColor::default();
335    let s = source;
336
337    destination.set_blend_type(transfer_blend_type(s.blend_type()));
338
339    fn convert_u8color(rgba: &ssab::ssab::ss::format::U8Color) -> runtime::framedata::ss::runtime::U8Color {
340        runtime::framedata::ss::runtime::U8Color::new(rgba.a(), rgba.r(), rgba.g(), rgba.b())
341    }
342
343    if let Some(lt) = s.lt()
344        && let Some(rgba) = lt.rgba()
345    {
346        destination.set_lt(&runtime::framedata::ss::runtime::SsAttributePartColorKeyValueColor::new(&convert_u8color(&rgba), lt.rate()));
347    }
348    if let Some(rt) = s.rt()
349        && let Some(rgba) = rt.rgba()
350    {
351        destination.set_rt(&runtime::framedata::ss::runtime::SsAttributePartColorKeyValueColor::new(&convert_u8color(&rgba), rt.rate()));
352    }
353    if let Some(rb) = s.rb()
354        && let Some(rgba) = rb.rgba()
355    {
356        destination.set_rb(&runtime::framedata::ss::runtime::SsAttributePartColorKeyValueColor::new(&convert_u8color(&rgba), rb.rate()));
357    }
358    if let Some(lb) = s.lb()
359        && let Some(rgba) = lb.rgba()
360    {
361        destination.set_lb(&runtime::framedata::ss::runtime::SsAttributePartColorKeyValueColor::new(&convert_u8color(&rgba), lb.rate()));
362    }
363
364    destination
365}
366
367#[inline]
368fn transfer_shader(source: &ssab::ssab::ss::format::PartAttributeShader) -> runtime::framedata::ss::runtime::PartAttributeShader {
369    let s = source;
370
371    runtime::framedata::ss::runtime::PartAttributeShader::new(
372        s.id_hash(),
373        s.param0(),
374        s.param1(),
375        s.param2(),
376        s.param3(),
377        s.param4(),
378        s.param5(),
379        s.param6(),
380        s.param7(),
381        s.map0_cellmap_name_hash(),
382        s.map0_name_hash(),
383        s.map1_cellmap_name_hash(),
384        s.map1_name_hash(),
385    )
386}
387
388#[inline]
389fn transfer_vertex(source: &ssab::ssab::ss::format::PartAttributeVertex) -> runtime::framedata::ss::runtime::PartAttributeVertex {
390    let s = source;
391
392    let lt = s.lt().map(|lt| runtime::framedata::ss::runtime::Vec2::new(lt.v1(), lt.v2())).unwrap_or_default();
393    let rt = s.rt().map(|rt| runtime::framedata::ss::runtime::Vec2::new(rt.v1(), rt.v2())).unwrap_or_default();
394    let lb = s.lb().map(|lb| runtime::framedata::ss::runtime::Vec2::new(lb.v1(), lb.v2())).unwrap_or_default();
395    let rb = s.rb().map(|rb| runtime::framedata::ss::runtime::Vec2::new(rb.v1(), rb.v2())).unwrap_or_default();
396
397    // The center is left at zero: `compute_local_vertices_for_parts` computes it once pivot/size/flip/deform are applied.
398    runtime::framedata::ss::runtime::PartAttributeVertex::new(&lt, &rt, &lb, &rb, &runtime::framedata::ss::runtime::Vec2::default())
399}
400
401/// A `Keyframes` table with every column present and empty, for tests that
402/// need one but read no key.
403#[cfg(test)]
404pub(crate) fn create_empty_keyframes<'a>(fb: &mut flatbuffers::FlatBufferBuilder<'a>) -> flatbuffers::WIPOffset<Keyframes<'a>> {
405    use flatbuffers::WIPOffset;
406    use ssab::ssab::ss::format::{PartAttributePartColor, PartAttributeShader, PartAttributeVertex, Vec2};
407    let args = ssab::ssab::ss::format::KeyframesArgs {
408        runs: Some(fb.create_vector::<u32>(&[0])),
409        frame: Some(fb.create_vector::<u16>(&[])),
410        interpolation: Some(fb.create_vector::<InterpolationType>(&[])),
411        curve: Some(fb.create_vector::<u16>(&[])),
412        value: Some(fb.create_vector::<u32>(&[])),
413        curves: Some(fb.create_vector::<KeyCurve>(&[])),
414        easing_rates: Some(fb.create_vector::<f32>(&[])),
415        cells: Some(fb.create_vector::<WIPOffset<PartAttributeCell>>(&[])),
416        part_colors: Some(fb.create_vector::<WIPOffset<PartAttributePartColor>>(&[])),
417        shaders: Some(fb.create_vector::<WIPOffset<PartAttributeShader>>(&[])),
418        vertices: Some(fb.create_vector::<WIPOffset<PartAttributeVertex>>(&[])),
419        skews: Some(fb.create_vector::<WIPOffset<Vec2>>(&[])),
420        deforms: Some(fb.create_vector::<WIPOffset<PartAttributeDeform>>(&[])),
421    };
422    Keyframes::create(fb, &args)
423}
424
425/// [`create_empty_keyframes`] as a buffer of its own.
426#[cfg(test)]
427pub(crate) fn empty_keyframes() -> alloc::vec::Vec<u8> {
428    let mut fb = flatbuffers::FlatBufferBuilder::new();
429    let root = create_empty_keyframes(&mut fb);
430    fb.finish(root, None);
431    fb.finished_data().to_vec()
432}