Repository navigation
Expand file tree
/
Copy pathrig.rs
More file actions
1866 lines (1750 loc) · 69.7 KB
/
Copy pathrig.rs
File metadata and controls
1866 lines (1750 loc) · 69.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! The `.p2lrt` rig and its reader. Version 1 is documented with the writer, `targets/runtime/.../P2lrt.kt`;
//! version 2 (chunks, the same records) in `docs/zh/spec/P2LRT_V2.md`. Every reference is an index and parents
//! come before children; both versions read into the same [Rig].
use crate::container::{self, Chunk};
use crate::expression::{Blend, Expression};
use crate::pose::PoseGroup;
use crate::sim::Simulation;
use std::fmt;
/// The newest major version this reader understands; version 1 is read too.
pub const VERSION: u32 = 2;
/// The chunks this reader understands, with the newest version of each.
pub const CHUNKS: [(&str, u16); 23] = [
("STRS", 1), ("CANV", 1), ("PARM", 1), ("DEFM", 1), ("PART", 1), ("MESH", 1), ("GLUE", 1),
("DRAW", 1), ("TEXR", 1), ("PHYS", 2), ("CLIP", 1), ("ROLE", 1), ("PGUI", 1), ("META", 1),
("BONE", 1), ("SKIN", 1), ("COLL", 1), ("SIMS", 1), ("EXPR", 1), ("HITA", 1), ("UDAT", 1), ("POSE", 1),
("CEXT", 1),
];
#[derive(Debug)]
pub struct Error(pub String);
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl std::error::Error for Error {}
pub type Result<T> = std::result::Result<T, Error>;
fn err<T>(message: impl Into<String>) -> Result<T> {
Err(Error(message.into()))
}
pub type Rgb = [f32; 3];
pub const WHITE: Rgb = [1.0, 1.0, 1.0];
pub const BLACK: Rgb = [0.0, 0.0, 0.0];
#[derive(Debug, Clone, PartialEq)]
pub struct Canvas {
pub width: f32,
pub height: f32,
pub origin_x: f32,
pub origin_y: f32,
pub pixels_per_unit: Option<f32>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Parameter {
pub id: String,
pub name: String,
pub min: f32,
pub max: f32,
pub default: f32,
pub blend: bool,
pub repeat: bool,
}
impl Parameter {
/// The value the rig is evaluated at: wrapped into a repeating range, clamped otherwise.
pub fn normalize(&self, value: f32) -> f32 {
if !value.is_finite() {
return self.default;
}
// A repeating range wraps values outside it; both ends stay as they are.
if self.repeat && self.max > self.min && (value < self.min || value > self.max) {
return (value - self.min).rem_euclid(self.max - self.min) + self.min;
}
value.clamp(self.min.min(self.max), self.max.max(self.min))
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Axis {
pub parameter: usize,
pub keys: Vec<f32>,
}
/// Forms keyed over the cartesian product of parameter axes; cells may be sparse.
#[derive(Debug, Clone, PartialEq)]
pub struct Grid<F> {
pub axes: Vec<Axis>,
pub cells: Vec<(Vec<u16>, F)>,
/// Cell index at each dense coordinate, `u32::MAX` where the combination is not authored.
pub(crate) dense: Vec<u32>,
pub(crate) strides: Vec<usize>,
}
impl<F> Grid<F> {
pub(crate) fn new(axes: Vec<Axis>, cells: Vec<(Vec<u16>, F)>) -> Result<Self> {
let mut strides = Vec::with_capacity(axes.len());
let mut size = 1usize;
for axis in &axes {
if axis.keys.is_empty() {
return err("A keyform axis has no keys");
}
strides.push(size);
size = size.checked_mul(axis.keys.len()).filter(|s| *s <= 1 << 24).ok_or(Error("Keyform grid too large".into()))?;
}
let mut dense = vec![u32::MAX; size];
for (index, (coordinate, _)) in cells.iter().enumerate() {
let mut at = 0;
for (i, c) in coordinate.iter().enumerate() {
if *c as usize >= axes[i].keys.len() {
return err("Keyform cell outside its axes");
}
at += *c as usize * strides[i];
}
dense[at] = index as u32;
}
if cells.is_empty() {
return err("Keyform grid without cells");
}
Ok(Grid { axes, cells, dense, strides })
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Channel {
DrawOrder,
Opacity,
MultiplyColor,
ScreenColor,
FlipX,
FlipY,
GlueIntensity,
}
const CHANNELS: [Channel; 7] = [
Channel::DrawOrder, Channel::Opacity, Channel::MultiplyColor, Channel::ScreenColor, Channel::FlipX, Channel::FlipY, Channel::GlueIntensity,
];
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum ChannelValue {
Scalar(f32),
Color(Rgb),
Flag(bool),
}
pub type Channels = Vec<(Channel, Grid<ChannelValue>)>;
#[derive(Debug, Clone, PartialEq)]
pub struct Limit {
pub parameter: usize,
pub points: Vec<(f32, f32)>,
}
/// An additive shape keyed on one parameter; `shapes` has one entry per key.
#[derive(Debug, Clone, PartialEq)]
pub struct Binding<S> {
pub parameter: usize,
pub keys: Vec<f32>,
pub neutral: usize,
pub shapes: Vec<Option<S>>,
pub limits: Vec<Limit>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct LatticeShape {
pub points: Vec<f32>,
pub opacity: f32,
pub multiply: Rgb,
pub screen: Rgb,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Pivot {
pub x: f32,
pub y: f32,
pub angle: f32,
pub scale: f32,
}
#[derive(Debug, Clone, PartialEq)]
pub struct PivotShape {
pub pivot: Pivot,
pub flip_x: bool,
pub flip_y: bool,
pub opacity: f32,
pub multiply: Rgb,
pub screen: Rgb,
}
#[derive(Debug, Clone, PartialEq)]
pub struct MeshShape {
pub deltas: Vec<f32>,
pub draw_order: f32,
pub opacity: f32,
pub multiply: Rgb,
pub screen: Rgb,
}
#[derive(Debug, Clone, PartialEq)]
pub struct PartShape {
pub draw_order: f32,
pub opacity: f32,
pub multiply: Rgb,
pub screen: Rgb,
}
#[derive(Debug, Clone, PartialEq)]
pub enum DeformerKind {
Warp { columns: usize, rows: usize, bilinear: bool, lattice: Option<Grid<Vec<f32>>>, shapes: Vec<Binding<LatticeShape>> },
Rotation { base_angle: f32, pivot: Option<Grid<Pivot>>, flip_x: bool, flip_y: bool, shapes: Vec<Binding<PivotShape>> },
}
#[derive(Debug, Clone, PartialEq)]
pub struct Deformer {
pub id: String,
pub parent: Option<usize>,
pub part: Option<usize>,
pub visible: bool,
pub enabled: bool,
pub opacity: f32,
pub multiply: Rgb,
pub screen: Rgb,
pub channels: Channels,
pub kind: DeformerKind,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Child {
Part(usize),
Mesh(usize),
}
#[derive(Debug, Clone, PartialEq)]
pub struct Composite {
pub blend: u8,
pub alpha_blend: u8,
pub masked_by: Vec<usize>,
pub masked_by_parts: Vec<usize>,
pub invert_mask: bool,
pub opacity: f32,
pub multiply: Rgb,
pub screen: Rgb,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Part {
pub id: String,
pub name: String,
pub visible: bool,
pub sketch: bool,
pub group_mode: u8,
pub draw_order: i32,
pub children: Vec<Child>,
pub channels: Channels,
pub composite: Composite,
pub shapes: Vec<Binding<PartShape>>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Geometry {
pub positions: Vec<f32>,
pub uvs: Vec<f32>,
pub indices: Vec<u32>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Mesh {
pub id: String,
pub name: String,
pub parent: Option<usize>,
pub blend: u8,
pub alpha_blend: u8,
pub masked_by: Vec<usize>,
pub invert_mask: bool,
pub culling: bool,
pub visible: bool,
pub page: i32,
pub geometry: Option<Geometry>,
pub offsets: Option<Grid<Vec<f32>>>,
pub channels: Channels,
pub draw_order: f32,
pub opacity: f32,
pub multiply: Rgb,
pub screen: Rgb,
pub shapes: Vec<Binding<MeshShape>>,
}
impl Mesh {
pub fn vertex_count(&self) -> usize {
self.geometry.as_ref().map_or(0, |g| g.positions.len() / 2)
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct GluePair {
pub a: usize,
pub b: usize,
pub weight_a: f32,
pub weight_b: f32,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Glue {
pub id: String,
pub mesh_a: usize,
pub mesh_b: usize,
pub intensity: f32,
pub pairs: Vec<GluePair>,
pub channels: Channels,
}
#[derive(Debug, Clone, PartialEq)]
pub enum RenderNode {
Mesh(usize),
Group(RenderGroup),
}
#[derive(Debug, Clone, PartialEq)]
pub struct RenderGroup {
pub part: Option<usize>,
pub draw_order: i32,
pub channels: Channels,
pub composite: Option<Composite>,
pub children: Vec<RenderNode>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TextureKind {
Png,
Ktx2,
/// A file next to the rig, named by [Texture::uri]; the host loads it.
External,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Texture {
pub width: u32,
pub height: u32,
pub kind: TextureKind,
/// The PNG or KTX2 bytes; empty for an external page.
pub data: Vec<u8>,
pub uri: String,
}
/// What an extension chunk overrides in the core evaluation, readable without understanding the rest of it.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct ExtensionHeader {
/// The `p2l_set_advanced` bit that turns the extension on.
pub feature: u16,
/// The evaluation hooks it uses: H1 = 1, H2 = 2, H3 = 4, H4 = 8, H6 = 32.
pub hooks: u16,
/// H1: parameters evaluated at their defaults for the geometry while the extension is on.
pub parameters: Vec<usize>,
/// H1: physics groups skipped while the extension is on.
pub physics_groups: Vec<usize>,
/// H2: deformers whose frames the extension replaces.
pub deformers: Vec<usize>,
/// H4: per mesh, the keyform axes evaluated at their defaults and the blend shapes left out.
pub meshes: Vec<MeshOverride>,
/// Tags of the extension chunks this one needs.
pub depends_on: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct MeshOverride {
pub mesh: usize,
pub axes: Vec<usize>,
pub bindings: Vec<usize>,
}
/// A mesh the runtime skins: it follows [bones] (rotation deformers, its parent among them) with two-bone
/// weights, which the file gives or the runtime fits to the baked keyforms over [axes].
#[derive(Debug, Clone, PartialEq)]
pub struct Skin {
pub mesh: usize,
/// The parameters whose keys the baked skin was sampled at, each with those keys.
pub axes: Vec<(usize, Vec<f32>)>,
pub bones: Vec<usize>,
/// Per vertex: the bone it follows, the bone it blends toward and how far; empty to fit at load.
pub from: Vec<u32>,
pub to: Vec<u32>,
pub weight: Vec<f32>,
}
/// A rotation deformer whose keyed pivot positions along [parameter] lie on a circle about [center] (in its
/// parent's space): with exact links on they are interpolated along that circle rather than its chords.
#[derive(Debug, Clone, PartialEq)]
pub struct Arc {
pub deformer: usize,
pub parameter: usize,
pub center: [f32; 2],
}
/// A circle, or a capsule from [a] to [b], that simulated particles keep out of: in [deformer]'s space, between
/// [mesh]'s vertices as evaluated, or fixed in canvas space. Radii are canvas pixels.
#[derive(Debug, Clone, PartialEq)]
pub struct Collider {
pub id: String,
pub capsule: bool,
pub deformer: Option<usize>,
pub mesh: Option<usize>,
pub vertex_a: usize,
pub vertex_b: usize,
pub a: [f32; 2],
pub b: [f32; 2],
pub radius_a: f32,
pub radius_b: f32,
pub friction: f32,
}
/// The runtime's advanced data: skeleton bones, exact links, skins, colliders and simulations.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Extensions {
pub bone_header: Option<ExtensionHeader>,
/// Bones the rig folded into keyforms, as rotations only skinning evaluates. Deformer index `n + i` (n the
/// rig's deformer count) is virtual bone `i`; a parent is a rig deformer or an earlier virtual bone.
pub virtual_bones: Vec<Deformer>,
/// Deformers a host can attach things to, with their bone ids.
pub bones: Vec<(usize, String)>,
pub arcs: Vec<Arc>,
pub skin_header: Option<ExtensionHeader>,
pub skins: Vec<Skin>,
pub collider_header: Option<ExtensionHeader>,
pub colliders: Vec<Collider>,
pub simulation_header: Option<ExtensionHeader>,
pub simulations: Vec<Simulation>,
/// Per simulation, the parameters it holds at their defaults and the physics groups it skips.
pub simulation_overrides: Vec<(Vec<usize>, Vec<usize>)>,
}
/// How a parameter panel groups and shows the parameters; it does not affect evaluation.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Gui {
/// Values a parameter snaps to, ascending.
pub snaps: Vec<(usize, Vec<f32>)>,
/// Pairs of parameters shown as one two-dimensional control: horizontal, vertical.
pub joysticks: Vec<(usize, usize)>,
/// The group tree in pre-order; each node is followed by its children.
pub nodes: Vec<GuiNode>,
}
#[derive(Debug, Clone, PartialEq)]
pub enum GuiLabel {
None,
Preset(String),
Custom(u32),
}
#[derive(Debug, Clone, PartialEq)]
pub struct GuiNode {
/// The parameter a leaf shows; `None` for a group.
pub parameter: Option<usize>,
pub id: String,
pub name: String,
pub open: bool,
pub label: GuiLabel,
pub children: usize,
}
/// What a physics input drives or an output reads: sideways or vertical travel, or tilt and segment angle.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PhysicsSource {
X,
Angle,
/// Vertical travel, Cubism's Y; physics chunk version 2.
Y,
}
#[derive(Debug, Clone, PartialEq)]
pub struct PhysicsInput {
pub parameter: usize,
pub weight: f32,
pub source: PhysicsSource,
pub reflect: bool,
}
#[derive(Debug, Clone, PartialEq)]
pub struct PhysicsOutput {
pub parameter: usize,
pub vertex: usize,
pub scale: f32,
pub weight: f32,
pub source: PhysicsSource,
pub reflect: bool,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct PhysicsSegment {
pub length: f32,
pub mobility: f32,
pub delay: f32,
pub acceleration: f32,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Normalization {
pub position_min: f32,
pub position_default: f32,
pub position_max: f32,
pub angle_min: f32,
pub angle_default: f32,
pub angle_max: f32,
}
#[derive(Debug, Clone, PartialEq)]
pub struct PhysicsGroup {
pub id: String,
pub name: String,
pub inputs: Vec<PhysicsInput>,
pub outputs: Vec<PhysicsOutput>,
pub segments: Vec<PhysicsSegment>,
pub normalization: Normalization,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Segment {
Linear { time: f32, value: f32 },
Bezier { c1: (f32, f32), c2: (f32, f32), time: f32, value: f32 },
Stepped { time: f32, value: f32 },
InverseStepped { time: f32, value: f32 },
}
impl Segment {
pub fn end(&self) -> (f32, f32) {
match *self {
Segment::Linear { time, value }
| Segment::Bezier { time, value, .. }
| Segment::Stepped { time, value }
| Segment::InverseStepped { time, value } => (time, value),
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Curve {
pub parameter: usize,
pub start_time: f32,
pub start_value: f32,
pub segments: Vec<Segment>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Clip {
pub id: String,
pub name: String,
pub group: String,
pub duration: f32,
pub fps: f32,
pub looping: bool,
pub fade_in: Option<f32>,
pub fade_out: Option<f32>,
pub curves: Vec<Curve>,
/// What the clip extensions chunk adds; empty without it.
pub extras: ClipExtras,
}
/// What a non-parameter curve of a clip drives.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CurveTarget {
/// The opacity of a part, set outright as Cubism sets it.
PartOpacity(usize),
/// The opacity of the whole rig.
ModelOpacity,
/// Multiplies the EyeBlink parameters while the clip plays.
EyeBlink,
/// Adds to the LipSync parameters while the clip plays.
LipSync,
}
/// A clip curve on something other than a parameter, with fade times of its own (`None` takes the clip's).
#[derive(Debug, Clone, PartialEq)]
pub struct TargetCurve {
pub target: CurveTarget,
pub fade_in: Option<f32>,
pub fade_out: Option<f32>,
pub curve: Curve,
}
/// What `CEXT` adds to a clip: events, curves on parts, the rig and the blink and lip sync effects, and fade
/// times for the clip's own curves.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct ClipExtras {
/// Events in time order: when, and the text the host receives.
pub events: Vec<(f32, String)>,
pub curves: Vec<TargetCurve>,
/// Per parameter curve of the clip that has its own fades: the curve's index and its fade-in and fade-out.
pub fades: Vec<(usize, Option<f32>, Option<f32>)>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Role {
pub role: String,
pub parameters: Vec<usize>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Rig {
pub canvas: Canvas,
pub parameters: Vec<Parameter>,
pub deformers: Vec<Deformer>,
pub parts: Vec<Part>,
pub meshes: Vec<Mesh>,
pub glues: Vec<Glue>,
pub render: RenderGroup,
pub textures: Vec<Texture>,
/// Physics steps per second, or 0 for the runtime's default.
pub physics_fps: f32,
pub physics: Vec<PhysicsGroup>,
pub clips: Vec<Clip>,
pub roles: Vec<Role>,
/// Parameter panel layout, when the file carries one.
pub gui: Option<Gui>,
/// Generator and other information as key-value pairs.
pub meta: Vec<(String, String)>,
/// Advanced data, off until a host enables it.
pub extensions: Extensions,
pub expressions: Vec<Expression>,
/// Hit areas: id, name and the meshes they cover.
pub hit_areas: Vec<(String, String, Vec<usize>)>,
/// User data per mesh.
pub user_data: Vec<(usize, String)>,
/// Part poses and how long the shown part takes to fade in.
pub poses: Vec<PoseGroup>,
pub pose_fade_in: f32,
}
impl Rig {
/// Deformer [i] counting the virtual bones after the rig's own.
pub fn deformer_or_bone(&self, i: usize) -> &Deformer {
self.deformers.get(i).unwrap_or_else(|| &self.extensions.virtual_bones[i - self.deformers.len()])
}
/// The rig's deformers and the virtual bones after them.
pub fn deformer_count_with_bones(&self) -> usize {
self.deformers.len() + self.extensions.virtual_bones.len()
}
pub fn read(bytes: &[u8]) -> Result<Rig> {
Rig::read_with(bytes, false)
}
/// Reads version 1 or 2; with [verify_crc], chunks that carry a CRC are checked against it.
pub fn read_with(bytes: &[u8], verify_crc: bool) -> Result<Rig> {
if bytes.len() < 12 || &bytes[..8] != b"P2LRT" {
return err("Not a .p2lrt rig");
}
let version = u32::from_le_bytes(bytes[8..12].try_into().unwrap());
let rig = if version == 1 {
Reader::new(bytes, None).rig()?
} else if version & 0xFFFF == 2 {
read_chunks(bytes, verify_crc)?
} else {
return err(format!("Unsupported .p2lrt version {}", version & 0xFFFF));
};
rig.validate()?;
Ok(rig)
}
/// Extensions refer to rotation deformers and to meshes whose vertices they weigh.
fn validate_extensions(&self) -> Result<()> {
let rotation = |d: usize| matches!(self.deformer_or_bone(d).kind, DeformerKind::Rotation { .. });
for arc in &self.extensions.arcs {
if !matches!(&self.deformer_or_bone(arc.deformer).kind, DeformerKind::Rotation { pivot: Some(g), .. } if g.axes.len() == 1 && g.axes[0].parameter == arc.parameter) {
return err(format!("Arc on {} is not a rotation keyed on its parameter alone", self.deformer_or_bone(arc.deformer).id));
}
}
for skin in &self.extensions.skins {
let mesh = &self.meshes[skin.mesh];
let parent_is_bone = mesh.parent.is_some_and(|p| rotation(p) && skin.bones.contains(&p));
if !parent_is_bone || skin.bones.iter().any(|b| !rotation(*b)) {
return err(format!("Skin of {} must hang from one of its bones, all rotations", mesh.id));
}
if !skin.from.is_empty() && skin.from.len() != mesh.vertex_count() {
return err(format!("Skin weights of {} do not match its vertices", mesh.id));
}
}
for c in &self.extensions.colliders {
if let Some(m) = c.mesh {
if c.vertex_a.max(c.vertex_b) >= self.meshes[m].vertex_count() {
return err(format!("Collider {} rides vertices its mesh does not have", c.id));
}
}
}
for sim in &self.extensions.simulations {
let particles = sim.particles();
let last = sim.targets.last().map_or(0, |(m, first)| first + self.meshes[*m].vertex_count());
if last != particles || sim.targets.iter().enumerate().any(|(k, (m, first))| sim.targets.get(k + 1).map_or(false, |(_, next)| next - first != self.meshes[*m].vertex_count())) {
return err("A simulation's targets do not match their meshes");
}
if sim.anchors.iter().flatten().any(|(m, v)| *m >= self.meshes.len() || *v >= self.meshes[*m].vertex_count()) {
return err("A simulation pins to a vertex the rig does not have");
}
for (_, keys, offsets) in &sim.statics {
if offsets.iter().any(|(m, per)| per.iter().any(|o| o.len() != self.meshes[*m].vertex_count() * 2) || per.len() != keys.len()) {
return err("A simulation's static offsets do not match their meshes");
}
}
}
Ok(())
}
/// Checks that hold across sections: glue pairs and keyform offsets against their meshes' vertices.
fn validate(&self) -> Result<()> {
for g in &self.glues {
for p in &g.pairs {
if p.a >= self.meshes[g.mesh_a].vertex_count() || p.b >= self.meshes[g.mesh_b].vertex_count() {
return err(format!("Glue {} pairs a vertex its meshes do not have", g.id));
}
}
}
for mesh in &self.meshes {
if let (Some(g), Some(offsets)) = (&mesh.geometry, &mesh.offsets) {
if offsets.cells.iter().any(|(_, d)| !d.is_empty() && d.len() != g.positions.len()) {
return err(format!("Offsets of mesh {} do not match its vertices", mesh.id));
}
}
}
Ok(())
}
pub fn parameter(&self, id: &str) -> Option<usize> {
self.parameters.iter().position(|p| p.id == id)
}
pub fn mesh(&self, id: &str) -> Option<usize> {
self.meshes.iter().position(|m| m.id == id)
}
/// Every parameter at its default.
pub fn defaults(&self) -> Vec<f32> {
self.parameters.iter().map(|p| p.default).collect()
}
}
struct Reader<'a> {
bytes: &'a [u8],
at: usize,
// Counts of what references may point at, checked as they are read.
parameters: usize,
deformers: usize,
parts: usize,
meshes: usize,
/// Version 2's string table: strings are indices into it and arrays carry a codec. `None` reads version 1.
strings: Option<&'a [String]>,
}
/// Array codecs of version 2.
const F32: u8 = 0;
const F16: u8 = 1;
const UNORM16: u8 = 2;
const U16: u8 = 16;
const U32: u8 = 17;
const U8: u8 = 32;
impl<'a> Reader<'a> {
fn new(bytes: &'a [u8], strings: Option<&'a [String]>) -> Self {
Reader { bytes, at: 0, parameters: 0, deformers: 0, parts: 0, meshes: 0, strings }
}
fn take(&mut self, n: usize) -> Result<&'a [u8]> {
if self.bytes.len() - self.at < n {
return err(format!("Truncated rig at byte {}", self.at));
}
let slice = &self.bytes[self.at..self.at + n];
self.at += n;
Ok(slice)
}
fn u8(&mut self) -> Result<u8> {
Ok(self.take(1)?[0])
}
fn u16(&mut self) -> Result<u16> {
Ok(u16::from_le_bytes(self.take(2)?.try_into().unwrap()))
}
fn u32(&mut self) -> Result<u32> {
Ok(u32::from_le_bytes(self.take(4)?.try_into().unwrap()))
}
fn i32(&mut self) -> Result<i32> {
Ok(i32::from_le_bytes(self.take(4)?.try_into().unwrap()))
}
fn f32(&mut self) -> Result<f32> {
let v = f32::from_le_bytes(self.take(4)?.try_into().unwrap());
if !v.is_finite() {
return err("Non-finite value in the rig");
}
Ok(v)
}
fn bool(&mut self) -> Result<bool> {
Ok(self.u8()? != 0)
}
fn rgb(&mut self) -> Result<Rgb> {
Ok([self.f32()?, self.f32()?, self.f32()?])
}
/// A count of items each at least [min_size] bytes, bounded by what remains.
fn count(&mut self, min_size: usize) -> Result<usize> {
let n = self.u32()? as usize;
if n.saturating_mul(min_size.max(1)) > self.bytes.len() - self.at {
return err(format!("Count {} exceeds the rig at byte {}", n, self.at));
}
Ok(n)
}
fn str(&mut self) -> Result<String> {
if let Some(strings) = self.strings {
let i = self.u32()?;
if i == u32::MAX {
return Ok(String::new());
}
return strings.get(i as usize).cloned().ok_or(Error(format!("Invalid string reference {}", i)));
}
let n = self.count(1)?;
String::from_utf8(self.take(n)?.to_vec()).map_err(|_| Error("Invalid UTF-8 in the rig".into()))
}
/// A version 2 array header, after zero padding to a four-byte boundary: its codec and length.
fn array(&mut self, codecs: &[u8]) -> Result<(u8, usize)> {
while self.at % 4 != 0 {
if self.u8()? != 0 {
return err("Non-zero padding before an array");
}
}
let codec = self.u8()?;
self.take(3)?;
if !codecs.contains(&codec) {
return err(format!("Array codec {} is not allowed here", codec));
}
let size = match codec {
F32 | U32 => 4,
F16 | UNORM16 | U16 => 2,
_ => 1,
};
Ok((codec, self.count(size)?))
}
fn floats(&mut self) -> Result<Vec<f32>> {
if self.strings.is_none() {
let n = self.count(4)?;
return (0..n).map(|_| self.f32()).collect();
}
let (codec, n) = self.array(&[F32, F16, UNORM16])?;
(0..n)
.map(|_| match codec {
F32 => self.f32(),
F16 => Some(container::f16_to_f32(self.u16()?)).filter(|v| v.is_finite()).ok_or(Error("Non-finite value in the rig".into())),
_ => Ok(self.u16()? as f32 / 65535.0),
})
.collect()
}
fn indices(&mut self) -> Result<Vec<u32>> {
if self.strings.is_none() {
let n = self.count(4)?;
return (0..n).map(|_| self.u32()).collect();
}
let (codec, n) = self.array(&[U16, U32])?;
(0..n).map(|_| if codec == U16 { self.u16().map(u32::from) } else { self.u32() }).collect()
}
fn bytes_field(&mut self) -> Result<Vec<u8>> {
let n = if self.strings.is_none() { self.count(1)? } else { self.array(&[U8])?.1 };
Ok(self.take(n)?.to_vec())
}
/// The end of a version 2 chunk, which its records must fill exactly.
fn end(&self, tag: &str) -> Result<()> {
if self.at != self.bytes.len() {
return err(format!("Chunk {} has {} bytes its records do not cover", tag, self.bytes.len() - self.at));
}
Ok(())
}
fn index(&mut self, limit: usize, what: &str) -> Result<usize> {
let i = self.u32()? as usize;
if i >= limit {
return err(format!("Invalid {} reference {}", what, i));
}
Ok(i)
}
fn optional(&mut self, limit: usize, what: &str) -> Result<Option<usize>> {
let i = self.i32()?;
if i < 0 {
return Ok(None);
}
if i as usize >= limit {
return err(format!("Invalid {} reference {}", what, i));
}
Ok(Some(i as usize))
}
fn parameter(&mut self) -> Result<usize> {
self.index(self.parameters, "parameter")
}
fn rig(&mut self) -> Result<Rig> {
if self.take(8)? != b"P2LRT\0\0\0" {
return err("Not a .p2lrt rig");
}
let version = self.u32()?;
if version != 1 {
return err(format!("Unsupported .p2lrt version {}", version));
}
let canvas = self.canvas()?;
let parameters = self.parameters()?;
self.parameters = parameters.len();
// Sections refer forward (deformers to parts, parts to meshes), so their counts come from a first
// pass that only skips; reading twice keeps the format free of an index table.
let start = self.at;
let deformer_count = self.count(1)?;
self.deformers = deformer_count;
self.parts = usize::MAX;
self.meshes = usize::MAX;
for _ in 0..deformer_count {
self.deformer()?;
}
let part_count = self.count(1)?;
for _ in 0..part_count {
self.part()?;
}
let mesh_count = self.count(1)?;
self.at = start;
self.parts = part_count;
self.meshes = mesh_count;
self.count(1)?;
let deformers = self.deformers(deformer_count)?;
self.count(1)?;
let parts = (0..part_count).map(|_| self.part()).collect::<Result<Vec<_>>>()?;
self.count(1)?;
let meshes = (0..mesh_count).map(|_| self.mesh()).collect::<Result<Vec<_>>>()?;
let glues = self.glues()?;
let render = self.group(0)?;
let n = self.count(12)?;
let mut textures = Vec::with_capacity(n);
for _ in 0..n {
textures.push(Texture { width: self.u32()?, height: self.u32()?, kind: TextureKind::Png, data: self.bytes_field()?, uri: String::new() });
}
let (physics_fps, physics) = self.physics()?;
let clips = self.clips()?;
let roles = self.roles()?;
if self.at != self.bytes.len() {
return err("Trailing bytes after the rig");
}
Ok(Rig {
canvas, parameters, deformers, parts, meshes, glues, render, textures, physics_fps, physics, clips, roles, gui: None, meta: vec![],
extensions: Extensions::default(), expressions: vec![], hit_areas: vec![], user_data: vec![], poses: vec![], pose_fade_in: 0.0,
})
}
fn canvas(&mut self) -> Result<Canvas> {
Ok(Canvas {
width: self.f32()?,
height: self.f32()?,
origin_x: self.f32()?,
origin_y: self.f32()?,
pixels_per_unit: Some(self.f32()?).filter(|v| *v >= 0.0),
})
}
fn parameters(&mut self) -> Result<Vec<Parameter>> {
let n = self.count(if self.strings.is_some() { 21 } else { 25 })?;
let mut parameters = Vec::with_capacity(n);
for _ in 0..n {
let id = self.str()?;
let name = self.str()?;
let (min, max, default) = (self.f32()?, self.f32()?, self.f32()?);
let flags = self.u8()?;
parameters.push(Parameter { id, name, min, max, default, blend: flags & 1 != 0, repeat: flags & 2 != 0 });
}
Ok(parameters)
}
/// Deformers, each parent before its children.
fn deformers(&mut self, count: usize) -> Result<Vec<Deformer>> {
let mut deformers: Vec<Deformer> = Vec::with_capacity(count);
for i in 0..count {
let d = self.deformer()?;
if let Some(parent) = d.parent {
if parent >= i {
return err("A deformer's parent must come before it");
}
}
deformers.push(d);
}
Ok(deformers)
}
fn glues(&mut self) -> Result<Vec<Glue>> {
let n = self.count(1)?;
(0..n).map(|_| self.glue()).collect()
}
fn physics(&mut self) -> Result<(f32, Vec<PhysicsGroup>)> {
let fps = self.f32()?;
let n = self.count(1)?;
Ok((fps, (0..n).map(|_| self.physics_group()).collect::<Result<Vec<_>>>()?))
}
fn clips(&mut self) -> Result<Vec<Clip>> {
let n = self.count(1)?;
(0..n).map(|_| self.clip()).collect()
}
fn roles(&mut self) -> Result<Vec<Role>> {
let n = self.count(8)?;
let mut roles = Vec::with_capacity(n);
for _ in 0..n {
let role = self.str()?;
let count = self.count(4)?;
let parameters = (0..count).map(|_| self.parameter()).collect::<Result<Vec<_>>>()?;
roles.push(Role { role, parameters });
}
Ok(roles)