threers 0.1.0

Drop-in three.js replacement for Rust and WebAssembly (wgpu) — THREE.* API, scene graph, PBR, post-fx, mesh BVH, CSG, an OpenSCAD front end with a watertight exact-CSG kernel, headless render, and native media codecs
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
//! Camera rays, including a thin lens.
//!
//! Rays are generated by unprojecting through the camera's own matrices rather
//! than by rebuilding a frustum from a field of view. That costs two matrix
//! inversions once per frame and buys exactness: an
//! [`OrthographicCamera`](crate::cameras::OrthographicCamera), a
//! [`PerspectiveCamera`](crate::cameras::PerspectiveCamera), and a camera
//! carrying an oblique-clip `projection_override` all work with no special
//! cases, and the traced image lines up with the rasterised one pixel for
//! pixel.

use crate::cameras::Camera;
use crate::math::{Matrix4, Vector2, Vector3};

use super::settings::RaytraceSettings;

/// A camera resolved into the form the tracer needs: world-space ray origins
/// and directions, plus a lens.
#[derive(Debug, Clone)]
pub struct RtCamera {
    inv_view: Matrix4,
    inv_proj: Matrix4,
    position: Vector3,
    /// Camera basis in world space, for the lens offset.
    right: Vector3,
    up: Vector3,
    forward: Vector3,
    /// False for an orthographic projection, where every ray is parallel and
    /// the origin varies instead of the direction.
    perspective: bool,
    aperture: f32,
    focus_distance: f32,
    /// Bokeh shape, from the camera's own lens.
    lens: crate::cameras::Lens,
    /// Previous-frame camera for motion blur interpolation.
    motion_prev: Option<Box<RtCamera>>,
    motion_shutter: f32,
}

impl RtCamera {
    /// Resolve `camera` for tracing. `focus_distance` of 0 in the settings is
    /// left as 0 here; [`Self::with_focus_distance`] fills it in once the scene
    /// is known.
    pub fn new(camera: &dyn Camera, settings: &RaytraceSettings) -> Self {
        let lens = camera.lens();
        let view = camera.view_matrix();
        let proj = camera.projection_matrix();
        let inv_view = view.invert();
        // The inverse view matrix is the camera's world transform: its columns
        // are the basis vectors, and view space looks down its own -Z.
        let e = &inv_view.elements;
        let right = Vector3::new(e[0], e[1], e[2]).normalize();
        let up = Vector3::new(e[4], e[5], e[6]).normalize();
        let forward = Vector3::new(-e[8], -e[9], -e[10]).normalize();
        // A perspective matrix puts -1 in the w row; an orthographic one has 0
        // there. That single element is the whole distinction.
        let perspective = proj.elements[11].abs() > 1e-6;
        Self {
            inv_view,
            inv_proj: proj.invert(),
            position: camera.position(),
            right,
            up,
            forward,
            perspective,
            // The settings win where they are set, so existing callers are
            // unchanged; otherwise the camera's own lens is used, which is
            // what makes `PerspectiveCamera::f_stop` and a USD camera's
            // `fStop` do anything at all.
            aperture: if settings.aperture > 0.0 {
                settings.aperture
            } else {
                lens.aperture
            },
            focus_distance: if settings.focus_distance > 0.0 {
                settings.focus_distance
            } else {
                lens.focus_distance
            },
            lens,
            motion_prev: None,
            motion_shutter: settings.motion_blur_shutter.max(0.0),
        }
    }

    /// Attach the previous camera pose for motion blur. `shutter` is the fraction
    /// of the frame over which the lens is open (`0..=1`).
    pub fn with_motion_previous(mut self, prev: RtCamera, shutter: f32) -> Self {
        if shutter > 0.0 {
            self.motion_prev = Some(Box::new(prev));
            self.motion_shutter = shutter.clamp(0.0, 1.0);
        }
        self
    }

    /// Set the focal distance — used to apply autofocus once the scene has been
    /// probed.
    pub fn with_focus_distance(mut self, d: f32) -> Self {
        self.focus_distance = d.max(1e-4);
        self
    }

