rust-usd 0.0.4

Rust bindings to OpenUSD (pxr C++): stage open, prim/mesh attrs, variants, sublayer authoring, UsdShade read+write, ArResolver hook.
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
//! Rust bindings to OpenUSD (pxr).
//!
//! v0.0.5 surface:
//! - Stage: open with explicit `InitialLoadSet`, post-open `load`/`unload`,
//!   `prim_at_path`, `open_for_painting` (sublayer authoring), `save_edit_layer`.
//! - Prim tree walk (path, type_name, children, is_mesh, as_mesh).
//! - UsdGeomMesh attrs: points, face vertex counts/indices, normals,
//!   primvars:st (+indices), subdivision scheme, world-space transform.
//! - UsdShade: bound texture paths from a mesh's material.
//! - Variant sets: enumerate, read selection, set/clear selection.
//! - `forge://` URI resolution via [`AssetResolver`] + [`install_forge_resolver`].

use std::path::Path;
use std::sync::{Arc, Mutex};

use cxx::UniquePtr;

#[cxx::bridge(namespace = "rust_usd")]
mod ffi {
    unsafe extern "C++" {
        include!("usd_bridge.h");

        type Stage;
        type Prim;
        type Mesh;
        type VariantSet;
        type Primvar;
        type Material;
        type Shader;

        fn open_stage(path: &str) -> Result<UniquePtr<Stage>>;
        fn open_stage_with_load(path: &str, load_all: bool) -> Result<UniquePtr<Stage>>;
        fn open_for_painting(asset_path: &str, edit_layer_path: &str)
            -> Result<UniquePtr<Stage>>;

        fn copy_prim(prim: &Prim) -> UniquePtr<Prim>;
        fn copy_mesh(mesh: &Mesh) -> UniquePtr<Mesh>;
        fn install_preferred_resolver();
        fn register_plugin_directory(dir: &str);
        fn register_uri_scheme(scheme: &str);
        fn clear_uri_schemes();

        fn pseudo_root(self: &Stage) -> UniquePtr<Prim>;
        fn prim_at_path(self: &Stage, sdf_path: &str) -> UniquePtr<Prim>;
        fn all_meshes(self: &Stage) -> UniquePtr<CxxVector<Mesh>>;
        fn load_path(self: &Stage, sdf_path: &str);
        fn unload_path(self: &Stage, sdf_path: &str);
        fn save_edit_layer(self: &Stage);
        fn edit_layer_path(self: &Stage) -> String;

        fn define_prim(self: &Stage, sdf_path: &str, type_name: &str) -> UniquePtr<Prim>;
        fn create_material(self: &Stage, sdf_path: &str) -> UniquePtr<Material>;
        fn material_at_path(self: &Stage, sdf_path: &str) -> UniquePtr<Material>;

        fn path(self: &Prim) -> String;
        fn type_name(self: &Prim) -> String;
        fn is_mesh(self: &Prim) -> bool;
        fn children(self: &Prim) -> UniquePtr<CxxVector<Prim>>;
        fn as_mesh(self: &Prim) -> UniquePtr<Mesh>;
        fn variant_set_names(self: &Prim) -> UniquePtr<CxxVector<CxxString>>;
        fn get_variant_set(self: &Prim, name: &str) -> UniquePtr<VariantSet>;

        fn name(self: &VariantSet) -> String;
        fn variant_names(self: &VariantSet) -> UniquePtr<CxxVector<CxxString>>;
        fn selection(self: &VariantSet) -> String;
        fn set_selection(self: &VariantSet, variant_name: &str) -> bool;
        fn clear_selection(self: &VariantSet);
        fn has_authored_selection(self: &VariantSet) -> bool;

        fn prim_path(self: &Mesh) -> String;
        fn subdivision_scheme(self: &Mesh) -> String;
        fn points(self: &Mesh) -> UniquePtr<CxxVector<f32>>;
        fn face_vertex_counts(self: &Mesh) -> UniquePtr<CxxVector<i32>>;
        fn face_vertex_indices(self: &Mesh) -> UniquePtr<CxxVector<i32>>;
        fn normals(self: &Mesh) -> UniquePtr<CxxVector<f32>>;
        fn normals_interpolation(self: &Mesh) -> String;
        fn orientation(self: &Mesh) -> String;
        fn st(self: &Mesh) -> UniquePtr<CxxVector<f32>>;
        fn st_indices(self: &Mesh) -> UniquePtr<CxxVector<i32>>;
        fn local_to_world(self: &Mesh) -> UniquePtr<CxxVector<f32>>;
        fn bound_texture_paths(self: &Mesh) -> UniquePtr<CxxVector<CxxString>>;

        fn primvar_names(self: &Mesh) -> UniquePtr<CxxVector<CxxString>>;
        fn primvar(self: &Mesh, name: &str) -> UniquePtr<Primvar>;
        fn create_primvar_float(self: &Mesh, name: &str, values: &[f32], interpolation: &str) -> bool;
        fn create_primvar_int(self: &Mesh, name: &str, values: &[i32], interpolation: &str) -> bool;
        fn create_primvar_vec2f(self: &Mesh, name: &str, values: &[f32], interpolation: &str) -> bool;
        fn create_primvar_vec3f(self: &Mesh, name: &str, values: &[f32], interpolation: &str) -> bool;
        fn create_primvar_color3f(self: &Mesh, name: &str, values: &[f32], interpolation: &str) -> bool;
        fn remove_primvar(self: &Mesh, name: &str) -> bool;

        fn name(self: &Primvar) -> String;
        fn interpolation(self: &Primvar) -> String;
        fn type_name(self: &Primvar) -> String;
        fn has_authored_value(self: &Primvar) -> bool;
        fn is_indexed(self: &Primvar) -> bool;
        fn indices(self: &Primvar) -> UniquePtr<CxxVector<i32>>;
        fn as_float_array(self: &Primvar) -> UniquePtr<CxxVector<f32>>;
        fn as_int_array(self: &Primvar) -> UniquePtr<CxxVector<i32>>;
        fn as_vec2f_array(self: &Primvar) -> UniquePtr<CxxVector<f32>>;
        fn as_vec3f_array(self: &Primvar) -> UniquePtr<CxxVector<f32>>;

        fn bind_material(self: &Mesh, material: &Material) -> bool;

        fn path(self: &Material) -> String;
        fn create_shader(self: &Material, name: &str, shader_id: &str) -> UniquePtr<Shader>;
        fn connect_surface(self: &Material, source: &Shader) -> bool;

        fn path(self: &Shader) -> String;
        fn shader_id(self: &Shader) -> String;
        fn set_input_float(self: &Shader, name: &str, value: f32) -> bool;
        fn set_input_color3f(self: &Shader, name: &str, r: f32, g: f32, b: f32) -> bool;
        fn set_input_asset(self: &Shader, name: &str, asset_path: &str) -> bool;
        fn set_input_token(self: &Shader, name: &str, value: &str) -> bool;
        fn connect_input(self: &Shader, input_name: &str, source: &Shader, output_name: &str) -> bool;
        fn declare_output(self: &Shader, output_name: &str, type_name: &str) -> bool;
    }

