animsmith-fbx 0.4.1

FBX ingestion into the animsmith core model, via the official ufbx bindings
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
//! Format-neutral source facts projected from one successfully parsed ufbx scene.

use animsmith_core::{
    InputIdentity, RAW_SOURCE_V1_MAX_TEXT_BYTES, RawSourceFactsBuilderV1, SourceAxisV1,
    SourceChannelFactV1, SourceChannelPropertyV1, SourceClipFactV1, SourceComponentMaskV1,
    SourceConstructFactV1, SourceConstructKindV1, SourceCoordinateBasisV1, SourceFactDomainV1,
    SourceFactSetV1, SourceFormatV1, SourceFramesPerSecondV1, SourceLinearUnitV1,
    SourceLoaderDispositionV1, SourceLogicalLocatorV1, SourceObservationV1, SourceProvenanceV1,
    SourceResourceKindV1, SourceResourceLocatorV1, SourceResourceReferenceV1, SourceTargetKindV1,
    SourceTargetV1, SourceTextV1, SourceTimeRangeV1, SourceUnavailableReasonV1,
};

/// Project raw FBX facts before the loader performs rooted dependency capture.
///
/// The caller retains this builder long enough to attach a closure constructed
/// from its exact resource row prefix.
pub(crate) fn project(
    scene: &ufbx::Scene,
    construct_counts: SourceConstructCounts,
    primary_bytes: &[u8],
) -> RawSourceFactsBuilderV1 {
    let mut builder = RawSourceFactsBuilderV1::new(
        SourceFormatV1::Fbx,
        InputIdentity::from_bytes(primary_bytes),
    );
    project_coordinate_facts(scene, &mut builder);
    project_clips(scene, &mut builder);
    project_constructs(construct_counts, &mut builder);
    project_resources(scene, &mut builder);
    builder
}

fn project_coordinate_facts(scene: &ufbx::Scene, builder: &mut RawSourceFactsBuilderV1) {
    let unit_provenance = parser_provenance("fbx:scene.settings.unit_meters");
    builder.set_linear_unit(match SourceLinearUnitV1::new(scene.settings.unit_meters) {
        Ok(unit) => SourceObservationV1::observed(
            unit,
            unit_provenance,
            SourceLoaderDispositionV1::Normalized,
        ),
        Err(_) => SourceObservationV1::unavailable(
            SourceUnavailableReasonV1::ParserUnavailable,
            Some(unit_provenance),
            SourceLoaderDispositionV1::Normalized,
        ),
    });

    let basis_provenance = parser_provenance("fbx:scene.settings.axes");
    let axes = scene.settings.axes;
    let basis = axis(axes.right)
        .zip(axis(axes.up))
        .zip(axis(axes.front))
        .and_then(|((right, up), forward)| SourceCoordinateBasisV1::new(right, up, forward).ok());
    builder.set_coordinate_basis(match basis {
        Some(basis) => SourceObservationV1::observed(
            basis,
            basis_provenance,
            SourceLoaderDispositionV1::Normalized,
        ),
        None => SourceObservationV1::unavailable(
            SourceUnavailableReasonV1::ParserUnavailable,
            Some(basis_provenance),
            SourceLoaderDispositionV1::Normalized,
        ),
    });

    let fps_provenance = parser_provenance("fbx:scene.settings.frames_per_second");
    builder.set_frames_per_second(
        match SourceFramesPerSecondV1::new(scene.settings.frames_per_second) {
            Ok(fps) => SourceObservationV1::observed(
                fps,
                fps_provenance,
                SourceLoaderDispositionV1::Discarded,
            ),
            Err(_) => SourceObservationV1::unavailable(
                SourceUnavailableReasonV1::ParserUnavailable,
                Some(fps_provenance),
                SourceLoaderDispositionV1::Discarded,
            ),
        },
    );
}

fn axis(axis: ufbx::CoordinateAxis) -> Option<SourceAxisV1> {
    match axis {
        ufbx::CoordinateAxis::PositiveX => Some(SourceAxisV1::PositiveX),
        ufbx::CoordinateAxis::NegativeX => Some(SourceAxisV1::NegativeX),
        ufbx::CoordinateAxis::PositiveY => Some(SourceAxisV1::PositiveY),
        ufbx::CoordinateAxis::NegativeY => Some(SourceAxisV1::NegativeY),
        ufbx::CoordinateAxis::PositiveZ => Some(SourceAxisV1::PositiveZ),
        ufbx::CoordinateAxis::NegativeZ => Some(SourceAxisV1::NegativeZ),
        ufbx::CoordinateAxis::Unknown => None,
    }
}