    /// Aperture radius actually in force, after the settings and the
    /// camera's own lens have been reconciled.
    pub fn aperture(&self) -> f32 {
        self.aperture
    }

    /// The bokeh shape in force — blades and squeeze, with the resolved
    /// aperture and focus substituted in.
    pub fn lens(&self) -> crate::cameras::Lens {
        crate::cameras::Lens {
            aperture: self.aperture,
            focus_distance: self.focus_distance,
            ..self.lens
        }
    }

    pub fn focus_distance(&self) -> f32 {
        self.focus_distance
    }

    pub fn is_perspective(&self) -> bool {
        self.perspective
    }

    pub fn forward(&self) -> Vector3 {
        self.forward
    }

    pub fn position(&self) -> Vector3 {
        self.position
    }

    /// Camera basis in world space — the lens offset is built from these, and
    /// the GPU kernel needs them for the same reason.
    pub fn right(&self) -> Vector3 {
        self.right
    }

    pub fn up(&self) -> Vector3 {
        self.up
    }

    pub fn motion_shutter(&self) -> f32 {
        self.motion_shutter
    }

    /// Previous pose when motion blur is active.
    pub fn motion_previous(&self) -> Option<&RtCamera> {
        self.motion_prev.as_deref()
    }

    /// The inverted matrices ray generation unprojects through. Exposed so a
    /// device backend can do the same arithmetic rather than re-deriving a
    /// frustum from a field of view and drifting out of alignment.
    pub fn inv_view_matrix(&self) -> Matrix4 {
        self.inv_view
    }

    pub fn inv_proj_matrix(&self) -> Matrix4 {
        self.inv_proj
    }

    /// A ray through normalised device coordinates `ndc` ∈ [-1, 1]².
    ///
    /// `lens` is a pair of uniform randoms used to pick a point on the aperture;
    /// it is ignored for a pinhole.
    pub fn ray(&self, ndc: Vector2, lens: (f32, f32)) -> (Vector3, Vector3) {
        // WebGPU's clip space runs z from 0 at the near plane to 1 at the far
        // one, unlike OpenGL's -1..1 — unprojecting at -1 would put the near
        // point behind the camera.
        let near = Vector3::new(ndc.x, ndc.y, 0.0)
            .apply_matrix4(&self.inv_proj)
            .apply_matrix4(&self.inv_view);
        let far = Vector3::new(ndc.x, ndc.y, 1.0)
            .apply_matrix4(&self.inv_proj)
            .apply_matrix4(&self.inv_view);

        let (mut origin, mut dir) = if self.perspective {
            let o = self.position;
            let d = far - o;
            if d.length_sq() <= 1e-20 {
                (o, self.forward)
            } else {
                (o, d.normalize())
            }
        } else {
            let d = far - near;
            if d.length_sq() <= 1e-20 {
                (near, self.forward)
            } else {
                (near, d.normalize())
            }
        };

        if self.aperture > 0.0 && self.focus_distance > 0.0 {
            // Thin lens: every ray through the lens that would meet at the
            // focal plane still meets there, so that plane stays sharp and
            // everything else spreads into a circle of confusion.
            let cos = dir.dot(self.forward);
            if cos.abs() > 1e-6 {
                let t = self.focus_distance / cos;
                let focal_point = origin + dir * t;
                // Shape comes from the camera's iris: a circle wide open, a
                // polygon stopped down, squeezed if the lens is anamorphic.
                let (lx, ly) = self.lens.sample(lens.0, lens.1);
                origin =
                    origin + self.right * (lx * self.aperture) + self.up * (ly * self.aperture);
                let d = focal_point - origin;
                if d.length_sq() > 1e-20 {
                    dir = d.normalize();
                }
            }
        }
        (origin, dir)
    }

