openusd 0.4.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
//! Composition compliance tests.
//!
//! Each test opens a scene via `Stage::open` and validates the composed result
//! against the `pcp.json` baseline from the vendor test suite.

use std::path::Path;

use openusd::{sdf, usd};

const ASSETS: &str = "vendor/core-spec-supplemental-release_dec2025/composition/tests/assets";

/// JSON schema for loading pcp.json baselines.
mod schema {
    use std::collections::HashMap;

    #[derive(serde::Deserialize)]
    #[serde(rename_all = "PascalCase")]
    pub struct Baseline {
        pub entry: String,
        #[serde(default)]
        pub composing: HashMap<String, PrimData>,
        #[serde(default)]
        pub errors: Vec<String>,
    }

    #[derive(serde::Deserialize, Debug)]
    pub struct PrimData {
        #[serde(default, rename = "Child names")]
        pub child_names: Vec<String>,
        #[serde(default, rename = "Property names")]
        pub property_names: Vec<String>,
    }
}

#[derive(Clone, Copy)]
enum Format {
    Text,
    Binary,
}

fn run(name: &str, format: Format) {
    let test_dir = Path::new(ASSETS).join(name);
    let baseline_path = test_dir.join("pcp.json");
    let json =
        std::fs::read_to_string(&baseline_path).unwrap_or_else(|e| panic!("read {}: {e}", baseline_path.display()));
    let baseline: schema::Baseline = serde_json::from_str(&json).expect("parse pcp.json");

    // Skip error test cases — they test failure modes we don't validate yet.
    if !baseline.errors.is_empty() {
        return;
    }

    // Skip if no composing data.
    if baseline.composing.is_empty() {
        return;
    }

    let entry = match format {
        Format::Text => test_dir.join("usda").join(&baseline.entry),
        Format::Binary => test_dir.join(&baseline.entry),
    };

    if !entry.exists() {
        return;
    }

    let stage = usd::Stage::builder()
        .on_error(|_| Ok(()))
        .open(entry.to_str().unwrap())
        .unwrap();

    // Collect every prim, including inactive/class/over prims, so the PCP
    // baselines can validate composition independent of stage traversal policy.
    let mut prims = Vec::new();
    stage.traverse_all(|path| prims.push(path.to_string())).unwrap();

    let mut failures = Vec::new();

    for (prim_path, expected) in &baseline.composing {
        // Check prim exists.
        if !prims.iter().any(|p| p == prim_path) {
            failures.push(format!("missing prim: {prim_path}"));
            continue;
        }

        // Check child names.
        for child in &expected.child_names {
            let child_path = format!("{prim_path}/{child}");
            if !prims.iter().any(|p| p == &child_path) {
                failures.push(format!("missing child: {child_path}"));
            }
        }

        // Check property names.
        for prop in &expected.property_names {
            let prop_path = format!("{prim_path}.{prop}");
            if !stage.has_spec(sdf::path(&prop_path).unwrap()).unwrap_or(false) {
                failures.push(format!("missing property: {prop_path}"));
            }
        }
    }

    assert!(
        failures.is_empty(),
        "composition test {name} ({format}) failed:\n  {}",
        failures.join("\n  "),
        format = match format {
            Format::Text => "text",
            Format::Binary => "binary",
        },
    );
}

macro_rules! composition_tests {
    ($($name:ident),* $(,)?) => {
        composition_tests!(@expand $($name),*);
    };
    (@expand $($name:ident),*) => {
        $(
            composition_tests!(@one $name);
        )*
    };
    (@one $name:ident) => {
        #[cfg(test)]
        #[allow(non_snake_case)]
        mod $name {
            use super::*;
            #[test]
            fn text() { run(stringify!($name), Format::Text); }
            #[test]
            fn binary() { run(stringify!($name), Format::Binary); }
        }
    };
}

