hydra-rs 0.0.4

Rust bindings to OpenUSD's Hydra rendering layer: scene-index ingestion, render-delegate enumeration, headless render to RGBA via Storm.
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
//! Rust bindings to OpenUSD's Hydra rendering layer.
//!
//! Two layers of API:
//!
//! 1. The stateless [`render_to_rgba`] convenience: open a stage, render
//!    once with a hardcoded camera and default light, throw the engine away.
//! 2. The stateful [`Renderer`]: holds a stage + HGI + `UsdImagingGLEngine`
//!    across calls so a viewport can re-render at interactive rates without
//!    rebuilding any of the scaffolding. Camera, lights, time code, output
//!    size, and clear color are all mutable between renders.
//!
//! Plus low-level inspection: [`SceneIndex::from_path`] for ingesting a stage
//! into a `UsdImagingStageSceneIndex` and walking what Hydra sees, and
//! [`list_render_delegates`] for enumerating the registered render plugins.

use std::path::Path;

use cxx::UniquePtr;

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

        type SceneIndex;
        type Renderer;

        fn populate_from_path(usd_path: &str) -> Result<UniquePtr<SceneIndex>>;
        fn list_render_delegate_ids() -> UniquePtr<CxxVector<CxxString>>;
        fn create_renderer(
            usd_path: &str,
            render_delegate_id: &str,
        ) -> Result<UniquePtr<Renderer>>;
        fn render_to_rgba(
            usd_path: &str,
            render_delegate_id: &str,
            width: u32,
            height: u32,
        ) -> Result<UniquePtr<CxxVector<u8>>>;

        fn stage_root(self: &SceneIndex) -> String;
        fn prim_count(self: &SceneIndex) -> usize;
        fn prim_paths(self: &SceneIndex) -> UniquePtr<CxxVector<CxxString>>;

        fn set_size(self: Pin<&mut Renderer>, width: u32, height: u32);
        fn set_camera_matrices(
            self: Pin<&mut Renderer>,
            view: &[f32],
            projection: &[f32],
        );
        fn set_time(self: Pin<&mut Renderer>, time: f64);
        fn use_default_time(self: Pin<&mut Renderer>);
        fn clear_lights(self: Pin<&mut Renderer>);
        fn use_default_light(self: Pin<&mut Renderer>);
        fn add_distant_light(
            self: Pin<&mut Renderer>,
            dx: f32,
            dy: f32,
            dz: f32,
            r: f32,
            g: f32,
            b: f32,
            intensity: f32,
        );
        fn add_positional_light(
            self: Pin<&mut Renderer>,
            px: f32,
            py: f32,
            pz: f32,
            r: f32,
            g: f32,
            b: f32,
            intensity: f32,
        );
        fn set_clear_color(self: Pin<&mut Renderer>, r: f32, g: f32, b: f32, a: f32);
        fn set_scene_ambient(self: Pin<&mut Renderer>, r: f32, g: f32, b: f32, a: f32);
        fn set_dome_light(
            self: Pin<&mut Renderer>,
            hdri_path: &str,
            intensity: f32,
            exposure: f32,
            rotation_y_degrees: f32,
        ) -> Result<()>;
        fn clear_dome_light(self: Pin<&mut Renderer>);
        fn set_external_material(
            self: Pin<&mut Renderer>,
            source_usd_path: &str,
            prim_path: &str,
        ) -> Result<()>;
        fn clear_external_material(self: Pin<&mut Renderer>);
        // Per-light flat-float payload. Layout per light (16 floats):
        //   [0..3]  direction (light travel direction, will be
        //           re-normalised by the bridge)
        //   [3]     type: 0.0 directional, 1.0 spot
        //   [4..7]  position (spot only — directional ignores)
        //   [7]     enabled: 1.0 active / 0.0 skipped
        //   [8..11] linear-space colour
        //   [11]    intensity multiplier (→ UsdLux `inputs:intensity`)
        //   [12]    cos(inner half-angle)   (spot only)
        //   [13]    cos(outer half-angle)   (spot only)
        //   [14..15] reserved (zero)
        // `data.len()` MUST be a multiple of 16; otherwise the bridge
        // throws. Flat-float instead of a cxx shared struct because
        // cxx's bridge-emitted structs can't be referenced from the
        // hand-written hydra_bridge.h without extra header juggling.
        fn set_user_lights(
            self: Pin<&mut Renderer>,
            data: &[f32],
        ) -> Result<()>;
        fn clear_user_lights(self: Pin<&mut Renderer>);
        fn set_painted_material(
            self: Pin<&mut Renderer>,
            base_color_asset_path: &str,
            roughness_asset_path: &str,
            metallic_asset_path: &str,
            normal_asset_path: &str,
        ) -> Result<()>;
        fn clear_painted_material(self: Pin<&mut Renderer>);
        fn set_show_render(self: Pin<&mut Renderer>, show: bool);
        fn set_show_proxy(self: Pin<&mut Renderer>, show: bool);
        fn set_show_guides(self: Pin<&mut Renderer>, show: bool);
        fn current_renderer(self: &Renderer) -> String;
        fn set_renderer_plugin(self: &Renderer, plugin_id: &str) -> bool;
        fn render_color(self: &Renderer) -> Result<UniquePtr<CxxVector<u8>>>;
        fn is_converged(self: &Renderer) -> bool;
    }
}

