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
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
//! One import for the things nearly every scene uses.
//!
//! ```
//! use threers::prelude::*;
//!
//! let mut scene = Scene::new();
//! scene.add(Object3D::mesh(Mesh::new(
//!     BoxGeometry::new(1.0, 1.0, 1.0),
//!     Material::Standard(StandardMaterial::new(Color::from_hex(0xff8844))),
//! )));
//! scene.add_light(DirectionalLight::new(Color::WHITE, 3.0));
//!
//! let mut camera = PerspectiveCamera::new(50.0, 16.0 / 9.0, 0.1, 100.0);
//! camera.position = Vector3::new(3.0, 2.0, 4.0);
//! camera.look_at(Vector3::ZERO);
//! ```
//!
//! # What is in the root prelude
//!
//! The scene graph, the geometry and material types, lights, cameras, textures,
//! the renderers, the vector maths, and the [`Camera`] trait — which has to be
//! in scope to call `view_matrix` on a camera, and is the sort of thing a
//! prelude exists for.
//!
//! # Nested modules (opt-in)
//!
//! A prelude is glob-imported, so every name in the root is a name your own
//! code cannot use. Subsystems you reach for deliberately live in nested
//! modules — import them explicitly:
//!
//! ```ignore
//! use threers::prelude::*;
//! use threers::prelude::controls::*;
//! use threers::prelude::animation::*;
//! ```
//!
//! | Module | Contents |
//! |--------|----------|
//! | [`controls`] | Orbit / trackball / first-person / … |
//! | [`animation`] | Mixer, clips, keyframe tracks |
//! | [`loaders`] | glTF, OBJ, HDR, … |
//! | [`helpers`] | Axes, grid, light helpers, … |
//! | [`lattice`] | Infill lattices — TPMS, struts, foams, cuboct voxels — their regions, grading and homogenised stiffness, and scale-rich networks |
//! | `sketch` | A window, a scene and a loop in one call (native) |
//! | `csg` | CSG evaluator / brush (`bvh-csg`) |
//! | `openscad` | Solid DSL + `.scad` parse (`openscad`) |
//! | `nurbs` | NURBS curve/surface + geometry (`nurbs`) |
//! | `raytrace` | Path tracer entry points (`raytrace`) |
//! | [`captions`] | Cue tracks / overlay (`captions`) |
//! | `ui` | A retained UI: threers-ui's prelude (the tree, styles, input, gauges and charts), its CPU painter, and its GPU pass with `render` (`ui`) |
//! | `xr` | Headsets: an app, its frame and GPU, a UI on a panel and the areas the system highlights (`xr`) |
//! | `metal` | The Metal backend's full working set — surfaces, the reusable render-thread pool, attachments, post chain, pixel formats (`metal`; macOS, iOS, tvOS, visionOS) |
//! | `video` | GIF/APNG/WebM/H.264/HEVC encoders, MP4, the hardware-first `Mp4Encoder`, and the decoders (`native-codec`; decoders also `video` or `native-decode`) |
//!
//! # What is deliberately not in any prelude module
//!
//! - **Maths shapes** — `Plane`, `Sphere`, `Triangle`, `Ray`, `Box2`, `Box3`,
//!   `Frustum`, … Common words; a scene rarely needs them by name.
//! - **Curves and paths** — `Path`, `Shape`, `Curve2`, `Curve3` and friends.
//! - **Companion crates** — physics and cinematic animation stay in
//!   `threers_physics::prelude` / `threers_animation::prelude`.
//!
//! Everything the crate exports is still available from the root
//! (`threers::Frustum`, `threers::Path`, …); the prelude is a curated subset,
//! not a second API.

// Traits first: these have to be in scope for their methods to be callable.
pub use crate::cameras::Camera;