    extern "Rust" {
        fn uri_resolve(uri: &str) -> String;
    }
}

#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum InitialLoadSet {
    All,
    None,
}

/// User-supplied resolver for a URI scheme. Implementations must be safe to
/// call from any thread USD uses internally — the resolver is invoked lazily
/// during stage composition, including potentially from worker threads.
///
/// Return `Some(local_path)` to map the URI to a filesystem path, or `None`
/// to signal "no mapping" (USD will then surface a resolution error).
pub trait AssetResolver: Send + Sync {
    fn resolve(&self, uri: &str) -> Option<String>;
}

static URI_RESOLVER: Mutex<Option<Arc<dyn AssetResolver>>> = Mutex::new(None);

/// Install a resolver for one or more URI schemes (e.g. `&["forge"]`,
/// `&["forge", "s3"]`). Pass the URI scheme without `://`. rust-usd's C++
/// side intercepts any path whose scheme matches one of the registered
/// schemes and dispatches it to the trait. Non-matching schemes (including
/// plain file paths) fall through to USD's default resolver behavior.
///
/// Must be called before the first [`Stage::open`] in the process — USD
/// picks its primary resolver on first use and won't switch afterwards.
/// Calling this more than once replaces the resolver and the scheme list.
pub fn install_uri_resolver<R: AssetResolver + 'static>(schemes: &[&str], resolver: R) {
    *URI_RESOLVER.lock().expect("URI_RESOLVER mutex poisoned") = Some(Arc::new(resolver));

    if let Err(e) = ensure_plugin_registered() {
        eprintln!("rust-usd: failed to register resolver plugInfo: {}", e);
        return;
    }

    ffi::clear_uri_schemes();
    for s in schemes {
        ffi::register_uri_scheme(s);
    }
    ffi::install_preferred_resolver();
}

