animsmith-core 0.4.1

Engine-agnostic data model, sampling, measurements, and checks for the animsmith animation-clip linter
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
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
//! Mutation-style check tests, after the incubating pipeline's
//! discipline: start from a clean document (zero findings), corrupt
//! exactly one thing, and assert exactly the expected check fires.

use animsmith_core::config::{CheckSettings, ClipExpectations, Pinned};
use animsmith_core::model::*;
use animsmith_core::profile::ResolvedRoles;
use animsmith_core::{
    CheckCtx, CheckSelection, Config, MetricGrids, Severity, SeveritySetting, evaluate_checks,
    mechanical_checks,
};
use glam::{Quat, Vec3};

/// A clean 2-bone document with a rotation and a translation track.
fn clean_doc() -> Document {
    let skeleton = Skeleton {
        bones: vec![
            Bone {
                name: "hips".into(),
                parent: None,
                rest: Transform::IDENTITY,
                inverse_bind: None,
            },
            Bone {
                name: "spine".into(),
                parent: Some(0),
                rest: Transform {
                    translation: Vec3::new(0.0, 0.3, 0.0),
                    ..Transform::IDENTITY
                },
                inverse_bind: None,
            },
        ],
    };
    let rotation = Track {
        bone: 1,
        property: Property::Rotation,
        interpolation: Interpolation::Linear,
        times: vec![0.0, 0.5, 1.0],
        values: TrackValues::Quats(vec![
            Quat::IDENTITY,
            Quat::from_rotation_y(0.8),
            Quat::from_rotation_y(1.6),
        ]),
    };
    let translation = Track {
        bone: 0,
        property: Property::Translation,
        interpolation: Interpolation::Linear,
        times: vec![0.0, 0.5, 1.0],
        values: TrackValues::Vec3s(vec![
            Vec3::ZERO,
            Vec3::new(0.0, 0.05, 0.5),
            Vec3::new(0.0, 0.0, 1.0),
        ]),
    };
    Document {
        skeleton,
        clips: vec![Clip {
            name: "walk".into(),
            duration_s: 1.0,
            tracks: vec![rotation, translation],
        }],
        assets: Default::default(),
        source: SourceInfo::default(),
    }
}

fn lint(doc: &Document) -> Vec<animsmith_core::Finding> {
    lint_with_config(doc, &Config::default())
}

fn lint_with_config(doc: &Document, config: &Config) -> Vec<animsmith_core::Finding> {
    evaluations_with_config(doc, config)
        .into_iter()
        .flat_map(|check| check.findings().to_vec())
        .collect()
}

fn evaluations_with_config(
    doc: &Document,
    config: &Config,
) -> Vec<animsmith_core::CheckEvaluation> {
    let roles = ResolvedRoles::default();
    let grids = MetricGrids::new(doc);
    let ctx = CheckCtx::new(&grids, &roles, config);
    evaluate_checks(&ctx, &mechanical_checks(), CheckSelection::All)
        .expect("valid built-in catalog")
}

fn assert_single(doc: &Document, check_id: &str, severity: Severity) {
    let findings = lint(doc);
    assert_eq!(
        findings.len(),
        1,
        "expected exactly one finding, got: {findings:#?}"
    );
    assert_eq!(findings[0].check_id, check_id);
    assert_eq!(findings[0].severity, severity);
}

#[test]
fn clean_document_has_no_findings() {
    let findings = lint(&clean_doc());
    assert!(findings.is_empty(), "clean doc flagged: {findings:#?}");
}

#[test]
fn nan_value_is_flagged() {
    let mut doc = clean_doc();
    if let TrackValues::Vec3s(v) = &mut doc.clips[0].tracks[1].values {
        v[1].y = f32::NAN;
    }
    assert_single(&doc, "nan", Severity::Error);
}

#[test]
fn nan_time_is_flagged() {
    let mut doc = clean_doc();
    doc.clips[0].tracks[1].times[1] = f32::INFINITY;
    // The corrupted time also breaks monotonicity; the nan finding must
    // be among the results and attributed to the right bone.
    let findings = lint(&doc);
    let nan = findings
        .iter()
        .find(|f| f.check_id == "nan")
        .expect("nan finding");
    assert_eq!(nan.bone.as_deref(), Some("hips"));
}

#[test]
fn non_monotonic_times_are_flagged() {
    let mut doc = clean_doc();
    // Corrupt ordering mid-track, keeping start (0.0) and end (1.0)
    // intact so no other check fires.
    doc.clips[0].tracks[0].times = vec![0.0, 0.6, 0.4, 1.0];
    if let TrackValues::Quats(v) = &mut doc.clips[0].tracks[0].values {
        v.push(Quat::from_rotation_y(2.0));
    }
    assert_single(&doc, "time-monotonic", Severity::Error);
}