fn project_clips(scene: &ufbx::Scene, builder: &mut RawSourceFactsBuilderV1) {
    for (stack_index, stack) in scene.anim_stacks.iter().enumerate() {
        if builder.remaining_clip_rows() == 0 || builder.remaining_observation_rows() == 0 {
            builder.mark_budget_exceeded(SourceFactDomainV1::Clips);
            return;
        }

        let stack_locator_bytes = "fbx:anim_stacks/"
            .len()
            .saturating_add(decimal_len_usize(stack_index));
        let name_locator_bytes = stack_locator_bytes.saturating_add("/name".len());
        let range_locator_bytes = stack_locator_bytes.saturating_add("/time_range".len());
        let retained_name_bytes = if stack.element.name.is_empty()
            || stack.element.name.len() > RAW_SOURCE_V1_MAX_TEXT_BYTES
        {
            0
        } else {
            stack.element.name.len()
        };
        let fixed_text_bytes = name_locator_bytes
            .saturating_add(retained_name_bytes)
            .saturating_add(stack_locator_bytes)
            .saturating_add(range_locator_bytes);
        if fixed_text_bytes > builder.remaining_text_bytes() {
            builder.mark_budget_exceeded(SourceFactDomainV1::Clips);
            return;
        }
        let stack_locator = format!("fbx:anim_stacks/{stack_index}");
        let name_locator = format!("{stack_locator}/name");
        let range_locator = format!("{stack_locator}/time_range");
        let channel_budget = builder.remaining_observation_rows().saturating_sub(1);
        let channel_text_budget = builder
            .remaining_text_bytes()
            .saturating_sub(fixed_text_bytes);
        let (channels, channels_truncated) =
            project_channels(stack, channel_budget, channel_text_budget);
        let channels = if channels_truncated {
            SourceFactSetV1::partial(
                channels,
                SourceUnavailableReasonV1::ProjectionBudgetExceeded,
            )
        } else {
            SourceFactSetV1::complete(channels)
        };

        let source_name = if stack.element.name.is_empty() {
            SourceObservationV1::unavailable(
                SourceUnavailableReasonV1::ParserUnavailable,
                Some(parser_provenance(&name_locator)),
                SourceLoaderDispositionV1::Preserved,
            )
        } else if stack.element.name.len() > RAW_SOURCE_V1_MAX_TEXT_BYTES {
            SourceObservationV1::unavailable(
                SourceUnavailableReasonV1::ProjectionBudgetExceeded,
                Some(parser_provenance(&name_locator)),
                SourceLoaderDispositionV1::Preserved,
            )
        } else {
            SourceObservationV1::observed(
                SourceTextV1::new(stack.element.name.as_ref())
                    .expect("source name length checked before cloning"),
                parser_provenance(&name_locator),
                SourceLoaderDispositionV1::Preserved,
            )
        };

        let normalized_clip_index = SourceObservationV1::observed(
            stack_index,
            derived_provenance(&stack_locator),
            SourceLoaderDispositionV1::Baked,
        );
        let source_range = match SourceTimeRangeV1::new(stack.time_begin, stack.time_end) {
            Ok(range) => SourceObservationV1::observed(
                range,
                parser_provenance(&range_locator),
                SourceLoaderDispositionV1::Baked,
            ),
            Err(_) => SourceObservationV1::unavailable(
                SourceUnavailableReasonV1::Malformed,
                Some(parser_provenance(&range_locator)),
                SourceLoaderDispositionV1::Baked,
            ),
        };
        let sampler_range = SourceObservationV1::unavailable(
            SourceUnavailableReasonV1::ParserUnavailable,
            None,
            SourceLoaderDispositionV1::NotApplicable,
        );

        if !builder.push_clip(SourceClipFactV1::new(
            stack_index,
            source_name,
            normalized_clip_index,
            source_range,
            sampler_range,
            channels,
        )) {
            return;
        }
        if channels_truncated {
            return;
        }
    }
    builder.mark_complete(SourceFactDomainV1::Clips);
}

fn project_channels(
    stack: &ufbx::AnimStack,
    channel_budget: usize,
    total_text_budget: usize,
) -> (Vec<SourceChannelFactV1>, bool) {
    let mut channels = Vec::new();
    let mut retained_text_bytes = 0usize;

    for layer in &stack.layers {
        let layer_index = layer.element.typed_id as usize;
        for (property_index, property) in layer.anim_props.as_ref().iter().enumerate() {
            if channels.len() >= channel_budget {
                return (channels, true);
            }
            let channel_index = channels.len();
            let (kind, disposition) = property_kind(property.prop_name.as_ref());
            let property_name_bytes = if kind == SourceChannelPropertyV1::Other {
                property.prop_name.len()
            } else {
                0
            };
            if property_name_bytes > RAW_SOURCE_V1_MAX_TEXT_BYTES {
                return (channels, true);
            }
            // The row and unavailable-interpolation observations each retain
            // their parser locator. Standard TRS properties need no duplicate
            // source spelling because the enum is the complete identity.
            let locator_bytes = "fbx:anim_layers/"
                .len()
                .saturating_add(decimal_len_usize(layer_index))
                .saturating_add("/anim_props/".len())
                .saturating_add(decimal_len_usize(property_index));
            let row_text_bytes = locator_bytes
                .saturating_mul(2)
                .saturating_add(property_name_bytes);
            if retained_text_bytes
                .checked_add(row_text_bytes)
                .is_none_or(|bytes| bytes > total_text_budget)
            {
                return (channels, true);
            }

            let locator = format!("fbx:anim_layers/{layer_index}/anim_props/{property_index}");
            let provenance = parser_provenance(&locator);
            let interpolation = SourceObservationV1::unavailable(
                SourceUnavailableReasonV1::BakedAway,
                Some(provenance.clone()),
                disposition,
            );
            let target = if property.element.type_ == ufbx::ElementType::Node {
                SourceTargetV1::new(
                    SourceTargetKindV1::Node,
                    u64::from(property.element.typed_id),
                )
            } else {
                SourceTargetV1::new(
                    SourceTargetKindV1::Element,
                    u64::from(property.element.element_id),
                )
            };
            let curves = &property.anim_value.curves;
            let mut row = SourceChannelFactV1::new(
                channel_index,
                target,
                kind,
                SourceComponentMaskV1::new(
                    curves[0].is_some(),
                    curves[1].is_some(),
                    curves[2].is_some(),
                ),
                interpolation,
                disposition,
                provenance,
            )
            .with_source_layer_index(layer_index);
            if kind == SourceChannelPropertyV1::Other && !property.prop_name.is_empty() {
                row = row.with_property_name(
                    SourceTextV1::new(property.prop_name.as_ref())
                        .expect("source property length checked before cloning"),
                );
            }
            channels.push(row);
            retained_text_bytes = retained_text_bytes.saturating_add(row_text_bytes);
        }
    }
    (channels, false)
}

