openusd 0.6.0

Rust native USD library
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
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
//! Value clips (spec 12.3.4): the explicit clip-set metadata model, the
//! stage-to-clip time mapping, and the value resolution that reads them during
//! attribute composition (the [`ClipCache`] entity, C++ `Usd_Clips`).
//!
//! A clip set is a named group of value clips that partition an attribute's
//! time samples across external clip layers. The set is described by a
//! dictionary-valued `clips` metadata field; the `clipSets` field orders the
//! sets by strength. Only the explicit form is modelled here — template clips
//! (spec 12.3.4.1.3) are resolved to explicit metadata elsewhere and are not
//! parsed by [`ClipSet::parse`].

use std::collections::HashMap;

use anyhow::Result;

use crate::gf;
use crate::sdf::schema::FieldKey;
use crate::sdf::{self, AssetPath, LayerOffset, Path, Value};

use super::index_cache::block_to_none;
use super::layer_graph::LayerGraph;
use super::LayerId;

/// Dictionary keys inside a single clip set's metadata (spec 12.3.4.1).
pub(crate) mod keys {
    /// Ordered asset paths to the clips holding time-varying data (explicit).
    pub const ASSET_PATHS: &str = "assetPaths";
    /// Asset path of the layer indexing the attributes carried by the clips.
    pub const MANIFEST_ASSET_PATH: &str = "manifestAssetPath";
    /// Prim path substituted for the stage prim's path when querying clips.
    pub const PRIM_PATH: &str = "primPath";
    /// `(stageTime, assetIndex)` pairs selecting the active clip over time.
    pub const ACTIVE: &str = "active";
    /// `(stageTime, clipTime)` pairs forming the stage-to-clip timing curve.
    pub const TIMES: &str = "times";
    /// `bool` — interpolate across surrounding clips for an attribute whose
    /// active clip has a gap, instead of falling to the manifest default
    /// (spec 12.3.4.6-7).
    pub const INTERPOLATE_MISSING: &str = "interpolateMissingClipValues";

    // ── Template clip keys (spec 12.3.4.1.3) ──────────────────────────────
    /// `#`-pattern asset path expanded into explicit `assetPaths`.
    pub const TEMPLATE_ASSET_PATH: &str = "templateAssetPath";
    /// Inclusive start of the time range searched for template clips.
    pub const TEMPLATE_START_TIME: &str = "templateStartTime";
    /// Inclusive end of the time range searched for template clips.
    pub const TEMPLATE_END_TIME: &str = "templateEndTime";
    /// Step between successive template clip times.
    pub const TEMPLATE_STRIDE: &str = "templateStride";
    /// Offset applied to each clip's active stage time.
    pub const TEMPLATE_ACTIVE_OFFSET: &str = "templateActiveOffset";
}

/// A single explicit clip set: a named group of value clips with sequencing
/// and timing metadata (spec 12.3.4.1).
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct ClipSet {
    /// Clip set name — the key in the `clips` dictionary.
    pub name: String,
    /// Prim path substituted for the stage prim's path when querying clip
    /// layers (spec 12.3.4.1.1.1). `None` means use the stage prim's own path.
    pub prim_path: Option<Path>,
    /// Asset path of the manifest layer (spec 12.3.4.1.1.2), if authored.
    pub manifest_asset: Option<String>,
    /// Ordered clip asset paths holding time-varying data (an `asset[]`,
    /// C++ `VtArray<SdfAssetPath>`).
    pub asset_paths: Vec<AssetPath>,
    /// `(stageTime, assetIndex)` pairs, sorted by stage time. Each entry marks
    /// the clip active from its stage time up to the next entry (spec 12.3.4.3).
    pub active: Vec<(f64, usize)>,
    /// `(stageTime, clipTime)` knots (`gf::Vec2d`), sorted by stage time,
    /// forming the timing curve (spec 12.3.4.4). Duplicate stage times encode
    /// jump discontinuities (spec 12.3.4.8).
    pub times: Vec<gf::Vec2d>,
    /// When `true`, a gap in the active clip is filled by interpolating across
    /// the nearest surrounding clips rather than by the manifest default
    /// (spec 12.3.4.6-7).
    pub interpolate_missing: bool,
}

/// A parsed clip set plus the layer provenance needed for asset resolution.
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct ResolvedClipSet {
    pub set: ClipSet,
    pub asset_layer: LayerId,
    pub manifest_layer: Option<LayerId>,
}

impl ClipSet {
    /// Parses every explicit clip set from a composed `clips` dictionary value.
    ///
    /// `clip_sets_order` is the resolved `clipSets` field, when authored: it
    /// orders the returned sets strongest-first. Without it, sets are returned
    /// sorted by name for determinism. Sets lacking explicit `assetPaths`
    /// (e.g. template-only sets) are skipped.
    pub(crate) fn parse(clips: &Value, clip_sets_order: Option<&[String]>) -> Vec<ClipSet> {
        let Value::Dictionary(sets) = clips else {
            return Vec::new();
        };

        let ordered_names: Vec<&String> = match clip_sets_order {
            Some(order) => order.iter().filter(|name| sets.contains_key(*name)).collect(),
            None => {
                let mut names: Vec<&String> = sets.keys().collect();
                names.sort();
                names
            }
        };

        ordered_names
            .into_iter()
            .filter_map(|name| match sets.get(name) {
                Some(Value::Dictionary(set)) => Self::parse_set(name, set),
                _ => None,
            })
            .collect()
    }

    /// Parses a single clip set from its metadata dictionary. Returns `None`
    /// when the set declares neither explicit `assetPaths` nor a usable
    /// `templateAssetPath`.
    ///
    /// Template sets (spec 12.3.4.1.3) authoring `templateAssetPath` +
    /// `templateStartTime` / `templateEndTime` / `templateStride` (and
    /// optionally `templateActiveOffset`) are expanded here into the explicit
    /// `assetPaths` / `active` / `times` form before resolution, so the rest
    /// of the pipeline only ever sees explicit clip sets. Explicit
    /// `assetPaths`, when authored, take precedence over the template form.
    fn parse_set(name: &str, set: &HashMap<String, Value>) -> Option<ClipSet> {
        let prim_path = set
            .get(keys::PRIM_PATH)
            .and_then(Value::as_str)
            .and_then(|s| Path::new(s).ok());
        let manifest_asset = set
            .get(keys::MANIFEST_ASSET_PATH)
            .and_then(Value::as_str)
            .map(str::to_owned);

        // Explicit form wins; otherwise expand a template set. `assetPaths` is
        // a strict `asset[]`, and `active` / `times` a strict `double2[]`, so
        // each extracts through `get` (exact `TryFrom`) rather than `cast`.
        let (asset_paths, active, times) = match get::<Vec<AssetPath>>(set, keys::ASSET_PATHS) {
            Some(asset_paths) => {
                let mut active: Vec<(f64, usize)> = get::<Vec<gf::Vec2d>>(set, keys::ACTIVE)
                    .unwrap_or_default()
                    .into_iter()
                    .map(|p| (p.x, p.y as usize))
                    .collect();
                active.sort_by(|a, b| a.0.total_cmp(&b.0));

                let mut times = get::<Vec<gf::Vec2d>>(set, keys::TIMES).unwrap_or_default();
                times.sort_by(|a, b| a.x.total_cmp(&b.x));
                (asset_paths, active, times)
            }
            None => expand_template(set)?,
        };

        let interpolate_missing = get::<bool>(set, keys::INTERPOLATE_MISSING).unwrap_or(false);

        Some(ClipSet {
            name: name.to_string(),
            prim_path,
            manifest_asset,
            asset_paths,
            active,
            times,
            interpolate_missing,
        })
    }