#[test]
fn negative_time_beyond_tolerance_is_flagged() {
    let mut doc = clean_doc();
    doc.clips[0].tracks[0].times = vec![-0.01, 0.5, 1.0];
    assert_single(&doc, "time-monotonic", Severity::Error);
}

#[test]
fn f32_quantization_dust_at_zero_is_tolerated() {
    // Bake pipelines that slice frame ranges leave first keys like
    // -1e-6 s; engines clamp these harmlessly.
    let mut doc = clean_doc();
    doc.clips[0].tracks[0].times = vec![-1e-6, 0.5, 1.0];
    let findings = lint(&doc);
    assert!(findings.is_empty(), "dust flagged: {findings:#?}");
}

#[test]
fn late_first_key_is_noted() {
    let mut doc = clean_doc();
    doc.clips[0].tracks[0].times = vec![0.4, 0.7, 1.0];
    let findings = lint(&doc);
    assert!(
        findings
            .iter()
            .any(|f| f.check_id == "time-monotonic" && f.severity == Severity::Note),
        "got: {findings:#?}"
    );
}

#[test]
fn denormalized_quat_is_flagged() {
    let mut doc = clean_doc();
    if let TrackValues::Quats(v) = &mut doc.clips[0].tracks[0].values {
        v[1] = Quat::from_xyzw(0.0, 0.65, 0.0, 0.65); // |q| ≈ 0.92
    }
    let findings = lint(&doc);
    let f = findings
        .iter()
        .find(|f| f.check_id == "quat-norm")
        .expect("quat-norm finding");
    assert_eq!(f.severity, Severity::Error);
    assert_eq!(f.bone.as_deref(), Some("spine"));
}

#[test]
fn hemisphere_flip_is_flagged() {
    let mut doc = clean_doc();
    if let TrackValues::Quats(v) = &mut doc.clips[0].tracks[0].values {
        v[1] = -v[1]; // same rotation, opposite hemisphere
    }
    assert_single(&doc, "quat-flip", Severity::Warning);
}

#[test]
fn zero_duration_is_flagged() {
    let mut doc = clean_doc();
    doc.clips[0].duration_s = 0.0;
    // Track end times no longer matter for a degenerate clip.
    let findings = lint(&doc);
    assert!(
        findings
            .iter()
            .any(|f| f.check_id == "duration-sanity" && f.severity == Severity::Error),
        "got: {findings:#?}"
    );
}

#[test]
fn degenerate_duration_with_a_pin_reports_measured_and_expected_seconds() {
    let mut doc = clean_doc();
    doc.clips[0].duration_s = 0.0;
    let findings = lint_with_config(&doc, &duration_pin(1.0, 0.02));
    let finding = findings
        .iter()
        .find(|finding| finding.check_id == "duration-sanity")
        .expect("degenerate duration finding");
    let value = serde_json::to_value(finding).expect("serializes finding");
    assert_eq!(finding.severity, Severity::Error);
    assert_eq!(value["measured"], 0.0);
    assert_eq!(value["expected"], 1.0);
}

fn duration_pin(value: f64, tolerance: f64) -> Config {
    let mut config = Config::default();
    config.clips.insert(
        "walk".into(),
        ClipExpectations {
            duration_s: Some(Pinned { value, tolerance }),
            ..Default::default()
        },
    );
    config
}

#[test]
fn duration_pin_tolerance_is_inclusive_in_both_directions() {
    let config = duration_pin(1.0, 0.25);
    for duration_s in [0.75, 1.25] {
        let mut doc = clean_doc();
        doc.clips[0].duration_s = duration_s;
        let findings = lint_with_config(&doc, &config);
        assert!(
            !findings
                .iter()
                .any(|finding| finding.check_id == "duration-sanity"),
            "boundary duration {duration_s} was rejected: {findings:#?}"
        );
    }

    for duration_s in [
        f64::from_bits(0.75f64.to_bits() - 1),
        f64::from_bits(1.25f64.to_bits() + 1),
    ] {
        let mut doc = clean_doc();
        doc.clips[0].duration_s = duration_s;
        let findings = lint_with_config(&doc, &config);
        let duration_findings: Vec<_> = findings
            .iter()
            .filter(|finding| finding.check_id == "duration-sanity")
            .collect();
        assert_eq!(
            duration_findings.len(),
            1,
            "next representable duration outside the boundary must fail: {findings:#?}"
        );
        assert_eq!(duration_findings[0].severity, Severity::Error);
        let value = serde_json::to_value(duration_findings[0]).expect("serializes finding");
        assert_eq!(value["measured"], duration_s);
        assert_eq!(value["expected"], 1.0);
    }
}