fn property_kind(name: &str) -> (SourceChannelPropertyV1, SourceLoaderDispositionV1) {
    match name {
        "Lcl Translation" => (
            SourceChannelPropertyV1::Translation,
            SourceLoaderDispositionV1::Baked,
        ),
        "Lcl Rotation" => (
            SourceChannelPropertyV1::Rotation,
            SourceLoaderDispositionV1::Baked,
        ),
        "Lcl Scaling" => (
            SourceChannelPropertyV1::Scale,
            SourceLoaderDispositionV1::Baked,
        ),
        _ => (
            SourceChannelPropertyV1::Other,
            SourceLoaderDispositionV1::Unsupported,
        ),
    }
}

fn project_constructs(counts: SourceConstructCounts, builder: &mut RawSourceFactsBuilderV1) {
    let mut source_order_index = 0usize;
    for (name, kind, count, disposition, locator) in [
        (
            "fbx:user-defined-properties",
            SourceConstructKindV1::CustomProperty,
            counts.rest_bind.user_defined_property_count,
            SourceLoaderDispositionV1::Unsupported,
            "fbx:scene.elements.props",
        ),
        (
            "fbx:unmodeled-elements",
            SourceConstructKindV1::UnknownElement,
            counts.rest_bind.total_unmodeled_element_count(),
            SourceLoaderDispositionV1::Unsupported,
            "fbx:scene.elements",
        ),
        (
            "fbx:stackless-animation",
            SourceConstructKindV1::UnknownElement,
            counts.stackless_animation_count,
            SourceLoaderDispositionV1::Unsupported,
            "fbx:scene.animation",
        ),
    ] {
        if count == 0 {
            continue;
        }
        let required_text = name.len().saturating_add(locator.len());
        if builder.remaining_observation_rows() == 0
            || required_text > builder.remaining_text_bytes()
        {
            builder.mark_budget_exceeded(SourceFactDomainV1::Constructs);
            return;
        }
        let row = SourceConstructFactV1::new(
            source_order_index,
            kind,
            SourceTextV1::new(name).expect("static construct name is bounded"),
            false,
            u64::try_from(count).unwrap_or(u64::MAX),
            disposition,
            parser_provenance(locator),
        )
        .expect("zero aggregate construct counts are skipped");
        if !builder.push_construct(row) {
            return;
        }
        source_order_index = source_order_index.saturating_add(1);
    }
    builder.mark_complete(SourceFactDomainV1::Constructs);
}

/// Raw parser counts shared by the source-facts projection and derived scale
/// inventory, computed exactly once per load.
#[derive(Debug, Clone, Copy)]
pub(crate) struct SourceConstructCounts {
    pub(crate) rest_bind: RestBindSourceConstructCounts,
    stackless_animation_count: usize,
}