/// Convenience wrapper for the painter's `forge://` use case. Equivalent to
/// `install_uri_resolver(&["forge"], resolver)`.
pub fn install_forge_resolver<R: AssetResolver + 'static>(resolver: R) {
    install_uri_resolver(&["forge"], resolver);
}

fn uri_resolve(uri: &str) -> String {
    let resolver = {
        let guard = URI_RESOLVER.lock().expect("URI_RESOLVER mutex poisoned");
        guard.clone()
    };
    match resolver.and_then(|r| r.resolve(uri)) {
        Some(path) => path,
        None => String::new(),
    }
}

// USD 25's plug registry refuses to instantiate a resolver type unless a
// plugInfo.json claims ownership, even when the TfType is already registered
// via static init. We sidestep that by generating a plugInfo.json at runtime
// with LibraryPath pointing at the executable itself — dlopen of an already
// loaded Mach-O image is a no-op on macOS, and the type is already in the
// type registry.
//
// Written into the OS temp dir under a per-process subdirectory so consumer
// deploy trees stay clean. The directory is short-lived; the OS reaps it on
// reboot. Only fires once per process, gated behind an AtomicBool.
fn ensure_plugin_registered() -> std::io::Result<()> {
    use std::sync::atomic::{AtomicBool, Ordering};
    static REGISTERED: AtomicBool = AtomicBool::new(false);
    if REGISTERED.swap(true, Ordering::AcqRel) {
        return Ok(());
    }

    let exe = std::env::current_exe()?;
    let plugin_dir = std::env::temp_dir().join(format!(
        "rust-usd-resolver-plug-{}",
        std::process::id()
    ));
    std::fs::create_dir_all(&plugin_dir)?;

    let exe_escaped = exe
        .to_string_lossy()
        .replace('\\', "\\\\")
        .replace('"', "\\\"");

    let plug_info = format!(
        r#"{{
  "Plugins": [
    {{
      "Info": {{
        "Types": {{
          "rust_usd::RustUriResolver": {{
            "bases": ["ArDefaultResolver"]
          }}
        }}
      }},
      "Name": "rustUsdUriResolver",
      "LibraryPath": "{}",
      "Type": "library"
    }}
  ]
}}
"#,
        exe_escaped
    );

    std::fs::write(plugin_dir.join("plugInfo.json"), plug_info)?;
    ffi::register_plugin_directory(plugin_dir.to_string_lossy().as_ref());
    Ok(())
}

pub struct Stage {
    inner: UniquePtr<ffi::Stage>,
}

impl Stage {
    /// Open a stage. Accepts any `AsRef<Path>` — string literals, `Path`,
    /// `PathBuf`, etc. The path is converted to a UTF-8 string at the FFI
    /// boundary; non-UTF-8 paths are passed lossily.
    pub fn open(path: impl AsRef<Path>) -> Result<Self, cxx::Exception> {
        let _ = ensure_plugin_registered();
        let path_str = path.as_ref().to_string_lossy();
        Ok(Self {
            inner: ffi::open_stage(&path_str)?,
        })
    }

