1use super::{Binding, Ptr, bound_clip, offset};
3use crate::ngui::{Object, V, pptr, s, st, vector};
4use crate::scene3d::{Layout, set};
5
6#[derive(Clone, Copy, Debug)]
7pub struct Key<const N: usize> {
8 pub time: f32,
9 pub value: [f32; N],
10 pub incoming: [f32; N],
11 pub outgoing: [f32; N],
12 pub weighted: i32,
13 pub in_weight: [f32; N],
14 pub out_weight: [f32; N],
15}
16
17impl<const N: usize> Key<N> {
18 #[must_use]
19 pub fn new(time: f32, value: [f32; N]) -> Self {
20 Self {
21 time,
22 value,
23 incoming: [0.; N],
24 outgoing: [0.; N],
25 weighted: 0,
26 in_weight: [1. / 3.; N],
27 out_weight: [1. / 3.; N],
28 }
29 }
30}
31
32fn components<const N: usize>(row: [f32; N]) -> V {
33 if N == 1 {
34 return V::Float(row[0]);
35 }
36 let name = if N == 4 { "Quaternionf" } else { "Vector3f" };
37 st(
38 name,
39 ["x", "y", "z", "w"]
40 .into_iter()
41 .zip(row.map(V::Float))
42 .collect(),
43 )
44}
45
46#[must_use]
49pub fn curve<const N: usize>(
50 path: &str,
51 keys: &[Key<N>],
52 wrap: [i32; 2],
53 order: Option<i32>,
54 weighted_layout: bool,
55 attribute: Option<(&str, i32)>,
56) -> V {
57 let key = |k: Key<N>| {
58 let mut fields = vec![
59 ("time", V::Float(k.time)),
60 ("value", components(k.value)),
61 ("inSlope", components(k.incoming)),
62 ("outSlope", components(k.outgoing)),
63 ];
64 if weighted_layout {
65 fields.extend([
66 ("weightedMode", V::Int(k.weighted)),
67 ("inWeight", components(k.in_weight)),
68 ("outWeight", components(k.out_weight)),
69 ]);
70 }
71 st("Keyframe", fields)
72 };
73 let mut data = vec![
74 (
75 "m_Curve",
76 vector(
77 key(Key::new(0., [0.; N])),
78 keys.iter().copied().map(key).collect(),
79 ),
80 ),
81 ("m_PreInfinity", V::Int(wrap[0])),
82 ("m_PostInfinity", V::Int(wrap[1])),
83 ];
84 if let Some(order) = order {
85 data.push(("m_RotationOrder", V::Int(order)));
86 }
87 let mut row = vec![("curve", st("AnimationCurve", data))];
88 if let Some((attribute, _)) = attribute {
89 row.push(("attribute", s(attribute)));
90 }
91 row.push(("path", s(path)));
92 if let Some((_, class)) = attribute {
93 row.extend([
94 ("classID", V::Int(class)),
95 ("script", pptr("MonoScript", (0, 0))),
96 ]);
97 }
98 st(
99 match N {
100 1 => "FloatCurve",
101 4 => "QuaternionCurve",
102 _ => "Vector3Curve",
103 },
104 row,
105 )
106}
107
108#[must_use]
109pub fn explicit(id: i64, rate: f32, fields: &[(&str, Vec<V>)]) -> Object {
110 let mut value = st(
111 "AnimationClip",
112 vec![
113 ("m_Name", s("explicit fixture")),
114 ("m_Legacy", V::Bool(true)),
115 ("m_Compressed", V::Bool(false)),
116 ("m_SampleRate", V::Float(rate)),
117 ("m_WrapMode", V::Int(2)),
118 ],
119 );
120 for (name, rows) in fields {
121 if let Some(shape) = rows.first() {
122 set(&mut value, name, vector(shape.clone(), rows.clone()));
123 }
124 }
125 Object::new(id, 74, value)
126}
127
128#[derive(Clone, Copy, Debug, Default)]
129pub struct Dense<'a> {
130 pub frames: i32,
131 pub curves: u32,
132 pub rate: f32,
133 pub begin: f32,
134 pub bits: &'a [u32],
135}
136
137#[derive(Clone, Copy, Debug, Default)]
138pub struct Storage<'a> {
139 pub interval: [f32; 2],
140 pub streamed_count: u32,
141 pub words: &'a [u32],
142 pub dense: Dense<'a>,
143 pub constants: &'a [u32],
144 pub discrete_count: Option<u32>,
146}
147
148fn uints(items: &[u32]) -> V {
149 vector(V::UInt(0), items.iter().copied().map(V::UInt).collect())
150}
151
152fn floats(items: &[u32]) -> V {
153 vector(
154 V::Float(0.),
155 items
156 .iter()
157 .copied()
158 .map(|bits| V::Float(f32::from_bits(bits)))
159 .collect(),
160 )
161}
162
163pub fn frame(words: &mut Vec<u32>, time: f32, keys: &[(u32, [u32; 4])]) {
168 words.extend([time.to_bits(), u32::try_from(keys.len()).unwrap()]);
169 for (slot, coefficients) in keys {
170 words.push(*slot);
171 words.extend(coefficients);
172 }
173}
174
175pub fn add_compiled(
176 object: &mut Object,
177 layout: Layout,
178 bindings: &[Binding],
179 mapping: &[Ptr],
180 storage: Storage<'_>,
181) {
182 let V::Struct(_, table) = bound_clip(object.path_id, layout, bindings, mapping).value else {
183 unreachable!()
184 };
185 for (name, value) in table {
186 set(&mut object.value, &name, value);
187 }
188 let dense = storage.dense;
189 let data = st(
190 "Clip",
191 vec![
192 (
193 "m_StreamedClip",
194 st(
195 "StreamedClip",
196 [
197 ("data", uints(storage.words)),
198 ("curveCount", V::UInt(storage.streamed_count)),
199 ]
200 .into_iter()
201 .chain(
202 storage
203 .discrete_count
204 .map(|count| ("discreteCurveCount", V::UInt(count))),
205 )
206 .collect(),
207 ),
208 ),
209 (
210 "m_DenseClip",
211 st(
212 "DenseClip",
213 vec![
214 ("m_FrameCount", V::Int(dense.frames)),
215 ("m_CurveCount", V::UInt(dense.curves)),
216 ("m_SampleRate", V::Float(dense.rate)),
217 ("m_BeginTime", V::Float(dense.begin)),
218 ("m_SampleArray", floats(dense.bits)),
219 ],
220 ),
221 ),
222 (
223 "m_ConstantClip",
224 st("ConstantClip", vec![("data", floats(storage.constants))]),
225 ),
226 ],
227 );
228 set(&mut object.value, "m_Legacy", V::Bool(false));
229 set(
230 &mut object.value,
231 "m_MuscleClip",
232 st(
233 "ClipMuscleConstant",
234 vec![
235 ("m_Clip", offset(data)),
236 ("m_StartTime", V::Float(storage.interval[0])),
237 ("m_StopTime", V::Float(storage.interval[1])),
238 ("m_IndexArray", vector(V::Int(-1), vec![V::Int(-1); 7])),
239 ("m_LoopTime", V::Bool(true)),
240 ],
241 ),
242 );
243}
244
245#[must_use]
246pub fn explicit_fixture() -> Object {
247 let mut left = Key::new(2., [2., -2., 3.]);
248 left.outgoing = [6., 0., f32::INFINITY];
249 let mut right = Key::new(6., [10., 8., 4.]);
250 right.incoming = [-2., 0., 0.];
251 explicit(
252 9,
253 2.,
254 &[
255 (
256 "m_PositionCurves",
257 vec![curve("", &[left, right], [2; 2], Some(4), true, None)],
258 ),
259 (
260 "m_EditorCurves",
261 vec![curve(
262 "",
263 &[Key::new(100., [-99.])],
264 [2; 2],
265 Some(4),
266 true,
267 Some(("m_LocalPosition.x", 4)),
268 )],
269 ),
270 ],
271 )
272}
273
274#[must_use]
275pub fn compiled_fixture() -> Object {
276 let mut object = explicit_fixture();
277 let mut words = Vec::new();
278 frame(&mut words, f32::MIN, &[]);
279 frame(
280 &mut words,
281 3.,
282 &[
283 (0, [2_f32, -1., 3., 4.].map(f32::to_bits)),
284 (1, [0_f32, 0., 0., 5.].map(f32::to_bits)),
285 (2, [0_f32, 0., 0., 6.].map(f32::to_bits)),
286 ],
287 );
288 frame(
289 &mut words,
290 5.,
291 &[(0, [9_f32, 8., 7., -2.].map(f32::to_bits))],
292 );
293 frame(&mut words, f32::INFINITY, &[]);
294 let bindings = [1, 3].map(|attribute| Binding {
295 class: 4,
296 attribute,
297 ..Binding::default()
298 });
299 add_compiled(
300 &mut object,
301 Layout::Unity2022,
302 &bindings,
303 &[],
304 Storage {
305 interval: [2., 6.],
306 streamed_count: 3,
307 words: &words,
308 constants: &[2_f32, 3., 4.].map(f32::to_bits),
309 ..Storage::default()
310 },
311 );
312 object
313}
314
315#[must_use]
317pub fn explicit_replay() -> Object {
318 let mut object = explicit_fixture();
319 let euler = curve(
320 "",
321 &[
322 Key::new(2., [10., 20., 30.]),
323 Key::new(6., [370., -80., 60.]),
324 ],
325 [2; 2],
326 Some(5),
327 true,
328 None,
329 );
330 set(&mut object.value, "m_EulerCurves", one_row(euler));
331 let mut left = Key::new(2., [4.]);
332 left.outgoing = [20.];
333 left.out_weight = [0.25];
334 left.weighted = 2;
335 let mut right = Key::new(6., [60.]);
336 right.incoming = [-8.];
337 let weights = curve(
338 "",
339 &[left, right],
340 [2; 2],
341 Some(4),
342 true,
343 Some(("blendShape.Lift", 137)),
344 );
345 set(&mut object.value, "m_FloatCurves", one_row(weights));
346 let stale_euler = curve(
347 "",
348 &[Key::new(100., [0., 0., 0.])],
349 [2; 2],
350 Some(0),
351 true,
352 None,
353 );
354 set(
355 &mut object.value,
356 "m_EulerEditorCurves",
357 one_row(stale_euler),
358 );
359 let event = st(
360 "AnimationEvent",
361 vec![
362 ("time", V::Float(3.)),
363 ("functionName", s("fixture_marker")),
364 ("data", s("inert")),
365 ("objectReferenceParameter", pptr("Object", (0, -10))),
366 ("floatParameter", V::Float(6.)),
367 ("intParameter", V::Int(-9)),
368 ("messageOptions", V::Int(0)),
369 ],
370 );
371 set(&mut object.value, "m_Events", one_row(event));
372 let key = |time, value| {
373 st(
374 "PPtrKeyframe",
375 vec![("time", V::Float(time)), ("value", pptr("Object", value))],
376 )
377 };
378 let pointer = st(
379 "PPtrCurve",
380 vec![
381 (
382 "curve",
383 vector(key(0., (0, 0)), vec![key(2., (0, -7)), key(6., (1, -8))]),
384 ),
385 ("attribute", s("texture")),
386 ("path", s("")),
387 ("classID", V::Int(137)),
388 ("script", pptr("MonoScript", (0, 0))),
389 ],
390 );
391 set(&mut object.value, "m_PPtrCurves", one_row(pointer));
392 object
393}
394
395#[must_use]
396pub fn one_row(row: V) -> V {
397 vector(row.clone(), vec![row])
398}
399
400#[must_use]
402pub fn dense_replay() -> Object {
403 let mut object = explicit(10, 4., &[]);
404 add_compiled(
405 &mut object,
406 Layout::Unity2022,
407 &[
408 Binding {
409 class: 4,
410 attribute: 2,
411 ..Binding::default()
412 },
413 Binding {
414 class: 137,
415 custom: 20,
416 attribute: 3_545_215_282,
417 ..Binding::default()
418 },
419 ],
420 &[],
421 Storage {
422 interval: [2., 6.],
423 dense: Dense {
424 frames: 3,
425 curves: 5,
426 rate: 4.,
427 begin: 3.,
428 bits: &[
429 0_f32, 0., 0., 1., 4., 0., 0., 1., 1., 20., 0., 0., 1., 0., 84.,
430 ]
431 .map(f32::to_bits),
432 },
433 ..Storage::default()
434 },
435 );
436 object
437}
438
439#[must_use]
442pub fn packed_row(slopes: bool) -> V {
443 let packed = 3u32 | (256 << 3) | (512 << 12) | (512 << 22);
444 let values = [packed.to_le_bytes(), (packed | 4).to_le_bytes()].concat();
445 let mut fields = vec![
446 ("m_Path", s("")),
447 (
448 "m_Times",
449 st(
450 "PackedIntVector",
451 vec![
452 ("m_NumItems", V::UInt(2)),
453 ("m_Data", V::Bytes(vec![50, 125])),
454 ("m_BitSize", V::AlignedUInt8(8)),
455 ],
456 ),
457 ),
458 (
459 "m_Values",
460 st(
461 "PackedQuatVector",
462 vec![("m_NumItems", V::UInt(2)), ("m_Data", V::Bytes(values))],
463 ),
464 ),
465 ];
466 if slopes {
467 fields.push((
468 "m_Slopes",
469 st(
470 "PackedFloatVector",
471 vec![
472 ("m_NumItems", V::UInt(3)),
473 ("m_Range", V::Float(12.)),
474 ("m_Start", V::Float(-4.)),
475 ("m_Data", V::Bytes(vec![0b00_11_01_00])),
476 ("m_BitSize", V::AlignedUInt8(2)),
477 ],
478 ),
479 ));
480 }
481 fields.extend([("m_PreInfinity", V::Int(2)), ("m_PostInfinity", V::Int(2))]);
482 st("CompressedAnimationCurve", fields)
483}
484
485#[must_use]
489pub fn stripped_position_payload(big_endian: bool) -> Vec<u8> {
490 use crate::ByteWriter;
491 let mut out = if big_endian {
492 ByteWriter::be()
493 } else {
494 ByteWriter::le()
495 };
496 out.i32(0) .u8(1)
498 .u8(0)
499 .u8(0)
500 .align(4) .i32(0)
502 .i32(0)
503 .i32(0) .i32(1)
505 .i32(1); for value in [2_f32, 4., 5., 6.] {
507 out.u32(value.to_bits());
508 }
509 out.bytes(&[0; 24]).i32(0).bytes(&[0; 24]); out.i32(2)
511 .i32(2)
512 .i32(4)
513 .i32(0) .i32(0)
515 .i32(0)
516 .i32(0) .u32(24_f32.to_bits())
518 .i32(0) .bytes(&[0; 28]) .bytes(&[0; 452]) .i32(0)
522 .i32(0) .u8(0)
524 .u8(0)
525 .align(4)
526 .i32(0); out.into_inner()
528}