    /// Returns the index into [`Self::asset_paths`] of the clip active at
    /// `stage_time` (spec 12.3.4.3). The first entry is active for all earlier
    /// times and the last entry for all later times. Returns `None` when no
    /// `active` entries are authored.
    pub(crate) fn active_clip(&self, stage_time: f64) -> Option<usize> {
        let mut chosen = self.active.first()?.1;
        for &(stage, index) in &self.active {
            if stage <= stage_time {
                chosen = index;
            } else {
                break;
            }
        }
        Some(chosen)
    }

    /// Maps `stage_time` to clip time through the `times` timing curve
    /// (spec 12.3.4.4). With no `times` authored, the stage time is returned
    /// unchanged.
    pub(crate) fn map_stage_to_clip(&self, stage_time: f64) -> f64 {
        map_stage_to_clip(&self.times, stage_time)
    }

    /// Retimes the schedule through `offset`, shifting the stage component of
    /// every `active` and `times` entry while leaving the clip-time targets and
    /// asset paths untouched. A template-derived schedule is produced in clip
    /// time and brought into stage time here; explicit `active`/`times` are
    /// retimed as they compose.
    pub(crate) fn retime_stage_times(&mut self, offset: LayerOffset) {
        if offset.is_identity() {
            return;
        }
        for (stage, _) in &mut self.active {
            *stage = offset.apply(*stage);
        }
        for knot in &mut self.times {
            knot.x = offset.apply(knot.x);
        }
        // A positive scale preserves the existing stage ordering; only a
        // negative scale (time reversal) needs a re-sort.
        if offset.scale < 0.0 {
            self.active.sort_by(|a, b| a.0.total_cmp(&b.0));
            self.times.sort_by(|a, b| a.x.total_cmp(&b.x));
        }
    }

    /// The stage times at which a clipped attribute's value changes under this
    /// set (the clip half of `UsdAttribute::GetTimeSamples`). `per_clip[i]` is
    /// the in-clip sample times the clip at `asset_paths[i]` authors for the
    /// attribute; an active entry referencing an index past `per_clip` is
    /// treated as authoring none.
    ///
    /// For each clip active over a stage interval, the result gathers the
    /// timing-curve knots in the interval and the clip's in-clip sample times
    /// mapped to stage time through [`Self::stage_times_for_clip_time`] and
    /// clamped to the interval, plus the clip-switch boundary. The first active
    /// entry is active from negative infinity (spec 12.3.4.3, matching
    /// [`Self::active_clip`]), so its interval has no lower bound and its stage
    /// time is not a switch; each later entry's stage time bounds its interval
    /// and is itself a switch boundary (the value can jump as the active clip
    /// changes). Returns the union sorted ascending; empty when no clip is active.
    ///
    /// Every active interval contributes its switch boundary, mirroring C++
    /// `Usd_ClipSet` with `interpolateMissingClipValues` off: a clip authoring
    /// no in-interval sample still reports the boundary where it becomes active,
    /// since the active clip changes there. Whether the set sources the
    /// attribute at all is decided by the caller's participation check before
    /// this routine runs.
    pub(crate) fn stage_sample_times(&self, per_clip: &[Vec<f64>]) -> Vec<f64> {
        let mut out: Vec<f64> = Vec::new();
        for (k, &(start, clip_index)) in self.active.iter().enumerate() {
            let samples = per_clip.get(clip_index).map_or(&[][..], Vec::as_slice);
            let end = self.active.get(k + 1).map(|next| next.0);
            // The first entry is active from negative infinity; later entries
            // start at `start`, which is also a clip-switch sample time.
            let lower = (k > 0).then_some(start);
            let in_interval = |t: f64| lower.is_none_or(|l| t >= l) && end.is_none_or(|e| t < e);

            if let Some(boundary) = lower {
                out.push(boundary);
            }
            out.extend(self.times.iter().map(|knot| knot.x).filter(|&x| in_interval(x)));
            for &clip_time in samples {
                out.extend(
                    self.stage_times_for_clip_time(clip_time)
                        .into_iter()
                        .filter(|&t| in_interval(t)),
                );
            }
        }
        // Drop non-finite times before dedup: a clip may author a NaN time-
        // sample key, and `dedup` (PartialEq) would not collapse repeated NaNs.
        out.retain(|t| t.is_finite());
        out.sort_by(f64::total_cmp);
        out.dedup();
        out
    }

    /// Whether this set's active-clip schedule alone can make the value vary
    /// over time, the clip-schedule half of
    /// [`UsdAttribute::ValueMightBeTimeVarying`]. True when more than one clip
    /// window is active, since switching the active clip can change the value.
    /// A conservative over-approximation: it does not check whether the windows
    /// resolve to distinct values (matching the "might" in the C++ name), and
    /// time variation within a single window is reported through the sample-time
    /// count instead.
    ///
    /// [`UsdAttribute::ValueMightBeTimeVarying`]: crate::usd::Attribute::value_might_be_time_varying
    pub(crate) fn may_be_time_varying(&self) -> bool {
        self.active.len() > 1
    }

    /// The stage times mapping to clip time `clip_time` — the inverse of
    /// [`Self::map_stage_to_clip`] over the timing curve. With no `times`
    /// authored the mapping is identity (the clip time is its own stage time).
    /// Each linear segment that crosses `clip_time` contributes one stage time;
    /// a constant segment (no clip-time change) contributes none, since the
    /// value is held there and only the activation boundary marks a change.
    fn stage_times_for_clip_time(&self, clip_time: f64) -> Vec<f64> {
        if self.times.is_empty() {
            return vec![clip_time];
        }
        self.times
            .windows(2)
            .filter_map(|seg| {
                let (sa, ca) = (seg[0].x, seg[0].y);
                let (sb, cb) = (seg[1].x, seg[1].y);
                let (lo, hi) = if ca <= cb { (ca, cb) } else { (cb, ca) };
                if ca == cb || clip_time < lo || clip_time > hi {
                    return None;
                }
                Some(sa + (clip_time - ca) / (cb - ca) * (sb - sa))
            })
            .collect()
    }
}

