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
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
//! Curve / patch / points / tet-mesh / point-instancer authoring.
//!
//! Covers `UsdGeomBasisCurves`, `UsdGeomNurbsCurves`,
//! `UsdGeomNurbsPatch`, `UsdGeomHermiteCurves`, `UsdGeomPoints`,
//! `UsdGeomTetMesh`, and `UsdGeomPointInstancer`. Each helper
//! authors a typed prim and exposes chainable setters for the
//! attribute set documented in `usdGeom/schema.usda`.

use anyhow::Result;

use crate::sdf::Path;
use crate::usd::{Prim, Stage};

use crate::schemas::geom::tokens::{
    A_ACCELERATIONS, A_ANGULAR_VELOCITIES, A_BASIS, A_CURVE_VERTEX_COUNTS, A_IDS, A_INVISIBLE_IDS, A_KNOTS, A_ORDER,
    A_ORIENTATIONS, A_POINTS, A_POSITIONS, A_PROTO_INDICES, A_RANGES, A_SCALES, A_TANGENTS, A_TET_VERTEX_INDICES,
    A_TYPE, A_U_FORM, A_U_KNOTS, A_U_ORDER, A_U_RANGE, A_U_VERTEX_COUNT, A_VELOCITIES, A_V_FORM, A_V_KNOTS, A_V_ORDER,
    A_V_RANGE, A_V_VERTEX_COUNT, A_WIDTHS, A_WRAP, REL_PROTOTYPES, T_BASIS_CURVES, T_HERMITE_CURVES, T_NURBS_CURVES,
    T_NURBS_PATCH, T_POINTS, T_POINT_INSTANCER, T_TET_MESH,
};

use super::common::{
    author_double_array, author_int64_array, author_int_vec, author_point3f_array, author_primvar, author_quatf_array,
    author_rel_targets, author_token, author_vec3f_array,
};
use crate::schemas::geom::types::Interpolation;
use crate::sdf::{Value, Variability};

// ── BasisCurves ────────────────────────────────────────────────────

pub fn define_basis_curves<'s>(stage: &'s Stage, path: impl Into<Path>) -> Result<BasisCurvesAuthor<'s>> {
    let prim = stage.define_prim(path)?.set_type_name(T_BASIS_CURVES)?;
    Ok(BasisCurvesAuthor { prim })
}

pub struct BasisCurvesAuthor<'s> {
    prim: Prim<'s>,
}

impl<'s> BasisCurvesAuthor<'s> {
    pub fn into_prim(self) -> Prim<'s> {
        self.prim
    }
    pub fn set_points(self, points: Vec<[f32; 3]>) -> Result<Self> {
        author_point3f_array(self.prim.stage(), self.prim.path(), A_POINTS, points)?;
        Ok(self)
    }
    pub fn set_curve_vertex_counts(self, counts: Vec<i32>) -> Result<Self> {
        author_int_vec(self.prim.stage(), self.prim.path(), A_CURVE_VERTEX_COUNTS, counts)?;
        Ok(self)
    }
    /// Set `type` (`linear` / `cubic`).
    pub fn set_curve_type(self, type_name: impl Into<String>) -> Result<Self> {
        author_token(self.prim.stage(), self.prim.path(), A_TYPE, type_name)?;
        Ok(self)
    }
    /// Set `basis` (`bezier` / `bspline` / `catmullRom`).
    pub fn set_basis(self, basis: impl Into<String>) -> Result<Self> {
        author_token(self.prim.stage(), self.prim.path(), A_BASIS, basis)?;
        Ok(self)
    }
    /// Set `wrap` (`nonperiodic` / `periodic` / `pinned`).
    pub fn set_wrap(self, wrap: impl Into<String>) -> Result<Self> {
        author_token(self.prim.stage(), self.prim.path(), A_WRAP, wrap)?;
        Ok(self)
    }
    /// Set `widths` along the curve. `interpolation` is required: Pixar's
    /// reference treats `widths` on a curve as primvar-like with its own
    /// interpolation (typically `Vertex` or `Varying`); leaving it unauthored
    /// makes external consumers fall back to `constant` and lose all but the
    /// first sample.
    pub fn set_widths(self, widths: Vec<f32>, interpolation: Interpolation) -> Result<Self> {
        author_primvar(
            self.prim.stage(),
            self.prim.path(),
            A_WIDTHS,
            "float[]",
            Value::FloatVec(widths),
            interpolation,
        )?;
        Ok(self)
    }
}

// ── NurbsCurves ────────────────────────────────────────────────────