#[test]
fn invalid_duration_pins_are_explicit_errors() {
    for pin in [
        Pinned {
            value: f64::NAN,
            tolerance: 0.02,
        },
        Pinned {
            value: 0.0,
            tolerance: 0.02,
        },
        Pinned {
            value: 1.0,
            tolerance: f64::NAN,
        },
        Pinned {
            value: 1.0,
            tolerance: -0.02,
        },
    ] {
        let mut config = Config::default();
        config.clips.insert(
            "walk".into(),
            ClipExpectations {
                duration_s: Some(pin),
                ..Default::default()
            },
        );
        let findings = lint_with_config(&clean_doc(), &config);
        let finding = findings
            .iter()
            .find(|finding| finding.check_id == "duration-sanity")
            .expect("invalid duration pin finding");
        assert_eq!(finding.severity, Severity::Error);
        assert!(finding.message.contains("invalid declared duration pin"));
    }
}

#[test]
fn duration_pin_miss_reports_structured_measured_and_expected_seconds() {
    let doc = clean_doc();
    let findings = lint_with_config(&doc, &duration_pin(1.033, 0.02));
    let finding = findings
        .iter()
        .find(|finding| finding.check_id == "duration-sanity")
        .expect("duration pin finding");
    let value = serde_json::to_value(finding).expect("serializes finding");
    assert_eq!(finding.severity, Severity::Error);
    assert_eq!(value["clip"], "walk");
    assert_eq!(value["measured"], 1.0);
    assert_eq!(value["expected"], 1.033);
}

#[test]
fn duration_pin_is_still_judged_for_an_empty_clip() {
    let mut doc = clean_doc();
    doc.clips[0].tracks.clear();
    let findings = lint_with_config(&doc, &duration_pin(1.033, 0.02));
    let duration_findings: Vec<_> = findings
        .iter()
        .filter(|finding| finding.check_id == "duration-sanity")
        .collect();
    assert_eq!(
        duration_findings.len(),
        2,
        "empty-track and duration-contract failures should both remain visible: {findings:#?}"
    );
    assert!(duration_findings.iter().any(|finding| {
        finding.severity == Severity::Warning && finding.message == "clip has no tracks"
    }));
    let pin_miss = duration_findings
        .iter()
        .find(|finding| finding.severity == Severity::Error)
        .expect("duration pin error");
    let value = serde_json::to_value(pin_miss).expect("serializes finding");
    assert_eq!(value["measured"], 1.0);
    assert_eq!(value["expected"], 1.033);
}

#[test]
fn empty_zero_duration_without_a_pin_remains_warning_only() {
    let mut doc = clean_doc();
    doc.clips[0].tracks.clear();
    doc.clips[0].duration_s = 0.0;
    let findings = lint(&doc);
    assert_eq!(findings.len(), 1, "got: {findings:#?}");
    assert_eq!(findings[0].check_id, "duration-sanity");
    assert_eq!(findings[0].severity, Severity::Warning);
    assert_eq!(findings[0].message, "clip has no tracks");
}

#[test]
fn mismatched_channel_ends_are_flagged() {
    let mut doc = clean_doc();
    doc.clips[0].tracks[1].times = vec![0.0, 0.3, 0.6]; // rotation still ends at 1.0
    assert_single(&doc, "duration-sanity", Severity::Warning);
}

#[test]
fn single_key_pin_does_not_count_toward_end_spread() {
    // A one-key track at t=0 is a pinned value (a common bake idiom),
    // not a truncated channel.
    let mut doc = clean_doc();
    doc.clips[0].tracks.push(Track {
        bone: 1,
        property: Property::Translation,
        interpolation: Interpolation::Linear,
        times: vec![0.0],
        values: TrackValues::Vec3s(vec![Vec3::new(0.0, 0.3, 0.0)]),
    });
    let findings = lint(&doc);
    assert!(findings.is_empty(), "pin flagged: {findings:#?}");
}

#[test]
fn empty_clip_is_flagged() {
    let mut doc = clean_doc();
    doc.clips[0].tracks.clear();
    assert_single(&doc, "duration-sanity", Severity::Warning);
}

#[test]
fn scale_keys_are_flagged() {
    let mut doc = clean_doc();
    doc.clips[0].tracks.push(Track {
        bone: 1,
        property: Property::Scale,
        interpolation: Interpolation::Linear,
        times: vec![0.0, 1.0],
        values: TrackValues::Vec3s(vec![Vec3::ONE, Vec3::splat(1.2)]),
    });
    assert_single(&doc, "scale-keys", Severity::Warning);
}