    pub fn open_with_load_set(
        path: impl AsRef<Path>,
        load: InitialLoadSet,
    ) -> Result<Self, cxx::Exception> {
        let _ = ensure_plugin_registered();
        let load_all = matches!(load, InitialLoadSet::All);
        let path_str = path.as_ref().to_string_lossy();
        Ok(Self {
            inner: ffi::open_stage_with_load(&path_str, load_all)?,
        })
    }

    /// Open a stage rooted at `edit_layer_path`, with `asset_path` mounted as
    /// a sublayer. Edits are directed to `edit_layer_path` so the asset file
    /// is never mutated. If `edit_layer_path` doesn't exist, a new layer is
    /// created (in-memory until [`Stage::save_edit_layer`] is called).
    pub fn open_for_painting(
        asset_path: impl AsRef<Path>,
        edit_layer_path: impl AsRef<Path>,
    ) -> Result<Self, cxx::Exception> {
        let _ = ensure_plugin_registered();
        let asset = asset_path.as_ref().to_string_lossy();
        let edits = edit_layer_path.as_ref().to_string_lossy();
        Ok(Self {
            inner: ffi::open_for_painting(&asset, &edits)?,
        })
    }

    pub fn load(&self, sdf_path: &str) {
        self.inner.load_path(sdf_path);
    }

    pub fn unload(&self, sdf_path: &str) {
        self.inner.unload_path(sdf_path);
    }

    pub fn pseudo_root(&self) -> Prim {
        Prim {
            inner: self.inner.pseudo_root(),
        }
    }

    pub fn prim_at_path(&self, sdf_path: &str) -> Option<Prim> {
        let p = self.inner.prim_at_path(sdf_path);
        if p.is_null() {
            None
        } else {
            Some(Prim { inner: p })
        }
    }

    pub fn meshes(&self) -> Vec<Mesh> {
        self.inner
            .all_meshes()
            .iter()
            .map(|m| Mesh {
                inner: ffi::copy_mesh(m),
            })
            .collect()
    }

    /// Persist the current edit target's layer to its on-disk identifier.
    /// No-op when the edit target is anonymous (in-memory only).
    pub fn save_edit_layer(&self) {
        self.inner.save_edit_layer();
    }

    pub fn edit_layer_path(&self) -> String {
        self.inner.edit_layer_path()
    }

    /// Defines a typed prim at `sdf_path`. Idempotent if the prim already
    /// exists with a matching type. Useful for explicitly authoring a
    /// `Scope` parent before [`create_material`].
    pub fn define_prim(&self, sdf_path: &str, type_name: &str) -> Option<Prim> {
        let p = self.inner.define_prim(sdf_path, type_name);
        if p.is_null() {
            None
        } else {
            Some(Prim { inner: p })
        }
    }

    pub fn create_material(&self, sdf_path: &str) -> Option<Material> {
        let m = self.inner.create_material(sdf_path);
        if m.is_null() {
            None
        } else {
            Some(Material { inner: m })
        }
    }

    pub fn material_at_path(&self, sdf_path: &str) -> Option<Material> {
        let m = self.inner.material_at_path(sdf_path);
        if m.is_null() {
            None
        } else {
            Some(Material { inner: m })
        }
    }
}

pub struct Prim {
    inner: UniquePtr<ffi::Prim>,
}

impl Prim {
    pub fn path(&self) -> String {
        self.inner.path()
    }

    pub fn type_name(&self) -> String {
        self.inner.type_name()
    }

    pub fn is_mesh(&self) -> bool {
        self.inner.is_mesh()
    }

    pub fn as_mesh(&self) -> Option<Mesh> {
        let m = self.inner.as_mesh();
        if m.is_null() {
            None
        } else {
            Some(Mesh { inner: m })
        }
    }

    pub fn children(&self) -> Vec<Prim> {
        self.inner
            .children()
            .iter()
            .map(|p| Prim {
                inner: ffi::copy_prim(p),
            })
            .collect()
    }