pub fn define_nurbs_curves<'s>(stage: &'s Stage, path: impl Into<Path>) -> Result<NurbsCurvesAuthor<'s>> {
    let prim = stage.define_prim(path)?.set_type_name(T_NURBS_CURVES)?;
    Ok(NurbsCurvesAuthor { prim })
}

pub struct NurbsCurvesAuthor<'s> {
    prim: Prim<'s>,
}

impl<'s> NurbsCurvesAuthor<'s> {
    pub fn into_prim(self) -> Prim<'s> {
        self.prim
    }
    pub fn set_points(self, points: Vec<[f32; 3]>) -> Result<Self> {
        author_point3f_array(self.prim.stage(), self.prim.path(), A_POINTS, points)?;
        Ok(self)
    }
    pub fn set_curve_vertex_counts(self, counts: Vec<i32>) -> Result<Self> {
        author_int_vec(self.prim.stage(), self.prim.path(), A_CURVE_VERTEX_COUNTS, counts)?;
        Ok(self)
    }
    pub fn set_order(self, order: Vec<i32>) -> Result<Self> {
        author_int_vec(self.prim.stage(), self.prim.path(), A_ORDER, order)?;
        Ok(self)
    }
    pub fn set_knots(self, knots: Vec<f64>) -> Result<Self> {
        author_double_array(self.prim.stage(), self.prim.path(), A_KNOTS, knots)?;
        Ok(self)
    }
    pub fn set_ranges(self, ranges: Vec<[f64; 2]>) -> Result<Self> {
        let attr = self.prim.path().append_property(A_RANGES)?;
        self.prim
            .stage()
            .create_attribute(attr, "double2[]")?
            .set_custom(false)?
            .set(Value::Vec2dVec(ranges))?;
        Ok(self)
    }
    /// Set `widths` along the curve with explicit `interpolation` (see
    /// [`BasisCurvesAuthor::set_widths`] for the rationale).
    pub fn set_widths(self, widths: Vec<f32>, interpolation: Interpolation) -> Result<Self> {
        author_primvar(
            self.prim.stage(),
            self.prim.path(),
            A_WIDTHS,
            "float[]",
            Value::FloatVec(widths),
            interpolation,
        )?;
        Ok(self)
    }
}

// ── NurbsPatch ─────────────────────────────────────────────────────

pub fn define_nurbs_patch<'s>(stage: &'s Stage, path: impl Into<Path>) -> Result<NurbsPatchAuthor<'s>> {
    let prim = stage.define_prim(path)?.set_type_name(T_NURBS_PATCH)?;
    Ok(NurbsPatchAuthor { prim })
}

pub struct NurbsPatchAuthor<'s> {
    prim: Prim<'s>,
}

impl<'s> NurbsPatchAuthor<'s> {
    pub fn into_prim(self) -> Prim<'s> {
        self.prim
    }
    pub fn set_points(self, points: Vec<[f32; 3]>) -> Result<Self> {
        author_point3f_array(self.prim.stage(), self.prim.path(), A_POINTS, points)?;
        Ok(self)
    }
    pub fn set_uv_vertex_counts(self, u_count: i32, v_count: i32) -> Result<Self> {
        let attr_u = self.prim.path().append_property(A_U_VERTEX_COUNT)?;
        self.prim
            .stage()
            .create_attribute(attr_u, "int")?
            .set_custom(false)?
            .set(Value::Int(u_count))?;
        let attr_v = self.prim.path().append_property(A_V_VERTEX_COUNT)?;
        self.prim
            .stage()
            .create_attribute(attr_v, "int")?
            .set_custom(false)?
            .set(Value::Int(v_count))?;
        Ok(self)
    }
    pub fn set_uv_order(self, u_order: i32, v_order: i32) -> Result<Self> {
        let attr_u = self.prim.path().append_property(A_U_ORDER)?;
        self.prim
            .stage()
            .create_attribute(attr_u, "int")?
            .set_custom(false)?
            .set(Value::Int(u_order))?;
        let attr_v = self.prim.path().append_property(A_V_ORDER)?;
        self.prim
            .stage()
            .create_attribute(attr_v, "int")?
            .set_custom(false)?
            .set(Value::Int(v_order))?;
        Ok(self)
    }
    pub fn set_uv_knots(self, u_knots: Vec<f64>, v_knots: Vec<f64>) -> Result<Self> {
        author_double_array(self.prim.stage(), self.prim.path(), A_U_KNOTS, u_knots)?;
        author_double_array(self.prim.stage(), self.prim.path(), A_V_KNOTS, v_knots)?;
        Ok(self)
    }
    pub fn set_uv_range(self, u_range: [f64; 2], v_range: [f64; 2]) -> Result<Self> {
        let attr_u = self.prim.path().append_property(A_U_RANGE)?;
        self.prim
            .stage()
            .create_attribute(attr_u, "double2")?
            .set_custom(false)?
            .set(Value::Vec2d(u_range))?;
        let attr_v = self.prim.path().append_property(A_V_RANGE)?;
        self.prim
            .stage()
            .create_attribute(attr_v, "double2")?
            .set_custom(false)?
            .set(Value::Vec2d(v_range))?;
        Ok(self)
    }
    /// Set `uForm` / `vForm` (uniform token, `open` / `closed` / `periodic`).
    pub fn set_forms(self, u_form: impl Into<String>, v_form: impl Into<String>) -> Result<Self> {
        let attr_u = self.prim.path().append_property(A_U_FORM)?;
        self.prim
            .stage()
            .create_attribute(attr_u, "token")?
            .set_variability(Variability::Uniform)?
            .set_custom(false)?
            .set(Value::Token(u_form.into()))?;
        let attr_v = self.prim.path().append_property(A_V_FORM)?;
        self.prim
            .stage()
            .create_attribute(attr_v, "token")?
            .set_variability(Variability::Uniform)?
            .set_custom(false)?
            .set(Value::Token(v_form.into()))?;
        Ok(self)
    }
}