#[test]
fn non_uniform_scale_gets_second_finding() {
    let mut doc = clean_doc();
    doc.clips[0].tracks.push(Track {
        bone: 1,
        property: Property::Scale,
        interpolation: Interpolation::Linear,
        times: vec![0.0, 1.0],
        values: TrackValues::Vec3s(vec![Vec3::ONE, Vec3::new(1.2, 1.0, 1.0)]),
    });
    let findings = lint(&doc);
    assert_eq!(
        findings
            .iter()
            .filter(|f| f.check_id == "scale-keys")
            .count(),
        1,
        "got: {findings:#?}"
    );
    assert_eq!(
        findings
            .iter()
            .filter(|f| f.check_id == "non-uniform-scale")
            .count(),
        1,
        "got: {findings:#?}"
    );
    assert!(findings.iter().any(|finding| {
        finding.check_id == "non-uniform-scale" && finding.severity == Severity::Warning
    }));
}

#[test]
fn all_ones_scale_track_is_constant_not_scaling() {
    let mut doc = clean_doc();
    doc.clips[0].tracks.push(Track {
        bone: 1,
        property: Property::Scale,
        interpolation: Interpolation::Linear,
        times: vec![0.0, 1.0],
        values: TrackValues::Vec3s(vec![Vec3::ONE, Vec3::ONE]),
    });
    assert_single(&doc, "constant-track", Severity::Note);
}

fn add_scale_track(
    doc: &mut Document,
    interpolation: Interpolation,
    times: Vec<f32>,
    values: Vec<Vec3>,
) {
    doc.clips[0].tracks.push(Track {
        bone: 1,
        property: Property::Scale,
        interpolation,
        times,
        values: TrackValues::Vec3s(values),
    });
}

fn scale_finding_ids(doc: &Document) -> Vec<&'static str> {
    scale_finding_ids_with_config(doc, &Config::default())
}

fn scale_finding_ids_with_config(doc: &Document, config: &Config) -> Vec<&'static str> {
    let mut ids: Vec<_> = lint_with_config(doc, config)
        .into_iter()
        .filter(|finding| {
            matches!(
                finding.check_id,
                "scale-keys" | "non-uniform-scale" | "constant-nonunit-scale" | "constant-track"
            )
        })
        .map(|finding| finding.check_id)
        .collect();
    ids.sort_unstable();
    ids
}

fn presence_enabled_config_with(severity: SeveritySetting) -> Config {
    let mut config = Config::default();
    config.checks.insert(
        "constant-nonunit-scale".into(),
        CheckSettings {
            severity: Some(severity),
            ..CheckSettings::default()
        },
    );
    config
}

fn presence_enabled_config() -> Config {
    presence_enabled_config_with(SeveritySetting::Note)
}

#[test]
fn constant_uniform_scale_is_redundancy_not_temporal_variation() {
    let mut doc = clean_doc();
    add_scale_track(
        &mut doc,
        Interpolation::Linear,
        vec![0.0, 0.5, 1.0],
        vec![Vec3::ONE; 3],
    );
    assert_eq!(scale_finding_ids(&doc), vec!["constant-track"]);
}

#[test]
fn step_and_linear_scale_changes_are_temporal_variation() {
    for interpolation in [Interpolation::Step, Interpolation::Linear] {
        let mut doc = clean_doc();
        add_scale_track(
            &mut doc,
            interpolation,
            vec![0.0, 1.0],
            vec![Vec3::splat(2.0), Vec3::splat(3.0)],
        );
        assert_eq!(scale_finding_ids(&doc), vec!["scale-keys"]);
        assert_eq!(
            lint(&doc)
                .iter()
                .filter(|finding| finding.check_id == "scale-keys")
                .count(),
            1
        );
    }
}

#[test]
fn cubic_interior_temporal_excursion_is_not_constant() {
    let mut doc = clean_doc();
    // Equal endpoints, but equal positive tangents generate an interior
    // Hermite excursion. A key-only test would incorrectly call this bloat.
    add_scale_track(
        &mut doc,
        Interpolation::CubicSpline,
        vec![0.0, 1.0],
        vec![
            Vec3::ZERO,
            Vec3::ONE,
            Vec3::splat(0.004),
            Vec3::splat(0.004),
            Vec3::ONE,
            Vec3::ZERO,
        ],
    );
    assert_eq!(scale_finding_ids(&doc), vec!["scale-keys"]);
}