    pub fn variant_set_names(&self) -> Vec<String> {
        self.inner
            .variant_set_names()
            .iter()
            .map(|s| s.to_string())
            .collect()
    }

    pub fn variant_set(&self, name: &str) -> Option<VariantSet> {
        let v = self.inner.get_variant_set(name);
        if v.is_null() {
            None
        } else {
            Some(VariantSet { inner: v })
        }
    }
}

pub struct VariantSet {
    inner: UniquePtr<ffi::VariantSet>,
}

impl VariantSet {
    pub fn name(&self) -> String {
        self.inner.name()
    }

    pub fn variants(&self) -> Vec<String> {
        self.inner
            .variant_names()
            .iter()
            .map(|s| s.to_string())
            .collect()
    }

    /// Returns the currently composed selection, or `None` if no opinion is
    /// authored anywhere in the layer stack.
    pub fn selection(&self) -> Option<String> {
        let s = self.inner.selection();
        if s.is_empty() {
            None
        } else {
            Some(s)
        }
    }

    /// Authors a selection in the current edit target. Returns `false` if the
    /// variant name doesn't exist in this set.
    pub fn set_selection(&self, variant: &str) -> bool {
        self.inner.set_selection(variant)
    }

    pub fn clear_selection(&self) {
        self.inner.clear_selection();
    }

    pub fn has_authored_selection(&self) -> bool {
        self.inner.has_authored_selection()
    }
}

pub struct Mesh {
    inner: UniquePtr<ffi::Mesh>,
}

impl Mesh {
    pub fn prim_path(&self) -> String {
        self.inner.prim_path()
    }

    pub fn subdivision_scheme(&self) -> String {
        self.inner.subdivision_scheme()
    }

    /// Flattened `[x, y, z, x, y, z, ...]`. Most consumers want
    /// [`Mesh::points_xyz`] which returns `Vec<[f32; 3]>` and skips the
    /// chunk-by-3 step.
    pub fn points(&self) -> Vec<f32> {
        cxx_to_vec(self.inner.points())
    }

    /// Points as `[x, y, z]` triples.
    pub fn points_xyz(&self) -> Vec<[f32; 3]> {
        self.points()
            .chunks_exact(3)
            .map(|c| [c[0], c[1], c[2]])
            .collect()
    }

    /// Per-face vertex counts. Returns `i32` for symmetry with USD's wire
    /// type; if you only consume them as positive counts, prefer
    /// [`Mesh::face_vertex_counts_u32`].
    pub fn face_vertex_counts(&self) -> Vec<i32> {
        cxx_to_vec(self.inner.face_vertex_counts())
    }

    /// Per-face vertex counts as `u32` (USD treats these as unsigned).
    pub fn face_vertex_counts_u32(&self) -> Vec<u32> {
        self.face_vertex_counts()
            .into_iter()
            .map(|v| v as u32)
            .collect()
    }

    pub fn face_vertex_indices(&self) -> Vec<i32> {
        cxx_to_vec(self.inner.face_vertex_indices())
    }

    /// Face vertex indices as `u32`. Indices are non-negative in well-formed
    /// USD assets.
    pub fn face_vertex_indices_u32(&self) -> Vec<u32> {
        self.face_vertex_indices()
            .into_iter()
            .map(|v| v as u32)
            .collect()
    }

    pub fn normals(&self) -> Vec<f32> {
        cxx_to_vec(self.inner.normals())
    }

    /// Normals as `[x, y, z]` triples.
    pub fn normals_xyz(&self) -> Vec<[f32; 3]> {
        self.normals()
            .chunks_exact(3)
            .map(|c| [c[0], c[1], c[2]])
            .collect()
    }

    /// `"vertex"` / `"faceVarying"` / `"varying"` etc — load-bearing for
    /// downstream consumers that need to know whether the flat normals
    /// array is per-vertex or per-face-vertex.
    pub fn normals_interpolation(&self) -> String {
        self.inner.normals_interpolation()
    }