/// Wraps a `UsdImagingStageSceneIndex` and the `UsdStage` that backs it.
pub struct SceneIndex {
    inner: UniquePtr<ffi::SceneIndex>,
}

impl SceneIndex {
    pub fn from_path(path: impl AsRef<Path>) -> Result<Self, cxx::Exception> {
        let p = path.as_ref().to_string_lossy();
        Ok(Self {
            inner: ffi::populate_from_path(&p)?,
        })
    }

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

    pub fn prim_count(&self) -> usize {
        self.inner.prim_count()
    }

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

/// Render delegate plugin IDs registered with USD's plug system in this
/// process (e.g. `"HdStormRendererPlugin"`, `"HdEmbreeRendererPlugin"`).
pub fn list_render_delegates() -> Vec<String> {
    ffi::list_render_delegate_ids()
        .iter()
        .map(|s| s.to_string())
        .collect()
}

/// Stateful Hydra renderer. Hold one of these across frames in a viewport;
/// call `set_camera_matrices` / `set_size` / `set_time` between renders.
pub struct Renderer {
    inner: UniquePtr<ffi::Renderer>,
}

impl Renderer {
    /// Create a renderer for `usd_path` using the default render delegate
    /// (Storm on macOS, Linux with GL/Vulkan, Windows with DX/GL).
    pub fn new(usd_path: impl AsRef<Path>) -> Result<Self, cxx::Exception> {
        Self::with_delegate(usd_path, "")
    }

    /// Create a renderer for `usd_path` using the named render delegate
    /// (e.g. `"HdStormRendererPlugin"`, `"HdEmbreeRendererPlugin"`).
    pub fn with_delegate(
        usd_path: impl AsRef<Path>,
        delegate_id: &str,
    ) -> Result<Self, cxx::Exception> {
        let p = usd_path.as_ref().to_string_lossy();
        Ok(Self {
            inner: ffi::create_renderer(&p, delegate_id)?,
        })
    }

    /// Output size in pixels. Resets the default-camera projection so the
    /// aspect ratio stays correct if the caller hasn't supplied their own.
    pub fn set_size(&mut self, width: u32, height: u32) {
        self.inner.pin_mut().set_size(width, height);
    }

    /// Set the view and projection matrices as row-major 4x4 floats. Each
    /// slice must be exactly 16 entries long. Convention is GfMatrix4d's:
    /// `m[r * 4 + c]` is row `r`, column `c`. Pixar uses row-vector
    /// convention internally, so a "view matrix" here is what you'd plug
    /// into `vec_world * view = vec_camera`.
    pub fn set_camera_matrices(&mut self, view: &[f32; 16], projection: &[f32; 16]) {
        self.inner.pin_mut().set_camera_matrices(view, projection);
    }

    /// Override the time code rendered. Defaults to `UsdTimeCode::Default`.
    pub fn set_time(&mut self, time: f64) {
        self.inner.pin_mut().set_time(time);
    }

