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.

Streaming a world as the camera moves: readAsset, a binding that syncs what changed, the in-place rules it needs (#196)

Evan (Yifeng) Wang910826fa9f76
diff --git a/docs/RUNTIME.md b/docs/RUNTIME.md
index 03cb911..2e9e930 100644
--- a/docs/RUNTIME.md
+++ b/docs/RUNTIME.md
@@ -805,6 +805,31 @@ core.write_stream("screen", 640, 360, &rgba)?; // LiveCore, bef
- The script side has no call for it: pictures come from the app (`write_stream`), not through the script
runtime. A script's own `DataTexture` with `needsUpdate` still rebuilds, as before.
+## Streaming: reading assets and adding them in place
+
+A game that streams its world as the camera moves (a city of baked cells: [threert/tokyo-1980](https://github.com/threert/tokyo-1980))
+reads files under the asset root as it goes and adds what they hold without rebuilding the scene.
+
+- **`readAsset(path, offset?, length?)`** (`@threert/scene`; `__engine.readAsset`): a file under the asset root as an
+ `ArrayBuffer`, whole or `length` bytes from `offset` (relative paths, no `..`). Native renderer only. The root is the
+ host's `--assets`.
+- **The script's heap** is 1 GiB; `THREERT_SCRIPT_MB` sets another size (a resident city keeps its cells' arrays).
+- **The binding syncs what changed.** Objects added under a parent or taken from one since the last sync are bound or
+ dropped with their subtrees; the graph is walked whole only at the first sync. A world removes a childless object
+ without looking for its children (`World::remove` keeps a count of each object's children).
+- **In place:** a new mesh (any geometry) with materials the scene has; a model whose file the scene has (another
+ copy); moving or showing an object the build placed as an instance; new materials without textures that neither
+ emit nor are glass.
+- **Rebuilds:** a new group (place the meshes themselves under groups the scene made); a material with textures or a
+ function that the scene has not seen (make every material at setup, and put each on a mesh, out of sight if need
+ be); showing an object that was hidden when the scene was built or rebuilt (move it out of sight instead of hiding
+ it); a model of nodes the file lacks (it draws nothing and has no instance to hide).
+- **Emitters cost the commit**: each commit that adds or removes emitting triangles writes the emitter CDF and the
+ light tree's dynamic part over every emitter of the scene. Add a cell's emitting meshes together, and draw far lights
+ with unlit materials (`MeshBasicMaterial`, or glTF `KHR_materials_unlit`, whose emission is then what it shows): they
+ are seen and light nothing.
+- `THREERT_EDIT_LOG=1` prints where an edit or a world change decided on a rebuild.
+
## The runtime's shape: Rust owns the world, the script engine is a guest
Decided by the user on 2026-11-10, with the measurements below.
diff --git a/packages/scene/src/core.ts b/packages/scene/src/core.ts
index b2d65ec..8c1cde6 100644
--- a/packages/scene/src/core.ts
+++ b/packages/scene/src/core.ts
@@ -14,7 +14,12 @@ import type { ExposureDesc, Vec3 } from "./engine.ts";
*/
export interface SceneChanges {
objects: Set<Object3D>;
+ /** The whole graph is to be walked again (a binding's first sync). */
structure: boolean;
+ /** Objects added under a parent / taken from one since the last look: the subtrees a binding binds or drops alone,
+ * without walking the graph (a streamed city adds and removes thousands of objects among tens of thousands). */
+ added?: Set<Object3D>;
+ removed?: Set<Object3D>;
}
// An array, not a Set: `touched` runs for every write of a tracked property, and a for-of over a Set costs QuickJS an
@@ -259,8 +264,17 @@ export function unbindBody(o: Object3D): void {
o._body = undefined;
}
-function restructured(): void {
- for (const t of trackers) t.structure = true;
+function restructured(kind: "added" | "removed", objects: Object3D[]): void {
+ for (const t of trackers) {
+ if (!t.added || !t.removed) {
+ t.structure = true;
+ continue;
+ }
+ for (const o of objects) {
+ if (kind === "added") t.added.add(o);
+ else t.removed.add(o);
+ }
+ }
}
/** Object3D.position / scale: a Vector3 that reports writes to its object. */
@@ -531,7 +545,7 @@ export class Object3D {
o.parent = this;
this.children.push(o);
}
- restructured();
+ restructured("added", objects);
return this;
}
@@ -543,7 +557,7 @@ export class Object3D {
o.parent = null;
}
}
- restructured();
+ restructured("removed", objects);
return this;
}
diff --git a/packages/scene/src/engine.ts b/packages/scene/src/engine.ts
index 60b55fa..fdf4f88 100644
--- a/packages/scene/src/engine.ts
+++ b/packages/scene/src/engine.ts
@@ -199,6 +199,8 @@ export interface SettingsDesc {
export interface Engine extends RenderingBinding {
/** `groups`: (first index, index count, material index) per group, for meshes with several materials. */
/** `colors`: the vertex colours (three.js's `color` attribute), linear RGB per vertex. */
+ /** A file under the asset root, whole or a range (native only; a page's throws): `readAsset` below. */
+ readAsset?(path: string, offset?: number, length?: number): ArrayBuffer;
geometry(id: number, positions: Float32Array, normals: Float32Array, uvs: Float32Array, indices: Uint32Array, groups?: Uint32Array | null, colors?: Float32Array | null): void;
texture(id: number, desc: TextureDesc, data: Uint8Array | null): void;
shader(name: string, code: string, helpers: string): void;
@@ -355,7 +357,7 @@ export class SceneBinding {
private settingsKey = "";
private readonly trs = new Float32Array(10);
private readonly scratch = new Float64Array(Math.max(HOT, LIGHT_VALUES));
- private readonly changes: SceneChanges = { objects: new Set(), structure: true };
+ private readonly changes: SceneChanges = { objects: new Set(), structure: true, added: new Set(), removed: new Set() };
private readonly untrack: () => void;
private epoch = 0;
// Physics: ids of bodies (a body's collider has its id) and joints, the slots of the engine's pose table, the joints
@@ -414,8 +416,10 @@ export class SceneBinding {
const stats: SyncStats = { created: 0, updated: 0, removed: 0 };
const ch = this.changes;
if (ch.structure || !this.objects.has(this.camera)) {
- // Objects were added or removed: walk the graph (creates new objects, re-parents, removes what is gone).
+ // The whole graph: walk it (creates new objects, re-parents, removes what is gone).
ch.structure = false;
+ ch.added?.clear();
+ ch.removed?.clear();
ch.objects.clear();
const epoch = ++this.epoch;
const visit = (o: Object3D, parent: number | null) => {
@@ -427,16 +431,46 @@ export class SceneBinding {
if (this.objects.get(this.camera)?.epoch !== epoch) visit(this.camera, null);
for (const [o, b] of this.objects) {
if (b.epoch === epoch) continue;
- this.dropBody(o, b);
- if (o instanceof Joint) this.dropJoint(o);
- this.engine.remove(b.id);
- this.objects.delete(o);
- this.byName.delete(b.name);
- const cut = b.name.lastIndexOf("_"), n = Number(b.name.slice(cut + 1));
- if (cut > 0 && Number.isInteger(n) && n >= 1 && n < (this.nameFloor.get(b.name.slice(0, cut)) ?? 1)) this.nameFloor.set(b.name.slice(0, cut), n);
- if (o instanceof Light) this.lights.delete(o);
- if (o instanceof PerspectiveCamera) this.cameras.delete(o);
- stats.removed++;
+ this.dropObject(o, b, stats);
+ }
+ } else if (ch.added?.size || ch.removed?.size) {
+ // Objects added or removed since the last sync: their subtrees alone. Removed first (what is no longer under the
+ // scene goes, with everything below it), then added (bound from the highest ancestor the engine has not got).
+ const inScene = (o: Object3D) => {
+ for (let p: Object3D | null = o; p; p = p.parent) if (p === this.scene) return true;
+ return o === this.camera;
+ };
+ const removed = [...(ch.removed ?? [])], added = [...(ch.added ?? [])];
+ ch.removed?.clear();
+ ch.added?.clear();
+ for (const r of removed) {
+ const stack = [r];
+ while (stack.length) {
+ const o = stack.pop()!;
+ const b = this.objects.get(o);
+ if (b && !inScene(o)) this.dropObject(o, b, stats);
+ for (const c of o.children) stack.push(c);
+ }
+ }
+ // what changed of objects the engine has (as the full walk meets them before what is new), then what is new
+ const touched = [...ch.objects].filter((o) => this.objects.has(o));
+ ch.objects.clear();
+ for (const o of touched) {
+ const b = this.objects.get(o);
+ if (b) this.bindObject(o, b.parent, stats);
+ }
+ const visit = (o: Object3D, parent: number | null) => {
+ const b = this.bindObject(o, parent, stats);
+ for (const c of o.children) visit(c, b.id);
+ };
+ const done = new Set<Object3D>();
+ for (const a of added) {
+ if (!inScene(a)) continue;
+ let top = a;
+ while (top.parent && top.parent !== this.scene && !this.objects.has(top.parent)) top = top.parent;
+ if (done.has(top)) continue;
+ done.add(top);
+ visit(top, top.parent && top.parent !== this.scene ? this.objects.get(top.parent)!.id : null);
}
} else if (ch.objects.size) {
const touched = [...ch.objects];
@@ -531,6 +565,20 @@ export class SceneBinding {
}
/** Creates / re-creates the object in the engine if it is new or changed kind or parent, then sends its state. */
+ /** An object the scene no longer has: out of the engine, its names free again. */
+ private dropObject(o: Object3D, b: Bound, stats: SyncStats): void {
+ this.dropBody(o, b);
+ if (o instanceof Joint) this.dropJoint(o);
+ this.engine.remove(b.id);
+ this.objects.delete(o);
+ this.byName.delete(b.name);
+ const cut = b.name.lastIndexOf("_"), n = Number(b.name.slice(cut + 1));
+ if (cut > 0 && Number.isInteger(n) && n >= 1 && n < (this.nameFloor.get(b.name.slice(0, cut)) ?? 1)) this.nameFloor.set(b.name.slice(0, cut), n);
+ if (o instanceof Light) this.lights.delete(o);
+ if (o instanceof PerspectiveCamera) this.cameras.delete(o);
+ stats.removed++;
+ }
+
private bindObject(o: Object3D, parent: number | null, stats: SyncStats): Bound {
let b = this.objects.get(o);
const kind = this.kindKey(o);
@@ -1595,6 +1643,16 @@ function samePose(a: AnimationDesc | null, b: AnimationDesc | null): boolean {
return true;
}
+/**
+ * A file under the asset root, whole or `length` bytes of it from `offset` (`__engine.readAsset`, native renderer only;
+ * docs/RUNTIME.md "Streaming"): what a game reads as it goes, such as a city's baked cells as the camera moves.
+ */
+export function readAsset(path: string, offset?: number, length?: number): ArrayBuffer {
+ const e = (globalThis as { __engine?: Partial<Pick<Engine, "readAsset">> }).__engine;
+ if (!e?.readAsset) throw new Error("readAsset: this host reads no assets (the native renderer does)");
+ return offset === undefined ? e.readAsset(path) : e.readAsset(path, offset, length ?? 0);
+}
+
export function cameraDesc(c: PerspectiveCamera): CameraDesc {
return { fov: c.fov, near: c.near, far: c.far, exposure: { ...c.exposure }, ...(c.dof ? { dof: { ...c.dof } } : {}) };
}
@@ -1653,6 +1711,9 @@ function resolveOrientation(o: Object3D): Quaternion {
/** An engine that records the calls (tests, headless inspection). */
export class RecordingEngine implements Engine {
calls: [string, ...unknown[]][] = [];
+ readAsset(path: string): ArrayBuffer {
+ throw new Error(`readAsset ${path}: the recording engine reads no assets`);
+ }
geometry(...a: Parameters<Engine["geometry"]>) { this.calls.push(["geometry", ...a.filter((x, k) => k < 5 || x || (k === 5 && a[6]))]); }
texture(...a: Parameters<Engine["texture"]>) { this.calls.push(["texture", ...a]); }
shader(...a: Parameters<Engine["shader"]>) { this.calls.push(["shader", ...a]); }
diff --git a/renderer/src/live/edits.rs b/renderer/src/live/edits.rs
index 141cb8d..e49388c 100644
--- a/renderer/src/live/edits.rs
+++ b/renderer/src/live/edits.rs
@@ -588,6 +588,7 @@ impl LiveCore {
_ => false,
};
if !done {
+ if std::env::var("THREERT_EDIT_LOG").is_ok_and(|v| v == "1") && !changes.structural { eprintln!("edit: structural at edits.rs:568 (shown/hidden not in place: {:?})", world.objects.get(&id).map(|o| (o.name.clone(), std::mem::discriminant(&o.kind), self.sc.tables.retained.instance(id).is_some()))); }
changes.structural = true;
}
}
@@ -602,6 +603,7 @@ impl LiveCore {
} else {
self.fallback = Some("a new material that cannot be added in place (it emits, is glass or a cutout)".into());
self.fallbacks += 1;
+ if std::env::var("THREERT_EDIT_LOG").is_ok_and(|v| v == "1") && !changes.structural { eprintln!("edit: structural at edits.rs:582"); }
changes.structural = true;
}
}
@@ -616,6 +618,7 @@ impl LiveCore {
if !changes.structural && changes.moved.iter().any(stuck) {
self.fallback = Some("an object added in place moved".into());
self.fallbacks += 1;
+ if std::env::var("THREERT_EDIT_LOG").is_ok_and(|v| v == "1") && !changes.structural { eprintln!("edit: structural at edits.rs:596"); }
changes.structural = true;
if std::env::var("THREERT_EDIT_LOG").is_ok_and(|v| v == "1") {
eprintln!("edit: rebuild (an object added in place moved)");
@@ -646,6 +649,7 @@ impl LiveCore {
Err(why) => {
self.fallback = Some(why);
self.fallbacks += 1;
+ if std::env::var("THREERT_EDIT_LOG").is_ok_and(|v| v == "1") && !changes.structural { eprintln!("edit: structural at edits.rs:626"); }
changes.structural = true;
}
}
@@ -659,6 +663,7 @@ impl LiveCore {
// Still objects that moved for the first time: their meshes' instances move from now on, or the scene rebuilds.
for id in std::mem::take(&mut changes.started) {
if !changes.structural && !self.start_moving(world, id) {
+ if std::env::var("THREERT_EDIT_LOG").is_ok_and(|v| v == "1") && !changes.structural { eprintln!("edit: structural at edits.rs:639"); }
changes.structural = true;
}
}
@@ -782,15 +787,26 @@ impl LiveCore {
if changes.sky && !changes.structural && !self.apply_sky(world)? {
self.fallback = Some("a sky whose map does not fit the scene's buffers in place".into());
self.fallbacks += 1;
+ if std::env::var("THREERT_EDIT_LOG").is_ok_and(|v| v == "1") && !changes.structural { eprintln!("edit: structural at edits.rs:762"); }
changes.structural = true;
}
if (changes.camera || changes.view || changes.settings) && !changes.structural && !self.apply_view(world, &changes)? {
+ if std::env::var("THREERT_EDIT_LOG").is_ok_and(|v| v == "1") && !changes.structural { eprintln!("edit: structural at edits.rs:765"); }
changes.structural = true;
}
let now = shader_time(self.time);
// The tables' edits, then what the edits above left to build, once. Either may say the scene is to be rebuilt,
// and the rebuild builds all of it.
- let mut applied = self.sc.tables.apply(world, &changes, now).ok().flatten();
+ let applied_r = self.sc.tables.apply(world, &changes, now);
+ let log = std::env::var("THREERT_EDIT_LOG").is_ok_and(|v| v == "1");
+ if log {
+ match &applied_r {
+ Err(e) => eprintln!("edit: rebuild (tables: {e:#})"),
+ Ok(None) => eprintln!("edit: rebuild (tables: structural {}, {} added, {} removed, {} geometries, {} new materials)", changes.structural, changes.added.len(), changes.removed.len(), changes.geometries.len(), changes.new_materials.len()),
+ Ok(Some(_)) => {}
+ }
+ }
+ let mut applied = applied_r.ok().flatten();
// (Materials whose class changed: their instances' rows, bits and masks, before the build that reads the masks.)
if applied.is_some_and(|d| d.reclassed) {
if let Err(why) = self.remake_classes(world, &mut top) {
@@ -801,6 +817,9 @@ impl LiveCore {
}
self.sc.tables.reclassed.clear();
if applied.is_some() && !self.build_top(top) {
+ if log {
+ eprintln!("edit: rebuild (the top-level build refused)");
+ }
applied = None;
}
let Some(d) = applied else {
@@ -1236,6 +1255,7 @@ impl LiveCore {
}
self.fallback = Some(why);
self.fallbacks += 1;
+ if std::env::var("THREERT_EDIT_LOG").is_ok_and(|v| v == "1") && !changes.structural { eprintln!("edit: structural at edits.rs:1228"); }
changes.structural = true;
false
}
diff --git a/renderer/src/main.rs b/renderer/src/main.rs
index e1c0744..e31295d 100644
--- a/renderer/src/main.rs
+++ b/renderer/src/main.rs
@@ -152,6 +152,8 @@ fn main() -> Result<()> {
let cmd = args.get(1).map(String::as_str).unwrap_or("help");
let flag = |name: &str| args.iter().position(|a| a == name).and_then(|i| args.get(i + 1)).cloned();
let presets = flag("--presets").map(PathBuf::from).unwrap_or_else(default_presets_dir);
+ // (What scene code's `readAsset` reads under, for every command that runs a game.)
+ threert_render::script::set_asset_root(&PathBuf::from(flag("--assets").unwrap_or_else(|| ".".into())));
match cmd {
"info" => {
let g = gpu::Gpu::new()?;
diff --git a/renderer/src/scene.rs b/renderer/src/scene.rs
index a8c8ba6..e5a9b96 100644
--- a/renderer/src/scene.rs
+++ b/renderer/src/scene.rs
@@ -2347,12 +2347,18 @@ fn gltf_material(gm: Option<gltf::Material>, images: &[gltf::image::Data], key:
let strength = gm.emissive_strength().unwrap_or(1.0);
let e = gm.emissive_factor();
let clearcoat = |k: &str| gm.extension_value("KHR_materials_clearcoat").and_then(|c| c[k].as_f64()).unwrap_or(0.0).clamp(0.0, 1.0) as f32;
+ // KHR_materials_unlit: shown, never lit nor lighting (three.js MeshBasicMaterial, the kernel's unlit switch). An
+ // unlit material that says an emission shows it (its factor x strength, nits) as its colour: a far city's lit
+ // windows, seen and not light-sampled (tens of thousands of emitters fewer).
+ let unlit = gm.extension_value("KHR_materials_unlit").is_some();
+ let base_color = if unlit && e.iter().any(|&c| c > 0.0) { [e[0] * strength, e[1] * strength, e[2] * strength, 1.0] } else { pbr.base_color_factor() };
+ let (e, strength) = if unlit { ([0.0; 3], 0.0) } else { (e, strength) };
Ok(GpuMaterial {
- base_color: pbr.base_color_factor(),
+ base_color,
emissive: [e[0] * strength, e[1] * strength, e[2] * strength, 0.0],
params: [pbr.metallic_factor(), pbr.roughness_factor(), 0.5, gm.normal_texture().map(|n| n.scale()).unwrap_or(1.0)],
tex0: [tex(pbr.base_color_texture().map(|t| t.texture()), true)?, tex(gm.normal_texture().map(|t| t.texture()), false)?, mr, mr],
- tex1: [tex(gm.emissive_texture().map(|t| t.texture()), true)?, tex(gm.occlusion_texture().map(|t| t.texture()), false)?, if gm.double_sided() { MAT_DOUBLE_SIDED } else { 0 }, 0],
+ tex1: [tex(gm.emissive_texture().map(|t| t.texture()), true)?, tex(gm.occlusion_texture().map(|t| t.texture()), false)?, if unlit { MAT_UNLIT } else if gm.double_sided() { MAT_DOUBLE_SIDED } else { 0 }, 0],
uv: [1.0, 1.0, gm.transmission().and_then(|t| t.transmission_texture()).map_or(Ok(-1), |t| tex(Some(t.texture()), false))? as f32 + 1.0, 0.0],
// glTF MASK (and BLEND, approximated) -> alpha cutout
uv2: [0.0, 0.0, 0.0, match gm.alpha_mode() { gltf::material::AlphaMode::Opaque => 0.0, gltf::material::AlphaMode::Mask => gm.alpha_cutoff().unwrap_or(0.5), gltf::material::AlphaMode::Blend => 0.5 }],
diff --git a/renderer/src/script.rs b/renderer/src/script.rs
index 9b04e26..52bbfe9 100644
--- a/renderer/src/script.rs
+++ b/renderer/src/script.rs
@@ -97,6 +97,35 @@ const MAX_POST_BYTES: usize = 1 << 20;
const MAX_STORE_WRITE_BYTES: usize = 96 << 20;
const MAX_QUEUE_BYTES: usize = 192 << 20;
+/// The asset root scene code may read files under (`__engine.readAsset`): set by the host before a game loads.
+static ASSET_ROOT: std::sync::RwLock<Option<std::path::PathBuf>> = std::sync::RwLock::new(None);
+
+/// Where `__engine.readAsset` reads (the host's `--assets`).
+pub fn set_asset_root(root: &std::path::Path) {
+ *ASSET_ROOT.write().unwrap() = Some(root.to_path_buf());
+}
+
+/// `__engine.readAsset(path)`: a file under the asset root, whole, as an ArrayBuffer (a streamed city's tiles, baked data
+/// a game reads as it goes). Relative paths only, no `..`: nothing outside the root.
+fn read_asset(path: &str, range: Option<(u64, usize)>) -> anyhow::Result<Vec<u8>> {
+ use std::io::{Read, Seek, SeekFrom};
+ let p = std::path::Path::new(path);
+ anyhow::ensure!(p.is_relative() && !p.components().any(|c| matches!(c, std::path::Component::ParentDir)), "readAsset: {path}: a relative path under the asset root");
+ let root = ASSET_ROOT.read().unwrap().clone().unwrap_or_else(|| std::path::PathBuf::from("."));
+ let full = root.join(p);
+ match range {
+ None => std::fs::read(&full).map_err(|e| anyhow::anyhow!("readAsset: {path}: {e}")),
+ // (a part of it: a streamed cell's next meshes, without reading the rest)
+ Some((offset, length)) => {
+ let mut f = std::fs::File::open(&full).map_err(|e| anyhow::anyhow!("readAsset: {path}: {e}"))?;
+ f.seek(SeekFrom::Start(offset))?;
+ let mut buf = vec![0u8; length];
+ f.read_exact(&mut buf).map_err(|e| anyhow::anyhow!("readAsset: {path} [{offset}, +{length}]: {e}"))?;
+ Ok(buf)
+ }
+ }
+}
+
/// `__host_base64_encode(bytes: Uint8Array): string`.
fn base64_encode<'js>(ctx: Ctx<'js>, bytes: Value<'js>) -> rquickjs::Result<String> {
use base64::Engine;
@@ -360,6 +389,12 @@ fn install_engine<'js>(ctx: &Ctx<'js>, world: &Rc<RefCell<World>>, voxels: &Rc<R
e.set("voxelDebris", Function::new(ctx.clone(), move |ctx: Ctx<'js>| -> rquickjs::Result<TypedArray<'js, f32>> { TypedArray::new(ctx, v.borrow_mut().take_debris()) })?)?;
let (v, w, d) = (voxels.clone(), world.clone(), budget.clone());
e.set("voxelFrame", Function::new(ctx.clone(), move |ctx: Ctx, dt: f64| -> rquickjs::Result<String> { let _lent = Lent::new(&ctx, &d)?; api::voxel_frame(&mut v.borrow_mut(), &mut w.borrow_mut(), dt).map_err(|e| thrown(&ctx, e)) })?)?;
+ // readAsset(path, offset?, length?): the file, or `length` bytes of it from `offset`
+ e.set("readAsset", Function::new(ctx.clone(), move |ctx: Ctx<'js>, path: String, offset: rquickjs::function::Opt<f64>, length: rquickjs::function::Opt<f64>| -> rquickjs::Result<rquickjs::ArrayBuffer<'js>> {
+ let range = offset.0.zip(length.0).map(|(o, l)| (o as u64, l as usize));
+ let bytes = read_asset(&path, range).map_err(|e| fail(&ctx, e))?;
+ rquickjs::ArrayBuffer::new(ctx, bytes)
+ })?)?;
let w = world.clone();
// (…, groups?, colors?): the optional arguments as the rest (rquickjs takes seven parameters at most).
e.set("geometry", Function::new(ctx.clone(), move |ctx: Ctx<'js>, id: u32, p: TypedArray<f32>, n: TypedArray<f32>, uv: TypedArray<f32>, idx: TypedArray<u32>, rest: rquickjs::function::Rest<Value<'js>>| -> rquickjs::Result<()> {
@@ -477,7 +512,9 @@ impl ScriptHost {
fn load(code: impl for<'js> FnOnce(&Ctx<'js>) -> rquickjs::Result<()>) -> Result<ScriptHost> {
let rt = Runtime::new()?;
- rt.set_memory_limit(1 << 30);
+ // 1 GiB, or THREERT_SCRIPT_MB (a game that streams a city keeps its resident tiles' arrays)
+ let mb = std::env::var("THREERT_SCRIPT_MB").ok().and_then(|v| v.parse::<usize>().ok()).unwrap_or(1024);
+ rt.set_memory_limit(mb << 20);
rt.set_max_stack_size(4 << 20);
let epoch = Instant::now();
let budget = Arc::new(Budget { epoch, deadline: AtomicU64::new(0), lent: AtomicU64::new(0) });
diff --git a/renderer/src/view.rs b/renderer/src/view.rs
index 66ec8ac..a4c242b 100644
--- a/renderer/src/view.rs
+++ b/renderer/src/view.rs
@@ -829,6 +829,7 @@ fn texel(x: i32, y: i32) -> vec4<f32> {
/// Opens the window. `services`: what the app answers the game's posts with (`host::NoServices`: nothing).
pub fn run(args: ViewArgs, services: Box<dyn HostServices>) -> Result<()> {
+ crate::script::set_asset_root(&args.assets);
let (tx, rx) = mpsc::channel::<Cmd>();
std::thread::spawn(move || {
for line in std::io::stdin().lock().lines() {
diff --git a/renderer/src/world.rs b/renderer/src/world.rs
index 0418faa..094cfdb 100644
--- a/renderer/src/world.rs
+++ b/renderer/src/world.rs
@@ -351,6 +351,9 @@ pub fn edits_in_place(k: &Kind) -> bool {
#[derive(Clone)]
pub struct World {
pub objects: BTreeMap<u32, Object>,
+ /// How many objects each object is the parent of (`remove` skips the scan for children of a childless one: a
+ /// streamed city removes thousands of objects a frame among tens of thousands). Kept by `set_object` and `remove`.
+ kids: HashMap<u32, u32>,
pub geometries: HashMap<u32, Arc<Geometry>>,
pub textures: HashMap<u32, Texture>,
pub materials: HashMap<u32, desc::Material>,
@@ -391,6 +394,7 @@ impl Default for World {
fn default() -> World {
World {
objects: BTreeMap::new(),
+ kids: HashMap::new(),
geometries: HashMap::new(),
textures: HashMap::new(),
materials: HashMap::new(),
@@ -444,7 +448,16 @@ pub(crate) fn check_uri(uri: &str) -> Result<()> {
Ok(())
}
+/// The scene must be rebuilt (THREERT_EDIT_LOG=1 says where it was decided).
+fn mark_structural(c: &mut Changes, line: u32) {
+ if !c.structural && std::env::var("THREERT_EDIT_LOG").is_ok_and(|v| v == "1") {
+ eprintln!("world: structural at world.rs:{line}");
+ }
+ c.structural = true;
+}
+
impl World {
+
// ------------------------------------------------------------------------------------------ engine API
pub fn set_geometry(&mut self, id: u32, g: Geometry) -> Result<()> {
@@ -468,7 +481,7 @@ impl World {
let new = self.geometries.insert(id, Arc::new(g)).is_none();
if !self.changes.structural {
if !new && self.objects.values().any(|o| matches!(o.kind, Kind::Instanced { geometry, procedural: false, .. } if geometry == id)) {
- self.changes.structural = true;
+ mark_structural(&mut self.changes, line!());
} else {
self.changes.geometries.insert(id);
}
@@ -497,7 +510,7 @@ impl World {
check_uri(uri)?;
}
self.textures.insert(id, t);
- self.changes.structural = true;
+ mark_structural(&mut self.changes, line!());
Ok(())
}
@@ -506,7 +519,7 @@ impl World {
return;
}
self.shaders.insert(name.to_string(), (code, helpers));
- self.changes.structural = true;
+ mark_structural(&mut self.changes, line!());
}
pub fn set_material(&mut self, id: u32, m: desc::Material) {
@@ -520,7 +533,12 @@ impl World {
None if [m.map, m.normal_map, m.roughness_map, m.metalness_map, m.ao_map, m.emissive_map, m.transmission_map].iter().all(Option::is_none) && m.shader.is_none() && !m.transparent && !m.vertex_colors => {
self.changes.new_materials.insert(id);
}
- _ => self.changes.structural = true,
+ _ => {
+ if std::env::var("THREERT_EDIT_LOG").is_ok_and(|v| v == "1") {
+ eprintln!("world: structural: material {id} new with textures or a function, or changed beyond its parameters");
+ }
+ mark_structural(&mut self.changes, line!())
+ }
}
self.materials.insert(id, m);
}
@@ -576,6 +594,17 @@ impl World {
self.instanced.remove(&id);
}
}
+ let was_parent = self.objects.get(&id).map(|o| o.parent);
+ if was_parent != Some(parent) {
+ if let Some(Some(p)) = was_parent {
+ if let Some(n) = self.kids.get_mut(&p) {
+ *n = n.saturating_sub(1);
+ }
+ }
+ if let Some(p) = parent {
+ *self.kids.entry(p).or_default() += 1;
+ }
+ }
let o = match self.objects.remove(&id) {
Some(o) => Object { name, parent, kind, cast_shadow, movable: movable || o.movable, ..o },
None => Object { name, parent, kind, position: Vec3::ZERO, rotation: Quat::IDENTITY, scale: Vec3::ONE, visible: true, cast_shadow, power: 1.0, custom: [0.0; 4], movable, driven: false, sway: None, sway_rot: Quat::IDENTITY },
@@ -586,7 +615,11 @@ impl World {
} else if rematerialed {
self.changes.instanced.insert(id);
} else {
- self.changes.structural = true;
+ if std::env::var("THREERT_EDIT_LOG").is_ok_and(|v| v == "1") {
+ let o = &self.objects[&id];
+ eprintln!("world: structural: object {} ({:?}) set again or not placeable in place (movable {}, parent {:?})", o.name, std::mem::discriminant(&o.kind), o.movable, o.parent);
+ }
+ mark_structural(&mut self.changes, line!());
}
self.changes.created.insert(id);
Ok(())
@@ -610,7 +643,7 @@ impl World {
o.driven = true;
o.movable = true;
if !self.changes.added.contains(&id) {
- self.changes.structural = true;
+ mark_structural(&mut self.changes, line!());
}
}
Ok(())
@@ -722,7 +755,7 @@ impl World {
self.changes.moved.insert(id);
self.changes.started.insert(id);
} else {
- self.changes.structural = true;
+ mark_structural(&mut self.changes, line!());
}
}
}
@@ -806,7 +839,7 @@ impl World {
if in_place {
self.changes.shown.insert(id);
} else {
- self.changes.structural = true;
+ mark_structural(&mut self.changes, line!());
}
}
Ok(())
@@ -889,7 +922,7 @@ impl World {
t.custom = Some(Arc::new(c));
}
if t.colors.is_some() != colored {
- self.changes.structural = true;
+ mark_structural(&mut self.changes, line!());
} else if !self.changes.created.contains(&id) {
self.changes.instanced.insert(id);
}
@@ -902,7 +935,7 @@ impl World {
Kind::Light(old) if light_class(old) == light_class(&l) => {
self.changes.lights.insert(id);
}
- _ => self.changes.structural = true,
+ _ => mark_structural(&mut self.changes, line!()),
}
o.kind = Kind::Light(l);
Ok(())
@@ -917,7 +950,7 @@ impl World {
let (fov, rest) = match &o.kind {
Kind::Camera(old) => (old.fov != c.fov, old.dof != c.dof || old.exposure != c.exposure),
_ => {
- self.changes.structural = true;
+ mark_structural(&mut self.changes, line!());
(false, false)
}
};
@@ -959,9 +992,20 @@ impl World {
let mut k = 0;
while k < doomed.len() {
let p = doomed[k];
- doomed.extend(self.objects.iter().filter(|(_, o)| o.parent == Some(p)).map(|(i, _)| *i));
+ if self.kids.get(&p).is_some_and(|&n| n > 0) {
+ doomed.extend(self.objects.iter().filter(|(_, o)| o.parent == Some(p)).map(|(i, _)| *i));
+ }
k += 1;
}
+ // (the parents of what goes have one child fewer; what goes has none)
+ for d in &doomed {
+ if let Some(Some(p)) = self.objects.get(d).map(|o| o.parent) {
+ if let Some(n) = self.kids.get_mut(&p) {
+ *n = n.saturating_sub(1);
+ }
+ }
+ self.kids.remove(d);
+ }
// A mesh, procedural geometry, or a group of those, is removed in place, and so is a lone instanced mesh or
// model (or never added, if it came in this batch; live/edits.rs `edit_geometry` rebuilds for what it cannot
// take out).
@@ -981,10 +1025,13 @@ impl World {
}
return doomed;
}
+ if std::env::var("THREERT_EDIT_LOG").is_ok_and(|v| v == "1") {
+ eprintln!("world: structural: removal of {} objects not in place ({:?})", doomed.len(), doomed.iter().take(3).filter_map(|d| self.objects.get(d)).map(|o| (o.name.clone(), std::mem::discriminant(&o.kind))).collect::<Vec<_>>());
+ }
for &d in &doomed {
self.instanced.remove(&d);
if self.objects.remove(&d).is_some() {
- self.changes.structural = true;
+ mark_structural(&mut self.changes, line!());
}
}
doomed
@@ -1083,7 +1130,7 @@ impl World {
return;
}
self.volume_fns.insert(name.to_string(), (code, helpers));
- self.changes.structural = true;
+ mark_structural(&mut self.changes, line!());
}
pub fn set_grid_program(&mut self, name: &str, code: String, helpers: String) {
@@ -1091,7 +1138,7 @@ impl World {
return;
}
self.grid_programs.insert(name.to_string(), (code, helpers));
- self.changes.structural = true;
+ mark_structural(&mut self.changes, line!());
}
/// Creates or replaces a density grid. New data for a grid of the same size and program is uploaded in place; a
@@ -1131,7 +1178,7 @@ impl World {
self.grid_dirty.insert(id);
}
} else {
- self.changes.structural = true;
+ mark_structural(&mut self.changes, line!());
}
// (No data with a same grid: its contents stay, e.g. a simulated grid whose parameters were sent again.)
let keep = if same && data.is_none() { self.grids.get(&id).and_then(|g| g.data.clone()) } else { None };
@@ -1167,7 +1214,7 @@ impl World {
return;
}
self.geometry_fns.insert(name.to_string(), (code, helpers));
- self.changes.structural = true;
+ mark_structural(&mut self.changes, line!());
}
pub fn set_particle_program(&mut self, name: &str, emit: String, update: String, helpers: String) {
@@ -1176,7 +1223,7 @@ impl World {
return;
}
self.particle_programs.insert(name.to_string(), v);
- self.changes.structural = true;
+ mark_structural(&mut self.changes, line!());
}
/// Particles the game spawns into a `GpuParticles` node (8 floats each), taken by the live view's next frame.
@@ -1199,7 +1246,7 @@ impl World {
return;
}
self.particle_fns.insert(name.to_string(), (code, helpers));
- self.changes.structural = true;
+ mark_structural(&mut self.changes, line!());
}
/// Objects drawn: visible themselves and all their ancestors.
diff --git a/renderer/web/src/lib.rs b/renderer/web/src/lib.rs
index ddf9a4f..162093f 100644
--- a/renderer/web/src/lib.rs
+++ b/renderer/web/src/lib.rs
@@ -89,6 +89,12 @@ pub fn physics(op: &str, args: &str) -> Result<String, JsValue> {
engine(|e| api::physics(&mut e.physics, &mut e.world, op, &a)).map_err(thrown)
}
+/// `readAsset`: native only (a page has no asset root on disk; it fetches what it needs): throws.
+#[wasm_bindgen(js_name = readAsset)]
+pub fn read_asset(path: &str, _offset: Option<f64>, _length: Option<f64>) -> Result<Vec<u8>, JsValue> {
+ Err(JsValue::from_str(&format!("readAsset {path}: the native renderer reads assets; a page fetches them")))
+}
+
#[wasm_bindgen(js_name = physicsPoses)]
pub fn physics_poses() -> Vec<f32> {
engine(|e| api::physics_poses(&e.physics).to_vec())
diff --git a/renderer/web/www/engine.ts b/renderer/web/www/engine.ts
index 32d9912..bd8f4ea 100644
--- a/renderer/web/www/engine.ts
+++ b/renderer/web/www/engine.ts
@@ -22,6 +22,7 @@ export interface EngineExports {
voxelContacts(body: number, on: boolean): void;
voxelGone(): string;
voxelFrame(dt: number): string;
+ readAsset(path: string, offset?: number, length?: number): Uint8Array;
geometry(id: number, p: Float32Array, n: Float32Array, uv: Float32Array, idx: Uint32Array, groups?: Uint32Array | null, colors?: Float32Array | null): void;
texture(id: number, d: string, data?: Uint8Array | null): void;
shader(name: string, code: string, helpers: string): void;
@@ -88,6 +89,7 @@ export function webEngine(w: EngineExports): WebEngine {
voxelContacts: (body, on) => w.voxelContacts(body, on),
voxelGone: () => w.voxelGone(),
voxelFrame: (dt) => w.voxelFrame(dt),
+ readAsset: (path, offset, length) => w.readAsset(path, offset, length).buffer as ArrayBuffer,
geometry: (id, p, n, uv, idx, groups, colors) => w.geometry(id, p, n, uv, idx, groups, colors),
texture: (id, d, data) => w.texture(id, json(d), data),
shader: (name, code, helpers) => w.shader(name, code, helpers),