#[test]
fn cubic_opposite_tangents_create_a_one_component_excursion() {
    let mut doc = clean_doc();
    add_scale_track(
        &mut doc,
        Interpolation::CubicSpline,
        vec![0.0, 1.0],
        vec![
            Vec3::ZERO,
            Vec3::ONE,
            Vec3::new(0.004, 0.0, 0.0),
            Vec3::new(-0.004, 0.0, 0.0),
            Vec3::ONE,
            Vec3::ZERO,
        ],
    );
    assert_eq!(
        scale_finding_ids(&doc),
        vec!["non-uniform-scale", "scale-keys"]
    );
}

#[test]
fn cubic_y_and_z_only_tangents_are_temporal_variation_and_non_uniform() {
    for tangent in [Vec3::new(0.0, 0.004, 0.0), Vec3::new(0.0, 0.0, 0.004)] {
        let mut doc = clean_doc();
        add_scale_track(
            &mut doc,
            Interpolation::CubicSpline,
            vec![0.0, 1.0],
            vec![
                Vec3::ZERO,
                Vec3::ONE,
                tangent,
                -tangent,
                Vec3::ONE,
                Vec3::ZERO,
            ],
        );
        assert_eq!(
            scale_finding_ids(&doc),
            vec!["non-uniform-scale", "scale-keys"]
        );
    }
}

#[test]
fn cubic_temporal_variation_respects_the_tolerance_direction() {
    // Equal tangents produce a peak-to-trough range of about 0.1924 times the
    // tangent, placing these cases just below and above the 1e-4 threshold.
    let below_tolerance_tangent = 0.0005f32;
    let over_tolerance_tangent = 0.0006f32;
    for (tangent, expected) in [
        (below_tolerance_tangent, false),
        (over_tolerance_tangent, true),
    ] {
        let mut doc = clean_doc();
        add_scale_track(
            &mut doc,
            Interpolation::CubicSpline,
            vec![0.0, 1.0],
            vec![
                Vec3::ZERO,
                Vec3::ONE,
                Vec3::splat(tangent),
                Vec3::splat(tangent),
                Vec3::ONE,
                Vec3::ZERO,
            ],
        );
        assert_eq!(
            scale_finding_ids(&doc).contains(&"scale-keys"),
            expected,
            "tangent {tangent:?}"
        );
    }
}

#[test]
fn cubic_duration_scales_tangent_excursion() {
    // Put the decisive long segment on each side in turn. Both must exceed
    // tolerance after glTF's tangent-times-dt scaling.
    for times in [vec![0.0, 0.25, 2.25], vec![0.0, 2.0, 2.25]] {
        let mut doc = clean_doc();
        add_scale_track(
            &mut doc,
            Interpolation::CubicSpline,
            times,
            vec![
                Vec3::ZERO,
                Vec3::ONE,
                Vec3::splat(0.0003),
                Vec3::splat(0.0003),
                Vec3::ONE,
                Vec3::splat(0.0003),
                Vec3::splat(0.0003),
                Vec3::ONE,
                Vec3::ZERO,
            ],
        );
        assert_eq!(scale_finding_ids(&doc), vec!["scale-keys"]);
    }
}

#[test]
fn cubic_tangents_use_their_own_segment_duration() {
    let scale_values = vec![
        Vec3::ZERO,
        Vec3::ONE,
        Vec3::splat(0.0004),
        Vec3::ZERO,
        Vec3::ONE,
        Vec3::ZERO,
        Vec3::ZERO,
        Vec3::ONE,
        Vec3::ZERO,
    ];

    let mut short_first = clean_doc();
    add_scale_track(
        &mut short_first,
        Interpolation::CubicSpline,
        vec![0.0, 0.25, 2.25],
        scale_values.clone(),
    );
    assert_eq!(scale_finding_ids(&short_first), vec!["constant-track"]);

    let mut long_first = clean_doc();
    add_scale_track(
        &mut long_first,
        Interpolation::CubicSpline,
        vec![0.0, 2.0, 2.25],
        scale_values,
    );
    assert_eq!(scale_finding_ids(&long_first), vec!["scale-keys"]);
}

#[test]
fn cubic_interior_non_uniformity_has_its_own_finding() {
    let mut doc = clean_doc();
    add_scale_track(
        &mut doc,
        Interpolation::CubicSpline,
        vec![0.0, 1.0],
        vec![
            Vec3::ZERO,
            Vec3::ONE,
            Vec3::new(0.004, 0.0, 0.0),
            Vec3::new(0.004, 0.0, 0.0),
            Vec3::ONE,
            Vec3::ZERO,
        ],
    );
    assert_eq!(
        scale_finding_ids(&doc),
        vec!["non-uniform-scale", "scale-keys"]
    );
}