/// Same-parse breakdown of the aggregate unmodeled-construct row used by the
/// narrow rest/bind admission policy.
#[derive(Debug, Clone, Copy)]
pub(crate) struct RestBindSourceConstructCounts {
    pub(crate) user_defined_property_count: usize,
    pub(crate) safe_texture_file_link_count: usize,
    admitted_unmodeled_element_count: usize,
    unsupported_unmodeled_element_counts: [(&'static str, usize); 24],
}

impl RestBindSourceConstructCounts {
    pub(crate) fn total_unmodeled_element_count(self) -> usize {
        self.safe_texture_file_link_count
            .saturating_add(self.admitted_unmodeled_element_count)
            .saturating_add(self.unsupported_unmodeled_element_count())
    }

    pub(crate) fn unsupported_unmodeled_element_count(self) -> usize {
        self.unsupported_unmodeled_element_counts
            .into_iter()
            .fold(0usize, |total, (_, count)| total.saturating_add(count))
    }

    pub(crate) fn unsupported_kind_counts(self) -> impl Iterator<Item = (&'static str, usize)> {
        self.unsupported_unmodeled_element_counts
            .into_iter()
            .filter(|(_, count)| *count > 0)
    }
}

pub(crate) fn construct_counts(scene: &ufbx::Scene) -> SourceConstructCounts {
    let user_defined_property_count = scene
        .elements
        .iter()
        .flat_map(|element| element.props.props.iter())
        .filter(|prop| prop.flags.has_any(ufbx::PropFlags::USER_DEFINED))
        .count();
    let mut rest_bind = rest_bind_unmodeled_element_counts(scene);
    rest_bind.user_defined_property_count = user_defined_property_count;
    let stackless_animation_count = if scene.anim_stacks.is_empty() {
        scene
            .anim_layers
            .len()
            .saturating_add(scene.anim_values.len())
            .saturating_add(scene.anim_curves.len())
    } else {
        0
    };
    SourceConstructCounts {
        rest_bind,
        stackless_animation_count,
    }
}

#[derive(Debug, Clone, Copy, Default)]
struct BindPoseReconciliationCounts {
    admitted: usize,
    non_bind: usize,
    incomplete: usize,
    ambiguous: usize,
    non_finite: usize,
    mismatched: usize,
    allocation_budget_exceeded: usize,
}

const MAX_BIND_POSE_RECONCILIATION_NODES: usize = 65_536;
const MAX_BIND_POSE_RECONCILIATION_CLUSTERS: usize = 65_536;

#[derive(Debug, Clone, Copy)]
enum BindPoseReconciliation {
    Admitted,
    NonBind,
    Incomplete,
    Ambiguous,
    NonFinite,
    Mismatched,
}

/// Reconcile ufbx's converted BindPose matrices with the converted matrices
/// that feed the normalized rest/bind bridge.
///
/// ufbx uses a BindPose row to fill `SkinCluster::bind_to_world` only when the
/// cluster did not carry its own matrix. Otherwise both values remain
/// independently observable after the same axis/unit conversion. Cluster
/// bones therefore compare against that exact bind input; other PoseNodes
/// compare against the normalized node rest-world input. Other pose kinds
/// remain outside this narrow admission contract.
fn reconcile_bind_poses(scene: &ufbx::Scene) -> BindPoseReconciliationCounts {
    let bind_pose_count = scene.poses.iter().filter(|pose| pose.is_bind_pose).count();
    let non_bind_pose_count = scene.poses.len().saturating_sub(bind_pose_count);
    if bind_pose_count == 0 {
        return BindPoseReconciliationCounts {
            non_bind: non_bind_pose_count,
            ..BindPoseReconciliationCounts::default()
        };
    }
    if !bind_pose_reconciliation_allocation_within_budget(
        scene.nodes.len(),
        scene.skin_clusters.len(),
    ) {
        return BindPoseReconciliationCounts {
            non_bind: non_bind_pose_count,
            allocation_budget_exceeded: bind_pose_count,
            ..BindPoseReconciliationCounts::default()
        };
    }

    let mut bind_pose_coverage = vec![0u8; scene.nodes.len()];
    for pose in &scene.poses {
        if !pose.is_bind_pose {
            continue;
        }
        for bone_pose in &pose.bone_poses {
            let Ok(node_index) = usize::try_from(bone_pose.bone_node.element.typed_id) else {
                continue;
            };
            if let Some(coverage) = bind_pose_coverage.get_mut(node_index) {
                *coverage = coverage.saturating_add(1);
            }
        }
    }

    let mut clusters_by_node = vec![Vec::new(); scene.nodes.len()];
    for (cluster_index, cluster) in scene.skin_clusters.iter().enumerate() {
        let Some(bone_node) = &cluster.bone_node else {
            continue;
        };
        let Ok(node_index) = usize::try_from(bone_node.element.typed_id) else {
            continue;
        };
        if let Some(indices) = clusters_by_node.get_mut(node_index) {
            indices.push(cluster_index);
        }
    }

    let mut counts = BindPoseReconciliationCounts::default();
    for pose in &scene.poses {
        let outcome = reconcile_bind_pose(scene, pose, &bind_pose_coverage, &clusters_by_node);
        match outcome {
            BindPoseReconciliation::Admitted => counts.admitted = counts.admitted.saturating_add(1),
            BindPoseReconciliation::NonBind => counts.non_bind = counts.non_bind.saturating_add(1),
            BindPoseReconciliation::Incomplete => {
                counts.incomplete = counts.incomplete.saturating_add(1)
            }
            BindPoseReconciliation::Ambiguous => {
                counts.ambiguous = counts.ambiguous.saturating_add(1)
            }
            BindPoseReconciliation::NonFinite => {
                counts.non_finite = counts.non_finite.saturating_add(1)
            }
            BindPoseReconciliation::Mismatched => {
                counts.mismatched = counts.mismatched.saturating_add(1)
            }
        }
    }
    counts
}

fn bind_pose_reconciliation_allocation_within_budget(
    node_count: usize,
    cluster_count: usize,
) -> bool {
    node_count <= MAX_BIND_POSE_RECONCILIATION_NODES
        && cluster_count <= MAX_BIND_POSE_RECONCILIATION_CLUSTERS
}

fn reconcile_bind_pose(
    scene: &ufbx::Scene,
    pose: &ufbx::Pose,
    bind_pose_coverage: &[u8],
    clusters_by_node: &[Vec<usize>],
) -> BindPoseReconciliation {
    if !pose.is_bind_pose {
        return BindPoseReconciliation::NonBind;
    }
    if pose.bone_poses.is_empty() {
        return BindPoseReconciliation::Incomplete;
    }

    for skin in &scene.skin_deformers {
        if skin.clusters.is_empty() {
            continue;
        }
        let covered = skin
            .clusters
            .iter()
            .filter(|cluster| {
                cluster
                    .bone_node
                    .as_ref()
                    .and_then(|node| ufbx::get_bone_pose(pose, node))
                    .is_some()
            })
            .count();
        if covered > 0 && covered != skin.clusters.len() {
            return BindPoseReconciliation::Incomplete;
        }
    }

    let mut previous_node = None;
    for bone_pose in &pose.bone_poses {
        let Ok(node_index) = usize::try_from(bone_pose.bone_node.element.typed_id) else {
            return BindPoseReconciliation::Ambiguous;
        };
        if previous_node == Some(node_index)
            || bind_pose_coverage.get(node_index).copied() != Some(1)
        {
            return BindPoseReconciliation::Ambiguous;
        }
        previous_node = Some(node_index);

        if !matrix_is_finite(&bone_pose.bone_to_world) {
            return BindPoseReconciliation::NonFinite;
        }
        let Some(node) = scene.nodes.get(node_index) else {
            return BindPoseReconciliation::Ambiguous;
        };
        let Some(cluster_indices) = clusters_by_node.get(node_index) else {
            return BindPoseReconciliation::Ambiguous;
        };
        if cluster_indices.is_empty() {
            let outcome = compare_bind_pose_matrix(&bone_pose.bone_to_world, &node.node_to_world);
            if !matches!(outcome, BindPoseReconciliation::Admitted) {
                return outcome;
            }
            continue;
        }
        for cluster_index in cluster_indices {
            let Some(cluster) = scene.skin_clusters.get(*cluster_index) else {
                return BindPoseReconciliation::Ambiguous;
            };
            let outcome =
                compare_bind_pose_matrix(&bone_pose.bone_to_world, &cluster.bind_to_world);
            if !matches!(outcome, BindPoseReconciliation::Admitted) {
                return outcome;
            }
        }
    }
    BindPoseReconciliation::Admitted
}

fn compare_bind_pose_matrix(
    actual: &ufbx::Matrix,
    expected: &ufbx::Matrix,
) -> BindPoseReconciliation {
    if !matrix_is_finite(expected) {
        BindPoseReconciliation::NonFinite
    } else if !matrices_approximately_equal(actual, expected) {
        BindPoseReconciliation::Mismatched
    } else {
        BindPoseReconciliation::Admitted
    }
}

fn matrix_is_finite(matrix: &ufbx::Matrix) -> bool {
    matrix_components(matrix).into_iter().all(f64::is_finite)
}

fn matrices_approximately_equal(left: &ufbx::Matrix, right: &ufbx::Matrix) -> bool {
    matrix_components(left)
        .into_iter()
        .zip(matrix_components(right))
        .all(|(left, right)| {
            left.is_finite()
                && right.is_finite()
                && scalar_difference_within_tolerance(
                    (left - right).abs(),
                    left.abs().max(right.abs()),
                )
        })
}

fn scalar_difference_within_tolerance(difference: f64, magnitude: f64) -> bool {
    let policy = animsmith_core::scale::ScaleTolerancePolicy::APPENDIX_D_V6;
    difference <= policy.scalar_absolute + policy.scalar_relative * magnitude
}

fn matrix_components(matrix: &ufbx::Matrix) -> [f64; 12] {
    [
        matrix.m00, matrix.m10, matrix.m20, matrix.m01, matrix.m11, matrix.m21, matrix.m02,
        matrix.m12, matrix.m22, matrix.m03, matrix.m13, matrix.m23,
    ]
}

/// Classify every field in `ufbx::Scene` at one exhaustive structural
/// boundary. Omitting `..` is deliberate: a ufbx upgrade that adds a typed
/// list must fail to compile until that list receives a classification.
fn rest_bind_unmodeled_element_counts(scene: &ufbx::Scene) -> RestBindSourceConstructCounts {
    let bind_poses = reconcile_bind_poses(scene);
    let ufbx::Scene {
        metadata: _,
        settings: _,
        root_node: _,
        anim: _,
        // Unknown and source kinds without a normalized core representation.
        unknowns,
        nodes: _,
        meshes: _,
        // Cameras and lights have dedicated counts/core facts.
        lights: _,
        cameras: _,
        // Bone/empty attributes normalize into the complete node projection.
        bones: _,
        empties: _,
        line_curves,
        nurbs_curves,
        nurbs_surfaces,
        nurbs_trim_surfaces,
        nurbs_trim_boundaries,
        procedural_geometries,
        stereo_cameras,
        camera_switchers,
        markers,
        lod_groups,
        // Skin rows have dedicated bind/influence counts and sidecars.
        skin_deformers: _,
        skin_clusters: _,
        // Deformers are counted separately; their subordinate payload rows
        // are still unmodeled source elements.
        blend_deformers: _,
        blend_channels,
        blend_shapes,
        cache_deformers: _,
        cache_files,
        // The loader rebuilds its documented material/texture subset;
        // external payload absence is counted separately. Shader records are
        // material-evaluation metadata and do not feed the rest/bind bridge.
        materials: _,
        textures: _,
        videos: _,
        shaders,
        shader_bindings,
        // Animation lists are evaluated through bake_anim. Pose records are
        // admitted only after same-parse matrix reconciliation above.
        anim_stacks: _,
        anim_layers: _,
        anim_values: _,
        anim_curves: _,
        display_layers,
        selection_sets,
        selection_nodes,
        characters,
        constraints,
        audio_layers,
        audio_clips,
        poses: _,
        metadata_objects,
        // ufbx derives this deduplicated file view from `textures`; keep its
        // count as same-parse admission evidence rather than projecting a
        // second set of resource rows for the same logical declarations.
        texture_files,
        // Scene-wide structural indexes are parser-derived views, not source
        // element domains that need independent semantic counting.
        elements: _,
        connections_src: _,
        connections_dst: _,
        elements_by_name: _,
        dom_root: _,
    } = scene;

    RestBindSourceConstructCounts {
        user_defined_property_count: 0,
        safe_texture_file_link_count: texture_files.len(),
        // These typed node-attribute lists do not carry hierarchy transforms,
        // skin binds, animation tracks, or geometry into the normalized GLB
        // rest/bind bridge. Their source elements remain counted in the raw
        // aggregate, while same-load admission discharges only these exact
        // classes.
        admitted_unmodeled_element_count: stereo_cameras
            .len()
            .saturating_add(camera_switchers.len())
            .saturating_add(markers.len())
            .saturating_add(lod_groups.len())
            .saturating_add(shaders.len())
            .saturating_add(shader_bindings.len())
            .saturating_add(bind_poses.admitted),
        // Keep the diagnostic label and parser count together. Because every
        // destructured residual list is consumed here, compiler warnings also
        // fail a future edit that binds a ufbx list without classifying it.
        unsupported_unmodeled_element_counts: [
            ("unknowns", unknowns.len()),
            ("line_curves", line_curves.len()),
            ("nurbs_curves", nurbs_curves.len()),
            ("nurbs_surfaces", nurbs_surfaces.len()),
            ("nurbs_trim_surfaces", nurbs_trim_surfaces.len()),
            ("nurbs_trim_boundaries", nurbs_trim_boundaries.len()),
            ("procedural_geometries", procedural_geometries.len()),
            ("blend_channels", blend_channels.len()),
            ("blend_shapes", blend_shapes.len()),
            ("cache_files", cache_files.len()),
            ("display_layers", display_layers.len()),
            ("selection_sets", selection_sets.len()),
            ("selection_nodes", selection_nodes.len()),
            ("characters", characters.len()),
            ("constraints", constraints.len()),
            ("audio_layers", audio_layers.len()),
            ("audio_clips", audio_clips.len()),
            ("non_bind_poses", bind_poses.non_bind),
            ("incomplete_bind_poses", bind_poses.incomplete),
            ("ambiguous_bind_poses", bind_poses.ambiguous),
            ("non_finite_bind_poses", bind_poses.non_finite),
            ("mismatched_bind_poses", bind_poses.mismatched),
            (
                "bind_pose_reconciliation_budget_exceeded",
                bind_poses.allocation_budget_exceeded,
            ),
            ("metadata_objects", metadata_objects.len()),
        ],
    }
}

fn project_resources(scene: &ufbx::Scene, builder: &mut RawSourceFactsBuilderV1) {
    for resource in resource_declarations(scene) {
        if builder.remaining_resource_rows() == 0 || builder.remaining_observation_rows() == 0 {
            builder.mark_budget_exceeded(SourceFactDomainV1::Resources);
            return;
        }
        let (value, field, redacted_locator) = resource.source_locator();
        // Reserve exactly what classification retains before the only possible
        // source-string clone. Unsafe, absolute, remote, data, malformed, and
        // oversized spellings are redacted and therefore reserve zero bytes.
        let retained_locator_bytes =
            value.map_or(0, SourceResourceLocatorV1::retained_relative_bytes);
        let provenance_locator_bytes = "fbx:"
            .len()
            .saturating_add(resource.type_name.len())
            .saturating_add(1)
            .saturating_add(decimal_len_u64(resource.source_index()))
            .saturating_add(1)
            .saturating_add(field.len());
        if provenance_locator_bytes.saturating_add(retained_locator_bytes)
            > builder.remaining_text_bytes()
        {
            builder.mark_budget_exceeded(SourceFactDomainV1::Resources);
            return;
        }
        let provenance_locator = format!(
            "fbx:{}/{}/{field}",
            resource.type_name,
            resource.source_index()
        );
        let locator = redacted_locator.unwrap_or_else(|| {
            value.map_or(SourceResourceLocatorV1::Missing, |value| {
                SourceResourceLocatorV1::classify(value)
            })
        });
        let row = SourceResourceReferenceV1::new(
            resource.source_order_index(),
            resource.kind(),
            resource.source_index(),
            locator,
            resource.disposition,
            parser_provenance(&provenance_locator),
        );
        if !builder.push_resource(row) {
            return;
        }
    }
    builder.mark_complete(SourceFactDomainV1::Resources);
}

#[derive(Clone, Copy)]
enum FbxResourceList {
    Texture,
    Video,
    Cache,
}

impl FbxResourceList {
    const fn tie_breaker(self) -> u8 {
        match self {
            Self::Texture => 0,
            Self::Video => 1,
            Self::Cache => 2,
        }
    }
}

fn next_resource_list(
    scene: &ufbx::Scene,
    texture_index: usize,
    video_index: usize,
    cache_index: usize,
) -> Option<FbxResourceList> {
    [
        scene
            .textures
            .get(texture_index)
            .map(|texture| (texture.element.element_id, FbxResourceList::Texture)),
        scene
            .videos
            .get(video_index)
            .map(|video| (video.element.element_id, FbxResourceList::Video)),
        scene
            .cache_files
            .get(cache_index)
            .map(|cache| (cache.element.element_id, FbxResourceList::Cache)),
    ]
    .into_iter()
    .flatten()
    .min_by_key(|(element_id, list)| (*element_id, list.tie_breaker()))
    .map(|(_, list)| list)
}

/// One deterministic typed FBX resource declaration.
///
/// The iterator below is the sole authority for raw resource rows and the
/// dependency-closure capture pass. It retains only a boolean presence marker
/// for the parser-resolved absolute path so an external declaration is never
/// misreported as absent. That path is never retained, exposed, normalized,
/// or opened; only embedded content and source-relative declarations are
/// eligible for capture.
pub(crate) struct ResourceDeclaration<'a> {
    source_order_index: usize,
    kind: SourceResourceKindV1,
    source_index: u64,
    embedded: bool,
    relative_filename: &'a str,
    filename: &'a str,
    absolute_filename_present: bool,
    disposition: SourceLoaderDispositionV1,
    type_name: &'static str,
}

impl ResourceDeclaration<'_> {
    /// Stable source-order index shared by raw facts and closure rows.
    pub(crate) const fn source_order_index(&self) -> usize {
        self.source_order_index
    }