/// Maps `stage_time` to clip time through a sorted `(stageTime, clipTime)`
/// timing curve made of linear segments (spec 12.3.4.4). Duplicate stage times
/// encode a jump discontinuity (spec 12.3.4.8): the earlier entry's clip time
/// applies up to that stage time, the later entry's at and after it. Out-of-
/// range stage times clamp to the first or last clip time.
fn map_stage_to_clip(times: &[gf::Vec2d], stage_time: f64) -> f64 {
    let (Some(first), Some(last)) = (times.first(), times.last()) else {
        return stage_time;
    };
    if stage_time < first.x {
        return first.y;
    }
    if stage_time >= last.x {
        return last.y;
    }

    // Index of the last entry whose stage time does not exceed `stage_time`.
    // For a duplicated stage time this lands on the right-hand entry, so a
    // query exactly at the jump uses the "at and after" clip time.
    let lo = times.iter().rposition(|knot| knot.x <= stage_time).unwrap_or(0);
    let (lo_knot, hi_knot) = (times[lo], times[lo + 1]);
    let (stage0, clip0) = (lo_knot.x, lo_knot.y);
    let (stage1, clip1) = (hi_knot.x, hi_knot.y);

    if stage0 == stage1 {
        return clip1;
    }
    if stage_time == stage0 {
        return clip0;
    }
    let ratio = (stage_time - stage0) / (stage1 - stage0);
    gf::lerp(clip0, clip1, ratio)
}

/// Derived `(assetPaths, active, times)` from a template clip set.
type TemplateExpansion = (Vec<AssetPath>, Vec<(f64, usize)>, Vec<gf::Vec2d>);

/// Expand a template clip set (spec 12.3.4.1.3) into explicit
/// `(assetPaths, active, times)`.
///
/// Iterates clip times from `templateStartTime` to `templateEndTime`
/// (inclusive) by `templateStride`, substituting each time into the
/// `#`-pattern `templateAssetPath`. Each generated clip `i` contributes
/// `assetPaths[i]`, an `active` entry `(stageTime, i)`, and a `times`
/// entry `(clipTime, clipTime)`. `templateActiveOffset`, when authored,
/// shifts each clip's active stage time to `clipTime + offset` and adds
/// boundary knots to `times` at `start - |offset|` and `end + |offset|`.
///
/// Returns `None` when the required template fields are missing or
/// invalid (non-positive stride, `end < start`, `|activeOffset| > stride`,
/// or an unparseable pattern).
///
/// Times are scaled by a fixed promotion factor during iteration so a
/// fractional `stride` accumulates without binary-float drift, matching
/// C++ `Usd_ClipSetDefinition` template derivation.
fn expand_template(set: &HashMap<String, Value>) -> Option<TemplateExpansion> {
    let template = set
        .get(keys::TEMPLATE_ASSET_PATH)
        .and_then(Value::as_str)
        .map(str::to_owned)?;
    // Template timing is `double`, read strictly like C++ `IsHolding<double>`.
    let start = get::<f64>(set, keys::TEMPLATE_START_TIME)?;
    let end = get::<f64>(set, keys::TEMPLATE_END_TIME)?;
    let stride = get::<f64>(set, keys::TEMPLATE_STRIDE)?;
    let active_offset = get::<f64>(set, keys::TEMPLATE_ACTIVE_OFFSET);

    if stride.is_nan() || stride <= 0.0 || end < start {
        return None;
    }
    // Spec 12.3.4.1.3: the active offset magnitude may not exceed the stride.
    if active_offset.is_some_and(|off| off.abs() > stride) {
        return None;
    }

    let pattern = HashPattern::parse(&template)?;

    // Promote to integers so a fractional stride doesn't accumulate float
    // drift across the loop (C++ uses the same trick).
    const PROMOTION: f64 = 10000.0;
    let end_p = end * PROMOTION;
    let stride_p = stride * PROMOTION;

    let mut asset_paths = Vec::new();
    let mut active = Vec::new();
    let mut times = Vec::new();

    // An active offset lets a query reach `|offset|` before the first clip and
    // after the last. Author timing knots at those expanded boundaries so the
    // lead/trail range maps linearly to clip time instead of clamping to the
    // first or last clip time (spec 12.3.4.1.3, matching C++ derivation).
    if let Some(off) = active_offset {
        let front = start - off.abs();
        times.push(gf::vec2d(front, front));
    }

    let mut t = start * PROMOTION;
    let mut index = 0usize;
    // `+ 0.5` keeps the inclusive endpoint despite residual rounding.
    while t <= end_p + 0.5 {
        let clip_time = t / PROMOTION;
        asset_paths.push(pattern.format(clip_time).into());
        times.push(gf::vec2d(clip_time, clip_time));
        let stage_time = match active_offset {
            Some(off) => (t + off * PROMOTION) / PROMOTION,
            None => clip_time,
        };
        active.push((stage_time, index));
        index += 1;
        t += stride_p;
    }

    if let Some(off) = active_offset {
        let back = end + off.abs();
        times.push(gf::vec2d(back, back));
    }

    if asset_paths.is_empty() {
        return None;
    }
    active.sort_by(|a, b| a.0.total_cmp(&b.0));
    times.sort_by(|a, b| a.x.total_cmp(&b.x));
    Some((asset_paths, active, times))
}

/// A parsed `templateAssetPath` pattern: a prefix, one or two adjacent
/// `#`-groups (integer, optionally followed by a subinteger group), and
/// a suffix. Per spec the groups must be adjacent and number one or two.
struct HashPattern {
    prefix: String,
    int_width: usize,
    /// Width of the subinteger group, when the pattern has two groups.
    frac_width: Option<usize>,
    suffix: String,
}