    /// Restore the default time code.
    pub fn use_default_time(&mut self) {
        self.inner.pin_mut().use_default_time();
    }

    /// Drop all explicit lights AND disable the default headlight, so the
    /// next render is unlit (just diffuse albedo).
    pub fn clear_lights(&mut self) {
        self.inner.pin_mut().clear_lights();
    }

    /// Drop explicit lights and re-enable the built-in default headlight.
    pub fn use_default_light(&mut self) {
        self.inner.pin_mut().use_default_light();
    }

    /// Add a directional light with direction `(dx, dy, dz)` (need not be
    /// normalized), color `(r, g, b)`, and a multiplicative `intensity`.
    /// Disables the default headlight; multiple `add_*_light` calls
    /// accumulate.
    pub fn add_distant_light(
        &mut self,
        direction: [f32; 3],
        color: [f32; 3],
        intensity: f32,
    ) {
        self.inner.pin_mut().add_distant_light(
            direction[0],
            direction[1],
            direction[2],
            color[0],
            color[1],
            color[2],
            intensity,
        );
    }

    /// Add a positional (point) light at `(px, py, pz)` with the same
    /// `(r, g, b) * intensity` shading.
    pub fn add_positional_light(
        &mut self,
        position: [f32; 3],
        color: [f32; 3],
        intensity: f32,
    ) {
        self.inner.pin_mut().add_positional_light(
            position[0],
            position[1],
            position[2],
            color[0],
            color[1],
            color[2],
            intensity,
        );
    }

    /// Background color used by the AOV clear. Tuple is `(r, g, b, a)` in
    /// linear space.
    pub fn set_clear_color(&mut self, color: [f32; 4]) {
        self.inner
            .pin_mut()
            .set_clear_color(color[0], color[1], color[2], color[3]);
    }

    /// Constant ambient added to every shaded surface, independent of
    /// light direction. Default is `[0.05, 0.05, 0.05, 1.0]` — bump it
    /// into the `[0.15, 0.25]` range when the consumer has no IBL and
    /// wants shadowed regions to read instead of falling to black.
    /// Linear space, same as `set_clear_color`.
    pub fn set_scene_ambient(&mut self, color: [f32; 4]) {
        self.inner
            .pin_mut()
            .set_scene_ambient(color[0], color[1], color[2], color[3]);
    }

    /// Drop an HDRI environment onto the stage as a `UsdLuxDomeLight`
    /// authored into the session layer. Storm renders the dome both
    /// as the visible background behind geometry and as an IBL
    /// contributor (importance-sampled), so a single call sets the
    /// skybox AND the soft lighting that fills the shadow side.
    ///
    /// `path` is anything `Sdf` can resolve — an absolute file path or
    /// a registered URI scheme like `forge://`. `intensity` and
    /// `exposure` map straight to the UsdLux attributes (linear
    /// multiplier and stops). `rotation_y_degrees` rotates the dome
    /// around the Y axis in the stage's coordinate system, matching
    /// `xformOp:rotateY`'s sign convention (positive = CCW when
    /// looking down -Y).
    ///
    /// Idempotent. Calling it again with new values updates the
    /// existing dome rather than spawning a new prim, so it's cheap
    /// enough to hand the wgpu side's env state every frame.
    pub fn set_dome_light(
        &mut self,
        path: impl AsRef<Path>,
        intensity: f32,
        exposure: f32,
        rotation_y_degrees: f32,
    ) -> Result<(), cxx::Exception> {
        let p = path.as_ref().to_string_lossy();
        self.inner
            .pin_mut()
            .set_dome_light(&p, intensity, exposure, rotation_y_degrees)
    }

    /// Remove the dome authored by `set_dome_light` and stop routing
    /// scene lights through the render params. Explicit
    /// `add_distant_light` / `add_positional_light` lights are left
    /// alone — call `clear_lights` separately if you want a fully
    /// unlit render.
    pub fn clear_dome_light(&mut self) {
        self.inner.pin_mut().clear_dome_light();
    }