pub use crate::cameras::{OrthographicCamera, PerspectiveCamera};
pub use crate::core::{
    BufferAttribute, BufferGeometry, Clock, InstancedMesh, Layers, LineSegments, Mesh, Object3D,
    ObjectId, ObjectKind, Points, Raycaster, Sprite,
};
pub use crate::geometries::{
    BoxGeometry, CapsuleGeometry, CircleGeometry, ConeGeometry, CylinderGeometry, ExtrudeGeometry,
    IcosahedronGeometry, LatheGeometry, MeshBuilder, MeshReport, PlaneGeometry, QuadGeometry,
    RingGeometry, SphereGeometry, TorusGeometry, TorusKnotGeometry, TubeGeometry,
};
pub use crate::lights::{
    AmbientLight, DirectionalLight, HemisphereLight, Light, PointLight, RectAreaLight,
    ShadowSettings, ShadowType, SpotLight,
};
pub use crate::materials::{
    BasicMaterial, DepthMaterial, LambertMaterial, LineBasicMaterial, MatcapMaterial, Material,
    MaterialKind, NormalMaterial, PhongMaterial, PhysicalMaterial, PointsMaterial, ShaderMaterial,
    SpriteMaterial, StandardMaterial, ToonMaterial, TransparencyMode,
};
pub use crate::math::{Color, Euler, Matrix3, Matrix4, Quaternion, Vector2, Vector3, Vector4};
// The small things that get reached for constantly and were not here: a
// mapping from one range to another, a seeded generator, a gradient, an easing
// curve, noise. Every one of them was being hand-rolled at the call site —
// twenty-six separate copies of the generator alone.
pub use crate::easing::Easing;
pub use crate::extras::SimplexNoise;
pub use crate::math::ToneMapping;
pub use crate::math::{
    convex_hull, delaunay, inverse_lerp, lerp, map_range, map_range_clamped, smootherstep,
    smoothstep, ticks, voronoi_cells, ColorRamp, RampSpace, Rng, ScaleLinear, ScaleLog, ScalePow,
};
pub use crate::math::{ColorScale, ColorSpace, Palette, ScaleKind};
pub use crate::overlay::Overlay;
#[cfg(feature = "render")]
pub use crate::renderer::{RenderTarget, Renderer};
pub use crate::scene::{FogParams, Scene};
pub use crate::textures::{
    CubeTexture, DataTexture, Texture, TextureFilter, TextureFormat, TextureWrap,
};

/// Offscreen rendering, and the PNG round trip that usually follows it.
#[cfg(all(feature = "render", not(target_arch = "wasm32")))]
pub use crate::renderer::headless::{HeadlessBuilder, HeadlessConfig, HeadlessRenderer};
cfg_apple! {
    #[cfg(feature = "render")]
    pub use crate::renderer::layer::{LayerGpu, LayerRenderer};
}
pub use crate::utils::png::{decode_png, encode_png, PngImage};

/// Vector SVG export, and the raster-in-SVG passthrough beside it.
pub use crate::renderers::{svg_from_rgba, SvgOptions, SvgRenderer, SvgShading};

cfg_metal! {
    /// The Metal backend's entry points, when the `metal` feature is on.
    pub use crate::metal::{
        MetalDevice, MetalError, MetalHeadlessRenderer, MetalRenderTarget, MetalRenderer, RenderView,
    };
}

/// The visionOS frame loop, when the `visionos` feature is on and that is what
/// is being built.
#[cfg(all(feature = "visionos", target_os = "visionos"))]
pub use crate::metal::visionos::{ImmersiveRenderer, WorldTracking};

/// Orbit / trackball / FPS / drag controls.
pub mod controls {
    pub use crate::controls::{
        ArcballControls, DragControls, FirstPersonControls, OrbitControls, PointerEvent,
        PointerLockControls, TrackballControls,
    };
}

/// Scene-graph animation mixer and keyframe clips (crate-root animation, not
/// `threers-animation`).
pub mod animation {
    pub use crate::animation::{
        AnimationAction, AnimationClip, AnimationMixer, Interpolation, KeyframeTrack, TrackTarget,
    };
}

/// Common asset loaders.
pub mod loaders {
    pub use crate::loaders::{
        AlembicArchive, AlembicError, ColladaError, ColladaLoader, DracoError, ExrError, ExrLoader,
        FbxError, FbxLoader, FbxScene, GcodeLoader, GcodeToolpath, GltfError, GltfImages,
        GltfLoader, GltfScene, HdrError, HdrLoader, Ktx2, Ktx2Error, MeshoptError, ObjLoader, PlyLoader, PolyMesh, StlLoader,
        TtfError, TtfFont, TtfGlyph,
    };
    // Writing, not only reading.
    pub use crate::loaders::{scene_to_glb, scene_to_gltf, GltfExportOptions};
}