#[test]
fn cubic_off_grid_interior_extremum_is_detected() {
    let mut doc = clean_doc();
    // With equal endpoints and this tangent pair, the x extremum is at u=1/3,
    // not an endpoint or midpoint.
    add_scale_track(
        &mut doc,
        Interpolation::CubicSpline,
        vec![0.0, 1.0],
        vec![
            Vec3::ZERO,
            Vec3::ONE,
            Vec3::new(0.0008, 0.0, 0.0),
            Vec3::ZERO,
            Vec3::ONE,
            Vec3::ZERO,
        ],
    );
    assert_eq!(
        scale_finding_ids(&doc),
        vec!["non-uniform-scale", "scale-keys"]
    );
}

#[test]
fn constant_nonunit_scale_is_opt_in_and_distinct_from_nonuniformity() {
    let mut doc = clean_doc();
    add_scale_track(
        &mut doc,
        Interpolation::Linear,
        vec![0.0, 1.0],
        vec![Vec3::new(1.2, 1.0, 1.0); 2],
    );
    assert_eq!(
        scale_finding_ids(&doc),
        vec!["constant-track", "non-uniform-scale"]
    );
    assert_eq!(
        scale_finding_ids_with_config(&doc, &presence_enabled_config()),
        vec![
            "constant-nonunit-scale",
            "constant-track",
            "non-uniform-scale"
        ]
    );
    let evaluations = evaluations_with_config(&doc, &presence_enabled_config());
    let presence = evaluations
        .iter()
        .find(|evaluation| evaluation.check_id() == "constant-nonunit-scale")
        .expect("registered presence evaluation");
    assert_eq!(
        presence.evaluation(),
        animsmith_core::EvaluationState::Complete
    );
    assert_eq!(presence.findings().len(), 1);
    assert!(presence.gaps().is_empty());
    assert!(presence.evaluated_scopes().is_empty());
}

#[test]
fn constant_nonunit_scale_honors_each_enabling_severity() {
    let mut doc = clean_doc();
    add_scale_track(
        &mut doc,
        Interpolation::Linear,
        vec![0.0],
        vec![Vec3::splat(1.2)],
    );

    for (setting, expected) in [
        (SeveritySetting::Note, Severity::Note),
        (SeveritySetting::Warn, Severity::Warning),
        (SeveritySetting::Error, Severity::Error),
    ] {
        let findings = lint_with_config(&doc, &presence_enabled_config_with(setting));
        assert_eq!(findings.len(), 1);
        assert_eq!(findings[0].check_id, "constant-nonunit-scale");
        assert_eq!(findings[0].severity, expected);
    }
}

#[test]
fn constant_uniform_nonunit_scale_is_redundancy_plus_opt_in_presence() {
    let mut doc = clean_doc();
    add_scale_track(
        &mut doc,
        Interpolation::Linear,
        vec![0.0, 0.5, 1.0],
        vec![Vec3::splat(1.2); 3],
    );
    assert_eq!(scale_finding_ids(&doc), vec!["constant-track"]);
    assert_eq!(
        scale_finding_ids_with_config(&doc, &presence_enabled_config()),
        vec!["constant-nonunit-scale", "constant-track"]
    );
}

#[test]
fn single_key_nonunit_pin_is_not_redundant() {
    let mut doc = clean_doc();
    add_scale_track(
        &mut doc,
        Interpolation::Linear,
        vec![0.0],
        vec![Vec3::splat(1.2)],
    );
    assert!(scale_finding_ids(&doc).is_empty());
    assert_eq!(
        scale_finding_ids_with_config(&doc, &presence_enabled_config()),
        vec!["constant-nonunit-scale"]
    );
    let enabled_findings = lint_with_config(&doc, &presence_enabled_config());
    assert_eq!(enabled_findings.len(), 1);
    assert_eq!(enabled_findings[0].check_id, "constant-nonunit-scale");
    assert!(
        enabled_findings
            .iter()
            .all(|finding| finding.check_id != "constant-track")
    );
}

#[test]
fn single_key_yz_nonuniform_pin_has_presence_and_nonuniform_owners() {
    let mut doc = clean_doc();
    add_scale_track(
        &mut doc,
        Interpolation::Linear,
        vec![0.0],
        vec![Vec3::new(1.0, 1.0, 1.2)],
    );
    assert_eq!(scale_finding_ids(&doc), vec!["non-uniform-scale"]);
    assert_eq!(
        scale_finding_ids_with_config(&doc, &presence_enabled_config()),
        vec!["constant-nonunit-scale", "non-uniform-scale"]
    );
}