    /// `"rightHanded"` (default; CCW face winding) or `"leftHanded"` (CW).
    /// Renderers that back-face cull based on winding (wgpu's default
    /// `front_face = Ccw`) need to flip the index order for leftHanded
    /// meshes, otherwise the visible side gets culled.
    pub fn orientation(&self) -> String {
        self.inner.orientation()
    }

    pub fn st(&self) -> Vec<f32> {
        cxx_to_vec(self.inner.st())
    }

    /// UV coordinates as `[u, v]` pairs.
    pub fn st_uv(&self) -> Vec<[f32; 2]> {
        self.st()
            .chunks_exact(2)
            .map(|c| [c[0], c[1]])
            .collect()
    }

    /// Empty if `primvars:st` is not indexed.
    pub fn st_indices(&self) -> Vec<i32> {
        cxx_to_vec(self.inner.st_indices())
    }

    /// Same as [`Mesh::st_indices`] but `u32`. Indices are non-negative.
    pub fn st_indices_u32(&self) -> Vec<u32> {
        self.st_indices().into_iter().map(|v| v as u32).collect()
    }

    pub fn local_to_world(&self) -> [[f32; 4]; 4] {
        let v = self.inner.local_to_world();
        let mut m = [[0.0f32; 4]; 4];
        for r in 0..4 {
            for c in 0..4 {
                m[r][c] = *v.get(r * 4 + c).expect("local_to_world returned <16 floats");
            }
        }
        m
    }

    pub fn bound_texture_paths(&self) -> Vec<String> {
        self.inner
            .bound_texture_paths()
            .iter()
            .map(|s| s.to_string())
            .collect()
    }

    /// All primvar names on this mesh (without the `"primvars:"` prefix).
    pub fn primvar_names(&self) -> Vec<String> {
        self.inner
            .primvar_names()
            .iter()
            .map(|s| s.to_string())
            .collect()
    }

    pub fn primvar(&self, name: &str) -> Option<Primvar> {
        let p = self.inner.primvar(name);
        if p.is_null() {
            None
        } else {
            Some(Primvar { inner: p })
        }
    }

    /// Author `primvars:<name>` of type `float[]`. Writes go to the stage's
    /// current edit target; pair with [`Stage::open_for_painting`].
    pub fn create_primvar_float(&self, name: &str, values: &[f32], interpolation: &str) -> bool {
        self.inner.create_primvar_float(name, values, interpolation)
    }

    pub fn create_primvar_int(&self, name: &str, values: &[i32], interpolation: &str) -> bool {
        self.inner.create_primvar_int(name, values, interpolation)
    }

    /// Author a `float2[]` primvar. `values.len()` must be a multiple of 2.
    pub fn create_primvar_vec2f(&self, name: &str, values: &[f32], interpolation: &str) -> bool {
        self.inner.create_primvar_vec2f(name, values, interpolation)
    }

    /// Author a `float3[]` primvar. `values.len()` must be a multiple of 3.
    pub fn create_primvar_vec3f(&self, name: &str, values: &[f32], interpolation: &str) -> bool {
        self.inner.create_primvar_vec3f(name, values, interpolation)
    }

    /// Author a `color3f[]` primvar. `values.len()` must be a multiple of 3.
    pub fn create_primvar_color3f(&self, name: &str, values: &[f32], interpolation: &str) -> bool {
        self.inner.create_primvar_color3f(name, values, interpolation)
    }

    pub fn remove_primvar(&self, name: &str) -> bool {
        self.inner.remove_primvar(name)
    }

    /// Bind this mesh to a material via UsdShadeMaterialBindingAPI.
    pub fn bind_material(&self, material: &Material) -> bool {
        self.inner.bind_material(&material.inner)
    }
}

pub struct Material {
    inner: UniquePtr<ffi::Material>,
}

impl Material {
    pub fn path(&self) -> String {
        self.inner.path()
    }

    /// Define a child shader under this material with `info:id = shader_id`
    /// (e.g. `"UsdPreviewSurface"`, `"UsdUVTexture"`, `"UsdPrimvarReader_float2"`).
    pub fn create_shader(&self, name: &str, shader_id: &str) -> Option<Shader> {
        let s = self.inner.create_shader(name, shader_id);
        if s.is_null() {
            None
        } else {
            Some(Shader { inner: s })
        }
    }