composition_tests! {
    BasicAncestralReference_root,
    BasicDuplicateSublayer_root,
    BasicInherits_root,
    BasicInstancing_root,
    BasicInstancingAndNestedInstances_root,
    BasicInstancingAndVariants_root,
    BasicListEditing_root,
    BasicListEditingWithInherits_root,
    BasicLocalAndGlobalClassCombination_root,
    BasicNestedPayload_root,
    BasicNestedVariants_root,
    BasicNestedVariantsWithSameName_root,
    BasicOwner_root,
    BasicPayload_root,
    BasicPayloadDiamond_root,
    BasicReference_session,
    BasicReferenceAndClass_root,
    BasicReferenceAndClassDiamond_root,
    BasicReferenceDiamond_root,
    BasicRelocateToAnimInterface_root,
    BasicRelocateToAnimInterfaceAsNewRootPrim_root,
    BasicSpecializes_root,
    BasicSpecializesAndInherits_root,
    BasicSpecializesAndReferences_root,
    BasicSpecializesAndVariants_root,
    BasicTimeOffset_root,
    BasicVariantWithConnections_root,
    BasicVariantWithReference_root,
    bug69932_root,
    bug74847_root,
    bug92827_root,
    case1_root,
    ElidedAncestralRelocates_root,
    ErrorArcCycle_root,
    ErrorConnectionPermissionDenied_root,
    ErrorInconsistentProperties_root,
    ErrorInvalidAuthoredRelocates_root,
    ErrorInvalidConflictingRelocates_root,
    ErrorInvalidInstanceTargetPath_root,
    ErrorInvalidPayload_root,
    ErrorInvalidPreRelocateTargetPath_root,
    ErrorInvalidReferenceToRelocationSource_root,
    ErrorInvalidTargetPath_root,
    ErrorOpinionAtRelocationSource_root,
    ErrorOwner_root,
    ErrorPermissionDenied_root,
    ErrorRelocateWithVariantSelection_root,
    ErrorSublayerCycle_root,
    ExpressionsInPayloads_root,
    ExpressionsInReferences_root,
    ImpliedAndAncestralInherits_ComplexEvaluation_root,
    ImpliedAndAncestralInherits_root,
    PayloadsAndAncestralArcs_root,
    PayloadsAndAncestralArcs2_root,
    PayloadsAndAncestralArcs3_root,
    ReferenceListOpsWithOffsets_root,
    RelativePathPayloads_root,
    RelativePathReferences_root,
    RelocatePrimsWithSameName_root,
    RelocateToNone_root,
    SpecializesAndAncestralArcs_root,
    SpecializesAndAncestralArcs2_root,
    SpecializesAndAncestralArcs3_root,
    SpecializesAndAncestralArcs4_root,
    SpecializesAndAncestralArcs5_root,
    SpecializesAndVariants_root,
    SpecializesAndVariants2_root,
    SpecializesAndVariants3_root,
    SpecializesAndVariants4_root,
    SubrootInheritsAndVariants_root,
    SubrootReferenceAndClasses_root,
    SubrootReferenceAndRelocates_root,
    SubrootReferenceAndVariants_root,
    SubrootReferenceAndVariants2_root,
    SubrootReferenceNonCycle_root,
    TimeCodesPerSecond_root,
    TimeCodesPerSecond_root_12fps,
    TimeCodesPerSecond_root_24tcps_12fps,
    TimeCodesPerSecond_root_48tcps,
    TimeCodesPerSecond_session,
    TimeCodesPerSecond_session_24fps,
    TimeCodesPerSecond_session_48tcps,
    TrickyClassHierarchy_root,
    TrickyConnectionToRelocatedAttribute_root,
    TrickyInheritsAndRelocates_root,
    TrickyInheritsAndRelocates2_root,
    TrickyInheritsAndRelocates3_root,
    TrickyInheritsAndRelocates4_root,
    TrickyInheritsAndRelocates5_root,
    TrickyInheritsAndRelocatesToNewRootPrim_root,
    TrickyInheritsInVariants_root,
    TrickyInheritsInVariants2_root,
    TrickyListEditedTargetPaths_root,
    TrickyLocalClassHierarchyWithRelocates_root,
    TrickyMultipleRelocations_root,
    TrickyMultipleRelocations2_root,
    TrickyMultipleRelocations3_root,
    TrickyMultipleRelocations4_root,
    TrickyMultipleRelocations5_root,
    TrickyMultipleRelocationsAndClasses_root,
    TrickyMultipleRelocationsAndClasses2_root,
    TrickyNestedClasses_root,
    TrickyNestedClasses2_root,
    TrickyNestedClasses3_root,
    TrickyNestedClasses4_root,
    TrickyNestedSpecializes_root,
    TrickyNestedSpecializes2_root,
    TrickyNestedVariants_root,
    TrickyNonLocalVariantSelection_root,
    TrickyRelocatedTargetInVariant_root,
    TrickyRelocationOfPrimFromPayload_root,
    TrickyRelocationOfPrimFromVariant_root,
    TrickyRelocationSquatter_root,
    TrickySpecializesAndInherits_root,
    TrickySpecializesAndInherits2_root,
    TrickySpecializesAndInherits3_root,
    TrickySpecializesAndRelocates_root,
    TrickySpookyInherits_root,
    TrickySpookyInheritsInSymmetricArmRig_root,
    TrickySpookyInheritsInSymmetricBrowRig_root,
    TrickySpookyVariantSelection_root,
    TrickySpookyVariantSelectionInClass_root,
    TrickyVariantAncestralSelection_root,
    TrickyVariantIndependentSelection_root,
    TrickyVariantInPayload_root,
    TrickyVariantOverrideOfLocalClass_root,
    TrickyVariantOverrideOfRelocatedPrim_root,
    TrickyVariantSelectionInVariant_root,
    TrickyVariantSelectionInVariant2_root,
    TrickyVariantWeakerSelection_root,
    TrickyVariantWeakerSelection2_root,
    TrickyVariantWeakerSelection3_root,
    TrickyVariantWeakerSelection4_root,
    TypicalReferenceToChargroup_root,
    TypicalReferenceToChargroupWithRename_root,
    TypicalReferenceToRiggedModel_root,
    VariantSpecializesAndReference_root,
    VariantSpecializesAndReferenceSurprisingBehavior_root,
}

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

    fn open_fixture() -> usd::Stage {
        usd::Stage::open("fixtures/reorder.usda").expect("open reorder fixture")
    }

    #[test]
    fn prim_order_reorders_named_children() {
        let stage = open_fixture();
        let children = stage.prim_children(sdf::path("/Root").unwrap()).unwrap();
        assert_eq!(children, vec!["C", "B", "A", "D"]);
    }

    #[test]
    fn property_order_reorders_named_properties() {
        let stage = open_fixture();
        let props = stage.prim_properties(sdf::path("/Props").unwrap()).unwrap();
        assert_eq!(props, vec!["y", "x", "z"]);
    }
}