#[test]
fn exact_and_over_tolerance_temporal_ranges_are_distinguished() {
    let immediately_over = f32::from_bits(1e-4f32.to_bits() + 1);
    for sign in [1.0, -1.0] {
        let mut exact = clean_doc();
        add_scale_track(
            &mut exact,
            Interpolation::Linear,
            vec![0.0, 1.0],
            vec![Vec3::ZERO, Vec3::splat(sign * 1e-4)],
        );
        assert!(
            !scale_finding_ids(&exact).contains(&"scale-keys"),
            "exact tolerance must remain constant"
        );

        let mut over = clean_doc();
        add_scale_track(
            &mut over,
            Interpolation::Linear,
            vec![0.0, 1.0],
            vec![Vec3::ZERO, Vec3::splat(sign * immediately_over)],
        );
        assert!(
            scale_finding_ids(&over).contains(&"scale-keys"),
            "the next stored value over tolerance must vary"
        );
    }
}

#[test]
fn exact_and_over_tolerance_non_uniform_spreads_are_distinguished() {
    let immediately_over = f32::from_bits(1e-4f32.to_bits() + 1);
    for sign in [1.0, -1.0] {
        let mut exact = clean_doc();
        add_scale_track(
            &mut exact,
            Interpolation::Linear,
            vec![0.0],
            vec![Vec3::new(sign * 1e-4, 0.0, 0.0)],
        );
        assert!(
            !scale_finding_ids(&exact).contains(&"non-uniform-scale"),
            "exact tolerance must remain uniform"
        );

        let mut over = clean_doc();
        add_scale_track(
            &mut over,
            Interpolation::Linear,
            vec![0.0],
            vec![Vec3::new(sign * immediately_over, 0.0, 0.0)],
        );
        assert!(
            scale_finding_ids(&over).contains(&"non-uniform-scale"),
            "the next component spread over tolerance must be non-uniform"
        );
    }
}

#[test]
fn stored_values_above_and_below_unit_tolerance_are_distinguished() {
    let unit = 1.0f32;
    let tolerance_pairs = [true, false].map(|increasing| {
        let mut tolerated = unit;
        loop {
            let next_bits = if increasing {
                tolerated.to_bits() + 1
            } else {
                tolerated.to_bits() - 1
            };
            let next = f32::from_bits(next_bits);
            if (next - unit).abs() > 1e-4 {
                break (tolerated, next);
            }
            tolerated = next;
        }
    });

    let enabled = presence_enabled_config();
    for (tolerated_value, over_value) in tolerance_pairs {
        assert!((tolerated_value - unit).abs() <= 1e-4);
        assert!((over_value - unit).abs() > 1e-4);

        let mut tolerated = clean_doc();
        add_scale_track(
            &mut tolerated,
            Interpolation::Linear,
            vec![0.0],
            vec![Vec3::splat(tolerated_value)],
        );
        assert!(
            !scale_finding_ids_with_config(&tolerated, &enabled)
                .contains(&"constant-nonunit-scale")
        );

        let mut over = clean_doc();
        add_scale_track(
            &mut over,
            Interpolation::Linear,
            vec![0.0],
            vec![Vec3::splat(over_value)],
        );
        let findings = lint_with_config(&over, &enabled);
        assert!(findings.iter().any(|finding| {
            finding.check_id == "constant-nonunit-scale" && finding.severity == Severity::Note
        }));
    }
}

#[test]
fn invalid_scale_tracks_are_left_to_source_data_checks() {
    let invalid_tracks = [
        (
            Track {
                bone: 1,
                property: Property::Scale,
                interpolation: Interpolation::Linear,
                times: vec![0.0, 1.0],
                values: TrackValues::Vec3s(vec![Vec3::ONE, Vec3::splat(f32::NAN)]),
            },
            Some("nan"),
        ),
        (
            Track {
                bone: 1,
                property: Property::Scale,
                interpolation: Interpolation::Step,
                times: vec![0.0, 0.0],
                values: TrackValues::Vec3s(vec![Vec3::ONE, Vec3::splat(1.2)]),
            },
            Some("time-monotonic"),
        ),
        (
            Track {
                bone: 1,
                property: Property::Scale,
                interpolation: Interpolation::CubicSpline,
                times: vec![0.0, 1.0],
                values: TrackValues::Vec3s(vec![Vec3::ZERO, Vec3::ONE, Vec3::ZERO]),
            },
            None,
        ),
        (
            Track {
                bone: 1,
                property: Property::Scale,
                interpolation: Interpolation::CubicSpline,
                times: vec![0.0, 1.0],
                values: TrackValues::Vec3s(vec![
                    Vec3::ZERO,
                    Vec3::ONE,
                    Vec3::splat(f32::NAN),
                    Vec3::ZERO,
                    Vec3::ONE,
                    Vec3::ZERO,
                ]),
            },
            Some("nan"),
        ),
    ];

    for (track, owning_check) in invalid_tracks {
        let mut doc = clean_doc();
        doc.clips[0].tracks.push(track);
        assert!(
            scale_finding_ids_with_config(&doc, &presence_enabled_config()).is_empty(),
            "invalid source data must not also be classified as a scale fact"
        );
        if let Some(owning_check) = owning_check {
            assert!(
                lint(&doc)
                    .iter()
                    .any(|finding| finding.check_id == owning_check),
                "{owning_check} must retain invalid-source ownership"
            );
        }
    }
}