impl HashPattern {
    /// Parse `path/basename.###.usd` or `path/basename.##.##.usd`.
    /// Returns `None` when there is no `#`-group, more than two groups,
    /// or stray `#` outside the (adjacent) groups.
    fn parse(template: &str) -> Option<HashPattern> {
        let first = template.find('#')?;
        let prefix = template[..first].to_string();
        let rest = &template[first..];

        // First (integer) group.
        let int_width = rest.chars().take_while(|&c| c == '#').count();
        let after_int = &rest[int_width..];

        // Optional `.<##...>` subinteger group immediately following.
        let (frac_width, suffix) = if let Some(dot_rest) = after_int.strip_prefix('.') {
            if dot_rest.starts_with('#') {
                let frac_width = dot_rest.chars().take_while(|&c| c == '#').count();
                (Some(frac_width), dot_rest[frac_width..].to_string())
            } else {
                (None, after_int.to_string())
            }
        } else {
            (None, after_int.to_string())
        };

        // Spec: hash groups must be adjacent and number one or two — any
        // further `#` in the suffix means a malformed (3+ group) pattern.
        if suffix.contains('#') {
            return None;
        }

        Some(HashPattern {
            prefix,
            int_width,
            frac_width,
            suffix,
        })
    }

    /// Substitute `time` into the pattern. Integer group zero-pads to the
    /// hash count (widening when the value needs more digits); the
    /// subinteger group is fixed-width fractional precision.
    fn format(&self, time: f64) -> String {
        let body = match self.frac_width {
            // Two groups: `<int>.<frac>` at the given widths (spec example
            // `foo.#.###.usd` @ 1.15 -> `foo.1.150.usd`).
            Some(frac_width) => {
                let rendered = format!("{:.*}", frac_width, time);
                let (int_part, frac_part) = rendered.split_once('.').unwrap_or((rendered.as_str(), ""));
                let neg = int_part.starts_with('-');
                let digits = int_part.trim_start_matches('-');
                let padded = format!("{:0>width$}", digits, width = self.int_width);
                let sign = if neg { "-" } else { "" };
                format!("{sign}{padded}.{frac_part}")
            }
            // One group: zero-padded integer, truncating the clip time toward
            // zero like the C++ `int(time)` cast (spec example `foo.###.usd`
            // @ 12 -> `foo.012.usd`).
            None => format!("{:0width$}", time as i64, width = self.int_width),
        };
        format!("{}{}{}", self.prefix, body, self.suffix)
    }
}

/// Reads `key` from a clip-set dictionary and extracts it strictly as `T` — the
/// exact-variant [`TryFrom`] tier — yielding `None` when the key is absent or
/// the authored type does not match. Mirrors C++ `Usd_ClipSetDefinition`'s
/// `IsHolding<T>` reads, which likewise treat a type mismatch as unauthored.
fn get<T: TryFrom<Value>>(set: &HashMap<String, Value>, key: &str) -> Option<T> {
    set.get(key).cloned().and_then(|v| T::try_from(v).ok())
}

/// Value-clip resolution state owned by
/// [`IndexCache`](super::index_cache::IndexCache): the lazily-loaded clip and
/// manifest layers, plus the per-anchor clip-value and participation queries the
/// cache's clip orchestration delegates to (C++ `Usd_Clips`). Clip layers never
/// enter the composition [`LayerGraph`](super::layer_graph::LayerGraph) (spec
/// 12.3.4); they are held here, keyed by resolved identifier.
#[derive(Default)]
pub(crate) struct ClipCache {
    clip_layers: HashMap<String, sdf::Layer>,
}

/// The attribute a clip query resolves, plus the `anchor` prim its clip sets
/// were composed on (an ancestor of `attr_prim`, or `attr_prim` itself). Bundles
/// the three path arguments threaded together through the per-anchor
/// [`ClipCache`] queries.
pub(super) struct ClipQuery<'a> {
    /// The prim the queried clip sets were composed on.
    pub anchor: &'a Path,
    /// The prim owning the attribute being resolved.
    pub attr_prim: &'a Path,
    /// The attribute's property suffix (e.g. `.size`).
    pub suffix: &'a str,
}

impl ClipCache {
    /// Resolves a value-clip value for `query` at `time` from `sets` — the clip
    /// sets composed on `query.anchor` — returning the first set that provides a
    /// value, or `None` when none does. The per-anchor body of the cache's
    /// clip-value resolution; an authored value block presents as
    /// `Some(Value::ValueBlock)` so the caller stops fall-through to weaker
    /// sources.
    pub(super) fn value_in_sets(
        &mut self,
        graph: &LayerGraph,
        sets: &[ResolvedClipSet],
        query: &ClipQuery,
        time: f64,
        interp: &dyn Fn(&sdf::TimeSampleMap, f64) -> Option<Value>,
    ) -> Result<Option<Value>> {
        for resolved in sets {
            let set = &resolved.set;
            let base = set.prim_path.clone().unwrap_or_else(|| query.anchor.clone());
            let clip_path = clip_attr_path(query, &base)?;

            // Resolve the manifest once: its declaration gates the set and its
            // default later fills a gap (spec 12.3.4.6).
            let manifest = set
                .manifest_asset
                .as_deref()
                .map(|asset| (asset, resolved.manifest_layer.unwrap_or(resolved.asset_layer)));

            // A manifest, when authored, declares which attributes the clips
            // provide. A set whose manifest does not declare this attribute is
            // skipped. A set that *does* declare it owns the attribute's
            // time-varying value (spec 12.3.4.6): a gap in the active clip
            // resolves to a manifest default or a value block, never to a
            // weaker value source.
            let manifest_declared = self.clip_set_declares(graph, resolved, &clip_path)?;
            if manifest.is_some() && !manifest_declared {
                continue;
            }

            let Some(active) = set.active_clip(time) else {
                continue;
            };
            let Some(asset) = set.asset_paths.get(active) else {
                continue;
            };
            let clip_time = set.map_stage_to_clip(time);

            if let Some(value) = self.clip_sample_at(
                graph,
                asset.as_str(),
                resolved.asset_layer,
                &clip_path,
                clip_time,
                interp,
            )? {
                return Ok(Some(value));
            }

            // The active clip has no sample at `clip_time`. Only a
            // manifest-declared attribute gets the gap-filling treatment;
            // without a manifest there is no assurance this set owns the
            // attribute, so fall through to weaker value sources.
            if !manifest_declared {
                continue;
            }

            // (a) Manifest default: synthesize a sample at the clip's active
            //     time (spec 12.3.4.6). Reached only when the manifest declared
            //     the attribute, so the manifest asset is authored.
            if let Some((asset, layer)) = manifest {
                if let Some(value) = self.manifest_default(graph, asset, layer, &clip_path)? {
                    return Ok(Some(value));
                }
            }

            // (b) interpolateMissingClipValues: interpolate the gap across the
            //     nearest surrounding clips (spec 12.3.4.7).
            if set.interpolate_missing {
                if let Some(value) = self.interpolate_missing_value(graph, resolved, &clip_path, time, interp)? {
                    return Ok(Some(value));
                }
            }

            // (c) No default and nothing to interpolate: the manifest-declared
            //     attribute is authoritatively absent — a value block — which
            //     must not fall through to weaker sources (spec 12.3.4.6).
            return Ok(Some(Value::ValueBlock));
        }

        Ok(None)
    }