#[cfg(test)]
mod value_resolution {
    use std::collections::HashMap;

    use super::*;
    use openusd::sdf::{FieldKey, Specifier, Value, Variability};

    fn open_fixture() -> usd::Stage {
        usd::Stage::open("fixtures/value_resolution.usda").expect("open value_resolution fixture")
    }

    fn dictionary<'a>(dict: &'a HashMap<String, Value>, key: &str) -> &'a HashMap<String, Value> {
        match dict.get(key) {
            Some(Value::Dictionary(value)) => value,
            other => panic!("expected dictionary at {key:?}, got {other:?}"),
        }
    }

    fn string<'a>(dict: &'a HashMap<String, Value>, key: &str) -> &'a str {
        match dict.get(key) {
            Some(Value::String(value) | Value::Token(value)) => value,
            other => panic!("expected string/token at {key:?}, got {other:?}"),
        }
    }

    #[test]
    fn specifier_inherit_only_resolves_to_class() {
        // Local `over` opinion plus an inherit from a `class`. With strongest-
        // wins this would be `over`; per spec 12.2.1 it must be `class`.
        let stage = open_fixture();
        let value: Option<Value> = stage
            .field(sdf::path("/InheritOnly").unwrap(), FieldKey::Specifier)
            .unwrap();
        assert_eq!(value, Some(Value::Specifier(Specifier::Class)));
    }

    #[test]
    fn specifier_all_over_resolves_to_over() {
        let stage = open_fixture();
        let value: Option<Value> = stage
            .field(sdf::path("/AllOver").unwrap(), FieldKey::Specifier)
            .unwrap();
        assert_eq!(value, Some(Value::Specifier(Specifier::Over)));
    }

    #[test]
    fn specifier_def_resolves_to_def() {
        let stage = open_fixture();
        let value: Option<Value> = stage
            .field(sdf::path("/DefPrim").unwrap(), FieldKey::Specifier)
            .unwrap();
        assert_eq!(value, Some(Value::Specifier(Specifier::Def)));
    }

    #[test]
    fn variability_weakest_opinion_wins() {
        // The weak sublayer authors `uniform` while the strong layer omits the
        // field. Per spec 12.2.3 the resolved variability is the weakest
        // authored opinion (`uniform`).
        let stage = open_fixture();
        let value: Option<Value> = stage
            .field(sdf::path("/VarTest.attr").unwrap(), FieldKey::Variability)
            .unwrap();
        assert_eq!(value, Some(Value::Variability(Variability::Uniform)));
    }

    #[test]
    fn custom_any_true() {
        // Only the weak sublayer authors `custom`. Per spec 12.2.4 the
        // resolved value is `true` because *any* opinion in the stack is true.
        let stage = open_fixture();
        let value: Option<Value> = stage
            .field(sdf::path("/CustomTest.attr").unwrap(), FieldKey::Custom)
            .unwrap();
        assert_eq!(value, Some(Value::Bool(true)));
    }

    #[test]
    fn dictionary_values_compose_recursively() {
        let stage = open_fixture();
        let value: Option<Value> = stage
            .field(sdf::path("/DictTest").unwrap(), FieldKey::CustomData)
            .unwrap();
        let Some(Value::Dictionary(dict)) = value else {
            panic!("customData should resolve to a dictionary");
        };

        assert_eq!(string(&dict, "strongOnly"), "strong");
        assert_eq!(string(&dict, "weakOnly"), "weak");
        assert_eq!(string(&dict, "strongOver"), "strong");

        let nested = dictionary(&dict, "nested");
        assert_eq!(string(nested, "strongNested"), "strong");
        assert_eq!(string(nested, "weakNested"), "weak");

        let deep = dictionary(nested, "deep");
        assert_eq!(string(deep, "conflict"), "strong");
        assert_eq!(string(deep, "strongDeep"), "strong");
        assert_eq!(string(deep, "weakDeep"), "weak");

        assert_eq!(string(&dict, "strongScalarWins"), "strong-scalar");
        let strong_dict = dictionary(&dict, "strongDictWins");
        assert_eq!(string(strong_dict, "strongNested"), "strong");
    }

    #[test]
    fn layer_metadata_dictionary_uses_root_layer_only() {
        let stage = open_fixture();
        let value: Option<Value> = stage.field(sdf::Path::abs_root(), FieldKey::CustomLayerData).unwrap();
        let Some(Value::Dictionary(dict)) = value else {
            panic!("customLayerData should resolve to a dictionary");
        };

        assert_eq!(string(&dict, "rootOnly"), "root");
        assert!(!dict.contains_key("weakOnly"));

        let nested = dictionary(&dict, "nested");
        assert_eq!(string(nested, "rootNested"), "root");
        assert!(!nested.contains_key("weakNested"));
    }
}