// ── HermiteCurves ──────────────────────────────────────────────────

pub fn define_hermite_curves<'s>(stage: &'s Stage, path: impl Into<Path>) -> Result<HermiteCurvesAuthor<'s>> {
    let prim = stage.define_prim(path)?.set_type_name(T_HERMITE_CURVES)?;
    Ok(HermiteCurvesAuthor { prim })
}

pub struct HermiteCurvesAuthor<'s> {
    prim: Prim<'s>,
}

impl<'s> HermiteCurvesAuthor<'s> {
    pub fn into_prim(self) -> Prim<'s> {
        self.prim
    }
    pub fn set_points(self, points: Vec<[f32; 3]>) -> Result<Self> {
        author_point3f_array(self.prim.stage(), self.prim.path(), A_POINTS, points)?;
        Ok(self)
    }
    pub fn set_tangents(self, tangents: Vec<[f32; 3]>) -> Result<Self> {
        author_vec3f_array(self.prim.stage(), self.prim.path(), A_TANGENTS, tangents)?;
        Ok(self)
    }
    pub fn set_curve_vertex_counts(self, counts: Vec<i32>) -> Result<Self> {
        author_int_vec(self.prim.stage(), self.prim.path(), A_CURVE_VERTEX_COUNTS, counts)?;
        Ok(self)
    }
    /// Set `widths` along the curve with explicit `interpolation` (see
    /// [`BasisCurvesAuthor::set_widths`] for the rationale).
    pub fn set_widths(self, widths: Vec<f32>, interpolation: Interpolation) -> Result<Self> {
        author_primvar(
            self.prim.stage(),
            self.prim.path(),
            A_WIDTHS,
            "float[]",
            Value::FloatVec(widths),
            interpolation,
        )?;
        Ok(self)
    }
}

// ── Points ─────────────────────────────────────────────────────────

pub fn define_points<'s>(stage: &'s Stage, path: impl Into<Path>) -> Result<PointsAuthor<'s>> {
    let prim = stage.define_prim(path)?.set_type_name(T_POINTS)?;
    Ok(PointsAuthor { prim })
}

pub struct PointsAuthor<'s> {
    prim: Prim<'s>,
}

impl<'s> PointsAuthor<'s> {
    pub fn into_prim(self) -> Prim<'s> {
        self.prim
    }
    pub fn set_points(self, points: Vec<[f32; 3]>) -> Result<Self> {
        author_point3f_array(self.prim.stage(), self.prim.path(), A_POINTS, points)?;
        Ok(self)
    }
    /// Set per-point `widths` with explicit `interpolation` (typically
    /// `Vertex` — one width per point — or `Constant`).
    pub fn set_widths(self, widths: Vec<f32>, interpolation: Interpolation) -> Result<Self> {
        author_primvar(
            self.prim.stage(),
            self.prim.path(),
            A_WIDTHS,
            "float[]",
            Value::FloatVec(widths),
            interpolation,
        )?;
        Ok(self)
    }
    pub fn set_ids(self, ids: Vec<i64>) -> Result<Self> {
        author_int64_array(self.prim.stage(), self.prim.path(), A_IDS, ids)?;
        Ok(self)
    }
}

