Skip to main content

ssruntime/eval/
interpolation.rs

1use crate::eval::keyframes::{Key, KeyColumns, KeyRun};
2use crate::interpolate::*;
3use crate::runtime;
4use alloc::vec::Vec;
5use ssab::ssab::ss::format::InterpolationType;
6
7#[inline]
8pub fn get_interpolated_rate(interpolation: InterpolationType, frame_no: f32, prev_frame: f32, next_frame: f32, curve: Option<&ssab::ssab::ss::format::KeyCurve>, easing_rate: f32) -> f32 {
9    let rate = rate_linear(frame_no, prev_frame, next_frame);
10    match interpolation {
11        InterpolationType::None => 0.0,
12        InterpolationType::Linear => rate,
13        InterpolationType::Hermite => {
14            if let Some(c) = curve {
15                hermite(0.0_f32, 1.0_f32, rate, c.start_value(), c.end_value())
16            } else {
17                rate
18            }
19        }
20        InterpolationType::Bezier => {
21            if let Some(c) = curve {
22                bezier(prev_frame, 0.0_f32, next_frame, 1.0_f32, rate, c.start_time(), c.start_value(), c.end_time(), c.end_value())
23            } else {
24                rate
25            }
26        }
27        InterpolationType::Acceleration => rate_accelerate(rate),
28        InterpolationType::Deceleration => rate_decelerate(rate),
29        InterpolationType::EaseIn => rate_ease_in(rate, easing_rate),
30        InterpolationType::EaseOut => rate_ease_out(rate, easing_rate),
31        InterpolationType::EaseInOut => rate_ease_inout(rate, easing_rate),
32        InterpolationType::EaseExponentialIn => rate_ease_exponential_in(rate),
33        InterpolationType::EaseExponentialOut => rate_ease_exponential_out(rate),
34        InterpolationType::EaseExponentialInOut => rate_ease_exponential_inout(rate),
35        InterpolationType::EaseSineIn => rate_ease_sine_in(rate),
36        InterpolationType::EaseSineOut => rate_ease_sine_out(rate),
37        InterpolationType::EaseSineInOut => rate_ease_sine_inout(rate),
38        InterpolationType::EaseElasticIn => rate_ease_elastic_in(rate, easing_rate),
39        InterpolationType::EaseElasticOut => rate_ease_elastic_out(rate, easing_rate),
40        InterpolationType::EaseElasticInOut => rate_ease_elastic_inout(rate, easing_rate),
41        InterpolationType::EaseBounceIn => rate_ease_bounce_in(rate),
42        InterpolationType::EaseBounceOut => rate_ease_bounce_out(rate),
43        InterpolationType::EaseBounceInOut => rate_ease_bounce_inout(rate),
44        InterpolationType::EaseBackIn => rate_ease_back_in(rate),
45        InterpolationType::EaseBackOut => rate_ease_back_out(rate),
46        InterpolationType::EaseBackInOut => rate_ease_back_inout(rate),
47        _ => rate,
48    }
49}
50
51// Compute the interpolated value directly in (frame, value)-space for single-value attributes.
52//
53// Why: for Bezier/Hermite the curve handle Y values from `KeyCurve` are in attribute-value units
54// (e.g. pixels). Mapping the Y axis to [0,1] rate space and feeding those handles unchanged
55// loses both magnitude and sign of the handle relative to (next_value - prev_value), which makes
56// e.g. a Y position interpolation curve flip direction when the value range is descending.
57// For other interpolation types the rate is value-independent, so we use the existing rate path.
58#[inline]
59fn evaluate_curve_value_f32(interpolation: InterpolationType, frame_no: f32, prev_frame: f32, next_frame: f32, prev_value: f32, next_value: f32, curve: Option<&ssab::ssab::ss::format::KeyCurve>, easing_rate: f32) -> f32 {
60    match interpolation {
61        InterpolationType::Hermite => {
62            let rate = rate_linear(frame_no, prev_frame, next_frame);
63            if let Some(c) = curve { hermite(prev_value, next_value, rate, c.start_value(), c.end_value()) } else { linear(prev_value, next_value, rate) }
64        }
65        InterpolationType::Bezier => {
66            let rate = rate_linear(frame_no, prev_frame, next_frame);
67            if let Some(c) = curve { bezier(prev_frame, prev_value, next_frame, next_value, rate, c.start_time(), c.start_value(), c.end_time(), c.end_value()) } else { linear(prev_value, next_value, rate) }
68        }
69        _ => {
70            let rate = get_interpolated_rate(interpolation, frame_no, prev_frame, next_frame, curve, easing_rate);
71            linear(prev_value, next_value, rate)
72        }
73    }
74}
75
76/// The key at or before `frame_no` and, between two keys, the one after it. A
77/// frame on a key reads that key alone, and a frame before the first key reads
78/// the first key alone. `hint` is the run's cursor, as
79/// [`Frames::locate`](crate::eval::keyframes::Frames::locate) keeps it.
80#[inline]
81pub fn search_prev_next<'c, 'a>(keys: &'c KeyColumns<'a>, run: &KeyRun, frame_no: f32, hint: &mut u32) -> Option<(Key<'c, 'a>, Option<Key<'c, 'a>>)> {
82    let frames = keys.frames(run);
83    if frames.is_empty() {
84        return None;
85    }
86    let first = run.first() as usize;
87    let Some(i) = frames.locate(frame_no, hint) else {
88        return Some((keys.key(first), None));
89    };
90    let prev = keys.key(first + i);
91    let on_key = prev.index() as f32 == frame_no;
92    Some((prev, (i + 1 < frames.len() && !on_key).then(|| keys.key(first + i + 1))))
93}
94
95/// The key at or before `frame_no`, or `None` before the first. `hint` is as
96/// for [`search_prev_next`].
97#[inline]
98pub fn search_prev<'c, 'a>(keys: &'c KeyColumns<'a>, run: &KeyRun, frame_no: i32, hint: &mut u32) -> Option<Key<'c, 'a>> {
99    keys.frames(run).locate(frame_no as f32, hint).map(|i| keys.key(run.first() as usize + i))
100}
101
102#[inline]
103pub fn evaluate_float(keys: &KeyColumns<'_>, run: &KeyRun, frame_no: f32, hint: &mut u32) -> Option<f32> {
104    search_prev_next(keys, run, frame_no, hint).map(|(prev, next_opt)| {
105        if let Some(next) = next_opt {
106            let prev_index = prev.index() as i32 as f32;
107            let interpolation = prev.interpolation();
108            if interpolation == InterpolationType::None {
109                return prev.float();
110            }
111
112            let next_index = next.index() as i32 as f32;
113            evaluate_curve_value_f32(interpolation, frame_no, prev_index, next_index, prev.float(), next.float(), prev.curve(), prev.easing_rate())
114        } else {
115            prev.float()
116        }
117    })
118}
119
120#[inline]
121pub fn evaluate_int(keys: &KeyColumns<'_>, run: &KeyRun, frame_no: f32, hint: &mut u32) -> Option<i32> {
122    search_prev_next(keys, run, frame_no, hint).map(|(prev, next_opt)| {
123        if let Some(next) = next_opt {
124            let prev_index = prev.index() as i32 as f32;
125            let interpolation = prev.interpolation();
126            if interpolation == InterpolationType::None {
127                return prev.int();
128            }
129
130            let next_index = next.index() as i32 as f32;
131            let value = evaluate_curve_value_f32(interpolation, frame_no, prev_index, next_index, prev.int() as f32, next.int() as f32, prev.curve(), prev.easing_rate());
132
133            crate::eval::math::roundf(value) as i32
134        } else {
135            prev.int()
136        }
137    })
138}
139
140#[inline]
141pub fn evaluate_partcolor(keys: &KeyColumns<'_>, run: &KeyRun, frame_no: f32, hint: &mut u32) -> Option<runtime::framedata::ss::runtime::PartAttributePartColor> {
142    search_prev_next(keys, run, frame_no, hint).map(|(prev, next_opt)| {
143        if let Some(next) = next_opt {
144            let prev_index = prev.index() as i32 as f32;
145            let interpolation = prev.interpolation();
146            if interpolation == InterpolationType::None {
147                return *prev.part_color();
148            }
149
150            let next_index = next.index() as i32 as f32;
151            let rate = get_interpolated_rate(interpolation, frame_no, prev_index, next_index, prev.curve(), prev.easing_rate());
152
153            let mut current = runtime::framedata::ss::runtime::PartAttributePartColor::default();
154            let prev_val = prev.part_color();
155            let next_val = next.part_color();
156
157            let get_color = |c: &runtime::framedata::ss::runtime::SsAttributePartColorKeyValueColor| -> (f32, f32, f32, f32, f32) {
158                let rgba = c.rgba();
159                (rgba.a() as f32, rgba.r() as f32, rgba.g() as f32, rgba.b() as f32, c.rate())
160            };
161
162            let p_lt = get_color(prev_val.lt());
163            let p_rt = get_color(prev_val.rt());
164            let p_lb = get_color(prev_val.lb());
165            let p_rb = get_color(prev_val.rb());
166
167            let n_lt = get_color(next_val.lt());
168            let n_rt = get_color(next_val.rt());
169            let n_lb = get_color(next_val.lb());
170            let n_rb = get_color(next_val.rb());
171
172            let start_color = [p_lt.0, p_lt.1, p_lt.2, p_lt.3, p_rt.0, p_rt.1, p_rt.2, p_rt.3, p_lb.0, p_lb.1, p_lb.2, p_lb.3, p_rb.0, p_rb.1, p_rb.2, p_rb.3];
173            let end_color = [n_lt.0, n_lt.1, n_lt.2, n_lt.3, n_rt.0, n_rt.1, n_rt.2, n_rt.3, n_lb.0, n_lb.1, n_lb.2, n_lb.3, n_rb.0, n_rb.1, n_rb.2, n_rb.3];
174            let mut out_color = [0.0; 16];
175            interpolate_color_linear(&start_color, &end_color, rate, &mut out_color);
176
177            let start_rate = [p_lt.4, p_rt.4, p_lb.4, p_rb.4];
178            let end_rate = [n_lt.4, n_rt.4, n_lb.4, n_rb.4];
179            let mut out_rate = [0.0; 4];
180            interpolate_array_linear(&start_rate, &end_rate, rate, &mut out_rate);
181
182            let create_color = |idx: usize| -> runtime::framedata::ss::runtime::SsAttributePartColorKeyValueColor {
183                let base = idx * 4;
184                runtime::framedata::ss::runtime::SsAttributePartColorKeyValueColor::new(&runtime::framedata::ss::runtime::U8Color::new(out_color[base] as u8, out_color[base + 1] as u8, out_color[base + 2] as u8, out_color[base + 3] as u8), out_rate[idx])
185            };
186
187            current.set_lt(&create_color(0));
188            current.set_rt(&create_color(1));
189            current.set_lb(&create_color(2));
190            current.set_rb(&create_color(3));
191            current.set_blend_type(prev_val.blend_type());
192
193            current
194        } else {
195            *prev.part_color()
196        }
197    })
198}
199
200#[inline]
201pub fn evaluate_shader(keys: &KeyColumns<'_>, run: &KeyRun, frame_no: f32, hint: &mut u32) -> Option<runtime::framedata::ss::runtime::PartAttributeShader> {
202    search_prev_next(keys, run, frame_no, hint).map(|(prev, next_opt)| {
203        if let Some(next) = next_opt {
204            let prev_index = prev.index() as i32 as f32;
205            let interpolation = prev.interpolation();
206            if interpolation == InterpolationType::None {
207                return *prev.shader();
208            }
209
210            let next_index = next.index() as i32 as f32;
211            let rate = get_interpolated_rate(interpolation, frame_no, prev_index, next_index, prev.curve(), prev.easing_rate());
212
213            let prev_value = prev.shader();
214            let next_value = next.shader();
215
216            let start_params = [prev_value.param0(), prev_value.param1(), prev_value.param2(), prev_value.param3(), prev_value.param4(), prev_value.param5(), prev_value.param6(), prev_value.param7()];
217            let end_params = [next_value.param0(), next_value.param1(), next_value.param2(), next_value.param3(), next_value.param4(), next_value.param5(), next_value.param6(), next_value.param7()];
218            let mut out_params = [0.0f32; 8];
219            interpolate_array_linear(&start_params, &end_params, rate, &mut out_params);
220
221            runtime::framedata::ss::runtime::PartAttributeShader::new(
222                prev_value.id_hash(),
223                out_params[0],
224                out_params[1],
225                out_params[2],
226                out_params[3],
227                out_params[4],
228                out_params[5],
229                out_params[6],
230                out_params[7],
231                prev_value.map0_cellmap_name_hash(),
232                prev_value.map0_name_hash(),
233                prev_value.map1_cellmap_name_hash(),
234                prev_value.map1_name_hash(),
235            )
236        } else {
237            *prev.shader()
238        }
239    })
240}
241
242#[inline]
243pub fn evaluate_vertex(keys: &KeyColumns<'_>, run: &KeyRun, frame_no: f32, hint: &mut u32) -> Option<runtime::framedata::ss::runtime::PartAttributeVertex> {
244    search_prev_next(keys, run, frame_no, hint).map(|(prev, next_opt)| {
245        if let Some(next) = next_opt {
246            let prev_index = prev.index() as i32 as f32;
247            let interpolation = prev.interpolation();
248            if interpolation == InterpolationType::None {
249                return *prev.vertex();
250            }
251
252            let next_index = next.index() as i32 as f32;
253            let rate = get_interpolated_rate(interpolation, frame_no, prev_index, next_index, prev.curve(), prev.easing_rate());
254
255            let prev_value = prev.vertex();
256            let next_value = next.vertex();
257
258            let get_coords = |v: &runtime::framedata::ss::runtime::Vec2| -> (f32, f32) { (v.x(), v.y()) };
259
260            let p_lt = get_coords(prev_value.lt());
261            let p_rt = get_coords(prev_value.rt());
262            let p_lb = get_coords(prev_value.lb());
263            let p_rb = get_coords(prev_value.rb());
264
265            let n_lt = get_coords(next_value.lt());
266            let n_rt = get_coords(next_value.rt());
267            let n_lb = get_coords(next_value.lb());
268            let n_rb = get_coords(next_value.rb());
269
270            let start_arr = [p_lt.0, p_lt.1, p_rt.0, p_rt.1, p_lb.0, p_lb.1, p_rb.0, p_rb.1];
271            let end_arr = [n_lt.0, n_lt.1, n_rt.0, n_rt.1, n_lb.0, n_lb.1, n_rb.0, n_rb.1];
272            let mut out_arr = [0.0; 8];
273            interpolate_vertex_linear(&start_arr, &end_arr, rate, &mut out_arr);
274
275            let r_v1 = [out_arr[0], out_arr[2], out_arr[4], out_arr[6]];
276            let r_v2 = [out_arr[1], out_arr[3], out_arr[5], out_arr[7]];
277
278            // The center is left at zero: `compute_local_vertices_for_parts` computes it once pivot/size/flip/deform are applied.
279            runtime::framedata::ss::runtime::PartAttributeVertex::new(
280                &runtime::framedata::ss::runtime::Vec2::new(r_v1[0], r_v2[0]),
281                &runtime::framedata::ss::runtime::Vec2::new(r_v1[1], r_v2[1]),
282                &runtime::framedata::ss::runtime::Vec2::new(r_v1[2], r_v2[2]),
283                &runtime::framedata::ss::runtime::Vec2::new(r_v1[3], r_v2[3]),
284                &runtime::framedata::ss::runtime::Vec2::default(),
285            )
286        } else {
287            *prev.vertex()
288        }
289    })
290}
291
292#[inline]
293pub fn evaluate_skew(keys: &KeyColumns<'_>, run: &KeyRun, frame_no: f32, hint: &mut u32) -> Option<(f32, f32)> {
294    search_prev_next(keys, run, frame_no, hint).map(|(prev, next_opt)| {
295        if let Some(next) = next_opt {
296            let (prev_x, prev_y) = prev.skew();
297            let prev_index = prev.index() as i32 as f32;
298            let interpolation = prev.interpolation();
299            if interpolation == InterpolationType::None {
300                return (prev_x, prev_y);
301            }
302
303            let next_index = next.index() as i32 as f32;
304            let rate = get_interpolated_rate(interpolation, frame_no, prev_index, next_index, prev.curve(), prev.easing_rate());
305
306            let (next_x, next_y) = next.skew();
307            (linear(prev_x, next_x, rate), linear(prev_y, next_y, rate))
308        } else {
309            prev.skew()
310        }
311    })
312}
313
314/// Evaluates a deform attribute at `frame_no`, writing the interpolated
315/// coordinates into `coord_out` and the (non-interpolated) indices into
316/// `index_out`. Both output buffers are cleared at entry, so the caller
317/// can reuse them across parts without manual reset.
318///
319/// Returns `false` only for a run with no keys; a frame before the first key
320/// reads the first key, as [`search_prev_next`] does.
321#[inline]
322pub fn evaluate_deform(
323    keys: &KeyColumns<'_>,
324    run: &KeyRun,
325    frame_no: f32,
326    hint: &mut u32,
327    start_workspace: &mut Vec<f32>,
328    end_workspace: &mut Vec<f32>,
329    out_workspace: &mut Vec<f32>,
330    coord_out: &mut Vec<runtime::framedata::ss::runtime::Vec2>,
331    index_out: &mut Vec<i16>,
332) -> bool {
333    coord_out.clear();
334    index_out.clear();
335    let Some((prev, next_opt)) = search_prev_next(keys, run, frame_no, hint) else {
336        return false;
337    };
338    let Some(next) = next_opt else {
339        transfer_deform(&prev.deform(), coord_out, index_out);
340        return true;
341    };
342    let prev_index = prev.index() as i32 as f32;
343    let interpolation = prev.interpolation();
344    if interpolation == InterpolationType::None {
345        transfer_deform(&prev.deform(), coord_out, index_out);
346        return true;
347    }
348
349    let next_index = next.index() as i32 as f32;
350    let rate = get_interpolated_rate(interpolation, frame_no, prev_index, next_index, prev.curve(), prev.easing_rate());
351
352    let prev_val = prev.deform();
353    let next_val = next.deform();
354
355    if let (Some(prev_cx), Some(prev_cy), Some(next_cx), Some(next_cy), Some(prev_idx), Some(next_idx)) = (prev_val.coord_x(), prev_val.coord_y(), next_val.coord_x(), next_val.coord_y(), prev_val.index(), next_val.index()) {
356        // Deform keyframes store a sparse, vertex-keyed set of offsets:
357        // `index[k]` is the changed vertex and `coord_x[k]/coord_y[k]`
358        // its offset. The changed-vertex set differs between keyframes
359        // (e.g. an empty rest keyframe vs a deformed one), so the two
360        // sides cannot be interpolated position-by-position. Merge by
361        // vertex index instead — a vertex absent on one side
362        // interpolates against a zero offset. Authored index arrays
363        // are ascending, so a two-pointer merge keeps the output
364        // ascending and allocation-free.
365        let prev_n = prev_cx.len().min(prev_cy.len());
366        let next_n = next_cx.len().min(next_cy.len());
367        let prev_len = core::cmp::min(prev_idx.len(), prev_n);
368        let next_len = core::cmp::min(next_idx.len(), next_n);
369
370        start_workspace.clear();
371        end_workspace.clear();
372        index_out.reserve(prev_len + next_len);
373
374        let mut i = 0usize;
375        let mut j = 0usize;
376        while i < prev_len || j < next_len {
377            let pv = if i < prev_len { prev_idx.get(i) } else { i16::MAX };
378            let nv = if j < next_len { next_idx.get(j) } else { i16::MAX };
379            if pv == nv {
380                start_workspace.push(prev_cx.get(i));
381                start_workspace.push(prev_cy.get(i));
382                end_workspace.push(next_cx.get(j));
383                end_workspace.push(next_cy.get(j));
384                index_out.push(pv);
385                i += 1;
386                j += 1;
387            } else if pv < nv {
388                start_workspace.push(prev_cx.get(i));
389                start_workspace.push(prev_cy.get(i));
390                end_workspace.push(0.0);
391                end_workspace.push(0.0);
392                index_out.push(pv);
393                i += 1;
394            } else {
395                start_workspace.push(0.0);
396                start_workspace.push(0.0);
397                end_workspace.push(next_cx.get(j));
398                end_workspace.push(next_cy.get(j));
399                index_out.push(nv);
400                j += 1;
401            }
402        }
403
404        out_workspace.clear();
405        out_workspace.resize(start_workspace.len(), 0.0);
406        interpolate_array_linear(start_workspace, end_workspace, rate, out_workspace);
407
408        coord_out.reserve(index_out.len());
409        for k in 0..index_out.len() {
410            coord_out.push(runtime::framedata::ss::runtime::Vec2::new(out_workspace[k * 2], out_workspace[k * 2 + 1]));
411        }
412    } else if let (Some(prev_cx), Some(prev_cy), Some(next_cx), Some(next_cy)) = (prev_val.coord_x(), prev_val.coord_y(), next_val.coord_x(), next_val.coord_y()) {
413        // No per-vertex index array on one or both keyframes: the
414        // coordinate arrays are positionally aligned, so interpolate
415        // vertex-by-vertex. When prev is longer than next, its
416        // trailing vertices pass through unchanged.
417        let prev_n = prev_cx.len().min(prev_cy.len());
418        let next_n = next_cx.len().min(next_cy.len());
419        let length_full = prev_n;
420        let length = core::cmp::min(prev_n, next_n);
421
422        start_workspace.clear();
423        end_workspace.clear();
424        for i in 0..length {
425            start_workspace.push(prev_cx.get(i));
426            start_workspace.push(prev_cy.get(i));
427            end_workspace.push(next_cx.get(i));
428            end_workspace.push(next_cy.get(i));
429        }
430
431        out_workspace.clear();
432        out_workspace.resize(length * 2, 0.0);
433        interpolate_array_linear(start_workspace, end_workspace, rate, out_workspace);
434
435        coord_out.reserve(length_full);
436        for i in 0..length {
437            coord_out.push(runtime::framedata::ss::runtime::Vec2::new(out_workspace[i * 2], out_workspace[i * 2 + 1]));
438        }
439        for i in length..length_full {
440            coord_out.push(runtime::framedata::ss::runtime::Vec2::new(prev_cx.get(i), prev_cy.get(i)));
441        }
442        if let Some(index) = prev_val.index() {
443            index_out.extend(index.iter());
444        }
445    } else {
446        transfer_deform(&prev.deform(), coord_out, index_out);
447    }
448    true
449}
450
451#[inline]
452fn transfer_deform(source: &ssab::ssab::ss::format::PartAttributeDeform, coord_out: &mut Vec<runtime::framedata::ss::runtime::Vec2>, index_out: &mut Vec<i16>) {
453    let s = source;
454
455    if let (Some(cx), Some(cy)) = (s.coord_x(), s.coord_y()) {
456        let n = cx.len().min(cy.len());
457        coord_out.reserve(n);
458        for i in 0..n {
459            coord_out.push(runtime::framedata::ss::runtime::Vec2::new(cx.get(i), cy.get(i)));
460        }
461    }
462    if let Some(index) = s.index() {
463        index_out.reserve(index.len());
464        index_out.extend(index.iter());
465    }
466}
467
468#[inline]
469pub fn evaluate_bool(keys: &KeyColumns<'_>, run: &KeyRun, frame_no: f32, hint: &mut u32) -> Option<bool> {
470    let frame_no = crate::eval::math::floorf(frame_no) as i32;
471    search_prev(keys, run, frame_no, hint).map(|prev| prev.bool())
472}
473
474#[inline]
475pub fn evaluate_cell(keys: &KeyColumns<'_>, run: &KeyRun, frame_no: f32, hint: &mut u32) -> Option<u32> {
476    let frame_no = crate::eval::math::floorf(frame_no) as i32;
477    search_prev(keys, run, frame_no, hint).map(|prev| prev.cell())
478}
479
480#[inline]
481pub fn evaluate_texture(keys: &KeyColumns<'_>, run: &KeyRun, frame_no: f32, hint: &mut u32) -> Option<u32> {
482    let frame_no = crate::eval::math::floorf(frame_no) as i32;
483    search_prev(keys, run, frame_no, hint).map(|prev| prev.uint())
484}
485
486#[cfg(test)]
487mod tests {
488    use super::*;
489    use flatbuffers::{FlatBufferBuilder, WIPOffset};
490    use ssab::ssab::ss::format::{KeyCurve, Keyframes, KeyframesArgs, PartAttributeCell, PartAttributeDeform, PartAttributePartColor, PartAttributeShader, PartAttributeVertex, Vec2};
491
492    use ssab::NO_CURVE;
493
494    /// One key of a test pack: its frame, interpolation, value bits and
495    /// `Keyframes.curve` slot.
496    struct TestKey {
497        frame: u16,
498        interpolation: InterpolationType,
499        value: u32,
500        slot: u16,
501    }
502
503    fn key(frame: u16, interpolation: InterpolationType, value: u32) -> TestKey {
504        TestKey { frame, interpolation, value, slot: NO_CURVE }
505    }
506
507    fn curved(frame: u16, interpolation: InterpolationType, value: u32, slot: u16) -> TestKey {
508        TestKey { frame, interpolation, value, slot }
509    }
510
511    /// A pack whose keys are `keys`, with the given curve and easing tables and
512    /// whatever value tables `values` fills in; the rest are present and empty.
513    fn pack(keys: &[TestKey], curves: &[KeyCurve], easing_rates: &[f32], values: impl FnOnce(&mut FlatBufferBuilder<'static>, &mut KeyframesArgs<'static>)) -> alloc::vec::Vec<u8> {
514        let mut fb = FlatBufferBuilder::new();
515        let mut args = KeyframesArgs::default();
516        values(&mut fb, &mut args);
517        let frame: alloc::vec::Vec<u16> = keys.iter().map(|k| k.frame).collect();
518        let interpolation: alloc::vec::Vec<InterpolationType> = keys.iter().map(|k| k.interpolation).collect();
519        let curve: alloc::vec::Vec<u16> = keys.iter().map(|k| k.slot).collect();
520        let value: alloc::vec::Vec<u32> = keys.iter().map(|k| k.value).collect();
521        args.runs = Some(fb.create_vector(&[0u32, keys.len() as u32]));
522        args.frame = Some(fb.create_vector(&frame));
523        args.interpolation = Some(fb.create_vector(&interpolation));
524        args.curve = Some(fb.create_vector(&curve));
525        args.value = Some(fb.create_vector(&value));
526        args.curves = Some(fb.create_vector(curves));
527        args.easing_rates = Some(fb.create_vector(easing_rates));
528        args.cells = args.cells.or_else(|| Some(fb.create_vector::<WIPOffset<PartAttributeCell>>(&[])));
529        args.part_colors = args.part_colors.or_else(|| Some(fb.create_vector::<WIPOffset<PartAttributePartColor>>(&[])));
530        args.shaders = args.shaders.or_else(|| Some(fb.create_vector::<WIPOffset<PartAttributeShader>>(&[])));
531        args.vertices = args.vertices.or_else(|| Some(fb.create_vector::<WIPOffset<PartAttributeVertex>>(&[])));
532        args.skews = args.skews.or_else(|| Some(fb.create_vector::<WIPOffset<Vec2>>(&[])));
533        args.deforms = args.deforms.or_else(|| Some(fb.create_vector::<WIPOffset<PartAttributeDeform>>(&[])));
534        let root = Keyframes::create(&mut fb, &args);
535        fb.finish(root, None);
536        fb.finished_data().to_vec()
537    }
538
539    fn columns(buf: &[u8]) -> KeyColumns<'_> {
540        KeyColumns::new(flatbuffers::root::<Keyframes>(buf).unwrap(), None)
541    }
542
543    /// The run of the first `count` keys.
544    fn run(count: usize) -> KeyRun {
545        KeyRun::new(0, count as u32)
546    }
547
548    fn f(value: f32) -> u32 {
549        value.to_bits()
550    }
551
552    #[test]
553    fn test_linear_interpolation() {
554        assert_eq!(linear(0.0, 10.0, 0.5), 5.0);
555        assert_eq!(linear(10.0, 20.0, 0.0), 10.0);
556        assert_eq!(linear(10.0, 20.0, 1.0), 20.0);
557    }
558
559    #[test]
560    fn test_evaluate_bool() {
561        let buf = pack(&[key(0, InterpolationType::None, 1), key(10, InterpolationType::None, 0)], &[], &[], |_, _| {});
562        let (keys, run) = (columns(&buf), run(2));
563
564        let mut hint = 0;
565        // Exact match
566        assert_eq!(evaluate_bool(&keys, &run, 0.0, &mut hint), Some(true));
567        // Interpolated (should use prev)
568        assert_eq!(evaluate_bool(&keys, &run, 5.0, &mut hint), Some(true));
569        // Exact match
570        assert_eq!(evaluate_bool(&keys, &run, 10.0, &mut hint), Some(false));
571        // Beyond last key
572        assert_eq!(evaluate_bool(&keys, &run, 15.0, &mut hint), Some(false));
573        // Before first key
574        assert_eq!(evaluate_bool(&keys, &run, -1.0, &mut hint), None);
575        // Fractional: floor() applied internally — 9.9 → 9 → still uses prev (true)
576        assert_eq!(evaluate_bool(&keys, &run, 9.9, &mut hint), Some(true));
577        // Back on the key after a fractional frame: 10.0 → 10 → false
578        assert_eq!(evaluate_bool(&keys, &run, 10.0, &mut hint), Some(false));
579    }
580
581    #[test]
582    fn test_evaluate_texture() {
583        let buf = pack(&[key(0, InterpolationType::None, 100), key(10, InterpolationType::None, 200)], &[], &[], |_, _| {});
584        let (keys, run) = (columns(&buf), run(2));
585
586        let mut hint = 0;
587        assert_eq!(evaluate_texture(&keys, &run, 0.0, &mut hint), Some(100));
588        assert_eq!(evaluate_texture(&keys, &run, 5.0, &mut hint), Some(100));
589        assert_eq!(evaluate_texture(&keys, &run, 10.0, &mut hint), Some(200));
590        assert_eq!(evaluate_texture(&keys, &run, 15.0, &mut hint), Some(200));
591        // Fractional: floor() applied internally — 9.99 → 9 → still 100
592        assert_eq!(evaluate_texture(&keys, &run, 9.99, &mut hint), Some(100));
593    }
594
595    #[test]
596    fn test_evaluate_int_no_interpolation() {
597        let buf = pack(&[key(0, InterpolationType::None, 100), key(10, InterpolationType::None, 200)], &[], &[], |_, _| {});
598        let (keys, run) = (columns(&buf), run(2));
599
600        let mut hint = 0;
601        // At frame 0, the key's own value.
602        let val = evaluate_int(&keys, &run, 0.0, &mut hint).unwrap();
603        assert_eq!(val, 100);
604
605        // At frame 5, the value is held from frame 0 (InterpolationType::None
606        // doesn't tween) and still comes from a key, so it is `Some`: that is
607        // what `evaluate_part` sets the attribute's update flag from, which
608        // cell-default fallbacks and Player render-path checks rely on so they
609        // don't silently overwrite the held animated value.
610        let val = evaluate_int(&keys, &run, 5.0, &mut hint).unwrap();
611        assert_eq!(val, 100);
612
613        // At frame 10, the second key.
614        let val = evaluate_int(&keys, &run, 10.0, &mut hint).unwrap();
615        assert_eq!(val, 200);
616    }
617
618    #[test]
619    fn test_evaluate_int_linear_interpolation_fractional() {
620        let buf = pack(&[key(0, InterpolationType::Linear, 0), key(10, InterpolationType::None, 100)], &[], &[], |_, _| {});
621        let (keys, run) = (columns(&buf), run(2));
622
623        // Fractional frame: 5.5 should yield round(linear(0,100,0.55)) == 55
624        let mut hint = 0;
625        let val = evaluate_int(&keys, &run, 5.5, &mut hint).unwrap();
626        assert_eq!(val, 55);
627
628        // Integer frame between the keys (rate=0.5 -> 50)
629        let mut hint = 0;
630        let val = evaluate_int(&keys, &run, 5.0, &mut hint).unwrap();
631        assert_eq!(val, 50);
632    }
633
634    #[test]
635    fn test_evaluate_float_linear_interpolation_fractional() {
636        let buf = pack(&[key(0, InterpolationType::Linear, f(0.0)), key(10, InterpolationType::None, f(1.0))], &[], &[], |_, _| {});
637        let (keys, run) = (columns(&buf), run(2));
638
639        // Fractional 2.5 → rate 0.25
640        let mut hint = 0;
641        let val = evaluate_float(&keys, &run, 2.5, &mut hint).unwrap();
642        assert!((val - 0.25).abs() < 1e-6, "expected ~0.25, got {val}");
643
644        // Integer 5 → rate 0.5
645        let mut hint = 0;
646        let val = evaluate_float(&keys, &run, 5.0, &mut hint).unwrap();
647        assert!((val - 0.5).abs() < 1e-6);
648    }
649
650    #[test]
651    fn test_evaluate_float_reads_only_its_own_run() {
652        // Two runs side by side in one pack: each sees only its own keys.
653        let buf = pack(&[key(0, InterpolationType::None, f(1.0)), key(10, InterpolationType::None, f(2.0)), key(0, InterpolationType::Linear, f(5.0)), key(4, InterpolationType::None, f(9.0))], &[], &[], |_, _| {});
654        let keys = columns(&buf);
655        let (first, second) = (KeyRun::new(0, 2), KeyRun::new(2, 2));
656
657        let mut hint = 0;
658        assert_eq!(evaluate_float(&keys, &first, 20.0, &mut hint).unwrap(), 2.0);
659        let mut hint = 0;
660        assert_eq!(evaluate_float(&keys, &second, 2.0, &mut hint).unwrap(), 7.0);
661        let mut hint = 0;
662        assert_eq!(evaluate_float(&keys, &second, 20.0, &mut hint).unwrap(), 9.0);
663        let mut hint = 0;
664        assert_eq!(evaluate_float(&keys, &KeyRun::new(2, 0), 2.0, &mut hint), None);
665    }
666
667    #[test]
668    fn test_evaluate_cell() {
669        let buf = pack(&[key(0, InterpolationType::None, 0), key(10, InterpolationType::None, 1)], &[], &[], |fb, args| {
670            let cell_a = PartAttributeCell::create(fb, &ssab::ssab::ss::format::PartAttributeCellArgs { cellmap_name_hash: 1, name_hash: 111 });
671            let cell_b = PartAttributeCell::create(fb, &ssab::ssab::ss::format::PartAttributeCellArgs { cellmap_name_hash: 2, name_hash: 222 });
672            args.cells = Some(fb.create_vector(&[cell_a, cell_b]));
673        });
674        let (keys, run) = (columns(&buf), run(2));
675
676        let mut hint = 0;
677        let res = keys.cell(evaluate_cell(&keys, &run, 5.0, &mut hint).unwrap()).cell;
678        assert_eq!(res.cellmap_name_hash(), 1);
679        assert_eq!(res.name_hash(), 111);
680
681        let res = keys.cell(evaluate_cell(&keys, &run, 10.0, &mut hint).unwrap()).cell;
682        assert_eq!(res.cellmap_name_hash(), 2);
683        assert_eq!(res.name_hash(), 222);
684
685        // Fractional: floor() applied internally — 9.999 → 9 → still cell A
686        let mut hint = 0;
687        let res = keys.cell(evaluate_cell(&keys, &run, 9.999, &mut hint).unwrap()).cell;
688        assert_eq!(res.cellmap_name_hash(), 1);
689    }
690
691    #[test]
692    fn test_evaluate_float_hermite() {
693        // start_value/end_value are absolute target values for tangents, so
694        // (0, 1) → tangent (s_start - v_start) = 0 at start, (s_end - v_end) = 0 at end.
695        let curve = KeyCurve::new(0.0, 0.0, 0.0, 1.0);
696        let buf = pack(&[curved(0, InterpolationType::Hermite, f(0.0), 0), key(10, InterpolationType::None, f(1.0))], &[curve], &[], |_, _| {});
697        let (keys, run) = (columns(&buf), run(2));
698
699        // Hermite with zero tangents at midpoint: rate = 3*0.5^2 - 2*0.5^3 = 0.5
700        let mut hint = 0;
701        let val = evaluate_float(&keys, &run, 5.0, &mut hint).unwrap();
702        assert!((val - 0.5).abs() < 1e-6, "expected ~0.5, got {val}");
703
704        // Sub-frame between integer keys: smooth Hermite curve
705        let mut hint = 0;
706        let val_25 = evaluate_float(&keys, &run, 2.5, &mut hint).unwrap();
707        let val_3 = evaluate_float(&keys, &run, 3.0, &mut hint).unwrap();
708        assert!(val_25 < val_3, "Hermite must be monotonically increasing on this segment");
709        assert!(val_25 > 0.0 && val_25 < 1.0);
710    }
711
712    #[test]
713    fn locate_finds_the_last_key_at_or_before_a_frame_from_any_hint() {
714        // Two keys share frame 20, where the later one is the answer. The keys
715        // are far enough apart that some hints settle by walking and others
716        // fall back to the binary search, both ways, and the last hints are
717        // past the run's end.
718        let frames = [0u16, 10, 20, 20, 30, 40, 50, 60, 70, 80];
719        let buf = pack(&frames.map(|frame| key(frame, InterpolationType::None, 0)), &[], &[], |_, _| {});
720        let (keys, run) = (columns(&buf), run(frames.len()));
721        let expected = |frame_no: f32| frames.iter().rposition(|&k| k as f32 <= frame_no);
722        for start in 0..frames.len() as u32 + 2 {
723            for frame_no in [-1.0, 0.0, 5.0, 10.0, 19.5, 20.0, 25.0, 59.0, 80.0, 81.0] {
724                let mut hint = start;
725                assert_eq!(keys.frames(&run).locate(frame_no, &mut hint), expected(frame_no), "frame {frame_no}, hint {start}");
726                assert_eq!(hint, expected(frame_no).unwrap_or(0) as u32, "the hint is left on the key found");
727            }
728        }
729    }
730
731    #[test]
732    fn a_frame_on_a_key_reads_that_key_whatever_the_hint() {
733        // The Bezier solve does not land exactly on a segment's start, so
734        // reading key 10 as "the 10..20 segment at rate 0" would come out a
735        // little off key 10's own value. Every hint must give the key's value.
736        let curve = KeyCurve::new(3.0, 40.0, -3.0, -40.0);
737        let keys = [curved(0, InterpolationType::Bezier, f(0.0), 0), curved(10, InterpolationType::Bezier, f(100.0), 0), curved(20, InterpolationType::Bezier, f(50.0), 0), key(30, InterpolationType::None, f(0.0))];
738        let buf = pack(&keys, &[curve], &[], |_, _| {});
739        let (keys, run) = (columns(&buf), run(4));
740        for start in 0..4 {
741            for (frame, value) in [(10.0, 100.0), (20.0, 50.0)] {
742                let mut hint = start;
743                assert_eq!(evaluate_float(&keys, &run, frame, &mut hint).unwrap(), value, "frame {frame}, hint {start}");
744            }
745        }
746    }
747
748    #[test]
749    fn test_evaluate_float_ease_in() {
750        let buf = pack(&[curved(0, InterpolationType::EaseIn, f(0.0), 0), key(10, InterpolationType::None, f(1.0))], &[], &[2.0], |_, _| {});
751        let (keys, run) = (columns(&buf), run(2));
752
753        // EaseIn with power 2 at rate 0.5: 0.5^2 = 0.25
754        let mut hint = 0;
755        let val = evaluate_float(&keys, &run, 5.0, &mut hint).unwrap();
756        assert!((val - 0.25).abs() < 1e-5, "expected ~0.25, got {val}");
757
758        // Sub-frame: smooth, not stepped
759        let mut hint = 0;
760        let val_25 = evaluate_float(&keys, &run, 2.5, &mut hint).unwrap();
761        let val_3 = evaluate_float(&keys, &run, 3.0, &mut hint).unwrap();
762        assert!(val_25 < val_3);
763    }
764
765    #[test]
766    fn test_evaluate_skew_linear() {
767        let buf = pack(&[key(0, InterpolationType::Linear, 0), key(10, InterpolationType::None, 1)], &[], &[], |fb, args| {
768            let v0 = Vec2::create(fb, &ssab::ssab::ss::format::Vec2Args { v1: 0.0, v2: 0.0 });
769            let v10 = Vec2::create(fb, &ssab::ssab::ss::format::Vec2Args { v1: 10.0, v2: 20.0 });
770            args.skews = Some(fb.create_vector(&[v0, v10]));
771        });
772        let (keys, run) = (columns(&buf), run(2));
773
774        // Midpoint: linear interpolation of both axes
775        let mut hint = 0;
776        let (val_x, val_y) = evaluate_skew(&keys, &run, 5.0, &mut hint).unwrap();
777        assert!((val_x - 5.0).abs() < 1e-6);
778        assert!((val_y - 10.0).abs() < 1e-6);
779
780        // Sub-frame: smooth interpolation
781        let mut hint = 0;
782        let (val_x, val_y) = evaluate_skew(&keys, &run, 2.5, &mut hint).unwrap();
783        assert!((val_x - 2.5).abs() < 1e-6);
784        assert!((val_y - 5.0).abs() < 1e-6);
785    }
786
787    #[test]
788    fn test_evaluate_vertex_linear() {
789        use ssab::ssab::ss::format::{PartAttributeVertexArgs, Vec2Args};
790        let buf = pack(&[key(0, InterpolationType::Linear, 0), key(10, InterpolationType::None, 1)], &[], &[], |fb, args| {
791            let lt0 = Vec2::create(fb, &Vec2Args { v1: 0.0, v2: 0.0 });
792            let rt0 = Vec2::create(fb, &Vec2Args { v1: 0.0, v2: 0.0 });
793            let lb0 = Vec2::create(fb, &Vec2Args { v1: 0.0, v2: 0.0 });
794            let rb0 = Vec2::create(fb, &Vec2Args { v1: 0.0, v2: 0.0 });
795            let v0 = PartAttributeVertex::create(fb, &PartAttributeVertexArgs { lt: Some(lt0), rt: Some(rt0), lb: Some(lb0), rb: Some(rb0) });
796
797            let lt1 = Vec2::create(fb, &Vec2Args { v1: 10.0, v2: 10.0 });
798            let rt1 = Vec2::create(fb, &Vec2Args { v1: -10.0, v2: 10.0 });
799            let lb1 = Vec2::create(fb, &Vec2Args { v1: 10.0, v2: -10.0 });
800            let rb1 = Vec2::create(fb, &Vec2Args { v1: -10.0, v2: -10.0 });
801            let v10 = PartAttributeVertex::create(fb, &PartAttributeVertexArgs { lt: Some(lt1), rt: Some(rt1), lb: Some(lb1), rb: Some(rb1) });
802            args.vertices = Some(fb.create_vector(&[v0, v10]));
803        });
804        let (keys, run) = (columns(&buf), run(2));
805
806        // Midpoint: each corner linearly interpolated
807        let mut hint = 0;
808        let val = evaluate_vertex(&keys, &run, 5.0, &mut hint).unwrap();
809        assert!((val.lt().x() - 5.0).abs() < 1e-6);
810        assert!((val.rt().x() - -5.0).abs() < 1e-6);
811        assert!((val.lb().y() - -5.0).abs() < 1e-6);
812        assert!((val.rb().y() - -5.0).abs() < 1e-6);
813    }
814
815    // -- evaluate_deform tests --
816
817    /// A pack of deform keys, one value each, with given index, interpolation,
818    /// coordinates and indices.
819    #[allow(clippy::type_complexity)]
820    fn deform_buf(keys: &[(u16, InterpolationType, &[(f32, f32)], &[i16])]) -> alloc::vec::Vec<u8> {
821        deform_buf_with_curves(keys, &[])
822    }
823
824    #[allow(clippy::type_complexity)]
825    fn deform_buf_with_curves(keys: &[(u16, InterpolationType, &[(f32, f32)], &[i16])], curves: &[KeyCurve]) -> alloc::vec::Vec<u8> {
826        use ssab::ssab::ss::format::PartAttributeDeformArgs;
827        let test_keys: alloc::vec::Vec<TestKey> = keys.iter().enumerate().map(|(i, (idx, ip, _, _))| curved(*idx, *ip, i as u32, if curves.is_empty() || *ip == InterpolationType::None { NO_CURVE } else { 0 })).collect();
828        pack(&test_keys, curves, &[], |fb, args| {
829            let mut values = alloc::vec::Vec::new();
830            for (_, _, coords, indices) in keys {
831                let xs: alloc::vec::Vec<f32> = coords.iter().map(|(x, _)| *x).collect();
832                let ys: alloc::vec::Vec<f32> = coords.iter().map(|(_, y)| *y).collect();
833                let cx_off = if xs.is_empty() { None } else { Some(fb.create_vector(&xs)) };
834                let cy_off = if ys.is_empty() { None } else { Some(fb.create_vector(&ys)) };
835                let idx_off = if indices.is_empty() { None } else { Some(fb.create_vector(indices)) };
836                values.push(PartAttributeDeform::create(fb, &PartAttributeDeformArgs { coord_x: cx_off, coord_y: cy_off, index: idx_off }));
837            }
838            args.deforms = Some(fb.create_vector(&values));
839        })
840    }
841
842    /// Owning wrapper used only by tests so assertions can read back the
843    /// produced coordinate / index buffers without having to declare and
844    /// thread workspace `Vec`s through every call site.
845    struct DeformOut {
846        coordinate: alloc::vec::Vec<runtime::framedata::ss::runtime::Vec2>,
847        index: alloc::vec::Vec<i16>,
848    }
849
850    fn eval_deform_owned(buf: &[u8], frame_no: f32, hint: &mut u32) -> Option<DeformOut> {
851        let keys = columns(buf);
852        let run = run(keys_len(buf));
853        let mut start = alloc::vec::Vec::new();
854        let mut end = alloc::vec::Vec::new();
855        let mut out = alloc::vec::Vec::new();
856        let mut coordinate = alloc::vec::Vec::new();
857        let mut index = alloc::vec::Vec::new();
858        evaluate_deform(&keys, &run, frame_no, hint, &mut start, &mut end, &mut out, &mut coordinate, &mut index).then_some(DeformOut { coordinate, index })
859    }
860
861    fn keys_len(buf: &[u8]) -> usize {
862        flatbuffers::root::<Keyframes>(buf).unwrap().frame().len()
863    }
864
865    #[test]
866    fn test_evaluate_deform_simd_chunk_aligned() {
867        // 8 vertices = 16 interleaved floats: exactly 4 SIMD chunks, no tail.
868        let prev: alloc::vec::Vec<(f32, f32)> = (0..8).map(|i| (i as f32, i as f32 * 2.0)).collect();
869        let next: alloc::vec::Vec<(f32, f32)> = (0..8).map(|i| (i as f32 * 3.0, i as f32 * 4.0)).collect();
870        let buf = deform_buf(&[(0, InterpolationType::Linear, &prev, &[]), (10, InterpolationType::None, &next, &[])]);
871
872        // At rate=0.5, lerp(prev, next, 0.5) = (prev + next) / 2.
873        let mut hint = 0;
874        let data = eval_deform_owned(&buf, 5.0, &mut hint).unwrap();
875        assert_eq!(data.coordinate.len(), 8);
876        for i in 0..8 {
877            let exp_x = (prev[i].0 + next[i].0) / 2.0;
878            let exp_y = (prev[i].1 + next[i].1) / 2.0;
879            assert!((data.coordinate[i].x() - exp_x).abs() < 1e-6, "x mismatch at {i}: got {} want {exp_x}", data.coordinate[i].x());
880            assert!((data.coordinate[i].y() - exp_y).abs() < 1e-6, "y mismatch at {i}: got {} want {exp_y}", data.coordinate[i].y());
881        }
882    }
883
884    #[test]
885    fn test_evaluate_deform_simd_with_tail() {
886        // 7 vertices = 14 interleaved floats: 3 SIMD chunks + a 1-vertex tail. Both branches must produce identical results.
887        let prev: alloc::vec::Vec<(f32, f32)> = (0..7).map(|i| (i as f32, i as f32 * 10.0)).collect();
888        let next: alloc::vec::Vec<(f32, f32)> = (0..7).map(|i| ((i as f32) + 100.0, (i as f32) * 10.0 + 1000.0)).collect();
889        let buf = deform_buf(&[(0, InterpolationType::Linear, &prev, &[]), (10, InterpolationType::None, &next, &[])]);
890
891        let mut hint = 0;
892        let data = eval_deform_owned(&buf, 2.5, &mut hint).unwrap();
893        assert_eq!(data.coordinate.len(), 7);
894        // rate = 0.25
895        for i in 0..7 {
896            let exp_x = prev[i].0 + (next[i].0 - prev[i].0) * 0.25;
897            let exp_y = prev[i].1 + (next[i].1 - prev[i].1) * 0.25;
898            assert!((data.coordinate[i].x() - exp_x).abs() < 1e-4, "x mismatch at {i}: got {} want {exp_x}", data.coordinate[i].x());
899            assert!((data.coordinate[i].y() - exp_y).abs() < 1e-4, "y mismatch at {i}: got {} want {exp_y}", data.coordinate[i].y());
900        }
901    }
902
903    #[test]
904    fn test_evaluate_deform_simd_one_chunk_and_tail() {
905        // 3 vertices = 6 interleaved floats: 1 SIMD chunk + a 1-vertex tail.
906        let prev = [(0.0, 0.0), (1.0, 2.0), (3.0, 4.0)];
907        let next = [(10.0, 20.0), (11.0, 22.0), (13.0, 24.0)];
908        let buf = deform_buf(&[(0, InterpolationType::Linear, &prev, &[]), (10, InterpolationType::None, &next, &[])]);
909
910        let mut hint = 0;
911        let data = eval_deform_owned(&buf, 5.0, &mut hint).unwrap();
912        assert_eq!(data.coordinate.len(), 3);
913        for i in 0..3 {
914            let exp_x = (prev[i].0 + next[i].0) / 2.0;
915            let exp_y = (prev[i].1 + next[i].1) / 2.0;
916            assert!((data.coordinate[i].x() - exp_x).abs() < 1e-6);
917            assert!((data.coordinate[i].y() - exp_y).abs() < 1e-6);
918        }
919    }
920
921    #[test]
922    fn test_evaluate_deform_overrun_prev_longer() {
923        // prev has 6 vertices, next has 4. The 2 extras must come from prev as-is.
924        let prev: alloc::vec::Vec<(f32, f32)> = (0..6).map(|i| (i as f32 + 100.0, i as f32 + 200.0)).collect();
925        let next: alloc::vec::Vec<(f32, f32)> = (0..4).map(|i| (i as f32, i as f32)).collect();
926        let buf = deform_buf(&[(0, InterpolationType::Linear, &prev, &[]), (10, InterpolationType::None, &next, &[])]);
927
928        let mut hint = 0;
929        let data = eval_deform_owned(&buf, 5.0, &mut hint).unwrap();
930        assert_eq!(data.coordinate.len(), 6, "output length should match prev's vertex count");
931        // First 4 are interpolated.
932        for i in 0..4 {
933            let exp_x = (prev[i].0 + next[i].0) / 2.0;
934            let exp_y = (prev[i].1 + next[i].1) / 2.0;
935            assert!((data.coordinate[i].x() - exp_x).abs() < 1e-4, "interpolated x mismatch at {i}");
936            assert!((data.coordinate[i].y() - exp_y).abs() < 1e-4, "interpolated y mismatch at {i}");
937        }
938        // Indices 4 and 5: passthrough from prev.
939        for (i, p) in prev.iter().enumerate().take(6).skip(4) {
940            assert_eq!(data.coordinate[i].x(), p.0, "overrun x at {i}");
941            assert_eq!(data.coordinate[i].y(), p.1, "overrun y at {i}");
942        }
943    }
944
945    #[test]
946    fn test_evaluate_deform_none_at_keyframe() {
947        // None interpolation at exact keyframe → found, prev value.
948        let prev = [(1.0, 2.0), (3.0, 4.0)];
949        let next = [(10.0, 20.0), (30.0, 40.0)];
950        let buf = deform_buf(&[(0, InterpolationType::None, &prev, &[]), (10, InterpolationType::None, &next, &[])]);
951
952        let mut hint = 0;
953        let data = eval_deform_owned(&buf, 0.0, &mut hint).unwrap();
954        assert_eq!(data.coordinate[0].x(), prev[0].0);
955        assert_eq!(data.coordinate[0].y(), prev[0].1);
956    }
957
958    #[test]
959    fn test_evaluate_deform_none_off_keyframe() {
960        // None interpolation off-keyframe: value is held from prev key, and it
961        // still comes from a key, so it is found. Consumers (e.g. Player
962        // render-path checks) need the flag set from that so they don't
963        // silently overwrite the held value.
964        let prev = [(1.0, 2.0), (3.0, 4.0)];
965        let next = [(10.0, 20.0), (30.0, 40.0)];
966        let buf = deform_buf(&[(0, InterpolationType::None, &prev, &[]), (10, InterpolationType::None, &next, &[])]);
967
968        let mut hint = 0;
969        let data = eval_deform_owned(&buf, 5.0, &mut hint).unwrap();
970        assert_eq!(data.coordinate[0].x(), prev[0].0);
971    }
972
973    #[test]
974    fn test_evaluate_deform_after_last_key() {
975        // After last key: value is held from the last key, and is found (the
976        // value still comes from animation data).
977        let prev = [(7.0, 8.0)];
978        let buf = deform_buf(&[(5, InterpolationType::Linear, &prev, &[])]);
979
980        let mut hint = 0;
981        let data = eval_deform_owned(&buf, 5.0, &mut hint).unwrap();
982        assert_eq!(data.coordinate[0].x(), 7.0);
983
984        let mut hint = 0;
985        let data = eval_deform_owned(&buf, 9.0, &mut hint).unwrap();
986        assert_eq!(data.coordinate[0].x(), 7.0);
987    }
988
989    #[test]
990    fn test_evaluate_deform_index_merged() {
991        // Deform keyframes may change different vertex sets. evaluate_deform
992        // merges prev and next by vertex index; a vertex present on only one
993        // side interpolates against a zero offset.
994        let prev = [(6.0, 6.0), (2.0, 2.0)];
995        let next = [(8.0, 8.0), (4.0, 4.0)];
996        let prev_indices: [i16; 2] = [1, 3];
997        let next_indices: [i16; 2] = [3, 5];
998        let buf = deform_buf(&[(0, InterpolationType::Linear, &prev, &prev_indices), (10, InterpolationType::None, &next, &next_indices)]);
999
1000        let mut hint = 0;
1001        let data = eval_deform_owned(&buf, 5.0, &mut hint).unwrap();
1002        // Ascending union of {1,3} and {3,5}.
1003        assert_eq!(data.index, alloc::vec![1, 3, 5]);
1004        // rate = 0.5. v1: prev-only  -> lerp((6,6), 0)      = (3,3).
1005        //             v3: both       -> lerp((2,2), (8,8))  = (5,5).
1006        //             v5: next-only  -> lerp(0,     (4,4))  = (2,2).
1007        assert!((data.coordinate[0].x() - 3.0).abs() < 1e-6, "v1 x: got {}", data.coordinate[0].x());
1008        assert!((data.coordinate[1].x() - 5.0).abs() < 1e-6, "v3 x: got {}", data.coordinate[1].x());
1009        assert!((data.coordinate[2].x() - 2.0).abs() < 1e-6, "v5 x: got {}", data.coordinate[2].x());
1010    }
1011
1012    #[test]
1013    fn test_evaluate_deform_hermite() {
1014        // Hermite interpolation with zero tangents matches midpoint at rate 0.5.
1015        let prev: alloc::vec::Vec<(f32, f32)> = (0..4).map(|i| (i as f32, 0.0)).collect();
1016        let next: alloc::vec::Vec<(f32, f32)> = (0..4).map(|i| ((i as f32) + 10.0, 0.0)).collect();
1017        let buf = deform_buf_with_curves(&[(0, InterpolationType::Hermite, &prev, &[]), (10, InterpolationType::None, &next, &[])], &[KeyCurve::new(0.0, 0.0, 0.0, 1.0)]);
1018
1019        let mut hint = 0;
1020        let data = eval_deform_owned(&buf, 5.0, &mut hint).unwrap();
1021        // Zero-tangent Hermite at midpoint = 0.5 → x = prev + (next-prev) * 0.5
1022        for (i, c) in data.coordinate[..4].iter().enumerate() {
1023            let exp = (i as f32) + 5.0;
1024            assert!((c.x() - exp).abs() < 1e-5, "x at {i}: got {} want {exp}", c.x());
1025        }
1026    }
1027}