    /// Typed source declaration kind.
    pub(crate) const fn kind(&self) -> SourceResourceKindV1 {
        self.kind
    }

    /// Parser-stable source declaration index.
    pub(crate) const fn source_index(&self) -> u64 {
        self.source_index
    }

    /// Whether content is carried by the exact primary FBX bytes.
    pub(crate) const fn is_embedded(&self) -> bool {
        self.embedded
    }

    fn source_locator(&self) -> (Option<&str>, &'static str, Option<SourceResourceLocatorV1>) {
        if self.is_embedded() {
            (None, "content", Some(SourceResourceLocatorV1::Embedded))
        } else if !self.relative_filename.is_empty() {
            (Some(self.relative_filename), "relative_filename", None)
        } else if !self.filename.is_empty() {
            // ufbx may surface a resolved absolute spelling here. It is only
            // classified/redacted by core and can never become a capture key.
            (Some(self.filename), "filename", None)
        } else if self.absolute_filename_present {
            // Preserve positive declaration evidence without retaining or
            // resolving the parser's host-specific absolute spelling.
            (
                None,
                "absolute_filename",
                Some(SourceResourceLocatorV1::Absolute),
            )
        } else {
            (None, "filename", Some(SourceResourceLocatorV1::Missing))
        }
    }
}