    /// The value-clip introspection from the first set in `sets` (composed on
    /// `query.anchor`) that participates in sourcing the attribute: its stage
    /// sample times (spec 12.3.4) and whether its schedule alone can vary the
    /// value ([`ClipSet::may_be_time_varying`]). `None` when none participates.
    /// The per-anchor body of the cache's clip introspection.
    pub(super) fn clip_introspection_in_sets(
        &mut self,
        graph: &LayerGraph,
        sets: &[ResolvedClipSet],
        query: &ClipQuery,
    ) -> Result<Option<(Vec<f64>, bool)>> {
        for resolved in sets {
            let base = resolved.set.prim_path.clone().unwrap_or_else(|| query.anchor.clone());
            let clip_path = clip_attr_path(query, &base)?;
            if let Some(per_clip) = self.clip_set_participates(graph, resolved, &clip_path)? {
                let set = &resolved.set;
                return Ok(Some((set.stage_sample_times(&per_clip), set.may_be_time_varying())));
            }
        }
        Ok(None)
    }

    /// Loads a value-clip or manifest layer referenced by `asset_path`,
    /// anchored to the layer `anchor_layer` (the layer that authored the
    /// clip metadata). Layers are loaded on demand through the graph's
    /// resolver and cached by resolved identifier; clip layers never enter the
    /// composition [`LayerGraph`] (spec 12.3.4).
    ///
    /// Returns `Ok(None)` when the asset path cannot be resolved.
    fn clip_layer(
        &mut self,
        graph: &LayerGraph,
        asset_path: &str,
        anchor_layer: LayerId,
    ) -> Result<Option<&sdf::Layer>> {
        // Anchor the clip asset path to the authoring layer's location so
        // relative paths resolve like any other dependency.
        let anchor = graph.anchor_location(Some(anchor_layer));
        let clip_id = graph.layer_registry().create_identifier(asset_path, anchor.as_ref());

        if !self.clip_layers.contains_key(&clip_id) {
            let Some(data) = graph.layer_registry().open(&clip_id)? else {
                return Ok(None);
            };
            self.clip_layers
                .insert(clip_id.clone(), sdf::Layer::new(clip_id.clone(), data));
        }

        Ok(self.clip_layers.get(&clip_id))
    }

    /// Whether `resolved` declares the attribute at `clip_path` through its
    /// manifest. A manifest that lists the attribute makes the set own it
    /// authoritatively (spec 12.3.4.6), gap-filling rather than falling through
    /// to weaker sources. A manifest-less set returns `false` here: its
    /// ownership is per-time, resolved by each caller's own sample handling.
    /// This is the shared manifest-declaration predicate behind
    /// [`Self::value_in_sets`] and [`Self::clip_set_participates`].
    fn clip_set_declares(&mut self, graph: &LayerGraph, resolved: &ResolvedClipSet, clip_path: &Path) -> Result<bool> {
        match resolved.set.manifest_asset.as_deref() {
            Some(asset) => {
                let layer = resolved.manifest_layer.unwrap_or(resolved.asset_layer);
                Ok(matches!(self.clip_layer(graph, asset, layer)?,
                            Some(opened) if opened.data().has_spec(clip_path)))
            }
            None => Ok(false),
        }
    }

    /// Whether the resolved clip `set` participates in sourcing the attribute at
    /// `clip_path`, returning each clip's in-clip authored sample times when it
    /// does and `None` when it does not. A set participates when its manifest
    /// declares the attribute ([`Self::clip_set_declares`]), or — manifest-less —
    /// when a clip the `active` schedule selects authors a sample for it. The
    /// single participation predicate behind [`Self::clip_introspection_in_sets`].
    ///
    /// Participation tracks what [`Self::value_in_sets`] can reach: it selects a
    /// clip only through [`ClipSet::active_clip`], so a set with no `active`
    /// schedule sources nothing, and a manifest-less set is sourced only by the
    /// clips its schedule names — an authored-but-unscheduled clip is never read.
    fn clip_set_participates(
        &mut self,
        graph: &LayerGraph,
        resolved: &ResolvedClipSet,
        clip_path: &Path,
    ) -> Result<Option<Vec<Vec<f64>>>> {
        let set = &resolved.set;
        let declared = self.clip_set_declares(graph, resolved, clip_path)?;
        // A manifest that does not declare the attribute does not source it.
        if set.manifest_asset.is_some() && !declared {
            return Ok(None);
        }
        // With no active schedule no clip is ever selected, so the set sources
        // nothing regardless of what its clips author.
        if set.active.is_empty() {
            return Ok(None);
        }
        let mut per_clip: Vec<Vec<f64>> = Vec::with_capacity(set.asset_paths.len());
        for asset in &set.asset_paths {
            per_clip.push(self.clip_in_clip_times(graph, asset.as_str(), resolved.asset_layer, clip_path)?);
        }
        // A manifest-less set sources the attribute only where a *scheduled* clip
        // authors a sample; if no `active` entry names a sampled clip, value_at
        // falls through to weaker sources, so the set does not participate.
        let scheduled_sample = set
            .active
            .iter()
            .any(|&(_, index)| per_clip.get(index).is_some_and(|s| !s.is_empty()));
        if !declared && !scheduled_sample {
            return Ok(None);
        }
        Ok(Some(per_clip))
    }

    /// The in-clip authored sample times for `clip_path` in a single clip layer,
    /// or empty when the layer is unresolved or authors no samples there.
    fn clip_in_clip_times(
        &mut self,
        graph: &LayerGraph,
        asset: &str,
        anchor_layer: LayerId,
        clip_path: &Path,
    ) -> Result<Vec<f64>> {
        Ok(self
            .clip_time_samples(graph, asset, anchor_layer, clip_path)?
            .map(|samples| samples.iter().map(|(t, _)| *t).collect())
            .unwrap_or_default())
    }

    /// Reads the `timeSamples` map authored for `clip_path` in a single clip
    /// layer, or `None` when the layer is unresolved or authors no samples
    /// there. The shared read behind [`Self::clip_sample_at`] (which
    /// interpolates) and [`Self::clip_in_clip_times`] (which lists the times).
    fn clip_time_samples(
        &mut self,
        graph: &LayerGraph,
        asset: &str,
        anchor_layer: LayerId,
        clip_path: &Path,
    ) -> Result<Option<sdf::TimeSampleMap>> {
        Ok(match self.clip_layer(graph, asset, anchor_layer)? {
            Some(layer) => match layer.data().try_field(clip_path, FieldKey::TimeSamples.as_str())? {
                Some(value) => match value.into_owned() {
                    Value::TimeSamples(samples) => Some(samples),
                    _ => None,
                },
                None => None,
            },
            None => None,
        })
    }