    /// A ray through pixel `(x, y)` with sub-pixel offset `jitter` ∈ [0, 1)².
    /// Row 0 is the top of the image, matching every other raster path in the
    /// crate.
    pub fn pixel_ray(
        &self,
        x: u32,
        y: u32,
        width: u32,
        height: u32,
        jitter: (f32, f32),
        lens: (f32, f32),
        shutter_time: f32,
    ) -> (Vector3, Vector3) {
        let u = (x as f32 + jitter.0) / width as f32;
        let v = (y as f32 + jitter.1) / height as f32;
        let ndc = Vector2::new(u * 2.0 - 1.0, 1.0 - v * 2.0);
        let (o, d) = self.ray(ndc, lens);
        let Some(prev) = self.motion_prev.as_ref() else {
            return (o, d);
        };
        if self.motion_shutter <= 0.0 {
            return (o, d);
        }
        let (o0, d0) = prev.ray(ndc, lens);
        let t = shutter_time.clamp(0.0, 1.0) * self.motion_shutter;
        let origin = o0.lerp(o, t);
        let direction = d0.lerp(d, 1.0 - t);
        if direction.length_sq() > 1e-20 {
            (origin, direction.normalize())
        } else {
            (origin, d)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cameras::{OrthographicCamera, PerspectiveCamera};

    fn perspective() -> PerspectiveCamera {
        let mut c = PerspectiveCamera::new(60.0, 1.0, 0.1, 100.0);
        c.position = Vector3::new(0.0, 0.0, 5.0);
        c.target = Vector3::ZERO;
        c
    }

    #[test]
    fn the_centre_ray_looks_down_the_view_axis() {
        let cam = perspective();
        let rt = RtCamera::new(&cam, &RaytraceSettings::default());
        assert!(rt.is_perspective());
        let (o, d) = rt.ray(Vector2::new(0.0, 0.0), (0.5, 0.5));
        assert!((o - Vector3::new(0.0, 0.0, 5.0)).length() < 1e-5, "{o:?}");
        assert!((d - Vector3::new(0.0, 0.0, -1.0)).length() < 1e-4, "{d:?}");
    }

    #[test]
    fn ndc_corners_spread_the_expected_way() {
        let cam = perspective();
        let rt = RtCamera::new(&cam, &RaytraceSettings::default());
        let (_, right) = rt.ray(Vector2::new(1.0, 0.0), (0.5, 0.5));
        let (_, up) = rt.ray(Vector2::new(0.0, 1.0), (0.5, 0.5));
        assert!(
            right.x > 0.0,
            "+X in NDC must go +X in world here: {right:?}"
        );
        assert!(up.y > 0.0, "+Y in NDC must go up: {up:?}");
        // A 60 degree vertical FOV: the top edge is 30 degrees off axis.
        let angle = up.dot(Vector3::new(0.0, 0.0, -1.0)).acos();
        assert!(
            (angle - 30f32.to_radians()).abs() < 1e-3,
            "{} deg",
            angle.to_degrees()
        );
    }

    #[test]
    fn pixel_row_zero_is_the_top_of_the_image() {
        let cam = perspective();
        let rt = RtCamera::new(&cam, &RaytraceSettings::default());
        let (_, top) = rt.pixel_ray(50, 0, 100, 100, (0.5, 0.5), (0.5, 0.5), 0.5);
        let (_, bottom) = rt.pixel_ray(50, 99, 100, 100, (0.5, 0.5), (0.5, 0.5), 0.5);
        assert!(
            top.y > bottom.y,
            "row 0 should look higher: {top:?} vs {bottom:?}"
        );
    }

    #[test]
    fn orthographic_rays_are_parallel() {
        let mut cam = OrthographicCamera::new(-2.0, 2.0, 2.0, -2.0, 0.1, 100.0);
        cam.position = Vector3::new(0.0, 0.0, 5.0);
        let rt = RtCamera::new(&cam, &RaytraceSettings::default());
        assert!(!rt.is_perspective());
        let (o1, d1) = rt.ray(Vector2::new(-0.5, -0.5), (0.5, 0.5));
        let (o2, d2) = rt.ray(Vector2::new(0.5, 0.5), (0.5, 0.5));
        assert!((d1 - d2).length() < 1e-5, "{d1:?} vs {d2:?}");
        assert!(
            (o1 - o2).length() > 0.5,
            "origins should differ: {o1:?} {o2:?}"
        );
        assert!((d1 - Vector3::new(0.0, 0.0, -1.0)).length() < 1e-4);
    }

    #[test]
    fn a_pinhole_ignores_the_lens_sample() {
        let cam = perspective();
        let rt = RtCamera::new(&cam, &RaytraceSettings::default());
        let (o1, d1) = rt.ray(Vector2::new(0.2, -0.3), (0.1, 0.9));
        let (o2, d2) = rt.ray(Vector2::new(0.2, -0.3), (0.8, 0.2));
        assert!((o1 - o2).length() < 1e-6);
        assert!((d1 - d2).length() < 1e-6);
    }

    /// Every ray through the lens must still cross the focal plane at the same
    /// point — that is the entire definition of "in focus".
    #[test]
    fn depth_of_field_keeps_the_focal_plane_sharp() {
        let cam = perspective();
        let settings = RaytraceSettings::default().with_depth_of_field(0.3, 5.0);
        let rt = RtCamera::new(&cam, &settings);
        let ndc = Vector2::new(0.4, -0.2);
        let mut reference = None;
        for lens in [(0.1, 0.1), (0.9, 0.5), (0.5, 0.95), (0.25, 0.75)] {
            let (o, d) = rt.ray(ndc, lens);
            let t = 5.0 / d.dot(rt.forward());
            let p = o + d * t;
            match reference {
                None => reference = Some(p),
                Some(r) => assert!((p - r).length() < 1e-3, "{p:?} vs {r:?}"),
            }
        }
        // And the origins really did move.
        let (o1, _) = rt.ray(ndc, (0.05, 0.5));
        let (o2, _) = rt.ray(ndc, (0.95, 0.5));
        assert!((o1 - o2).length() > 0.1, "the aperture had no effect");
    }

    /// The camera's own lens reaches the tracer.
    ///
    /// Before this, `PerspectiveCamera::aperture`, `focus_distance`,
    /// `f_stop`, `aperture_blades` and `anamorphic_ratio` were five public
    /// fields that nothing read — two of them written by the USD loader from
    /// the file, so a camera authored at f/2.8 rendered as a pinhole and said
    /// nothing. The settings still win where they are set, so this also checks
    /// that an explicit `RaytraceSettings::aperture` is not overridden.
    #[test]
    fn a_camera_with_an_f_stop_defocuses() {
        let mut cam = crate::PerspectiveCamera::new(50.0, 1.0, 0.1, 100.0);
        cam.position = crate::Vector3::new(0.0, 0.0, 5.0);
        cam.look_at(crate::Vector3::ZERO);
        cam.f_stop = 1.4;
        cam.focus_distance = 5.0;
        cam.aperture_blades = 6;
        assert!(cam.lens().aperture > 0.0, "the camera has no lens");

        let settings = RaytraceSettings::default();
        let rt = RtCamera::new(&cam, &settings);
        assert!(
            (rt.aperture() - cam.lens().aperture).abs() < 1e-9,
            "the tracer took {} from a camera at f/1.4 ({})",
            rt.aperture(),
            cam.lens().aperture
        );
        assert_eq!(rt.lens().blades, 6, "the iris did not come across");

        // Two different lens samples put the ray origin in two places, which
        // is the whole observable consequence of having an aperture.
        let ndc = crate::Vector2::new(0.0, 0.0);
        let (o1, _) = rt.ray(ndc, (0.05, 0.05));
        let (o2, _) = rt.ray(ndc, (0.95, 0.95));
        assert!(
            (o1 - o2).length() > 1e-4,
            "the camera's aperture had no effect on the ray"
        );

        // A pinhole camera is still a pinhole.
        let plain = crate::PerspectiveCamera::new(50.0, 1.0, 0.1, 100.0);
        assert_eq!(RtCamera::new(&plain, &settings).aperture(), 0.0);

        // And an explicit setting still wins over the camera's own.
        let overridden = RaytraceSettings {
            aperture: 0.75,
            ..RaytraceSettings::default()
        };
        assert_eq!(RtCamera::new(&cam, &overridden).aperture(), 0.75);
    }
}