/// Bounded, allocation-free traversal of the typed FBX resource lists.
pub(crate) struct ResourceDeclarations<'a> {
    scene: &'a ufbx::Scene,
    source_order_index: usize,
    texture_index: usize,
    video_index: usize,
    cache_index: usize,
}

/// Iterate texture, video, and cache declarations in stable scene-wide order.
pub(crate) fn resource_declarations(scene: &ufbx::Scene) -> ResourceDeclarations<'_> {
    ResourceDeclarations {
        scene,
        source_order_index: 0,
        texture_index: 0,
        video_index: 0,
        cache_index: 0,
    }
}

impl<'a> Iterator for ResourceDeclarations<'a> {
    type Item = ResourceDeclaration<'a>;

    fn next(&mut self) -> Option<Self::Item> {
        let list = next_resource_list(
            self.scene,
            self.texture_index,
            self.video_index,
            self.cache_index,
        )?;
        let source_order_index = self.source_order_index;
        self.source_order_index = self.source_order_index.saturating_add(1);
        Some(match list {
            FbxResourceList::Texture => {
                let texture = &self.scene.textures[self.texture_index];
                self.texture_index = self.texture_index.saturating_add(1);
                ResourceDeclaration {
                    source_order_index,
                    kind: SourceResourceKindV1::Texture,
                    source_index: u64::from(texture.element.typed_id),
                    embedded: !texture.content.is_empty(),
                    relative_filename: texture.relative_filename.as_ref(),
                    filename: texture.filename.as_ref(),
                    absolute_filename_present: !texture.absolute_filename.is_empty(),
                    disposition: SourceLoaderDispositionV1::Unknown,
                    type_name: "textures",
                }
            }
            FbxResourceList::Video => {
                let video = &self.scene.videos[self.video_index];
                self.video_index = self.video_index.saturating_add(1);
                ResourceDeclaration {
                    source_order_index,
                    kind: SourceResourceKindV1::Video,
                    source_index: u64::from(video.element.typed_id),
                    embedded: !video.content.is_empty(),
                    relative_filename: video.relative_filename.as_ref(),
                    filename: video.filename.as_ref(),
                    absolute_filename_present: !video.absolute_filename.is_empty(),
                    disposition: SourceLoaderDispositionV1::Discarded,
                    type_name: "videos",
                }
            }
            FbxResourceList::Cache => {
                let cache = &self.scene.cache_files[self.cache_index];
                self.cache_index = self.cache_index.saturating_add(1);
                ResourceDeclaration {
                    source_order_index,
                    kind: SourceResourceKindV1::Cache,
                    source_index: u64::from(cache.element.typed_id),
                    embedded: false,
                    relative_filename: cache.relative_filename.as_ref(),
                    filename: cache.filename.as_ref(),
                    absolute_filename_present: !cache.absolute_filename.is_empty(),
                    disposition: SourceLoaderDispositionV1::Unsupported,
                    type_name: "cache_files",
                }
            }
        })
    }
}