    /// Reads the time samples for `clip_path` from a single clip layer and
    /// interpolates at `clip_time`. Returns `None` when the layer is
    /// unresolved or the attribute has no time samples there.
    fn clip_sample_at(
        &mut self,
        graph: &LayerGraph,
        asset: &str,
        anchor_layer: LayerId,
        clip_path: &Path,
        clip_time: f64,
        interp: &dyn Fn(&sdf::TimeSampleMap, f64) -> Option<Value>,
    ) -> Result<Option<Value>> {
        Ok(self
            .clip_time_samples(graph, asset, anchor_layer, clip_path)?
            .and_then(|samples| interp(&samples, clip_time)))
    }

    /// Reads the manifest's authored `default` for `clip_path` (spec 12.3.4.6):
    /// when the active clip has a gap, the manifest default stands in as the
    /// sample value. Returns `None` when the manifest is unresolved or holds no
    /// usable default for the attribute.
    fn manifest_default(
        &mut self,
        graph: &LayerGraph,
        manifest: &str,
        manifest_layer: LayerId,
        clip_path: &Path,
    ) -> Result<Option<Value>> {
        let value = match self.clip_layer(graph, manifest, manifest_layer)? {
            Some(layer) => layer
                .data()
                .try_field(clip_path, FieldKey::Default.as_str())?
                .map(|value| value.into_owned()),
            None => None,
        };
        Ok(value.and_then(block_to_none))
    }

    /// Fills a gap in the active clip by interpolating across the nearest
    /// surrounding clips that contribute a value (spec 12.3.4.7). Each
    /// contributing clip is anchored on the stage timeline at the active stage
    /// time it owns and valued by its sample there; `interp` then brackets
    /// `time` between the nearest such anchors, exactly as if the clips' samples
    /// formed one virtual sample map. The forward bracket is the next
    /// contributing clip's start time and the backward bracket the previous
    /// one's, matching the C++ resolver. When only one side contributes, its
    /// value is held across the gap.
    fn interpolate_missing_value(
        &mut self,
        graph: &LayerGraph,
        resolved: &ResolvedClipSet,
        clip_path: &Path,
        time: f64,
        interp: &dyn Fn(&sdf::TimeSampleMap, f64) -> Option<Value>,
    ) -> Result<Option<Value>> {
        let set = &resolved.set;
        let anchor = resolved.asset_layer;
        // Position of the active clip among the `active` entries at `time`.
        let active_pos = set.active.iter().rposition(|&(stage, _)| stage <= time).unwrap_or(0);

        // Forward: nearest later clip that contributes, anchored at its start.
        let mut upper = None;
        for &(stage, idx) in set.active.iter().skip(active_pos + 1) {
            if let Some(asset) = set.asset_paths.get(idx) {
                let clip_time = set.map_stage_to_clip(stage);
                if let Some(value) = self.clip_sample_at(graph, asset.as_str(), anchor, clip_path, clip_time, interp)? {
                    upper = Some((stage, value));
                    break;
                }
            }
        }

        // Backward: nearest earlier clip that contributes, anchored at its start.
        let mut lower = None;
        for &(stage, idx) in set.active[..active_pos].iter().rev() {
            if let Some(asset) = set.asset_paths.get(idx) {
                let clip_time = set.map_stage_to_clip(stage);
                if let Some(value) = self.clip_sample_at(graph, asset.as_str(), anchor, clip_path, clip_time, interp)? {
                    lower = Some((stage, value));
                    break;
                }
            }
        }

        Ok(match (lower, upper) {
            (Some((lt, lv)), Some((ut, uv))) => interp(&vec![(lt, lv), (ut, uv)], time),
            (Some((_, value)), None) | (None, Some((_, value))) => Some(value),
            (None, None) => None,
        })
    }
}