/// Debug / authoring helpers.
pub mod helpers {
    pub use crate::helpers::{
        ArrowHelper, AxesHelper, BoxHelper, CameraHelper, DirectionalLightHelper, GridHelper,
        HemisphereLightHelper, PointLightHelper, PolarGridHelper, SkeletonHelper, SpotLightHelper,
        VertexNormalsHelper, VertexTangentsHelper,
    };
}

/// Lattices and architected materials: the [`Lattice`](crate::Lattice)
/// builder with its five families, what it fills and grades, what it is worth
/// as a material, and grown [`ScaleRich`](crate::ScaleRich) networks.
pub mod lattice {
    pub use crate::geometries::{
        Conform, Cuboct, Field, Infill, Lattice, LatticeKind, LatticeMetrics, LatticeStyle, Region,
        ScaleRich, ScaleRichAngles, ScaleRichLigament, ScaleRichNet, SeedLayout, SolidMaterial,
        Stiffness, Stochastic, Strut, Tpms,
    };
}

/// Constructive solid geometry (`bvh-csg`).
#[cfg(feature = "bvh-csg")]
pub mod csg {
    pub use crate::csg::{
        CsgBrush, CsgEvaluator, CsgNode, CsgOperation, CsgOperationGroup, TriangleIntersection,
        ADDITION, DIFFERENCE, INTERSECTION, SUBTRACTION,
    };
}

/// OpenSCAD solid DSL and `.scad` parse (`openscad`).
#[cfg(feature = "openscad")]
pub mod openscad {
    pub use crate::openscad::scad::parse_scad;
    pub use crate::openscad::{cone, cube, cylinder, sphere, Solid};
}

/// NURBS curves / surfaces (`nurbs`).
#[cfg(feature = "nurbs")]
pub mod nurbs {
    pub use crate::geometries::NurbsGeometry;
    pub use crate::nurbs::{NurbsCurve, NurbsSurface, TessellationOptions};
}

/// Path tracer (`raytrace`).
#[cfg(feature = "raytrace")]
pub mod raytrace {
    pub use crate::raytrace::{
        Aov, BackgroundMode, CpuBackend, RaytraceBackend, RaytraceError, RaytraceRenderer,
        RaytraceScene, RaytraceSettings,
    };
}

/// Video and animation codecs (`native-codec`), and the decoders
/// (`native-decode`). The codec crate's own prelude, `threers::codec::prelude`,
/// goes further: audio, containers and every codec module.
///
/// `h264` and `hevc` are imported as modules because both have a
/// `CompressedEncoder`: write `h264::CompressedEncoder`.
#[cfg(feature = "native-codec")]
pub mod video {
    #[cfg(feature = "native-decode")]
    pub use crate::codec::decode::{Backend, DecodedFrame, Decoder, NativeDecoder};
    pub use crate::codec::hevc::Yuv420Frame;
    pub use crate::codec::hw::{EncodeBackend, EncodeOptions, Mp4Encoder};
    #[cfg(feature = "gif")]
    pub use crate::codec::GifEncoder;
    pub use crate::codec::{
        encode_animation_rgba, encode_webm, h264, hevc, mp4, mp4_demux, AnimationEncodeOptions,
        ApngEncoder, BrowserCodec,
    };
}

cfg_metal! {
    /// Everything a Metal app reaches for, on top of the root's renderer and
    /// device: windows and layers, the reusable render threads, attachments and
    /// views for stereo, the post chain, and the pixel formats (`metal`).
    ///
    /// ```ignore
    /// use threers::prelude::*;
    /// use threers::prelude::metal::*;
    ///
    /// let device = MetalDevice::new()?;
    /// let pool = MetalRenderPool::new(&device, MetalRenderPoolConfig::for_this_device());
    /// ```
    pub mod metal {
        pub use crate::metal::enums::pixel_format;
        pub use crate::metal::{
            MetalBloom, MetalDevice, MetalError, MetalHeadlessBuilder, MetalHeadlessConfig,
            MetalHeadlessRenderer, MetalJob, MetalJobError, MetalRenderPool, MetalRenderPoolConfig,
            MetalRenderStats, MetalRenderTarget, MetalRenderer, MetalSsao, MetalSurface, MetalWorker,
            MetalWorkerQos, PassAttachments, PostFxChain, RenderView, SsaoSettings, SurfaceFrame,
        };
        #[cfg(feature = "fluid")]
        pub use crate::metal::{fluid_shader_source, MetalFluid};
        #[cfg(all(feature = "visionos", target_os = "visionos"))]
        pub use crate::metal::visionos::{ImmersiveRenderer, WorldTracking};
    }
}