fn parser_provenance(locator: &str) -> SourceProvenanceV1 {
    SourceProvenanceV1::parser_projected(
        SourceLogicalLocatorV1::fbx_parser_path(locator)
            .expect("generated FBX logical locator is bounded and structural"),
    )
}

fn derived_provenance(locator: &str) -> SourceProvenanceV1 {
    SourceProvenanceV1::derived_from_source(
        SourceLogicalLocatorV1::fbx_parser_path(locator)
            .expect("generated FBX logical locator is bounded and structural"),
    )
}

fn decimal_len_usize(mut value: usize) -> usize {
    let mut digits = 1usize;
    while value >= 10 {
        value /= 10;
        digits += 1;
    }
    digits
}

fn decimal_len_u64(mut value: u64) -> usize {
    let mut digits = 1usize;
    while value >= 10 {
        value /= 10;
        digits += 1;
    }
    digits
}

#[cfg(test)]
mod tests {
    use super::*;

    fn matrix_with_component(index: usize, value: f64) -> ufbx::Matrix {
        let mut matrix = ufbx::Matrix::default();
        match index {
            0 => matrix.m00 = value,
            1 => matrix.m10 = value,
            2 => matrix.m20 = value,
            3 => matrix.m01 = value,
            4 => matrix.m11 = value,
            5 => matrix.m21 = value,
            6 => matrix.m02 = value,
            7 => matrix.m12 = value,
            8 => matrix.m22 = value,
            9 => matrix.m03 = value,
            10 => matrix.m13 = value,
            11 => matrix.m23 = value,
            _ => panic!("matrix component index out of range"),
        }
        matrix
    }