    /// Reference an external material defined in another USD layer
    /// into the stage's session layer at `/_hydraExternalMaterial`,
    /// and bind it to every mesh under the pseudo-root. Use this to
    /// surface a material library entry without copying its shader
    /// network into the local stage.
    ///
    /// `source_usd_path` is anything `Sdf` can resolve — an absolute
    /// file path or a registered URI like `forge://`. `prim_path` is
    /// the path of the `UsdShadeMaterial` inside that source (e.g.
    /// `/Materials/Brick`). Pass an empty string for `prim_path` to
    /// reference the source's default prim.
    ///
    /// Idempotent. Re-pointing at a different material is one call.
    /// An empty `source_usd_path` behaves like `clear_external_material`.
    pub fn set_external_material(
        &mut self,
        source: impl AsRef<Path>,
        prim_path: &str,
    ) -> Result<(), cxx::Exception> {
        let src = source.as_ref().to_string_lossy();
        self.inner
            .pin_mut()
            .set_external_material(&src, prim_path)
    }

    /// Drop the external material reference and unbind it from every
    /// mesh. Originally-authored material bindings (if any) drive
    /// shading again.
    pub fn clear_external_material(&mut self) {
        self.inner.pin_mut().clear_external_material();
    }

    /// Author a `UsdPreviewSurface` material into the stage's session
    /// layer and bind it to every mesh under the pseudo-root. Each
    /// non-empty asset path becomes a `UsdUVTexture` shader feeding
    /// the matching PBR input (`diffuseColor` → base colour,
    /// `roughness` → roughness, `metallic` → metallic, `normal` →
    /// tangent-space normal). Pass an empty string (or empty path)
    /// for any channel you haven't authored yet — the corresponding
    /// PBR input stays at its UsdPreviewSurface default.
    ///
    /// Asset paths may contain the `<UDIM>` token for multi-tile
    /// layouts; USD's asset resolver substitutes the per-tile id
    /// (`1001`, `1002`, …) at sample time. One material binding
    /// covers every tile.
    ///
    /// Idempotent — re-call after re-exporting paint targets to
    /// refresh. The previous painted material is removed before the
    /// new one is authored, so attribute changes never stack.
    ///
    /// Source colour space: `diffuseColor` reads sRGB (gamma-decoded
    /// to linear on sample); roughness / metallic / normal read raw
    /// (linear data, no curve). UsdUVTexture's `sourceColorSpace`
    /// attribute is set accordingly.
    pub fn set_painted_material(
        &mut self,
        base_color: impl AsRef<Path>,
        roughness: impl AsRef<Path>,
        metallic: impl AsRef<Path>,
        normal: impl AsRef<Path>,
    ) -> Result<(), cxx::Exception> {
        let bc = base_color.as_ref().to_string_lossy();
        let ro = roughness.as_ref().to_string_lossy();
        let me = metallic.as_ref().to_string_lossy();
        let nm = normal.as_ref().to_string_lossy();
        self.inner
            .pin_mut()
            .set_painted_material(&bc, &ro, &me, &nm)
    }

    /// Unbind the painted material from every mesh and remove the
    /// material prim from the session layer. The stage's originally-
    /// authored bindings (if any) drive shading again afterwards.
    pub fn clear_painted_material(&mut self) {
        self.inner.pin_mut().clear_painted_material();
    }

    /// Author one `UsdLuxDistantLight` (directional) or
    /// `UsdLuxSphereLight` with shaping cone (spot) per entry in
    /// `lights`, in the stage's session layer at `/_hydraLight<N>`.
    /// Mirrors the layout of forge-paint's `Vec<Light>` so the same
    /// CPU-side list drives both renderers.
    ///
    /// Each light is 16 floats:
    /// * `[0..3]` direction (will be re-normalised)
    /// * `[3]` type tag — `0.0` = directional, `1.0` = spot
    /// * `[4..7]` world position (spot only)
    /// * `[7]` enabled (`1.0` / `0.0`)
    /// * `[8..11]` linear-space colour
    /// * `[11]` intensity (→ `inputs:intensity`)
    /// * `[12]` `cos(inner_half_angle)` (spot)
    /// * `[13]` `cos(outer_half_angle)` (spot)
    /// * `[14..15]` reserved
    ///
    /// Idempotent. Any previously-authored `/_hydraLight<i>` prims
    /// beyond the new count get removed; entries within count get
    /// their attributes rewritten in place. Enables scene-lights in
    /// the render params automatically when any non-disabled light
    /// is present.
    pub fn set_user_lights(
        &mut self,
        lights: &[[f32; 16]],
    ) -> Result<(), cxx::Exception> {
        // Flatten to `&[f32]` for the cxx bridge. The shape is
        // already 16-aligned per light, so the flatten is just a
        // reinterpret.
        let flat: &[f32] = unsafe {
            std::slice::from_raw_parts(
                lights.as_ptr() as *const f32,
                lights.len() * 16,
            )
        };
        self.inner.pin_mut().set_user_lights(flat)
    }