/// A retained UI (`ui`): threers-ui's own prelude — the tree, `style!`,
/// layout, input and bindings, semantics, theme tokens, painters, gauges
/// and charts — with the painter onto an [`Overlay`] and, with `render`,
/// the GPU pass.
///
/// ```ignore
/// use threers::prelude::ui::*;
///
/// let mut ui = Ui::new();
/// let root = ui.root();
/// let mut g = gauge(&mut ui, root, "Battery", 0.0..=100.0, GaugeKind::Ring);
/// g.set(&mut ui, 72.0);
/// ```
#[cfg(feature = "ui")]
pub mod ui {
    #[cfg(feature = "render")]
    pub use crate::renderer::UiPass;
    pub use crate::ui::prelude::*;
    pub use crate::ui::{paint_to_rgba, OverlayPainter};
}

/// Headsets (`xr`): an [`App`](crate::xr::App) and the [`Frame`](crate::xr::Frame)
/// and [`Gpu`](crate::xr::Gpu) it is given, a UI on a [`Panel`](crate::xr::Panel)
/// drawn by a [`PanelPass`](crate::xr::PanelPass) (with the areas the system
/// highlights when looked at), and what a headset reports.
#[cfg(feature = "xr")]
pub mod xr {
    pub use crate::xr::{
        App, Frame, Gpu, Handedness, HoverArea, HoverTarget, Panel, PanelInput, PanelPass,
        PanelPlane, Pointer, TargetRayMode, XrEvent, XrEventKind, XrEye, XrInput, XrSource,
    };
}

/// Subtitle cues and on-screen overlay (`captions`).
#[cfg(feature = "captions")]
pub mod captions {
    pub use crate::captions::{
        CaptionAlign, CaptionAnchor, CaptionError, CaptionFont, CaptionFormat, CaptionOverlay,
        CaptionPainter, CaptionStyle, CaptionTrack, Cue,
    };
}

#[cfg(test)]
mod tests {
    //! The prelude's job is to compile. These build a scene using nothing but
    //! it, which is the only way to catch a name that quietly stopped being
    //! exported.
    use super::*;

    #[test]
    fn a_scene_can_be_built_from_the_prelude_alone() {
        let mut scene = Scene::new();
        scene.background = Color::from_hex(0x101010);
        let id = scene.add(Object3D::mesh(Mesh::new(
            SphereGeometry::new(1.0, 16, 12),
            Material::Standard(StandardMaterial::new(Color::WHITE).with_roughness(0.4)),
        )));
        scene.add_light(AmbientLight::new(Color::WHITE, 0.2));
        scene.add(Object3D::light(DirectionalLight::new(Color::WHITE, 2.0)));

        if let Some(object) = scene.get_mut(id) {
            object.position = Vector3::new(0.0, 1.0, 0.0);
            object.quaternion = Quaternion::from_axis_angle(Vector3::UP, 0.5);
            object.scale = Vector3::ONE * 2.0;
        }
        scene.update_world();

        let world = scene.get(id).unwrap().matrix_world;
        assert_eq!(world.elements[13], 1.0);
    }

    #[test]
    fn the_camera_trait_is_in_scope() {
        let mut camera = PerspectiveCamera::new(50.0, 1.5, 0.1, 100.0);
        camera.position = Vector3::new(0.0, 0.0, 5.0);
        camera.look_at(Vector3::ZERO);
        // `view_matrix` comes from the trait: this line is the test.
        let view = camera.view_matrix();
        assert_eq!(view.elements[14], -5.0);

        let ortho = OrthographicCamera::new(-1.0, 1.0, 1.0, -1.0, 0.1, 10.0);
        assert_eq!(ortho.near_far(), (0.1, 10.0));
    }