    #[test]
    fn matrix_reconciliation_checks_all_twelve_affine_components() {
        for index in 0..12 {
            assert!(matrices_approximately_equal(
                &matrix_with_component(index, 5.0e-7),
                &ufbx::Matrix::default(),
            ));
            assert!(!matrices_approximately_equal(
                &matrix_with_component(index, 2.0e-6),
                &ufbx::Matrix::default(),
            ));
        }
    }

    #[test]
    fn scalar_reconciliation_includes_the_exact_absolute_and_relative_boundary() {
        let policy = animsmith_core::scale::ScaleTolerancePolicy::APPENDIX_D_V6;
        for magnitude in [0.0, 100.0] {
            let boundary = policy.scalar_absolute + policy.scalar_relative * magnitude;
            assert!(scalar_difference_within_tolerance(boundary, magnitude));
            assert!(!scalar_difference_within_tolerance(
                f64::from_bits(boundary.to_bits() + 1),
                magnitude,
            ));
        }
    }

    #[test]
    fn bind_pose_reconciliation_allocation_budget_has_a_fixed_boundary() {
        assert!(bind_pose_reconciliation_allocation_within_budget(
            MAX_BIND_POSE_RECONCILIATION_NODES,
            MAX_BIND_POSE_RECONCILIATION_CLUSTERS,
        ));
        assert!(!bind_pose_reconciliation_allocation_within_budget(
            MAX_BIND_POSE_RECONCILIATION_NODES + 1,
            0,
        ));
        assert!(!bind_pose_reconciliation_allocation_within_budget(
            0,
            MAX_BIND_POSE_RECONCILIATION_CLUSTERS + 1,
        ));
    }
}