    /// Remove every `/_hydraLight<i>` prim authored by
    /// `set_user_lights`. Dome (`set_dome_light`) is untouched —
    /// HDRI keeps lighting the scene.
    pub fn clear_user_lights(&mut self) {
        self.inner.pin_mut().clear_user_lights();
    }

    /// `UsdGeomImageable::purpose` filters used by `render_color`.
    /// `default` always renders; the three optional purposes opt in.
    /// Defaults: render = true, proxy = true, guides = false —
    /// matches what a "show me the asset" preview usually wants.
    /// Pipeline assets that wrap detail geometry in
    /// `Scope { purpose = "render" }` (Maya / Houdini convention) only
    /// show when `set_show_render(true)` is in effect.
    pub fn set_show_render(&mut self, show: bool) {
        self.inner.pin_mut().set_show_render(show);
    }

    /// See [`Renderer::set_show_render`].
    pub fn set_show_proxy(&mut self, show: bool) {
        self.inner.pin_mut().set_show_proxy(show);
    }

    /// See [`Renderer::set_show_render`].
    pub fn set_show_guides(&mut self, show: bool) {
        self.inner.pin_mut().set_show_guides(show);
    }

    /// The currently-active render delegate plugin id.
    pub fn current_renderer(&self) -> String {
        self.inner.current_renderer()
    }

    /// Switch the render delegate. Returns `false` if the plugin id isn't
    /// registered.
    pub fn set_renderer_plugin(&self, plugin_id: &str) -> bool {
        self.inner.set_renderer_plugin(plugin_id)
    }

    /// Render one pass and return RGBA8 pixels of size
    /// `width * height * 4` in top-down order (origin = top-left).
    /// Storm writes the AOV in OpenGL convention (origin = bottom-
    /// left); the C++ bridge reverses rows before returning so
    /// callers don't each have to remember to flip.
    ///
    /// One call = one pass. Rasterising delegates (Storm) converge
    /// in one pass and `is_converged` flips to true immediately.
    /// Sampling delegates (hdNSI, Embree, Arnold, …) need to be
    /// re-called until `is_converged` returns true — the natural
    /// fit for an interactive viewport's continuous-repaint loop,
    /// which gets progressive convergence for free. For one-shot
    /// headless renders that need a converged image, drive the loop
    /// in user code; `render_to_rgba` is the canonical example.
    pub fn render(&self) -> Result<Vec<u8>, cxx::Exception> {
        Ok(self.inner.render_color()?.iter().copied().collect())
    }

    /// True once the active render delegate considers the current
    /// frame fully resolved. See [`Renderer::render`] for how to use
    /// this to drive progressive convergence in a sampling delegate.
    pub fn is_converged(&self) -> bool {
        self.inner.is_converged()
    }
}

/// Open a stage, render once with the default camera and headlight, return
/// RGBA8 pixels. Convenience wrapper around [`Renderer`] for simple cases.
pub fn render_to_rgba(
    usd_path: impl AsRef<Path>,
    render_delegate: &str,
    width: u32,
    height: u32,
) -> Result<Vec<u8>, cxx::Exception> {
    let p = usd_path.as_ref().to_string_lossy();
    Ok(ffi::render_to_rgba(&p, render_delegate, width, height)?
        .iter()
        .copied()
        .collect())
}