    #[test]
    fn glass_shadows_and_colour_from_the_prelude_alone() {
        let glass = PhysicalMaterial::new(Color::WHITE)
            .with_transmission(1.0, 1.5, 0.5)
            .with_transparency(TransparencyMode::Refract);
        assert_eq!(glass.transparency, TransparencyMode::Refract);
        let mut sun = DirectionalLight::new(Color::WHITE, 2.0);
        sun.shadow.filter = Some(ShadowType::Pcss);
        assert_eq!(sun.shadow.filter, Some(ShadowType::Pcss));

        let (red, alpha) = Color::parse_css("oklch(62.8% 0.2577 29.23 / 0.5)").unwrap();
        assert!(red.r > 0.9 && red.g < 0.05 && alpha == 0.5);
        let scale = ColorScale::sequential(ColorRamp::viridis(), 0.0, 1.0).log(10.0);
        let _ = scale.map(0.5);
        let palette = Palette::from_hex(&[0xff0000, 0x00ff00]);
        let _ = (palette, ScaleKind::Linear, ColorSpace::Oklch);
    }

    #[test]
    fn geometry_and_texture_types_are_reachable() {
        let mut geometry = BufferGeometry::new();
        geometry.set_attribute(
            "position",
            BufferAttribute::new(vec![0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0], 3),
        );
        assert_eq!(geometry.draw_count(), 3);

        let texture = Texture::new(1, 1, TextureFormat::Rgba8Unorm, vec![255, 0, 0, 255]);
        assert_eq!(texture.mag_filter, TextureFilter::Linear);
        assert_eq!(texture.wrap_s, TextureWrap::ClampToEdge);
    }

    #[test]
    fn png_round_trips_through_the_prelude() {
        let rgba = vec![255u8, 0, 0, 255, 0, 255, 0, 255];
        let png = encode_png(2, 1, &rgba);
        let image: PngImage = decode_png(&png).unwrap();
        assert_eq!((image.width, image.height), (2, 1));
        assert_eq!(image.rgba, rgba);
    }

    cfg_metal! {
            #[test]
        fn nested_metal_module_names_the_working_set() {
            use super::metal::*;
            let config = MetalRenderPoolConfig::for_this_device();
            assert!(config.threads >= 1);
            let _ = (pixel_format::BGRA8_UNORM_SRGB, MetalWorkerQos::UserInteractive);
            let _ = std::mem::size_of::<(MetalSurface, MetalRenderPool, PassAttachments, PostFxChain)>();
        }
    }

    #[cfg(feature = "ui")]
    #[test]
    fn nested_ui_module_builds_a_ui() {
        use super::ui::*;
        let mut ui = Ui::new();
        let root = ui.root();
        let card = ui.add_box(root, style! { padding: 8px; });
        ui.token_style(card, &[("background", Token::Surface)]);
        let mut g = gauge_styled(
            &mut ui,
            card,
            "Load",
            0.0..=1.0,
            GaugeKind::Circular,
            GaugeStyle {
                tint: GaugeTint::levels(),
                animate: false,
                ..Default::default()
            },
        );
        g.set(&mut ui, 0.9);
        ui.layout(200.0, 200.0, &mut FixedWidthText(7.0));
        let rgba = paint_to_rgba(&ui, 1.0, 200, 200);
        assert_eq!(rgba.len(), 200 * 200 * 4);
        assert_eq!(ui.hover_regions().len(), 0, "a gauge is not pressed");
        let _: Option<ArcShape> = ArcShape::from_svg("M50 10 A40 40 0 0 1 90 50");
    }

    #[cfg(feature = "xr")]
    #[test]
    fn nested_xr_module_places_a_panel() {
        use super::xr::*;
        let mut panel = Panel::new(1280.0, 800.0);
        panel.place_facing(&Matrix4::translation(Vector3::new(0.0, 1.6, 0.0)).elements);
        let plane: PanelPlane = panel.plane().unwrap();
        assert!(plane.half.0 > 0.0);
        let _ = (
            HoverArea {
                id: 1,
                rect: [0.0; 4],
                radius: 0.0,
            },
            TargetRayMode::Gaze,
            XrEventKind::Select,
        );
    }

    #[test]
    fn nested_controls_module_exports_orbit() {
        use super::controls::OrbitControls;
        let _ = std::mem::size_of::<OrbitControls>();
    }
}