/// The attribute's path inside a clip set's namespace: the `attr_prim + suffix`
/// path with the clip `anchor` prim replaced by the set's `base` prim (spec
/// 12.3.4.1.1.1). `query.anchor` is an ancestor of `query.attr_prim`, so the
/// replacement lands on a path boundary; the fallback keeps the path unchanged
/// if it ever is not a prefix.
fn clip_attr_path(query: &ClipQuery, base: &Path) -> Result<Path> {
    let attr = Path::new(&format!("{}{}", query.attr_prim, query.suffix))?;
    Ok(attr.replace_prefix(query.anchor, base).unwrap_or(attr))
}

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

    /// `ClipCache::clip_layer` loads a clip layer relative to the authoring
    /// layer, caches it (clip layers never enter the composition stack), and
    /// reports an unresolvable path as `None`. The cache resolves clips through
    /// an independently-owned [`ClipCache`], so this exercises it without an
    /// [`IndexCache`](super::super::index_cache::IndexCache).
    #[test]
    fn loads_and_caches_clip_layer() -> anyhow::Result<()> {
        let root = format!(
            "{}/vendor/core-spec-supplemental-release_dec2025/value_resolution/tests/assets/clip_basic/usda/root.usda",
            std::env::var("CARGO_MANIFEST_DIR").unwrap()
        );
        let registry = sdf::LayerRegistry::default();
        let id = registry.create_identifier(&root, None);
        let data = registry.open(&root).expect("open root").expect("root resolves");
        let graph = LayerGraph::from_layers(vec![sdf::Layer::new(id, data)], 0, registry);
        let root_id = graph.root_id().expect("root layer");

        let mut clips = ClipCache::default();
        {
            let clip = clips
                .clip_layer(&graph, "./clip.usda", root_id)?
                .expect("clip resolves");
            assert!(clip.identifier.contains("clip.usda"));
            assert!(clip.data().has_spec(&sdf::path("/Model.size")?));
        }

        // Second lookup is a cache hit; a bogus path resolves to None.
        assert!(clips.clip_layer(&graph, "./clip.usda", root_id)?.is_some());
        assert!(clips.clip_layer(&graph, "./does_not_exist.usda", root_id)?.is_none());
        Ok(())
    }

    /// Builds a `double2[]` knot list (`active` / `times`) from `(x, y)` pairs.
    fn knots(pairs: &[(f64, f64)]) -> Vec<gf::Vec2d> {
        pairs.iter().map(|&(x, y)| gf::vec2d(x, y)).collect()
    }

    // Template hash substitution (clipsAPI.h doc examples).

    #[test]
    fn hash_substitution_integer() {
        // foo.##.usd  @ 12  => foo.12.usd
        assert_eq!(HashPattern::parse("foo.##.usd").unwrap().format(12.0), "foo.12.usd");
        // foo.###.usd @ 12  => foo.012.usd
        assert_eq!(HashPattern::parse("foo.###.usd").unwrap().format(12.0), "foo.012.usd");
        // foo.#.usd   @ 333 => foo.333.usd
        assert_eq!(HashPattern::parse("foo.#.usd").unwrap().format(333.0), "foo.333.usd");
        // Fractional clip times truncate toward zero, not round:
        // foo.#.usd @ 1.6 => foo.1.usd.
        assert_eq!(HashPattern::parse("foo.#.usd").unwrap().format(1.6), "foo.1.usd");
    }

    #[test]
    fn hash_substitution_subinteger() {
        // foo.#.###.usd @ 1.15 => foo.1.150.usd
        assert_eq!(
            HashPattern::parse("foo.#.###.usd").unwrap().format(1.15),
            "foo.1.150.usd"
        );
        // foo.#.##.usd  @ 1.1  => foo.1.10.usd
        assert_eq!(HashPattern::parse("foo.#.##.usd").unwrap().format(1.1), "foo.1.10.usd");
    }

    #[test]
    fn hash_pattern_rejects_three_groups() {
        assert!(HashPattern::parse("foo.#.#.#.usd").is_none());
        assert!(HashPattern::parse("foo.usd").is_none());
    }

    #[test]
    fn template_expands_to_explicit_clip_set() {
        use std::collections::HashMap;
        let mut set = HashMap::new();
        set.insert(
            keys::TEMPLATE_ASSET_PATH.to_string(),
            Value::AssetPath("clip.##.usd".into()),
        );
        set.insert(keys::TEMPLATE_START_TIME.to_string(), Value::Double(101.0));
        set.insert(keys::TEMPLATE_END_TIME.to_string(), Value::Double(103.0));
        set.insert(keys::TEMPLATE_STRIDE.to_string(), Value::Double(1.0));

        let parsed = ClipSet::parse_set("default", &set).expect("template set");
        assert_eq!(
            parsed.asset_paths,
            vec![
                "clip.101.usd".to_string(),
                "clip.102.usd".to_string(),
                "clip.103.usd".to_string()
            ],
        );
        assert_eq!(parsed.active, vec![(101.0, 0), (102.0, 1), (103.0, 2)]);
        assert_eq!(parsed.times, knots(&[(101.0, 101.0), (102.0, 102.0), (103.0, 103.0)]));
    }

    #[test]
    fn template_active_offset_shifts_active_times() {
        use std::collections::HashMap;
        let mut set = HashMap::new();
        set.insert(
            keys::TEMPLATE_ASSET_PATH.to_string(),
            Value::AssetPath("c.#.usd".into()),
        );
        set.insert(keys::TEMPLATE_START_TIME.to_string(), Value::Double(0.0));
        set.insert(keys::TEMPLATE_END_TIME.to_string(), Value::Double(2.0));
        set.insert(keys::TEMPLATE_STRIDE.to_string(), Value::Double(1.0));
        set.insert(keys::TEMPLATE_ACTIVE_OFFSET.to_string(), Value::Double(-0.5));

        let parsed = ClipSet::parse_set("default", &set).expect("template set");
        // Active stage times shift by the offset; `times` keeps the clip-time
        // knots plus boundary knots expanded by |offset| at each end.
        assert_eq!(parsed.active, vec![(-0.5, 0), (0.5, 1), (1.5, 2)]);
        assert_eq!(
            parsed.times,
            knots(&[(-0.5, -0.5), (0.0, 0.0), (1.0, 1.0), (2.0, 2.0), (2.5, 2.5)])
        );
    }

    #[test]
    fn template_rejects_invalid_metadata() {
        use std::collections::HashMap;
        let base = |off: f64, stride: f64| {
            let mut set = HashMap::new();
            set.insert(
                keys::TEMPLATE_ASSET_PATH.to_string(),
                Value::AssetPath("c.#.usd".into()),
            );
            set.insert(keys::TEMPLATE_START_TIME.to_string(), Value::Double(0.0));
            set.insert(keys::TEMPLATE_END_TIME.to_string(), Value::Double(2.0));
            set.insert(keys::TEMPLATE_STRIDE.to_string(), Value::Double(stride));
            set.insert(keys::TEMPLATE_ACTIVE_OFFSET.to_string(), Value::Double(off));
            set
        };
        // |activeOffset| > stride is rejected (spec 12.3.4.1.3).
        assert!(ClipSet::parse_set("default", &base(2.0, 1.0)).is_none());
        // Non-positive stride is rejected.
        assert!(ClipSet::parse_set("default", &base(0.0, 0.0)).is_none());
    }

    #[test]
    fn explicit_asset_paths_win_over_template() {
        use std::collections::HashMap;
        let mut set = HashMap::new();
        set.insert(
            keys::ASSET_PATHS.to_string(),
            Value::AssetPathVec(vec!["explicit.usd".into()]),
        );
        set.insert(
            keys::TEMPLATE_ASSET_PATH.to_string(),
            Value::AssetPath("c.#.usd".into()),
        );
        set.insert(keys::TEMPLATE_START_TIME.to_string(), Value::Double(0.0));
        set.insert(keys::TEMPLATE_END_TIME.to_string(), Value::Double(2.0));
        set.insert(keys::TEMPLATE_STRIDE.to_string(), Value::Double(1.0));

        let parsed = ClipSet::parse_set("default", &set).expect("explicit set");
        assert_eq!(parsed.asset_paths, vec!["explicit.usd".to_string()]);
    }

    fn clip_set(active: Vec<(f64, usize)>, times: Vec<gf::Vec2d>) -> ClipSet {
        ClipSet {
            name: "default".into(),
            prim_path: None,
            manifest_asset: None,
            asset_paths: Vec::new(),
            active,
            times,
            interpolate_missing: false,
        }
    }

    #[test]
    fn active_clip_ranges() {
        // active = [(0,0),(1,1),(2,2)] (spec 12.3.4.3 example).
        let cs = clip_set(vec![(0.0, 0), (1.0, 1), (2.0, 2)], vec![]);
        assert_eq!(cs.active_clip(-5.0), Some(0)); // before first → first
        assert_eq!(cs.active_clip(0.0), Some(0));
        assert_eq!(cs.active_clip(1.5), Some(1));
        assert_eq!(cs.active_clip(2.0), Some(2));
        assert_eq!(cs.active_clip(100.0), Some(2)); // after last → last
    }

    #[test]
    fn active_clip_empty() {
        assert_eq!(clip_set(vec![], vec![]).active_clip(0.0), None);
    }

    #[test]
    fn map_times_linear() {
        // times = [(0,1),(1,2),(2,3)] (spec 12.3.4.4 example).
        let cs = clip_set(vec![], knots(&[(0.0, 1.0), (1.0, 2.0), (2.0, 3.0)]));
        assert_eq!(cs.map_stage_to_clip(0.0), 1.0);
        assert_eq!(cs.map_stage_to_clip(1.0), 2.0);
        assert_eq!(cs.map_stage_to_clip(1.5), 2.5); // interpolated
        assert_eq!(cs.map_stage_to_clip(-3.0), 1.0); // clamp low
        assert_eq!(cs.map_stage_to_clip(9.0), 3.0); // clamp high
    }

    #[test]
    fn map_times_identity() {
        // No times authored → stage time passes through.
        assert_eq!(clip_set(vec![], vec![]).map_stage_to_clip(7.5), 7.5);
    }

    #[test]
    fn stage_times_identity() {
        // Two clips, identity timing: each clip's in-clip samples are stage
        // times, clamped to that clip's active interval, plus the boundaries.
        let cs = clip_set(vec![(0.0, 0), (10.0, 1)], vec![]);
        // clip 0 authors {0,5,12} (12 is outside its [0,10) interval); clip 1 {10,15}.
        let times = cs.stage_sample_times(&[vec![0.0, 5.0, 12.0], vec![10.0, 15.0]]);
        assert_eq!(times, vec![0.0, 5.0, 10.0, 15.0]);
    }

    #[test]
    fn stage_times_empty_window_boundary() {
        // An active clip authoring no samples still reports the boundary where it
        // becomes active: clip 1's window opens at stage 10, a value-change point
        // (the active clip switches there), so 10 is reported alongside clip 0's
        // samples.
        let cs = clip_set(vec![(0.0, 0), (10.0, 1)], vec![]);
        let times = cs.stage_sample_times(&[vec![0.0, 5.0], vec![]]);
        assert_eq!(times, vec![0.0, 5.0, 10.0]);
    }

    #[test]
    fn stage_times_linear_timing() {
        // times maps stage→clip as clip = stage/2, so a clip time maps back to
        // stage 2*clip. Boundary 0 and timing knots {0,10} join the mapped
        // sample stage times {0,5,10}.
        let cs = clip_set(vec![(0.0, 0)], knots(&[(0.0, 0.0), (10.0, 5.0)]));
        let times = cs.stage_sample_times(&[vec![0.0, 2.5, 5.0]]);
        assert_eq!(times, vec![0.0, 5.0, 10.0]);
    }

    #[test]
    fn stage_times_before_first_active() {
        // The first clip is active from -∞ (matches active_clip): a sample
        // mapping before the first active entry's stage time is still reported,
        // and that stage time is not a spurious switch boundary.
        let cs = clip_set(vec![(10.0, 0)], vec![]);
        let times = cs.stage_sample_times(&[vec![5.0, 15.0]]);
        assert_eq!(times, vec![5.0, 15.0]);
    }

    #[test]
    fn stage_times_no_active() {
        // No active entries → no clip is scheduled → no sample times.
        assert!(clip_set(vec![], vec![])
            .stage_sample_times(&[vec![0.0, 1.0]])
            .is_empty());
    }

    #[test]
    fn map_times_jump_discontinuity() {
        // times = [(0,0),(10,10),(10,25),(20,35)] (spec 12.3.4.8).
        // [0,10): first clip [0,10); [10,20]: second clip [25,35].
        let cs = clip_set(vec![], knots(&[(0.0, 0.0), (10.0, 10.0), (10.0, 25.0), (20.0, 35.0)]));
        assert_eq!(cs.map_stage_to_clip(5.0), 5.0);
        assert!((cs.map_stage_to_clip(9.999) - 9.999).abs() < 1e-6); // left of jump
        assert_eq!(cs.map_stage_to_clip(10.0), 25.0); // at jump → "at and after"
        assert_eq!(cs.map_stage_to_clip(15.0), 30.0); // second segment
        assert_eq!(cs.map_stage_to_clip(20.0), 35.0);
    }

    #[test]
    fn map_times_initial_jump() {
        // At a duplicated first stage time, the right-hand entry applies
        // exactly at the jump.
        let cs = clip_set(vec![], knots(&[(0.0, 0.0), (0.0, 25.0), (10.0, 35.0)]));
        assert_eq!(cs.map_stage_to_clip(-1.0), 0.0);
        assert_eq!(cs.map_stage_to_clip(0.0), 25.0);
        assert_eq!(cs.map_stage_to_clip(5.0), 30.0);
    }

    #[test]
    fn map_times_looping() {
        // times = [(0,0),(25,25),(25,0),(50,25)] — 25 frames looped twice.
        let cs = clip_set(vec![], knots(&[(0.0, 0.0), (25.0, 25.0), (25.0, 0.0), (50.0, 25.0)]));
        assert_eq!(cs.map_stage_to_clip(20.0), 20.0);
        assert_eq!(cs.map_stage_to_clip(45.0), 20.0); // one loop later → same clip time
    }

    /// Parses a clip set from a real USDA `clips` metadata opinion, mirroring
    /// the spec 12.3.4.1.2.4 example.
    #[test]
    fn parse_explicit_from_usda() {
        use crate::sdf::AbstractData;

        let parsed = crate::usda::parser::Parser::new(
            r#"#usda 1.0
def Xform "Geo" (
    clips = {
        dictionary default = {
            double2[] active = [(0, 0), (1, 1), (2, 2)]
            asset[] assetPaths = [@./quad_1.usda@, @./quad_2.usda@, @./quad_3.usda@]
            asset manifestAssetPath = @./manifest.usda@
            string primPath = "/Geo"
            double2[] times = [(0, 1), (1, 2), (2, 3)]
        }
    }
)
{
}
"#,
        )
        .parse()
        .expect("parse usda");
        let data = sdf::Data::from_specs(parsed);

        let clips = data
            .try_field(&Path::new("/Geo").unwrap(), "clips")
            .expect("try_field")
            .expect("clips authored")
            .into_owned();

        let sets = ClipSet::parse(&clips, None);
        assert_eq!(sets.len(), 1);
        let cs = &sets[0];
        assert_eq!(cs.name, "default");
        assert_eq!(cs.prim_path, Some(Path::new("/Geo").unwrap()));
        assert_eq!(cs.manifest_asset.as_deref(), Some("./manifest.usda"));
        assert_eq!(cs.asset_paths, vec!["./quad_1.usda", "./quad_2.usda", "./quad_3.usda"]);
        assert_eq!(cs.active, vec![(0.0, 0), (1.0, 1), (2.0, 2)]);
        assert_eq!(cs.times, knots(&[(0.0, 1.0), (1.0, 2.0), (2.0, 3.0)]));
    }
}