// ── TetMesh ────────────────────────────────────────────────────────

pub fn define_tet_mesh<'s>(stage: &'s Stage, path: impl Into<Path>) -> Result<TetMeshAuthor<'s>> {
    let prim = stage.define_prim(path)?.set_type_name(T_TET_MESH)?;
    Ok(TetMeshAuthor { prim })
}

pub struct TetMeshAuthor<'s> {
    prim: Prim<'s>,
}

impl<'s> TetMeshAuthor<'s> {
    pub fn into_prim(self) -> Prim<'s> {
        self.prim
    }
    pub fn set_points(self, points: Vec<[f32; 3]>) -> Result<Self> {
        author_point3f_array(self.prim.stage(), self.prim.path(), A_POINTS, points)?;
        Ok(self)
    }
    /// Set `tetVertexIndices` — flat `int[]` of length
    /// `4 * num_tets`. Each consecutive 4-tuple is one tetrahedron
    /// in the order the reader expects.
    pub fn set_tet_vertex_indices(self, indices: Vec<i32>) -> Result<Self> {
        author_int_vec(self.prim.stage(), self.prim.path(), A_TET_VERTEX_INDICES, indices)?;
        Ok(self)
    }
}

// ── PointInstancer ─────────────────────────────────────────────────

pub fn define_point_instancer<'s>(stage: &'s Stage, path: impl Into<Path>) -> Result<PointInstancerAuthor<'s>> {
    let prim = stage.define_prim(path)?.set_type_name(T_POINT_INSTANCER)?;
    Ok(PointInstancerAuthor { prim })
}

pub struct PointInstancerAuthor<'s> {
    prim: Prim<'s>,
}