    /// Wire this material's `outputs:surface` to `source.outputs:surface`.
    pub fn connect_surface(&self, source: &Shader) -> bool {
        self.inner.connect_surface(&source.inner)
    }
}

pub struct Shader {
    inner: UniquePtr<ffi::Shader>,
}

impl Shader {
    pub fn path(&self) -> String {
        self.inner.path()
    }

    pub fn shader_id(&self) -> String {
        self.inner.shader_id()
    }

    pub fn set_input_float(&self, name: &str, value: f32) -> bool {
        self.inner.set_input_float(name, value)
    }

    pub fn set_input_color3f(&self, name: &str, r: f32, g: f32, b: f32) -> bool {
        self.inner.set_input_color3f(name, r, g, b)
    }

    /// Set an asset-typed input (e.g. `inputs:file = @./tex.<UDIM>.png@`).
    pub fn set_input_asset(&self, name: &str, asset_path: &str) -> bool {
        self.inner.set_input_asset(name, asset_path)
    }

    pub fn set_input_token(&self, name: &str, value: &str) -> bool {
        self.inner.set_input_token(name, value)
    }

    /// Connect `inputs:<input_name>` on this shader to
    /// `source.outputs:<output_name>`. The input is auto-created as `color3f`
    /// if it didn't already exist — for non-color3f inputs, declare with
    /// `set_input_*` first.
    pub fn connect_input(&self, input_name: &str, source: &Shader, output_name: &str) -> bool {
        self.inner
            .connect_input(input_name, &source.inner, output_name)
    }

    /// Declare an output. `type_name` accepts: `"float"`, `"float2"`,
    /// `"float3"`, `"color3f"`, `"asset"`, `"token"`, `"int"`, `"string"`.
    pub fn declare_output(&self, output_name: &str, type_name: &str) -> bool {
        self.inner.declare_output(output_name, type_name)
    }
}

pub struct Primvar {
    inner: UniquePtr<ffi::Primvar>,
}

impl Primvar {
    pub fn name(&self) -> String {
        self.inner.name()
    }

    pub fn interpolation(&self) -> String {
        self.inner.interpolation()
    }

    /// Type token, e.g. `"float[]"`, `"float3[]"`, `"color3f[]"`.
    pub fn type_name(&self) -> String {
        self.inner.type_name()
    }

    pub fn has_authored_value(&self) -> bool {
        self.inner.has_authored_value()
    }

    /// True if this primvar has authored indices (e.g. `primvars:st:indices`
    /// alongside `primvars:st`).
    pub fn is_indexed(&self) -> bool {
        self.inner.is_indexed()
    }

    /// Authored indices for this primvar, or empty if it isn't indexed.
    /// USD always stores these as `int[]`; cast as needed.
    pub fn indices(&self) -> Vec<i32> {
        cxx_to_vec(self.inner.indices())
    }

    /// Returns `Vec<f32>` if this primvar's type is `float[]`, otherwise empty.
    pub fn as_float_array(&self) -> Vec<f32> {
        cxx_to_vec(self.inner.as_float_array())
    }

    pub fn as_int_array(&self) -> Vec<i32> {
        cxx_to_vec(self.inner.as_int_array())
    }

    /// Flattened `[u, v, u, v, ...]` if type is `float2[]`, else empty.
    pub fn as_vec2f_array(&self) -> Vec<f32> {
        cxx_to_vec(self.inner.as_vec2f_array())
    }

    /// Flattened `[x, y, z, ...]` if type is `float3[]` or `color3f[]`, else empty.
    pub fn as_vec3f_array(&self) -> Vec<f32> {
        cxx_to_vec(self.inner.as_vec3f_array())
    }
}

fn cxx_to_vec<T: cxx::vector::VectorElement + Copy>(v: UniquePtr<cxx::CxxVector<T>>) -> Vec<T> {
    v.iter().copied().collect()
}