Skip to content

The native runtime for three.js: three.js, down to the metal. 45× smaller than Electron, on a Sony PS3, and path-traced at 60 fps on ray-tracing GPUs.

The engine's library builds for wasm32; natively nothing changes (#5)

Yujiabc93e83eb2a7
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 642578b..bfe9c72 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -42,3 +42,5 @@ jobs:
# in wasm32 (ROADMAP § 6 step 7).
- run: cd renderer/physics-core && cargo build --release --locked --target wasm32-unknown-unknown && cargo test --release --locked
- run: node tools/physics-determinism.ts
+ # The engine's library builds for the browser (wasm32; docs/RUNTIME.md "The engine's library in a browser").
+ - run: cd renderer && cargo build --release --locked --lib --target wasm32-unknown-unknown
diff --git a/README.md b/README.md
index 3362167..023c110 100644
--- a/README.md
+++ b/README.md
@@ -77,7 +77,8 @@ npm run test:render # the render test suite on the GPU
- `npm run typecheck`, `npm test`;
- the renderer's release build;
- the voxel core's wasm32 build and tests, and native / wasm32 edit determinism;
-- the physics core's wasm32 build and tests, and native / wasm32 determinism (a script and 1,000 random worlds).
+- the physics core's wasm32 build and tests, and native / wasm32 determinism (a script and 1,200 random worlds);
+- the engine library's wasm32 build.
The GPU checks (`test:render`, the perf smoke, the benches) run on a Mac, per [`docs/WORKFLOW.md`](docs/WORKFLOW.md).
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md
index 539c857..dc5dcd2 100644
--- a/docs/ROADMAP.md
+++ b/docs/ROADMAP.md
@@ -3755,6 +3755,19 @@ benchmark level. The order follows the dependencies; a step that meets a further
0.33–0.62 ms before (0.30–0.54 ms in step 7's table), 0.16–0.37 ms now; the commit and the first frame after a
click as before (0.29–0.53 ms in place, 3.9–4.0 ms). The frame's script time with no frame script is 0.083 ms
mean (0.094 ms with the old frame script): the host's call, the events and an empty sync.
+ - **The engine's library for wasm32** (2026-11-11, branch `wasm32-engine`; the first half of layout C, after a
+ probe of what a browser can run).
+ - The probe (measured on an M5 Pro, Chrome 157, the real GPU): the kernel itself, with software traversal and
+ the native renderer's scene data, costs 0.98–1.08 × its native time in Chrome (hello 4.19 ms against 3.9 ms
+ a full-resolution sample pass, Kabukichō 70.3 against 66.8–68.0), and draws the same image. WebGPU's limit
+ on storage buffers a stage (8 by default, 10 in that Chrome) is under what the kernel (20) and the live
+ `temporal` / `post` / `dtemporal` passes (19 / 13 / 11) bind: the web build gets a merged layout generated
+ from the one source. What stands in the way is software traversal itself: one flat BVH, so every added or
+ moving object rebuilds the scene (hello: 9 ms a frame while a body moves; the voxel level: 7 s an explosion),
+ and it holds 2.1 GB of triangle data for the voxel level.
+ - This step: the library builds for `wasm32-unknown-unknown` with the native shell left out, the GPU from
+ futures, `web_time`, and file reads behind one module (docs/RUNTIME.md "The engine's library in a browser").
+ Natively the renders are byte-identical.
8. **[engine] Voxel bodies.** The voxel collision shape and debris as bodies.
- Acceptance: about a hundred debris bodies within the frame budget on the level, with the CPU split recorded.
- Then the decision: keep Rapier or write our own.
diff --git a/docs/RUNTIME.md b/docs/RUNTIME.md
index 358e78a..7181181 100644
--- a/docs/RUNTIME.md
+++ b/docs/RUNTIME.md
@@ -293,6 +293,40 @@ Building a script engine into the wasm module (layout A), as far as it was taken
- Not verified by the probe: a real browser; wgpu in the same module as a script engine; the software BVH traversal's
frame rate in a browser (WebGPU has no hardware ray queries: the web's largest unknown, whichever layout).
+## The engine's library in a browser (wasm32)
+
+Layout C's first half: `renderer/` builds as a library for `wasm32-unknown-unknown` (CI builds it). Natively nothing
+changed: the same sources, the same shaders, byte-identical renders. What runs it in a page (the exports, the JS
+`Engine`, the canvas) is `renderer/web`, the step after this one.
+
+- **The native shell stays native:** the window (`view`, winit), the embedded script runtime (`script`, rquickjs: a
+ browser runs the game's TypeScript in its own engine), the denoiser (OIDN), image comparison, the headless runner
+ (`live::run`: stdin commands, frame log, snapshots), the offline render (`Gpu::render`) and the snapshot readbacks.
+ They are not compiled for wasm32.
+- **The GPU comes from futures:** `Gpu::new_async()`; the native `Gpu::new()` blocks on it. A browser resolves them
+ from its event loop, and nothing in the library may block there.
+- **Time** is `web_time::Instant`: std's natively (a re-export), `performance.now()` in a browser, where std's panics.
+- **Files** (`files.rs`): the library's reads go through one module. Natively the file system, as before. In a
+ browser the page fetches what the scene names (`World::files`) and hands the bytes over (`files::provide`) before
+ the scene is built; the two presets are compiled in. A glTF's external buffers and images are still read from disk
+ by the glTF crate: only GLB files (everything in one file) load in a browser.
+- **Waiting for the GPU.** wgpu's `poll(wait)` returns at once in a browser, and a buffer is mapped only after the
+ page's event loop turned. The 30 places that wait:
+
+ | where | what | in a browser |
+ | --- | --- | --- |
+ | `LiveCore::render`: at most two frames in flight | waits for the oldest submission | no wait (the page's frame callback paces) |
+ | `LiveCore::render`: GPU timestamps (`harvest`) | mapped asynchronously, read a later frame | works as it is |
+ | `LiveCore::render`: without timestamp queries, a frame timed by waiting for it | wait | reads ~0: dynamic resolution needs the `timestamp-query` feature there, or a fixed scale |
+ | `LiveCore::render`: `THREERT_PROFILE` | wait + map | not reachable (no environment) |
+ | `repose`, `repose_groups`, `edit_geometry`: `THREERT_PROFILE_BLAS` | wait | not reachable |
+ | `Gpu::upload`: after the uploads, and after the BLAS builds | wait | no wait; hardware RT is not in a browser |
+ | `Gpu::render`, `render_translucent` (offline), `read_hdr`, `read_signals`, `read_ev100`, `live::run`'s snapshots | wait + map + read | native only |
+- **Threads:** none in a browser. Scene builds (BVH, texture pages, model loading) run on the one thread (rayon falls
+ back to it). The dynamic sky's bake thread cannot start, so a sky whose sun moves keeps the sky it was built with.
+- Checked: the library's wasm32 build in CI; the physics' recorded hashes in the renderer's wasm32 graph
+ (`tools/physics-determinism.ts`). Not yet run in a page: that is `renderer/web`'s to show.
+
## Correctness
* `threert-render edit-check` builds the GPU tables both ways for a list of events: edited in place, and built fresh
diff --git a/renderer/Cargo.lock b/renderer/Cargo.lock
index 117138d..a540263 100644
--- a/renderer/Cargo.lock
+++ b/renderer/Cargo.lock
@@ -2366,6 +2366,7 @@ dependencies = [
"serde_json",
"sha2",
"voxel-core",
+ "web-time",
"wgpu",
"winit",
]
diff --git a/renderer/Cargo.toml b/renderer/Cargo.toml
index 55296d8..e15a211 100644
--- a/renderer/Cargo.toml
+++ b/renderer/Cargo.toml
@@ -8,7 +8,6 @@ description = "Native renderer for ThreeRT games: embedded scene runtime, GPU pa
voxel-core = { path = "voxel-core" }
physics-core = { path = "physics-core" }
wgpu = "30"
-pollster = "0.4"
bytemuck = { version = "1", features = ["derive"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
@@ -17,13 +16,28 @@ image = { version = "0.25", default-features = false, features = ["png", "jpeg",
glam = { version = "0.30", features = ["bytemuck"] }
rayon = "1.10"
anyhow = "1"
-winit = "0.30"
half = { version = "2", features = ["bytemuck"] }
+# Procedural geometry data: content hashes (asset files and inline data alike; src/procasset.rs).
+sha2 = "0.10"
+
+# The clock of a frame: std's natively (a re-export, nothing changes), the page's `performance.now()` in a browser,
+# where std's `Instant` panics.
+web-time = "1.1"
+
+# The native shell only: the window, the embedded script runtime, blocking on the GPU's futures, the denoiser. The
+# engine's library builds without them for wasm32 (docs/RUNTIME.md "The engine's library in a browser"): there the
+# page owns the window and the event loop, and scripts run in the browser's own engine.
+[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
+pollster = "0.4"
+winit = "0.30"
oidn = { version = "2.5", optional = true }
# Scene runtime of the render node (game bundles run in the renderer process, src/script.rs).
rquickjs = "0.12"
-# Procedural geometry data: content hashes (asset files and inline data alike; src/procasset.rs).
-sha2 = "0.10"
+
+# tools/physics-determinism.ts: the physics' recorded hashes in this crate's wasm32 graph.
+[[example]]
+name = "physics_bits"
+crate-type = ["cdylib"]
[features]
# Intel Open Image Denoise (needs OIDN_DIR at build time and the shared libs at runtime).
diff --git a/renderer/examples/physics_bits.rs b/renderer/examples/physics_bits.rs
new file mode 100644
index 0000000..a989cf2
--- /dev/null
+++ b/renderer/examples/physics_bits.rs
@@ -0,0 +1,17 @@
+//! The physics' recorded determinism hashes (physics_core::check) computed in the renderer's dependency graph, as a
+//! wasm32 module's exports: tools/physics-determinism.ts builds it for `wasm32-unknown-unknown` and compares them with
+//! the recorded ones: the engine's library in a browser steps to the bits the native build does.
+//! What this does not show is the glamx patch (third_party/glamx/PATCH.md): in wasm32 an f32's own `acos` is Rust's
+//! port of libm, the same function the patch calls by name, so these hashes come out right with or without it
+//! (measured). The patch matters natively, where the method is the platform's: the native test
+//! `physics::tests::the_renderers_physics_steps_to_the_recorded_bits` fails without it, and every native crate that
+//! depends on physics-core needs that test.
+#[no_mangle]
+pub extern "C" fn physics_script() -> u64 {
+ physics_core::check::script(600)
+}
+
+#[no_mangle]
+pub extern "C" fn physics_cases() -> u64 {
+ physics_core::check::cases()
+}
diff --git a/renderer/src/files.rs b/renderer/src/files.rs
new file mode 100644
index 0000000..62c973e
--- /dev/null
+++ b/renderer/src/files.rs
@@ -0,0 +1,77 @@
+//! Where the engine's library reads files from. Natively: the file system, as before (these are `std::fs`'s and the
+//! `image` / `gltf` crates' own readers, called from one place). In a browser (wasm32) there is no file system: the
+//! page fetches what a scene names (`World::files`) and hands the bytes over with `provide` before the scene is built,
+//! and the two presets are compiled in. The paths are the ones the native build would open (asset root joined with
+//! the scene's uri), so the same scene code names the same files on both.
+
+use anyhow::Result;
+use std::path::Path;
+
+#[cfg(target_arch = "wasm32")]
+thread_local! {
+ static PROVIDED: std::cell::RefCell<std::collections::HashMap<std::path::PathBuf, std::sync::Arc<[u8]>>> = Default::default();
+}
+
+/// A file's bytes for the path the engine will ask for (a browser's page, after it fetched them).
+#[cfg(target_arch = "wasm32")]
+pub fn provide(path: &Path, bytes: Vec<u8>) {
+ PROVIDED.with(|p| p.borrow_mut().insert(path.to_path_buf(), bytes.into()));
+}
+
+/// The file's bytes.
+pub fn read(path: &Path) -> std::io::Result<Vec<u8>> {
+ #[cfg(not(target_arch = "wasm32"))]
+ return std::fs::read(path);
+ #[cfg(target_arch = "wasm32")]
+ return PROVIDED
+ .with(|p| p.borrow().get(path).map(|b| b.to_vec()))
+ .ok_or_else(|| std::io::Error::new(std::io::ErrorKind::NotFound, format!("{}: not provided (a page fetches a scene's files before it is built)", path.display())));
+}
+
+/// The file's length and modification time (ns since the epoch), for the caches' keys; (0, 0) for one that is not
+/// there. In a browser: its length (bytes provided anew under a path are another version only if their length differs;
+/// a page that replaces a file reloads).
+pub fn version(path: &Path) -> (u64, u128) {
+ #[cfg(not(target_arch = "wasm32"))]
+ {
+ let m = std::fs::metadata(path).ok();
+ let mtime = m.as_ref().and_then(|m| m.modified().ok()).and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()).map_or(0, |d| d.as_nanos());
+ (m.map_or(0, |m| m.len()), mtime)
+ }
+ #[cfg(target_arch = "wasm32")]
+ {
+ (PROVIDED.with(|p| p.borrow().get(path).map_or(0, |b| b.len() as u64)), 0)
+ }
+}
+
+/// A texture file decoded to RGBA8.
+pub fn image(path: &Path) -> Result<image::RgbaImage> {
+ #[cfg(not(target_arch = "wasm32"))]
+ return Ok(image::open(path)?.to_rgba8());
+ #[cfg(target_arch = "wasm32")]
+ return Ok(image::load_from_memory(&read(path)?)?.to_rgba8());
+}
+
+/// A glTF / GLB file: its document, and the binary chunk of a GLB. (The buffers and images it names beside it are
+/// read by `gltf_base`.)
+pub fn gltf(path: &Path) -> gltf::Result<gltf::Gltf> {
+ #[cfg(not(target_arch = "wasm32"))]
+ return gltf::Gltf::open(path);
+ #[cfg(target_arch = "wasm32")]
+ return gltf::Gltf::from_slice(&read(path).map_err(gltf::Error::Io)?);
+}
+
+/// A render preset's JSON: `<dir>/<name>.json`; in a browser, the two the engine ships, compiled in.
+pub fn preset(dir: &Path, name: &str) -> std::io::Result<Vec<u8>> {
+ #[cfg(not(target_arch = "wasm32"))]
+ return std::fs::read(dir.join(format!("{name}.json")));
+ #[cfg(target_arch = "wasm32")]
+ {
+ let _ = dir;
+ match name {
+ "cinematic" => Ok(include_bytes!("../../presets/cinematic.json").to_vec()),
+ "preview" => Ok(include_bytes!("../../presets/preview.json").to_vec()),
+ other => Err(std::io::Error::new(std::io::ErrorKind::NotFound, format!("preset {other}: a browser build has cinematic and preview"))),
+ }
+ }
+}
diff --git a/renderer/src/gpu.rs b/renderer/src/gpu.rs
index b21fe59..0910dd5 100644
--- a/renderer/src/gpu.rs
+++ b/renderer/src/gpu.rs
@@ -3,7 +3,7 @@
use crate::scene::Scene;
use crate::GROUPS;
use anyhow::{anyhow, Result};
-use std::time::Instant;
+use web_time::Instant;
use wgpu::util::DeviceExt;
pub struct Gpu {
@@ -883,18 +883,22 @@ fn stamp() {
";
impl Gpu {
+ /// The GPU, waited for (the native shell; a browser has `new_async`: nothing may block there).
+ #[cfg(not(target_arch = "wasm32"))]
pub fn new() -> Result<Gpu> {
+ pollster::block_on(Self::new_async())
+ }
+
+ /// The adapter and the device come from futures: a browser resolves them from its event loop.
+ pub async fn new_async() -> Result<Gpu> {
let backends = wgpu::Backends::from_env().unwrap_or(wgpu::Backends::PRIMARY);
let mut desc = wgpu::InstanceDescriptor::new_without_display_handle();
desc.backends = backends;
let instance = wgpu::Instance::new(desc);
- let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {
- power_preference: wgpu::PowerPreference::HighPerformance,
- force_fallback_adapter: false,
- compatible_surface: None,
- ..Default::default()
- }))
- .map_err(|e| anyhow!("no GPU adapter: {e}"))?;
+ let adapter = instance
+ .request_adapter(&wgpu::RequestAdapterOptions { power_preference: wgpu::PowerPreference::HighPerformance, force_fallback_adapter: false, compatible_surface: None, ..Default::default() })
+ .await
+ .map_err(|e| anyhow!("no GPU adapter: {e}"))?;
let adapter_info = adapter.get_info();
let mut limits = wgpu::Limits::default();
let al = adapter.limits();
@@ -915,14 +919,14 @@ impl Gpu {
if timestamps {
features |= wgpu::Features::TIMESTAMP_QUERY;
}
- let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor {
+ let (device, queue) = adapter.request_device(&wgpu::DeviceDescriptor {
label: Some("threert"),
required_features: features,
required_limits: limits,
// Ray queries are still flagged experimental in wgpu 30.
experimental_features: if hwrt { unsafe { wgpu::ExperimentalFeatures::enabled() } } else { wgpu::ExperimentalFeatures::disabled() },
..Default::default()
- }))?;
+ }).await?;
let base = include_str!("../shaders/pathtrace.wgsl");
let src = if hwrt {
let (head, rest) = base.split_once("// @trace-begin").unwrap();
@@ -2238,6 +2242,7 @@ impl Gpu {
e.build_acceleration_structures(entries.iter(), [&accel.tlas]);
}
+ #[cfg(not(target_arch = "wasm32"))]
/// Offline translucency: the pass (translucent.wgsl) `spp` times at random points in each pixel, each with a fresh
/// lighting estimate per hit; the mean (colour, transmittance) per pixel. Empty without translucent particles.
fn render_translucent(&self, up: &Uploaded, base: Params, spp: u32) -> Result<Vec<[f32; 4]>> {
@@ -2283,6 +2288,7 @@ impl Gpu {
Ok(out)
}
+ #[cfg(not(target_arch = "wasm32"))]
/// Render `spp` samples. `base` holds everything except the per-dispatch sample index.
#[allow(clippy::too_many_arguments)]
pub fn render(&self, scene: &Scene, tri_verts: &[[f32; 4]], groups: [usize; GROUPS], nodes: &[u8], emitters: &[[f32; 4]], env: &EnvMap, env_cdf: &[f32], energy: &[[f32; 4]], base: Params, spp: u32, timings: &mut Vec<(String, f64)>) -> Result<Frame> {
diff --git a/renderer/src/lib.rs b/renderer/src/lib.rs
index c7df2b5..c4f7670 100644
--- a/renderer/src/lib.rs
+++ b/renderer/src/lib.rs
@@ -2,20 +2,25 @@
//! `threert-render` CLI and by the native playground client).
pub mod bvh;
+#[cfg(not(target_arch = "wasm32"))]
pub mod compare;
+#[cfg(not(target_arch = "wasm32"))]
pub mod denoise;
pub mod desc;
+pub mod files;
pub mod gpu;
pub mod live;
pub mod ltree;
pub mod post;
pub mod procasset;
pub mod scene;
+#[cfg(not(target_arch = "wasm32"))]
pub mod script;
pub mod skin;
pub mod sky;
pub mod tables;
pub mod texpack;
+#[cfg(not(target_arch = "wasm32"))]
pub mod view;
pub mod physics;
pub mod voxel;
@@ -23,7 +28,7 @@ pub mod world;
use glam::{Vec3, Vec3A};
use std::path::PathBuf;
-use std::time::Instant;
+use web_time::Instant;
/// `presets/` next to (an ancestor of) the executable, else ./presets.
pub fn default_presets_dir() -> PathBuf {
diff --git a/renderer/src/live.rs b/renderer/src/live.rs
index 6fc5590..9998212 100644
--- a/renderer/src/live.rs
+++ b/renderer/src/live.rs
@@ -23,14 +23,19 @@
use crate::world::World;
use crate::{gpu, post, prepare, scene, tables};
+// (The headless runner below, native only, is what uses all of it.)
+#[cfg_attr(target_arch = "wasm32", allow(unused_imports))]
use anyhow::{anyhow, Result};
use glam::Vec3;
+#[cfg_attr(target_arch = "wasm32", allow(unused_imports))]
use std::io::BufRead;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::mpsc;
use std::sync::Arc;
-use std::time::{Duration, Instant};
+#[cfg_attr(target_arch = "wasm32", allow(unused_imports))]
+use std::time::Duration;
+use web_time::Instant;
pub struct LiveOpts {
pub width: u32,
@@ -3546,6 +3551,7 @@ impl LiveCore {
self.frame = self.frame.wrapping_add(1);
}
+ #[cfg(not(target_arch = "wasm32"))]
/// The last frame's linear HDR radiance (nits, before exposure and post), RGB per output pixel. Waits for the GPU.
pub fn read_hdr(&self) -> Result<Vec<f32>> {
let d = &self.g.device;
@@ -3560,6 +3566,7 @@ impl LiveCore {
Ok(px)
}
+ #[cfg(not(target_arch = "wasm32"))]
/// The last frame's signals apart, linear RGB f32 per output pixel: diffuse (the composed image less the rest, so
/// with the sun's direct light, which view mode 6 leaves out), specular (the specular denoiser's output: mode 7) and
/// emission (what the camera saw directly). Without motion blur or depth of field they add up to
@@ -3598,6 +3605,7 @@ impl LiveCore {
Ok([dif, spe, emi])
}
+ #[cfg(not(target_arch = "wasm32"))]
/// The exposure the last frame was shown at, EV100 (auto exposure: its adapted value).
pub fn read_ev100(&self) -> Result<f32> {
if self.sc.exposure_settings.ae2[3] <= 0.5 {
@@ -3758,6 +3766,7 @@ pub fn next_spp(spp: u32, gpu_ms: f32, fps: u32) -> u32 {
target.clamp(1, 16).min(spp + 1).max(spp.saturating_sub(2).max(1))
}
+#[cfg(not(target_arch = "wasm32"))]
/// Headless runner: renders at a fixed frame rate and saves snapshots on request (tools/bench-live.ts).
pub fn run(presets: &Path, opts: LiveOpts) -> Result<()> {
let (w, h) = (opts.width, opts.height);
@@ -3934,6 +3943,7 @@ pub fn run(presets: &Path, opts: LiveOpts) -> Result<()> {
}
}
+#[cfg(not(target_arch = "wasm32"))]
/// Sleeps until `t` without trusting the timer's precision: macOS gives a process that is not a foreground app timer
/// leeway of half the interval (a 16 ms sleep returned after 24, measured from a terminal-launched viewport and from
/// plain Python alike). Pacing sleeps of the headless viewport overslept by ~5 ms once the GPU fit the frame: Bistro's
@@ -3954,6 +3964,7 @@ fn sleep_until(t: Instant) {
}
}
+#[cfg(not(target_arch = "wasm32"))]
pub fn save_bgra(path: &Path, px: &[u8], w: u32, h: u32) {
let rgba: Vec<u8> = px.chunks(4).flat_map(|p| [p[2], p[1], p[0], 255]).collect();
if let Err(e) = image::save_buffer(path, &rgba, w, h, image::ColorType::Rgba8) {
@@ -3961,6 +3972,7 @@ pub fn save_bgra(path: &Path, px: &[u8], w: u32, h: u32) {
}
}
+#[cfg(not(target_arch = "wasm32"))]
fn spawn_stdin_reader(cmd_tx: mpsc::Sender<Cmd>) {
std::thread::spawn(move || {
for line in std::io::stdin().lock().lines() {
@@ -3974,6 +3986,7 @@ fn spawn_stdin_reader(cmd_tx: mpsc::Sender<Cmd>) {
});
}
+#[cfg(not(target_arch = "wasm32"))]
pub fn parse_cmd(line: &str) -> Option<Cmd> {
let v: serde_json::Value = serde_json::from_str(line).ok()?;
let vec = |k: &str| v[k].as_array().map(|a| Vec3::new(a[0].as_f64().unwrap_or(0.0) as f32, a[1].as_f64().unwrap_or(0.0) as f32, a[2].as_f64().unwrap_or(0.0) as f32));
@@ -4007,6 +4020,7 @@ pub fn parse_cmd(line: &str) -> Option<Cmd> {
})
}
+#[cfg(not(target_arch = "wasm32"))]
pub fn parse_opts(args: &[String]) -> Result<LiveOpts> {
let flag = |name: &str| args.iter().position(|a| a == name).and_then(|i| args.get(i + 1)).cloned();
let num = |name: &str, d: u32| -> Result<u32> { flag(name).map(|v| v.parse().map_err(|_| anyhow!("{name} must be a number"))).transpose().map(|v| v.unwrap_or(d)) };
@@ -4023,6 +4037,7 @@ pub fn parse_opts(args: &[String]) -> Result<LiveOpts> {
})
}
+#[cfg(not(target_arch = "wasm32"))]
/// `--scale`: a fraction (0.25 .. 1) or `auto` (dynamic resolution).
pub fn parse_scale(v: Option<&str>, default: Option<f32>) -> Result<Option<f32>> {
match v {
diff --git a/renderer/src/physics.rs b/renderer/src/physics.rs
index ebc2c3a..67c5c10 100644
--- a/renderer/src/physics.rs
+++ b/renderer/src/physics.rs
@@ -12,7 +12,7 @@ use anyhow::{anyhow, Result};
use glam::{Mat4, Quat, Vec3};
use physics_core::bridge::{Bridge, Scene};
use serde_json::Value;
-use std::time::Instant;
+use web_time::Instant;
/// A frame's physics, for the frame log: the ticks stepped and their time, the time to place the driven objects, the
/// bodies and how many of them moved.
diff --git a/renderer/src/procasset.rs b/renderer/src/procasset.rs
index 6055e1e..6cb70b6 100644
--- a/renderer/src/procasset.rs
+++ b/renderer/src/procasset.rs
@@ -165,7 +165,7 @@ pub fn load(uri: &str, assets: &Path) -> Result<Arc<ProcBlob>> {
if let Some(b) = CACHE.lock().unwrap().as_ref().and_then(|c| c.get(&key)) {
return Ok(b.clone());
}
- let bytes = std::fs::read(&path).map_err(|e| anyhow!("procedural geometry {uri}: {e}"))?;
+ let bytes = crate::files::read(&path).map_err(|e| anyhow!("procedural geometry {uri}: {e}"))?;
let b = Arc::new(ProcBlob::parse(&bytes).map_err(|e| anyhow!("procedural geometry {uri}: {e}"))?);
let mut c = CACHE.lock().unwrap();
let c = c.get_or_insert_with(std::collections::HashMap::new);
diff --git a/renderer/src/scene.rs b/renderer/src/scene.rs
index c9f68a5..35e984a 100644
--- a/renderer/src/scene.rs
+++ b/renderer/src/scene.rs
@@ -700,9 +700,8 @@ impl TexCache {
/// Identity of a file version: (path, length, mtime). Assets and textures rarely change, so they are parsed /
/// decoded once per process.
pub(crate) fn file_key(path: &Path) -> String {
- let m = std::fs::metadata(path).ok();
- let mtime = m.as_ref().and_then(|m| m.modified().ok()).and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()).map_or(0, |d| d.as_nanos());
- format!("{}|{}|{mtime}", path.display(), m.map_or(0, |m| m.len()))
+ let (len, mtime) = crate::files::version(path);
+ format!("{}|{len}|{mtime}", path.display())
}
/// Process-wide parse / decode caches (bounded: cleared when they grow past a working set).
@@ -757,7 +756,7 @@ fn texture_image(t: &world::Texture, assets: &Path) -> Result<(String, Arc<image
world::TextureSource::File(uri) => {
let path = assets.join(uri);
let key = file_key(&path);
- Ok((key.clone(), cached_image(&key, || Ok(image::open(&path).with_context(|| format!("texture {uri}"))?.to_rgba8()))?))
+ Ok((key.clone(), cached_image(&key, || crate::files::image(&path).with_context(|| format!("texture {uri}")))?))
}
world::TextureSource::Encoded(bytes) => {
let key = bytes_key("encoded", bytes);
@@ -781,7 +780,7 @@ pub fn model_gltf(uri: &str, assets: &Path) -> Result<Arc<skin::Model>> {
fn import_gltf(path: &Path) -> gltf::Result<skin::Gltf> {
use rayon::prelude::*;
let base = path.parent().unwrap_or_else(|| Path::new("./"));
- let gltf::Gltf { document, blob } = gltf::Gltf::open(path)?;
+ let gltf::Gltf { document, blob } = crate::files::gltf(path)?;
let buffers = gltf::import_buffers(&document, Some(base), blob)?;
let images = document.images().collect::<Vec<_>>().into_par_iter().map(|i| gltf::image::Data::from_source(i.source(), Some(base), &buffers)).collect::<gltf::Result<Vec<_>>>()?;
Ok((document, buffers, images))
@@ -900,9 +899,9 @@ pub fn card_material(color: [f32; 3], intensity: f32) -> GpuMaterial {
/// Builds the GPU scene from the engine's world. Asset files (models, file textures) resolve against `assets`.
pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&serde_json::Value>) -> Result<Scene> {
- let t0 = std::time::Instant::now();
+ let t0 = web_time::Instant::now();
let st = &w.settings;
- let mut preset_json: serde_json::Value = serde_json::from_slice(&std::fs::read(presets_dir.join(format!("{}.json", st.preset))).with_context(|| format!("preset {}", st.preset))?)?;
+ let mut preset_json: serde_json::Value = serde_json::from_slice(&crate::files::preset(presets_dir, &st.preset).with_context(|| format!("preset {}", st.preset))?)?;
if let Some(o) = &st.overrides {
desc::merge_json(&mut preset_json, o);
}
diff --git a/renderer/src/skin.rs b/renderer/src/skin.rs
index 1cb624b..0785a26 100644
--- a/renderer/src/skin.rs
+++ b/renderer/src/skin.rs
@@ -424,7 +424,7 @@ mod bench {
let path = std::env::var("THREERT_SKIN_GLB").unwrap();
let m = super::Model::new(gltf::import(&path).unwrap()).unwrap();
let clip = m.clip_names()[0].clone();
- let t0 = std::time::Instant::now();
+ let t0 = web_time::Instant::now();
let mut n = 0;
for k in 0..100 {
let a = crate::desc::Animation { clip: clip.clone(), time: k as f32 * 0.016, r#loop: true };
@@ -433,7 +433,7 @@ mod bench {
eprintln!("{n} triangles: {:.3} ms per pose", t0.elapsed().as_secs_f64() * 1000.0 / 100.0);
let a = crate::desc::Animation { clip, time: 0.3, r#loop: true };
let tris = m.triangles(glam::Mat4::IDENTITY, None, Some(&a)).unwrap();
- let t0 = std::time::Instant::now();
+ let t0 = web_time::Instant::now();
let mut x = 0.0;
for _ in 0..100 {
for t in &tris {
diff --git a/renderer/src/voxel.rs b/renderer/src/voxel.rs
index acfb536..026956b 100644
--- a/renderer/src/voxel.rs
+++ b/renderer/src/voxel.rs
@@ -21,7 +21,7 @@ use serde::Deserialize;
use std::collections::{BTreeSet, HashMap};
use std::path::Path;
use std::rc::Rc;
-use std::time::Instant;
+use web_time::Instant;
use voxel_core::{decode, greedy_mesh, gravity_for, layout, to_fp, Edit, Granularity, Level, MeshPart, Placement, Shape, VoxelGrid, FALL_FP, RADII};
/// A loose part of fewer voxels is debris, not an object (`voxel_core::MIN_PIECE`).
@@ -1096,7 +1096,7 @@ mod tests {
}
let blob = crate::procasset::ProcBlob::parse(&std::fs::read(&p).unwrap()).unwrap();
let (g, corner, size) = voxel_core::decode(&blob.data).unwrap();
- let t = std::time::Instant::now();
+ let t = web_time::Instant::now();
let reps = 5;
let mut faces = 0;
for _ in 0..reps {
diff --git a/renderer/third_party/glamx/PATCH.md b/renderer/third_party/glamx/PATCH.md
index ecd00a8..cf98906 100644
--- a/renderer/third_party/glamx/PATCH.md
+++ b/renderer/third_party/glamx/PATCH.md
@@ -62,8 +62,11 @@ assert_eq!(check::script(600), check::EXPECTED);
assert_eq!(check::cases(), check::EXPECTED_CASES);
```
-Every such crate needs that test (for a wasm crate: run in wasm32, as `tools/physics-determinism.ts` runs
-physics-core's). Without the patch the renderer's fails: `f66d349c1eae947a` against the recorded case hash.
+Every such **native** crate needs that test. Without the patch the renderer's fails: `f66d349c1eae947a` against the
+recorded case hash. A crate built for wasm32 only (the web build) comes out right with or without the patch, because
+there an f32's own `acos` / `cos` are Rust's port of libm, the same functions the patch calls by name (measured:
+`renderer/examples/physics_bits.rs` gives the recorded hashes either way). It still names the patch, so the two
+builds have one source, and `tools/physics-determinism.ts` checks its hashes against the recorded ones.
Nothing else differs from the published crate (`.github`, `.gitignore` and cargo's packaging files are left out).
To update: copy the new version here, apply the same change, run `node tools/physics-determinism.ts` and
diff --git a/tools/physics-determinism.ts b/tools/physics-determinism.ts
index a3f6d81..9ddeee3 100644
--- a/tools/physics-determinism.ts
+++ b/tools/physics-determinism.ts
@@ -10,6 +10,8 @@
// feature: what a larger program's other dependencies do, the renderer's among them), where Rapier's crates take
// f32's own math functions unless they are kept from it (renderer/third_party/glamx/PATCH.md). Without the patch the
// first run passes and the second fails.
+// Then the renderer's dependency graph, built for wasm32 (renderer/examples/physics_bits.rs), against the recorded
+// hashes: the engine's library in a browser.
// `--without` builds without Rapier's `enhanced-determinism` instead and reports (the hashes differ; no exit code).
// node tools/physics-determinism.ts [--without] (needs the wasm32-unknown-unknown target)
import { execFileSync } from "node:child_process";
@@ -55,6 +57,16 @@ for (const [label, features] of builds) {
console.log(`physics determinism${label}: cases: native ${hex(folded)}, recorded ${constant("EXPECTED_CASES")}`);
failed ||= hex(folded) !== constant("EXPECTED_CASES");
}
+// The renderer's own dependency graph built for wasm32 (the engine's library in a browser): the same recorded hashes.
+// (It holds the wasm32 side; a glamx patch left out shows natively, in the renderer's own test, not here.)
+if (!without) {
+ const renderer = join(import.meta.dirname, "../renderer");
+ execFileSync("cargo", ["build", "--release", "--locked", "--quiet", "--target", "wasm32-unknown-unknown", "--example", "physics_bits"], { cwd: renderer, stdio: ["ignore", "ignore", "inherit"] });
+ const bits = await WebAssembly.instantiate(readFileSync(join(renderer, "target/wasm32-unknown-unknown/release/examples/physics_bits.wasm")), {});
+ const [script, cases] = [hex((bits.instance.exports.physics_script as () => bigint)()), hex((bits.instance.exports.physics_cases as () => bigint)())];
+ console.log(`physics determinism (the renderer's graph, wasm32): script ${script}, cases ${cases}`);
+ failed ||= script !== constant("EXPECTED") || cases !== constant("EXPECTED_CASES");
+}
if (without) process.exit(0);
if (failed) {
console.error("physics determinism: the hashes differ");