impl<'s> PointInstancerAuthor<'s> {
    pub fn into_prim(self) -> Prim<'s> {
        self.prim
    }
    /// Set the `prototypes` rel targets — paths to the prototype prims.
    pub fn set_prototypes<I, P>(self, prototypes: I) -> Result<Self>
    where
        I: IntoIterator<Item = P>,
        P: Into<Path>,
    {
        author_rel_targets(self.prim.stage(), self.prim.path(), REL_PROTOTYPES, prototypes)?;
        Ok(self)
    }
    pub fn set_proto_indices(self, indices: Vec<i32>) -> Result<Self> {
        author_int_vec(self.prim.stage(), self.prim.path(), A_PROTO_INDICES, indices)?;
        Ok(self)
    }
    pub fn set_positions(self, positions: Vec<[f32; 3]>) -> Result<Self> {
        author_point3f_array(self.prim.stage(), self.prim.path(), A_POSITIONS, positions)?;
        Ok(self)
    }
    pub fn set_scales(self, scales: Vec<[f32; 3]>) -> Result<Self> {
        let attr = self.prim.path().append_property(A_SCALES)?;
        self.prim
            .stage()
            .create_attribute(attr, "float3[]")?
            .set_custom(false)?
            .set(Value::Vec3fVec(scales))?;
        Ok(self)
    }
    pub fn set_orientations(self, quats: Vec<[f32; 4]>) -> Result<Self> {
        author_quatf_array(self.prim.stage(), self.prim.path(), A_ORIENTATIONS, quats)?;
        Ok(self)
    }
    pub fn set_velocities(self, velocities: Vec<[f32; 3]>) -> Result<Self> {
        author_vec3f_array(self.prim.stage(), self.prim.path(), A_VELOCITIES, velocities)?;
        Ok(self)
    }
    pub fn set_accelerations(self, accelerations: Vec<[f32; 3]>) -> Result<Self> {
        author_vec3f_array(self.prim.stage(), self.prim.path(), A_ACCELERATIONS, accelerations)?;
        Ok(self)
    }
    pub fn set_angular_velocities(self, vels: Vec<[f32; 3]>) -> Result<Self> {
        author_vec3f_array(self.prim.stage(), self.prim.path(), A_ANGULAR_VELOCITIES, vels)?;
        Ok(self)
    }
    pub fn set_ids(self, ids: Vec<i64>) -> Result<Self> {
        author_int64_array(self.prim.stage(), self.prim.path(), A_IDS, ids)?;
        Ok(self)
    }
    pub fn set_invisible_ids(self, ids: Vec<i64>) -> Result<Self> {
        author_int64_array(self.prim.stage(), self.prim.path(), A_INVISIBLE_IDS, ids)?;
        Ok(self)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::schemas::geom::{
        define_camera, define_cube, define_mesh, define_xform, set_translate, Projection, Purpose, Visibility,
    };
    use crate::sdf;

    #[test]
    fn basis_curves_roundtrip() -> Result<()> {
        let stage = Stage::builder().in_memory("anon.usda")?;
        define_basis_curves(&stage, sdf::path("/C")?)?
            .set_points(vec![[0.0, 0.0, 0.0], [1.0, 0.0, 0.0]])?
            .set_curve_vertex_counts(vec![2])?
            .set_curve_type("linear")?
            .set_basis("bezier")?
            .set_wrap("nonperiodic")?
            .set_widths(vec![0.1, 0.1], Interpolation::Vertex)?;

        let c = crate::schemas::geom::read_basis_curves(&stage, &sdf::path("/C")?)?.expect("BasisCurves");
        assert_eq!(c.points.len(), 2);
        assert_eq!(c.curve_vertex_counts, vec![2]);
        assert_eq!(c.widths.len(), 2);
        let interp = stage.field::<sdf::Value>("/C.widths", "interpolation")?;
        assert_eq!(interp, Some(sdf::Value::Token("vertex".into())));
        Ok(())
    }

    #[test]
    fn point_instancer_roundtrip() -> Result<()> {
        let stage = Stage::builder().in_memory("anon.usda")?;
        define_cube(&stage, sdf::path("/Proto/Marker")?)?.set_size(0.1)?;
        define_point_instancer(&stage, sdf::path("/Instances")?)?
            .set_prototypes([sdf::path("/Proto/Marker")?])?
            .set_proto_indices(vec![0, 0, 0])?
            .set_positions(vec![[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [2.0, 0.0, 0.0]])?
            .set_ids(vec![100, 200, 300])?
            .set_invisible_ids(vec![200])?;

        let inst =
            crate::schemas::geom::read_point_instancer(&stage, &sdf::path("/Instances")?)?.expect("PointInstancer");
        assert_eq!(inst.positions.len(), 3);
        assert_eq!(inst.proto_indices, vec![0, 0, 0]);
        assert_eq!(inst.prototypes, vec!["/Proto/Marker".to_string()]);
        assert_eq!(inst.invisible_ids, vec![200]);
        Ok(())
    }

    #[test]
    fn tet_mesh_roundtrip() -> Result<()> {
        let stage = Stage::builder().in_memory("anon.usda")?;
        define_tet_mesh(&stage, sdf::path("/T")?)?
            .set_points(vec![[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]])?
            .set_tet_vertex_indices(vec![0, 1, 2, 3])?;

        let t = crate::schemas::geom::read_tet_mesh(&stage, &sdf::path("/T")?)?.expect("TetMesh");
        assert_eq!(t.points.len(), 4);
        Ok(())
    }

    #[test]
    fn full_scene_authoring_to_reader_roundtrip() -> Result<()> {
        let stage = Stage::builder().in_memory("anon.usda")?;

        define_xform(&stage, sdf::path("/World")?)?;
        set_translate(&stage, &sdf::path("/World")?, [0.0, 1.0, 0.0])?;
        super::super::set_visibility(&stage, &sdf::path("/World")?, Visibility::Inherited)?;
        super::super::set_purpose(&stage, &sdf::path("/World")?, Purpose::Render)?;

        define_cube(&stage, sdf::path("/World/Box")?)?.set_size(0.5)?;
        define_mesh(&stage, sdf::path("/World/Mesh")?)?
            .set_points(vec![[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.0, 1.0, 0.0]])?
            .set_face_vertex_counts(vec![3])?
            .set_face_vertex_indices(vec![0, 1, 2])?;
        define_camera(&stage, sdf::path("/World/Cam")?)?
            .set_projection(Projection::Perspective)?
            .set_focal_length(35.0)?;

        // Read every prim back via the existing readers.
        assert_eq!(stage.type_name(&sdf::path("/World")?)?.as_deref(), Some("Xform"),);
        assert!(crate::schemas::geom::read_cube(&stage, &sdf::path("/World/Box")?)?.is_some());
        assert!(crate::schemas::geom::read_mesh(&stage, &sdf::path("/World/Mesh")?)?.is_some());
        assert!(crate::schemas::geom::read_camera(&stage, &sdf::path("/World/Cam")?)?.is_some());
        let order = crate::schemas::geom::read_xform_op_order(&stage, &sdf::path("/World")?)?.expect("xformOpOrder");
        assert_eq!(order, vec!["xformOp:translate".to_string()]);
        Ok(())
    }
}