#[test]
fn cubic_translation_tangents_do_not_count_as_redundant() {
    let mut doc = clean_doc();
    doc.clips[0].tracks[1] = Track {
        bone: 0,
        property: Property::Translation,
        interpolation: Interpolation::CubicSpline,
        times: vec![0.0, 1.0],
        values: TrackValues::Vec3s(vec![
            Vec3::ZERO,
            Vec3::ZERO,
            Vec3::new(0.004, 0.0, 0.0),
            Vec3::new(0.004, 0.0, 0.0),
            Vec3::ZERO,
            Vec3::ZERO,
        ]),
    };
    assert!(
        !lint(&doc)
            .iter()
            .any(|finding| finding.check_id == "constant-track"),
        "moving cubic translation must not be called redundant"
    );
}

#[test]
fn scale_findings_are_content_not_coverage_gaps_and_not_duplicated() {
    let mut doc = clean_doc();
    add_scale_track(
        &mut doc,
        Interpolation::CubicSpline,
        vec![0.0, 1.0],
        vec![
            Vec3::ZERO,
            Vec3::ONE,
            Vec3::new(0.004, 0.0, 0.0),
            Vec3::new(-0.004, 0.0, 0.0),
            Vec3::ONE,
            Vec3::ZERO,
        ],
    );
    let evaluations = evaluations_with_config(&doc, &Config::default());
    for check_id in ["scale-keys", "non-uniform-scale"] {
        let evaluation = evaluations
            .iter()
            .find(|evaluation| evaluation.check_id() == check_id)
            .expect("registered scale evaluation");
        assert_eq!(
            evaluation.evaluation(),
            animsmith_core::EvaluationState::Complete
        );
        assert_eq!(evaluation.findings().len(), 1);
        assert!(evaluation.gaps().is_empty());
        assert!(evaluation.evaluated_scopes().is_empty());
    }
}

#[test]
fn cubic_quaternion_tangents_do_not_count_as_redundant() {
    let mut doc = clean_doc();
    let q = Quat::IDENTITY;
    doc.clips[0].tracks[0] = Track {
        bone: 1,
        property: Property::Rotation,
        interpolation: Interpolation::CubicSpline,
        times: vec![0.0, 1.0],
        values: TrackValues::Quats(vec![
            Quat::from_xyzw(0.0, 0.0, 0.0, 0.0),
            q,
            Quat::from_xyzw(0.1, 0.0, 0.0, 0.0),
            Quat::from_xyzw(0.1, 0.0, 0.0, 0.0),
            q,
            Quat::from_xyzw(0.0, 0.0, 0.0, 0.0),
        ]),
    };
    assert!(
        !lint(&doc)
            .iter()
            .any(|finding| finding.check_id == "constant-track"),
        "moving cubic quaternion must not be called redundant"
    );
}

#[test]
fn constant_rotation_track_is_noted() {
    let mut doc = clean_doc();
    let q = Quat::from_rotation_y(0.8);
    if let TrackValues::Quats(v) = &mut doc.clips[0].tracks[0].values {
        *v = vec![q, q, q];
    }
    assert_single(&doc, "constant-track", Severity::Note);
}

#[test]
fn measurements_report_rotation_range() {
    let doc = clean_doc();
    let config = Config::default();
    let grids = MetricGrids::new(&doc);
    let measurements =
        animsmith_core::measure::measure_document(&grids, &ResolvedRoles::default(), &config);
    let walk = &measurements["walk"];
    assert_eq!(walk.frame_count, 3);
    assert_eq!(walk.animated_bones, vec!["hips", "spine"]);
    let range = walk.bone_rotation_range_deg["spine"];
    let expected = 1.6f64.to_degrees();
    assert!(
        (range - expected).abs() < 0.1,
        "expected ~{expected}, got {range}"
    );
}