Repository navigation
Expand file tree
/
Copy pathffi.rs
More file actions
1787 lines (1609 loc) · 71 KB
/
Copy pathffi.rs
File metadata and controls
1787 lines (1609 loc) · 71 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 C ABI. A model holds what one `.p2lrt` file defines, read-only and shared; each rig handle created
//! from it holds one character's state: parameters, clip player, physics and the last pose. Strings and
//! arrays returned stay valid until the handle is freed or, for pose data, until the next evaluation.
//! Every function tolerates a null handle. A panic never unwinds into the host: the handle fails and acts
//! as a null one from then on (`p2l_rig_failure`). See `include/p2l_runtime.h`.
use crate::advanced::{Advanced, Affine};
use crate::behavior::Behaviors;
use crate::clip::{Effects, Player};
use crate::eval::{render_commands, render_order, Evaluator};
use crate::expression::ExpressionPlayer;
use crate::pose::PosePlayer;
use crate::physics::Physics;
use crate::rig::{Child, Composite, GuiLabel, RenderGroup, RenderNode, Rig, TextureKind};
use std::any::Any;
use std::cell::OnceCell;
use std::ffi::{c_char, CStr, CString};
use std::panic::{self, AssertUnwindSafe};
use std::ptr;
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::Arc;
/// The ABI version, `p2l_abi_version`: the major changes when a function changes or goes, the minor when
/// functions are added. Kept equal to `P2L_ABI_VERSION_MAJOR` / `_MINOR` in the header.
pub const ABI_MAJOR: u32 = 1;
pub const ABI_MINOR: u32 = 4;
/// `p2l_update_stages` bits: the layers an update runs, in this order.
pub const STAGE_CLIPS: u32 = 1;
pub const STAGE_EXPRESSIONS: u32 = 2;
pub const STAGE_BEHAVIORS: u32 = 4;
pub const STAGE_POSES: u32 = 8;
pub const STAGE_PHYSICS: u32 = 16;
pub const STAGE_SIM: u32 = 32;
pub const STAGE_ALL: u32 = 63;
/// `p2l_render` flags: straight (not premultiplied) output, and drawing over what the image holds.
pub const RENDER_STRAIGHT: u32 = 1;
pub const RENDER_KEEP: u32 = 2;
/// `p2l_mesh_changes` bits: whether the mesh draws, then what changed since the evaluation before the last.
pub const MESH_VISIBLE: u32 = 1;
pub const MESH_VISIBILITY_CHANGED: u32 = 2;
pub const MESH_OPACITY_CHANGED: u32 = 4;
pub const MESH_DRAW_ORDER_CHANGED: u32 = 8;
pub const MESH_RENDER_ORDER_CHANGED: u32 = 16;
pub const MESH_VERTICES_CHANGED: u32 = 32;
pub const MESH_COLORS_CHANGED: u32 = 64;
/// How many clip layers a rig can play at once.
pub const MAX_LAYERS: u32 = 16;
/// `p2l_parameter_flags` bits.
pub const PARAMETER_REPEAT: u32 = 1;
pub const PARAMETER_BLEND_SHAPE: u32 = 2;
/// `p2l_part_flags` bits.
pub const PART_VISIBLE: u32 = 1;
pub const PART_SKETCH: u32 = 2;
/// How an isolated part's group composites, as the render tree (or else the part) gives it.
struct Group {
blend: i32,
alpha_blend: i32,
invert_mask: bool,
/// The meshes masking the group, the masking parts' meshes included.
masks: Vec<u32>,
}
/// What every rig loaded from one file shares, read-only: the rig and the strings and indices handed out about it.
pub struct Model {
rig: Rig,
/// Fitted skinning for each SKIN/EXACT_LINKS combination, initialized by a host's preparation thread.
skinning: [std::sync::OnceLock<Arc<crate::advanced::PreparedSkinning>>; 4],
parameter_ids: Vec<CString>,
parameter_names: Vec<CString>,
mesh_ids: Vec<CString>,
mesh_names: Vec<CString>,
clip_ids: Vec<CString>,
clip_names: Vec<CString>,
clip_groups: Vec<CString>,
texture_uris: Vec<CString>,
bone_ids: Vec<CString>,
expression_ids: Vec<CString>,
expression_names: Vec<CString>,
hit_area_ids: Vec<CString>,
hit_area_names: Vec<CString>,
user_data: Vec<CString>,
part_ids: Vec<CString>,
part_names: Vec<CString>,
gui_ids: Vec<CString>,
gui_names: Vec<CString>,
gui_presets: Vec<CString>,
meta_keys: Vec<CString>,
meta_values: Vec<CString>,
/// Per clip, the text of each of its events.
event_values: Vec<Vec<CString>>,
/// Each embedded PNG page decoded once, on the first render that needs it.
decoded: Vec<std::sync::OnceLock<Option<crate::png::Image>>>,
/// Per mesh, the part holding it, or -1.
mesh_part: Vec<i32>,
/// Per part, the part holding it, or -1.
part_parent: Vec<i32>,
groups: Vec<Group>,
}
fn c_string(text: &str) -> CString {
CString::new(text.replace('\0', "")).unwrap()
}
fn c_strings<'a>(texts: impl Iterator<Item = &'a String>) -> Vec<CString> {
texts.map(|t| c_string(t)).collect()
}
impl Model {
pub fn new(rig: Rig) -> Model {
let mut mesh_part = vec![-1; rig.meshes.len()];
let mut part_parent = vec![-1; rig.parts.len()];
for (p, part) in rig.parts.iter().enumerate() {
for child in &part.children {
match *child {
Child::Mesh(m) => mesh_part[m] = p as i32,
Child::Part(c) => part_parent[c] = p as i32,
}
}
}
// The part's own composite, unless the render tree gives its group one.
let mut composites: Vec<&Composite> = rig.parts.iter().map(|p| &p.composite).collect();
fn from_tree<'a>(g: &'a RenderGroup, out: &mut Vec<&'a Composite>) {
if let (Some(p), Some(c)) = (g.part, &g.composite) {
if let Some(slot) = out.get_mut(p) {
*slot = c;
}
}
for child in &g.children {
if let RenderNode::Group(child) = child {
from_tree(child, out);
}
}
}
from_tree(&rig.render, &mut composites);
let groups = composites
.iter()
.map(|c| {
let mut masks: Vec<u32> = c.masked_by.iter().map(|m| *m as u32).collect();
for &p in &c.masked_by_parts {
for m in part_meshes(&rig, p) {
if !masks.contains(&(m as u32)) {
masks.push(m as u32);
}
}
}
Group { blend: c.blend as i32, alpha_blend: c.alpha_blend as i32, invert_mask: c.invert_mask, masks }
})
.collect();
let mut user_data = vec![String::new(); rig.meshes.len()];
for (m, text) in &rig.user_data {
user_data[*m] = text.clone();
}
let gui = rig.gui.as_ref();
let gui_nodes = gui.map_or(&[][..], |g| &g.nodes[..]);
Model {
skinning: std::array::from_fn(|_| std::sync::OnceLock::new()),
parameter_ids: c_strings(rig.parameters.iter().map(|p| &p.id)),
parameter_names: c_strings(rig.parameters.iter().map(|p| &p.name)),
mesh_ids: c_strings(rig.meshes.iter().map(|m| &m.id)),
mesh_names: c_strings(rig.meshes.iter().map(|m| &m.name)),
clip_ids: c_strings(rig.clips.iter().map(|c| &c.id)),
clip_names: c_strings(rig.clips.iter().map(|c| &c.name)),
clip_groups: c_strings(rig.clips.iter().map(|c| &c.group)),
texture_uris: c_strings(rig.textures.iter().map(|t| &t.uri)),
bone_ids: c_strings(rig.extensions.bones.iter().map(|(_, id)| id)),
expression_ids: c_strings(rig.expressions.iter().map(|e| &e.id)),
expression_names: c_strings(rig.expressions.iter().map(|e| &e.name)),
hit_area_ids: c_strings(rig.hit_areas.iter().map(|h| &h.0)),
hit_area_names: c_strings(rig.hit_areas.iter().map(|h| &h.1)),
user_data: c_strings(user_data.iter()),
part_ids: c_strings(rig.parts.iter().map(|p| &p.id)),
part_names: c_strings(rig.parts.iter().map(|p| &p.name)),
gui_ids: c_strings(gui_nodes.iter().map(|n| &n.id)),
gui_names: c_strings(gui_nodes.iter().map(|n| &n.name)),
gui_presets: gui_nodes.iter().map(|n| c_string(if let GuiLabel::Preset(p) = &n.label { p } else { "" })).collect(),
meta_keys: c_strings(rig.meta.iter().map(|(k, _)| k)),
meta_values: c_strings(rig.meta.iter().map(|(_, v)| v)),
event_values: rig.clips.iter().map(|c| c_strings(c.extras.events.iter().map(|(_, v)| v))).collect(),
decoded: rig.textures.iter().map(|_| std::sync::OnceLock::new()).collect(),
mesh_part,
part_parent,
groups,
rig,
}
}
}
/// The meshes under [part], however deep.
fn part_meshes(rig: &Rig, part: usize) -> Vec<usize> {
let mut out = Vec::new();
let mut stack = vec![part];
let mut seen = vec![false; rig.parts.len()];
while let Some(p) = stack.pop() {
if p >= seen.len() || std::mem::replace(&mut seen[p], true) {
continue;
}
for child in &rig.parts[p].children {
match *child {
Child::Mesh(m) => out.push(m),
Child::Part(c) => stack.push(c),
}
}
}
out
}
/// Rigs created so far, so each after the first blinks on its own seed.
static INSTANCES: AtomicU32 = AtomicU32::new(0);
/// One clip layer: its player, the priority of what it plays, and its weight over the layers below.
struct Layer {
player: Player,
priority: u32,
weight: f32,
}
impl Layer {
fn new() -> Layer {
Layer { player: Player::new(), priority: 0, weight: 1.0 }
}
}
type Colors = ([f32; 3], [f32; 3]);
pub struct Handle {
model: Arc<Model>,
evaluator: Evaluator,
/// Clip layers, applied in order; layer 0 is the one p2l_play drives.
layers: Vec<Layer>,
/// Events the last update's clips passed: layer, clip and event.
events: Vec<(u32, usize, usize)>,
/// The rig's opacity: the host's, and the one clips set.
opacity: f32,
clip_opacity: f32,
/// Colors the host puts in place of a mesh's, or of every mesh under a part.
mesh_colors: Vec<Option<Colors>>,
part_colors: Vec<Option<Colors>>,
/// Textures the host gave pages in place of the file's, for the software renderer.
textures: Vec<Option<crate::png::Image>>,
/// What each mesh showed at the evaluation before the last, and what changed since.
shown: Shown,
changes: Vec<u32>,
behaviors: Behaviors,
physics: Physics,
/// The pose the host sets, under clips, expressions, behaviors and physics.
values: Vec<f32>,
/// The values the last evaluation used: [values] with every layer applied, rebuilt from it each time.
current: Vec<f32>,
/// The host's layer over clips and expressions: per parameter a value and the weight it takes over with.
overrides: Vec<(f32, f32)>,
expressions: ExpressionPlayer,
poses: PosePlayer,
advanced: Advanced,
render_order: Vec<u32>,
render_commands: Vec<i32>,
/// Why a call on this handle panicked; once set, the handle acts as a null one.
failure: OnceCell<CString>,
}
/// The message a panic carried.
fn panic_message(payload: &(dyn Any + Send)) -> String {
payload.downcast_ref::<&str>().map(|s| s.to_string())
.or_else(|| payload.downcast_ref::<String>().cloned())
.unwrap_or_else(|| "unknown panic".to_string())
}
fn write_error(message: &str, error: *mut c_char, capacity: usize) {
if error.is_null() || capacity == 0 {
return;
}
let bytes = message.as_bytes();
let n = bytes.len().min(capacity - 1);
unsafe {
ptr::copy_nonoverlapping(bytes.as_ptr(), error as *mut u8, n);
*error.add(n) = 0;
}
}
impl Handle {
/// A handle on [model] at its defaults, evaluated once.
pub fn new(model: Arc<Model>) -> Handle {
let rig = &model.rig;
let values = rig.defaults();
let mut behaviors = Behaviors::default();
let instance = INSTANCES.fetch_add(1, Ordering::Relaxed);
if instance > 0 {
behaviors.seed(instance.wrapping_mul(0x9e37_79b9) ^ 0x2545_f491);
}
let mut handle = Handle {
physics: Physics::new(rig),
poses: PosePlayer::new(rig),
overrides: vec![(0.0, 0.0); rig.parameters.len()],
expressions: ExpressionPlayer::new(),
advanced: Advanced::new(),
failure: OnceCell::new(),
evaluator: Evaluator::new(),
layers: vec![Layer::new()],
events: Vec::new(),
opacity: 1.0,
clip_opacity: 1.0,
mesh_colors: vec![None; rig.meshes.len()],
part_colors: vec![None; rig.parts.len()],
textures: vec![None; rig.textures.len()],
shown: Shown::default(),
changes: Vec::new(),
behaviors,
current: values.clone(),
values,
render_order: Vec::new(),
render_commands: Vec::new(),
model,
};
evaluate(&mut handle);
track_changes(&mut handle);
handle
}
/// Records the panic a call ended in; the handle stays failed.
fn fail(&self, payload: Box<dyn Any + Send>) {
let message = panic_message(payload.as_ref()).replace('\0', "");
crate::host::log(crate::host::ERROR, &format!("The rig failed: {}", message));
let _ = self.failure.set(CString::new(message).unwrap());
}
}
/// Load flag: check the CRC of every chunk that carries one.
pub const LOAD_VERIFY_CRC: u32 = 1;
/// The model [read] gives; a message when it does not read or panics.
fn read_model(read: impl FnOnce() -> crate::rig::Result<Rig>) -> Result<Arc<Model>, String> {
let model = match panic::catch_unwind(AssertUnwindSafe(|| read().map(|rig| Arc::new(Model::new(rig))))) {
Ok(Ok(model)) => Ok(model),
Ok(Err(e)) => Err(e.0),
Err(payload) => Err(format!("The rig could not be read: {}", panic_message(payload.as_ref()))),
};
model.inspect_err(|message| crate::host::log(crate::host::ERROR, message))
}
/// A rig handle on [model], evaluated once; null with a message in [error] when that first evaluation panics.
fn create(model: Arc<Model>, error: *mut c_char, error_capacity: usize) -> *mut Handle {
match panic::catch_unwind(AssertUnwindSafe(|| Handle::new(model))) {
Ok(handle) => Box::into_raw(Box::new(handle)),
Err(payload) => {
let message = format!("The rig could not be read: {}", panic_message(payload.as_ref()));
crate::host::log(crate::host::ERROR, &message);
write_error(&message, error, error_capacity);
ptr::null_mut()
}
}
}
/// What every mesh showed at an evaluation, to tell what the next one changes.
#[derive(Default)]
struct Shown {
vertices: Vec<Vec<f32>>,
opacity: Vec<f32>,
draw_order: Vec<f32>,
multiply: Vec<crate::rig::Rgb>,
screen: Vec<crate::rig::Rgb>,
/// Each mesh's place in the render order, -1 when it does not draw.
place: Vec<i64>,
}
/// Sets each mesh's MESH_* bits from the pose against the one shown before (everything changed the first time).
fn track_changes(h: &mut Handle) {
let pose = &h.evaluator.pose;
let n = h.model.rig.meshes.len();
let mut place = vec![-1i64; n];
for (k, &m) in h.render_order.iter().enumerate() {
if let Some(p) = place.get_mut(m as usize) {
*p = k as i64;
}
}
let first = h.shown.place.len() != n;
h.changes.clear();
for m in 0..n {
let opacity = pose.opacity.get(m).copied().unwrap_or(0.0);
let visible = place[m] >= 0 && opacity > 0.0;
let mut bits = if visible { MESH_VISIBLE } else { 0 };
if first {
bits |= MESH_VISIBILITY_CHANGED | MESH_OPACITY_CHANGED | MESH_DRAW_ORDER_CHANGED | MESH_RENDER_ORDER_CHANGED | MESH_VERTICES_CHANGED | MESH_COLORS_CHANGED;
} else {
let was_visible = h.shown.place[m] >= 0 && h.shown.opacity[m] > 0.0;
let changed = |bit: u32, differs: bool| if differs { bit } else { 0 };
bits |= changed(MESH_VISIBILITY_CHANGED, visible != was_visible)
| changed(MESH_OPACITY_CHANGED, opacity.to_bits() != h.shown.opacity[m].to_bits())
| changed(MESH_DRAW_ORDER_CHANGED, pose.draw_order.get(m).map(|d| d.to_bits()) != Some(h.shown.draw_order[m].to_bits()))
| changed(MESH_RENDER_ORDER_CHANGED, place[m] != h.shown.place[m])
| changed(MESH_VERTICES_CHANGED, pose.vertices.get(m).map_or(&[][..], |v| &v[..]) != &h.shown.vertices[m][..])
| changed(MESH_COLORS_CHANGED, pose.multiply.get(m) != h.shown.multiply.get(m) || pose.screen.get(m) != h.shown.screen.get(m));
}
h.changes.push(bits);
}
let shown = &mut h.shown;
shown.vertices.resize(n, Vec::new());
for (m, v) in pose.vertices.iter().enumerate().take(n) {
shown.vertices[m].clone_from(v);
}
shown.opacity.clone_from(&pose.opacity);
shown.opacity.resize(n, 0.0);
shown.draw_order.clone_from(&pose.draw_order);
shown.draw_order.resize(n, 0.0);
shown.multiply.clone_from(&pose.multiply);
shown.screen.clone_from(&pose.screen);
shown.place = place;
}
/// A rig handle on the rig [read] gives; null with a message in [error] when it does not read or panics,
/// reading or in its first evaluation.
fn open(read: impl FnOnce() -> crate::rig::Result<Rig>, error: *mut c_char, error_capacity: usize) -> *mut Handle {
match read_model(read) {
Ok(model) => create(model, error, error_capacity),
Err(message) => {
write_error(&message, error, error_capacity);
ptr::null_mut()
}
}
}
/// Loads a rig from [len] bytes; on failure returns null and writes a message into [error].
#[no_mangle]
pub unsafe extern "C" fn p2l_rig_load(bytes: *const u8, len: usize, error: *mut c_char, error_capacity: usize) -> *mut Handle {
p2l_rig_load_ex(bytes, len, 0, error, error_capacity)
}
/// [p2l_rig_load] with [flags], `LOAD_VERIFY_CRC` or 0.
#[no_mangle]
pub unsafe extern "C" fn p2l_rig_load_ex(bytes: *const u8, len: usize, flags: u32, error: *mut c_char, error_capacity: usize) -> *mut Handle {
if bytes.is_null() {
write_error("No rig bytes", error, error_capacity);
return ptr::null_mut();
}
let data = std::slice::from_raw_parts(bytes, len);
open(|| Rig::read_with(data, flags & LOAD_VERIFY_CRC != 0), error, error_capacity)
}
/// Loads a model to create rigs from, with [flags] as [p2l_rig_load_ex]; on failure returns null and writes a
/// message into [error].
#[no_mangle]
pub unsafe extern "C" fn p2l_model_load(bytes: *const u8, len: usize, flags: u32, error: *mut c_char, error_capacity: usize) -> *const Model {
if bytes.is_null() {
write_error("No rig bytes", error, error_capacity);
return ptr::null();
}
let data = std::slice::from_raw_parts(bytes, len);
match read_model(|| Rig::read_with(data, flags & LOAD_VERIFY_CRC != 0)) {
Ok(model) => Arc::into_raw(model),
Err(message) => {
write_error(&message, error, error_capacity);
ptr::null()
}
}
}
/// Sends what goes wrong (loads that fail, rigs that fail, pages that do not decode) to [log] with [user]; null for
/// none. Any thread may call it.
#[no_mangle]
pub unsafe extern "C" fn p2l_set_log(log: Option<crate::host::LogFunction>, user: *mut std::ffi::c_void) {
crate::host::set_log(log, user)
}
/// Takes all the runtime's memory from [allocate] and [free] from now on; call it first, from one thread, before
/// anything else of the runtime. False, changing nothing, once the runtime has taken memory from the system, for a
/// missing function, or in a build without the host-allocator feature.
#[no_mangle]
pub unsafe extern "C" fn p2l_set_allocator(
allocate: Option<unsafe extern "C" fn(usize, usize, *mut std::ffi::c_void) -> *mut std::ffi::c_void>,
free: Option<unsafe extern "C" fn(*mut std::ffi::c_void, usize, usize, *mut std::ffi::c_void)>,
user: *mut std::ffi::c_void,
) -> bool {
#[cfg(feature = "host-allocator")]
return crate::host::set_allocator(allocate, free, user);
#[cfg(not(feature = "host-allocator"))]
{
let _ = (allocate, free, user);
false
}
}
/// Lets go of [model]; rigs created from it keep it until they are freed.
#[no_mangle]
pub unsafe extern "C" fn p2l_model_free(model: *const Model) {
if !model.is_null() {
let model = Arc::from_raw(model);
let _ = panic::catch_unwind(AssertUnwindSafe(|| drop(model)));
}
}
/// A rig on [model] at its defaults, sharing the model with every other rig created from it; null with a
/// message in [error] when its first evaluation fails.
#[no_mangle]
pub unsafe extern "C" fn p2l_rig_create(model: *const Model, error: *mut c_char, error_capacity: usize) -> *mut Handle {
if model.is_null() {
write_error("No model", error, error_capacity);
return ptr::null_mut();
}
Arc::increment_strong_count(model);
create(Arc::from_raw(model), error, error_capacity)
}
#[no_mangle]
pub unsafe extern "C" fn p2l_rig_free(handle: *mut Handle) {
if !handle.is_null() {
let handle = Box::from_raw(handle);
let _ = panic::catch_unwind(AssertUnwindSafe(|| drop(handle)));
}
}
/// Why a call on the handle panicked, after which it acts as a null handle; null while it works.
#[no_mangle]
pub unsafe extern "C" fn p2l_rig_failure(handle: *const Handle) -> *const c_char {
match handle.as_ref().and_then(|h| h.failure.get()) {
Some(message) => message.as_ptr(),
None => ptr::null(),
}
}
fn evaluate(handle: &mut Handle) {
let rig = &handle.model.rig;
let advanced = if handle.advanced.enabled() != 0 { Some(&mut handle.advanced) } else { None };
let pose = handle.evaluator.evaluate_ext(rig, &handle.current, advanced);
handle.render_order = render_order(rig, pose);
handle.render_commands = render_commands(rig, pose);
handle.poses.apply(rig, &mut handle.evaluator.pose);
let pose = &mut handle.evaluator.pose;
let opacity = handle.opacity * handle.clip_opacity;
if opacity != 1.0 {
pose.opacity.iter_mut().for_each(|o| *o *= opacity);
}
if handle.mesh_colors.iter().chain(&handle.part_colors).any(Option::is_some) {
let model = &handle.model;
for m in 0..pose.multiply.len() {
// The mesh's own colors, else those of the nearest part above it that has some.
let mut colors = handle.mesh_colors[m];
let mut part = model.mesh_part[m];
let mut steps = 0;
while colors.is_none() && part >= 0 && steps <= model.part_parent.len() {
colors = handle.part_colors[part as usize];
part = model.part_parent[part as usize];
steps += 1;
}
if let Some((multiply, screen)) = colors {
pose.multiply[m] = multiply;
pose.screen[m] = screen;
}
}
}
}
/// Runs the layers in [stages] over the host's pose by [dt] seconds, then evaluates.
fn update(h: &mut Handle, dt: f32, stages: u32) {
// Every layer starts from the host's pose afresh, so blinks, sways and added expressions never pile up.
h.current.clone_from(&h.values);
let rig = &h.model.rig;
if stages & STAGE_CLIPS != 0 {
h.events.clear();
let mut effects = Effects::default();
for (l, layer) in h.layers.iter_mut().enumerate() {
10BC8
layer.player.update_layer(rig, dt, layer.weight, &mut h.current, &mut effects);
h.events.extend(effects.events.drain(..).map(|(c, e)| (l as u32, c, e)));
if layer.player.finished(rig) {
layer.priority = 0;
}
}
h.poses.set_clip_opacities(&effects.part_opacity);
h.clip_opacity = effects.model_opacity.map_or(1.0, |o| if o.is_finite() { o.clamp(0.0, 1.0) } else { 1.0 });
} else {
// A frame that skips clips must not keep the opacity the previous clip frame applied.
h.poses.set_clip_opacities(&[]);
h.clip_opacity = 1.0;
}
if stages & STAGE_EXPRESSIONS != 0 {
h.expressions.update(rig, dt, &mut h.current);
}
for (value, &(target, weight)) in h.current.iter_mut().zip(&h.overrides) {
if weight > 0.0 {
*value += (target - *value) * weight;
}
}
if stages & STAGE_BEHAVIORS != 0 {
h.behaviors.update(rig, dt, &mut h.current);
}
if stages & STAGE_POSES != 0 {
h.poses.update(rig, dt);
}
if stages & STAGE_PHYSICS != 0 {
let skip = h.advanced.skipped_physics(rig);
h.physics.step_skipping(rig, dt, &mut h.current, &skip);
}
evaluate(h);
let rig = &h.model.rig;
if stages & STAGE_SIM != 0 && h.advanced.enabled() & crate::advanced::SIM != 0 {
let values: Vec<f32> = rig.parameters.iter().zip(&h.current).map(|(p, v)| p.normalize(*v)).collect();
h.advanced.step_simulations(rig, &values, dt, &mut h.evaluator.pose);
} else {
h.advanced.show_simulations(rig, &mut h.evaluator.pose);
}
track_changes(h);
}
/// Runs [body] on a working handle, [default] for a null or failed one. A panic in [body] fails the handle and
/// gives [default] instead of unwinding into the host.
macro_rules! with {
($handle:expr, $default:expr, |$h:ident| $body:expr) => {{
match ($handle as *const Handle).as_ref() {
Some($h) if $h.failure.get().is_none() => match panic::catch_unwind(AssertUnwindSafe(|| $body)) {
Ok(value) => value,
Err(payload) => {
$h.fail(payload);
$default
}
},
_ => $default,
}
}};
}
macro_rules! with_mut {
($handle:expr, $default:expr, |$h:ident| $body:expr) => {{
match $handle.as_mut() {
Some($h) if $h.failure.get().is_none() => match panic::catch_unwind(AssertUnwindSafe(|| $body)) {
Ok(value) => value,
Err(payload) => {
$h.fail(payload);
$default
}
},
_ => $default,
}
}};
}
/// The string at [index] of [strings], or null.
fn string_at(strings: &[CString], index: u32) -> *const c_char {
strings.get(index as usize).map_or(ptr::null(), |s| s.as_ptr())
}
/// Writes [values] into [out] up to [capacity]; returns how many there are.
unsafe fn write_all<T: Copy>(values: &[T], out: *mut T, capacity: u32) -> u32 {
if !out.is_null() {
let n = values.len().min(capacity as usize);
ptr::copy_nonoverlapping(values.as_ptr(), out, n);
}
values.len() as u32
}
unsafe fn put<T>(out: *mut T, value: T) {
if !out.is_null() {
*out = value;
}
}
#[no_mangle]
pub unsafe extern "C" fn p2l_canvas(handle: *const Handle, width: *mut f32, height: *mut f32) {
with!(handle, (), |h| {
put(width, h.model.rig.canvas.width);
put(height, h.model.rig.canvas.height);
})
}
/// Where the canvas origin sits in canvas pixels and how many pixels make a model unit (0 when the file names none).
#[no_mangle]
pub unsafe extern "C" fn p2l_canvas_origin(handle: *const Handle, x: *mut f32, y: *mut f32, pixels_per_unit: *mut f32) {
with!(handle, (), |h| {
let canvas = &h.model.rig.canvas;
put(x, canvas.origin_x);
put(y, canvas.origin_y);
put(pixels_per_unit, canvas.pixels_per_unit.unwrap_or(0.0));
})
}
// --- parameters ---
#[no_mangle]
pub unsafe extern "C" fn p2l_parameter_count(handle: *const Handle) -> u32 {
with!(handle, 0, |h| h.model.rig.parameters.len() as u32)
}
#[no_mangle]
pub unsafe extern "C" fn p2l_parameter_id(handle: *const Handle, index: u32) -> *const c_char {
with!(handle, ptr::null(), |h| string_at(&h.model.parameter_ids, index))
}
#[no_mangle]
pub unsafe extern "C" fn p2l_parameter_name(handle: *const Handle, index: u32) -> *const c_char {
with!(handle, ptr::null(), |h| string_at(&h.model.parameter_names, index))
}
/// The index of the parameter with [id] as [p2l_parameter_id] gives it, or -1.
#[no_mangle]
pub unsafe extern "C" fn p2l_parameter_index(handle: *const Handle, id: *const c_char) -> i32 {
if id.is_null() {
return -1;
}
let id = CStr::from_ptr(id);
with!(handle, -1, |h| h.model.parameter_ids.iter().position(|s| s.as_c_str() == id).map_or(-1, |i| i as i32))
}
#[no_mangle]
pub unsafe extern "C" fn p2l_parameter_range(handle: *const Handle, index: u32, min: *mut f32, max: *mut f32, default: *mut f32) -> bool {
with!(handle, false, |h| match h.model.rig.parameters.get(index as usize) {
Some(p) => {
put(min, p.min);
put(max, p.max);
put(default, p.default);
true
}
None => false,
})
}
/// PARAMETER_REPEAT when values beyond the range wrap, PARAMETER_BLEND_SHAPE for a blend shape's parameter.
#[no_mangle]
pub unsafe extern "C" fn p2l_parameter_flags(handle: *const Handle, index: u32) -> u32 {
with!(handle, 0, |h| h.model.rig.parameters.get(index as usize).map_or(0, |p| {
(if p.repeat { PARAMETER_REPEAT } else { 0 }) | (if p.blend { PARAMETER_BLEND_SHAPE } else { 0 })
}))
}
/// The values a parameter panel snaps the parameter to, ascending, into [out] up to [capacity]; returns how many.
#[no_mangle]
pub unsafe extern "C" fn p2l_parameter_snaps(handle: *const Handle, index: u32, out: *mut f32, capacity: u32) -> u32 {
with!(handle, 0, |h| {
let snaps = h.model.rig.gui.as_ref().and_then(|g| g.snaps.iter().find(|(p, _)| *p == index as usize));
snaps.map_or(0, |(_, values)| write_all(values, out, capacity))
})
}
/// The pose the host sets, one value per parameter: what every update and evaluation starts from. Clips,
/// expressions, behaviors and physics apply over a copy of it, so additive layers never accumulate here.
#[no_mangle]
pub unsafe extern "C" fn p2l_parameter_values(handle: *mut Handle) -> *mut f32 {
with_mut!(handle, ptr::null_mut(), |h| h.values.as_mut_ptr())
}
/// The values the last evaluation used, after clips, expressions, behaviors and physics; read-only.
#[no_mangle]
pub unsafe extern "C" fn p2l_parameter_current(handle: *const Handle) -> *const f32 {
with!(handle, ptr::null(), |h| h.current.as_ptr())
}
#[no_mangle]
pub unsafe extern "C" fn p2l_set_parameter(handle: *mut Handle, index: u32, value: f32) {
with_mut!(handle, (), |h| if let Some(v) = h.values.get_mut(index as usize) {
*v = value
})
}
/// Sets the host's layer on parameter [index]: after clips and expressions, before behaviors and physics, the
/// value moves toward [value] by [weight] 0..1. Weight 0 takes the layer off the parameter.
#[no_mangle]
pub unsafe extern "C" fn p2l_set_parameter_override(handle: *mut Handle, index: u32, value: f32, weight: f32) -> bool {
with_mut!(handle, false, |h| match h.overrides.get_mut(index as usize) {
Some(slot) if value.is_finite() => {
*slot = (value, if weight.is_finite() { weight.clamp(0.0, 1.0) } else { 0.0 });
true
}
_ => false,
})
}
/// Takes the host's layer off every parameter.
#[no_mangle]
pub unsafe extern "C" fn p2l_clear_parameter_overrides(handle: *mut Handle) {
with_mut!(handle, (), |h| h.overrides.iter_mut().for_each(|o| *o = (0.0, 0.0)))
}
/// Indices of the parameters with [role] (such as EyeBlink or LipSync) into [out]; returns how many there are.
#[no_mangle]
pub unsafe extern "C" fn p2l_role_parameters(handle: *const Handle, role: *const c_char, out: *mut u32, capacity: u32) -> u32 {
if role.is_null() {
return 0;
}
let role = CStr::from_ptr(role).to_string_lossy();
with!(handle, 0, |h| {
let found: Vec<u32> = h.model.rig.roles.iter().filter(|r| r.role == role).flat_map(|r| r.parameters.iter().map(|p| *p as u32)).collect();
write_all(&found, out, capacity)
})
}
// --- parameter panel ---
/// Pairs of parameters a panel shows as one two-dimensional control, horizontal then vertical, two indices
/// each, into [out] up to [capacity] pairs; returns how many pairs there are.
#[no_mangle]
pub unsafe extern "C" fn p2l_gui_joysticks(handle: *const Handle, out: *mut u32, capacity: u32) -> u32 {
with!(handle, 0, |h| {
let pairs: Vec<u32> = h.model.rig.gui.as_ref().map_or(Vec::new(), |g| g.joysticks.iter().flat_map(|(x, y)| [*x as u32, *y as u32]).collect());
if !out.is_null() {
let n = (pairs.len() / 2).min(capacity as usize) * 2;
ptr::copy_nonoverlapping(pairs.as_ptr(), out, n);
}
(pairs.len() / 2) as u32
})
}
#[no_mangle]
pub unsafe extern "C" fn p2l_gui_node_count(handle: *const Handle) -> u32 {
with!(handle, 0, |h| h.model.gui_ids.len() as u32)
}
/// Panel node [index] in pre-order: the parameter a leaf shows (-1 for a group), how many nodes follow as its
/// children, and whether the group starts open; false when there is no such node.
#[no_mangle]
pub unsafe extern "C" fn p2l_gui_node(handle: *const Handle, index: u32, parameter: *mut i32, children: *mut u32, open: *mut bool) -> bool {
with!(handle, false, |h| match h.model.rig.gui.as_ref().and_then(|g| g.nodes.get(index as usize)) {
Some(node) => {
put(parameter, node.parameter.map_or(-1, |p| p as i32));
put(children, node.children as u32);
put(open, node.open);
true
}
None => false,
})
}
#[no_mangle]
pub unsafe extern "C" fn p2l_gui_node_id(handle: *const Handle, index: u32) -> *const c_char {
with!(handle, ptr::null(), |h| string_at(&h.model.gui_ids, index))
}
#[no_mangle]
pub unsafe extern "C" fn p2l_gui_node_name(handle: *const Handle, index: u32) -> *const c_char {
with!(handle, ptr::null(), |h| string_at(&h.model.gui_names, index))
}
/// Node [index]'s label: 0 none, 1 a preset named in [preset], 2 a custom color in [argb]; -1 for no such node.
#[no_mangle]
pub unsafe extern "C" fn p2l_gui_node_label(handle: *const Handle, index: u32, preset: *mut *const c_char, argb: *mut u32) -> i32 {
with!(handle, -1, |h| match h.model.rig.gui.as_ref().and_then(|g| g.nodes.get(index as usize)) {
Some(node) => {
put(preset, h.model.gui_presets[index as usize].as_ptr());
put(argb, if let GuiLabel::Custom(c) = node.label { c } else { 0 });
match node.label {
GuiLabel::None => 0,
GuiLabel::Preset(_) => 1,
GuiLabel::Custom(_) => 2,
}
}
None => -1,
})
}
// --- evaluation ---
/// Deforms the rig at the host's pose as it is, without clips, behaviors or physics.
#[no_mangle]
pub unsafe extern "C" fn p2l_evaluate(handle: *mut Handle) {
with_mut!(handle, (), |h| {
h.current.clone_from(&h.values);
h.poses.set_clip_opacities(&[]);
h.clip_opacity = 1.0;
evaluate(h);
h.advanced.show_simulations(&h.model.rig, &mut h.evaluator.pose);
track_changes(h);
})
}
/// Advances clips, expressions, behaviors and physics by [dt] seconds over the host's pose, then evaluates.
#[no_mangle]
pub unsafe extern "C" fn p2l_update(handle: *mut Handle, dt: f32) {
with_mut!(handle, (), |h| update(h, dt, STAGE_ALL))
}
/// [p2l_update] running only the layers in [stages]; the others neither advance nor apply.
#[no_mangle]
pub unsafe extern "C" fn p2l_update_stages(handle: *mut Handle, dt: f32, stages: u32) {
with_mut!(handle, (), |h| update(h, dt, stages))
}
#[no_mangle]
pub unsafe extern "C" fn p2l_physics_reset(handle: *mut Handle) {
with_mut!(handle, (), |h| {
let wind = h.physics.wind;
h.physics = Physics::new(&h.model.rig);
h.physics.wind = wind;
})
}
/// Wind on every pendulum besides gravity, in physics units (x right, y down), as Cubism's physics wind.
#[no_mangle]
pub unsafe extern "C" fn p2l_physics_wind(handle: *mut Handle, x: f32, y: f32) {
with_mut!(handle, (), |h| if x.is_finite() && y.is_finite() {
h.physics.wind = (x, y)
})
}
/// Hangs every pendulum at rest under the last evaluation's pose, as Cubism's stabilization does, and evaluates.
#[no_mangle]
pub unsafe extern "C" fn p2l_physics_stabilize(handle: *mut Handle) {
with_mut!(handle, (), |h| {
let mut values = h.current.clone();
h.physics.stabilize(&h.model.rig, &mut values);
h.current = values;
evaluate(h);
track_changes(h);
})
}
/// The rig's opacity, 0..1, multiplying every mesh on top of what clips set (1 until set).
#[no_mangle]
pub unsafe extern "C" fn p2l_set_opacity(handle: *mut Handle, opacity: f32) {
with_mut!(handle, (), |h| if opacity.is_finite() {
h.opacity = opacity.clamp(0.0, 1.0)
})
}
/// The rig's opacity at the last update: the host's times the one clips set.
#[no_mangle]
pub unsafe extern "C" fn p2l_opacity(handle: *const Handle) -> f32 {
with!(handle, 0.0, |h| h.opacity * h.clip_opacity)
}
/// Puts [multiply] and [screen] (three floats each) in place of the mesh's evaluated colors from the next
/// evaluation; both null gives the mesh its own back. False for no such mesh.
#[no_mangle]
pub unsafe extern "C" fn p2l_set_mesh_colors(handle: *mut Handle, index: u32, multiply: *const f32, screen: *const f32) -> bool {
with_mut!(handle, false, |h| match h.mesh_colors.get_mut(index as usize) {
Some(slot) => {
*slot = colors_from(multiply, screen);
true
}
None => false,
})
}
/// [p2l_set_mesh_colors] for every mesh under the part that has no colors of its own set.
#[no_mangle]
pub unsafe extern "C" fn p2l_set_part_colors(handle: *mut Handle, index: u32, multiply: *const f32, screen: *const f32) -> bool {
with_mut!(handle, false, |h| match h.part_colors.get_mut(index as usize) {
Some(slot) => {
*slot = colors_from(multiply, screen);
true
}
None => false,
})
}
/// Colors the host gives: null for none when both are null, white multiply and black screen standing in for a
/// null one.
unsafe fn colors_from(multiply: *const f32, screen: *const f32) -> Option<Colors> {
if multiply.is_null() && screen.is_null() {
return None;
}
let read = |p: *const f32, default: [f32; 3]| if p.is_null() { default } else { [*p, *p.add(1), *p.add(2)] };
Some((read(multiply, crate::rig::WHITE), read(screen, crate::rig::BLACK)))
}
// --- behaviors ---
/// Switches behaviors on: 1 blink, 2 breathing, 4 gaze, 8 lip sync. Blinking and breathing start on.
#[no_mangle]
pub unsafe extern "C" fn p2l_behaviors(handle: *mut Handle, flags: u32) {
with_mut!(handle, (), |h| h.behaviors.enabled = flags)
}
/// Blink timing in seconds: the interval drawn evenly between [interval_min] and [interval_max], and how long
/// the eyes take to close, stay closed and open; false, changing nothing, for negative or reversed times.
#[no_mangle]
pub unsafe extern "C" fn p2l_blink_settings(handle: *mut Handle, interval_min: f32, interval_max: f32, closing: f32, closed: f32, opening: f32) -> bool {
with_mut!(handle, false, |h| {
let times = [interval_min, interval_max, closing, closed, opening];
if times.iter().any(|t| !t.is_finite() || *t < 0.0) || interval_max < interval_min || closing <= 0.0 || opening <= 0.0 {
return false;
}
let s = &mut h.behaviors.settings;
s.blink_interval = (interval_min, interval_max);
(s.blink_closing, s.blink_closed, s.blink_opening) = (closing, closed, opening);
true
})
}
/// How strongly breathing sways and gaze turns (1 as they are), and how quickly gaze follows (1 settles in about
/// a third of a second); false, changing nothing, for negative values.
#[no_mangle]
pub unsafe extern "C" fn p2l_behavior_strength(handle: *mut Handle, sway: f32, look: f32, look_speed: f32) -> bool {
with_mut!(handle, false, |h| {
if [sway, look, look_speed].iter().any(|v| !v.is_finite() || *v < 0.0) {
return false;
}
let s = &mut h.behaviors.settings;
(s.sway, s.look, s.look_speed) = (sway, look, look_speed);
true
})
}
/// Lip sync from audio: the root mean square of [count] samples (-1..1) times [gain], clamped to 0..1, becomes
/// the mouth opening; returns it.
#[no_mangle]
pub unsafe extern "C" fn p2l_lip_sync_samples(handle: *mut Handle, samples: *const f32, count: usize, gain: f32) -> f32 {
with_mut!(handle, 0.0, |h| {
let samples = if samples.is_null() || count == 0 { &[][..] } else { std::slice::from_raw_parts(samples, count) };
h.behaviors.lip_sync_samples(samples, gain)