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.

A scene object is 8 JS objects, not 19, and none is a reference cycle (#205)

Evan (Yifeng) Wang95e2fbefc052
diff --git a/docs/RUNTIME.md b/docs/RUNTIME.md
index 459ba30..9a299c7 100644
--- a/docs/RUNTIME.md
+++ b/docs/RUNTIME.md
@@ -856,6 +856,12 @@ reads files under the asset root as it goes and adds what they hold without rebu
`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 script's objects are few and acyclic.** QuickJS frees an object when its last reference goes; only reference
+ cycles wait for its cycle collector, which walks every object there is (a streamed city's ~0.5 M: ~45 ms, a frame
+ lost). A scene object is 8 JS objects (an instanced mesh 13): what most never use (`up`, `tags`, `userData`,
+ `customData`, `matrix`, `matrixWorld`, an empty `children`) is made when first asked for, and its transform's parts
+ and instance tables reach it through one `WeakRef`, not a back-pointer each. The first collection waits for 256 MB
+ of heap (`THREERT_SCRIPT_GC_MB`), then QuickJS's own rule (the heap half as large again).
- **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).
diff --git a/packages/scene/src/core.ts b/packages/scene/src/core.ts
index 8c1cde6..ef07ae9 100644
--- a/packages/scene/src/core.ts
+++ b/packages/scene/src/core.ts
@@ -131,7 +131,7 @@ export interface BoundBody {
/** The physics epoch its pose was last read in. */
epoch: number;
/** The binding's record of the transform the engine has (position, quaternion, scale). */
- trs: Float64Array;
+ trs: number[];
/** `rotation` is behind `quaternion` (set when a pose is read; `rotation` catches up when it is read). */
euler: boolean;
}
@@ -282,10 +282,12 @@ class TrackedVector3 extends Vector3 {
declare _x: number;
declare _y: number;
declare _z: number;
- declare _owner: Object3D | undefined;
- constructor(owner: Object3D, x = 0, y = 0, z = 0) {
+ declare _owner: WeakRef<Object3D> | undefined;
+ constructor(owner: WeakRef<Object3D>, x = 0, y = 0, z = 0) {
super(x, y, z);
- // Not enumerable: JSON / structuredClone / spreads of a position must not drag the scene graph along.
+ // Not enumerable: JSON / structuredClone / spreads of a position must not drag the scene graph along. Weak: an
+ // object and its position made a reference cycle, which only QuickJS's cycle collector freed (a pause of ~100 ms
+ // over a streamed city's million objects).
Object.defineProperty(this, "_owner", { value: owner });
}
toJSON() {
@@ -296,7 +298,8 @@ class TrackedVector3 extends Vector3 {
this._x = x;
this._y = y;
this._z = z;
- if (this._owner) touched(this._owner);
+ const o = this._owner?.deref();
+ if (o) touched(o);
return this;
}
}
@@ -308,7 +311,8 @@ for (const k of ["x", "y", "z"] as const) {
},
set(this: TrackedVector3, v: number) {
this[slot] = v;
- if (this._owner) touched(this._owner);
+ const o = this._owner?.deref();
+ if (o) touched(o);
},
});
}
@@ -332,7 +336,23 @@ export interface SwayDesc {
let objectIds = 0;
/** What `Object3D.copy` does not take over as it is (transforms are copied by value, children cloned). */
-const COPY_SKIP = new Set(["parent", "children", "position", "quaternion", "rotation", "scale", "up", "matrix", "matrixWorld", "userData", "tags", "_id", "_autoId", "uuid", "_body", "_listeners"]);
+const COPY_SKIP = new Set(["parent", "children", "position", "quaternion", "rotation", "scale", "up", "matrix", "matrixWorld", "userData", "tags", "_id", "_autoId", "uuid", "_body", "_listeners", "_ref", "_up", "_matrix", "_matrixWorld", "_userData", "_tags", "_custom", "_children"]);
+const NO_CHILDREN = Object.freeze([]) as unknown as Object3D[];
+const NO_CUSTOM: readonly [number, number, number, number] = Object.freeze([0, 0, 0, 0] as [number, number, number, number]);
+/** An object's rotation changed: its quaternion follows (the object through the rotation's weak owner). */
+function rotationChanged(this: Euler): void {
+ const o = this._owner?.deref() as Object3D | undefined;
+ if (!o) return;
+ o.quaternion.setFromEuler(this, false);
+ touched(o);
+}
+/** An object's quaternion changed: its rotation follows. */
+function quaternionChanged(this: Quaternion): void {
+ const o = this._owner?.deref() as Object3D | undefined;
+ if (!o) return;
+ o.rotation.setFromQuaternion(this, false);
+ touched(o);
+}
export class Object3D {
readonly isObject3D = true;
@@ -341,29 +361,63 @@ export class Object3D {
declare private _id: string | undefined;
private readonly _autoId = ++objectIds;
parent: Object3D | null = null;
- children: Object3D[] = [];
- readonly position: Vector3 = new TrackedVector3(this);
+ declare private _children: Object3D[] | undefined;
+ /** The children; an object with none shares one empty list (most of a scene's objects are leaves). */
+ get children(): Object3D[] {
+ return this._children ?? NO_CHILDREN;
+ }
+ set children(v: Object3D[]) {
+ this._children = v;
+ }
+ /** @internal The object, weakly: what its transform's parts report their changes to (no reference cycle). */
+ readonly _ref: WeakRef<Object3D> = new WeakRef(this);
+ readonly position: Vector3 = new TrackedVector3(this._ref);
readonly quaternion = new Quaternion();
readonly rotation = new Euler();
- readonly scale: Vector3 = new TrackedVector3(this, 1, 1, 1);
- readonly up = new Vector3(0, 1, 0);
+ readonly scale: Vector3 = new TrackedVector3(this._ref, 1, 1, 1);
+ // (What most objects never use is made when first asked for: a streamed city holds tens of thousands of objects, and
+ // the script engine's cycle collector walks every object there is.)
+ declare private _up: Vector3 | undefined;
+ /** The object's up (`lookAt`), made when first asked for. */
+ get up(): Vector3 {
+ return (this._up ??= new Vector3(0, 1, 0));
+ }
private _visible = true;
private _power = 1;
- private _custom: [number, number, number, number] = [0, 0, 0, 0];
+ declare private _custom: [number, number, number, number] | undefined;
private _sway: SwayDesc | null = null;
private _castShadow = true;
private _movable = false;
receiveShadow = true;
- tags: string[] = [];
- userData: Record<string, unknown> = {};
+ declare private _tags: string[] | undefined;
+ declare private _userData: Record<string, unknown> | undefined;
+ get tags(): string[] {
+ return (this._tags ??= []);
+ }
+ set tags(v: string[]) {
+ this._tags = v;
+ }
+ get userData(): Record<string, unknown> {
+ return (this._userData ??= {});
+ }
+ set userData(v: Record<string, unknown>) {
+ this._userData = v;
+ }
/**
* The local transform as a matrix (three.js): `updateMatrix()` composes it from position / quaternion / scale, which
* `updateWorldMatrix` does first while `matrixAutoUpdate` is on. The engine is always sent position / rotation /
* scale, so a matrix set by hand moves only what reads it (`matrixWorld`, `setMatrixAt(i, o.matrix)`).
*/
- readonly matrix = new Matrix4();
+ get matrix(): Matrix4 {
+ return (this._matrix ??= new Matrix4());
+ }
+ declare private _matrix: Matrix4 | undefined;
matrixAutoUpdate = true;
- readonly matrixWorld = new Matrix4();
+ /** The world transform as a matrix (`updateWorldMatrix`), made when first asked for. */
+ get matrixWorld(): Matrix4 {
+ return (this._matrixWorld ??= new Matrix4());
+ }
+ declare private _matrixWorld: Matrix4 | undefined;
/**
* The stable id set by scene code (picking, gameplay events, the editor; the binding names the object by it); until
@@ -468,14 +522,12 @@ export class Object3D {
}
constructor() {
- this.rotation._onChange = () => {
- this.quaternion.setFromEuler(this.rotation, false);
- touched(this);
- };
- this.quaternion._onChange = () => {
- this.rotation.setFromQuaternion(this.quaternion, false);
- touched(this);
- };
+ // (shared functions, the object weakly: a closure over the object per rotation and quaternion made two cycles and
+ // two objects more an object)
+ for (const [part, changed] of [[this.rotation, rotationChanged], [this.quaternion, quaternionChanged]] as const) {
+ Object.defineProperty(part, "_owner", { value: this._ref, writable: true });
+ (part as { _onChange: () => void })._onChange = changed as () => void;
+ }
}
get visible(): boolean {
@@ -498,7 +550,7 @@ export class Object3D {
* variation seed, a tint, a state). Each instance of a shared mesh or model can carry its own.
*/
get customData(): readonly [number, number, number, number] {
- return this._custom;
+ return this._custom ?? NO_CUSTOM;
}
set customData(v: readonly number[]) {
this._custom = [v[0] ?? 0, v[1] ?? 0, v[2] ?? 0, v[3] ?? 0];
@@ -543,7 +595,7 @@ export class Object3D {
if ((o as { engineOwned?: boolean }).engineOwned) throw new TypeError(`${o.name || o.type}: the engine draws it; it is in no scene`);
o.parent?.remove(o);
o.parent = this;
- this.children.push(o);
+ (this._children ??= []).push(o);
}
restructured("added", objects);
return this;
@@ -1694,7 +1746,8 @@ export class InstancedBufferAttribute {
usage = StaticDrawUsage;
/** Bumped by `needsUpdate = true`: the binding sends the array again. */
version = 0;
- declare _owner: Object3D | undefined;
+ /** The instanced mesh whose table it is, weakly (no reference cycle). */
+ declare _owner: WeakRef<Object3D> | undefined;
constructor(array: ArrayLike<number>, itemSize: number) {
this.array = array instanceof Float32Array ? array : Float32Array.from(array);
this.itemSize = itemSize;
@@ -1706,7 +1759,8 @@ export class InstancedBufferAttribute {
set needsUpdate(v: boolean) {
if (!v) return;
this.version++;
- if (this._owner) touched(this._owner);
+ const o = this._owner?.deref();
+ if (o) touched(o);
}
setUsage(usage: number): this {
this.usage = usage;
@@ -1836,7 +1890,7 @@ export class InstancedMesh extends Object3D {
return this;
}
private own(a: InstancedBufferAttribute): InstancedBufferAttribute {
- a._owner = this;
+ a._owner = this._ref;
return a;
}
}
diff --git a/packages/scene/src/engine.ts b/packages/scene/src/engine.ts
index fdf4f88..bd4fa58 100644
--- a/packages/scene/src/engine.ts
+++ b/packages/scene/src/engine.ts
@@ -273,7 +273,8 @@ interface Bound {
name: string;
parent: number | null;
kind: string;
- trs: Float64Array;
+ /** The transform last sent (a plain array: a typed one is two objects, its buffer the second). */
+ trs: number[];
visible: boolean;
power: number;
/** Per-instance data last sent. */
@@ -286,7 +287,9 @@ interface Bound {
/** Model pose last sent (clip, time, loop). */
anim: AnimationDesc | null;
/** An instanced mesh's instances last sent: count, and each attribute with its version. */
- inst: { count: number; m: [unknown, number]; c: [unknown, number]; d: [unknown, number] } | null;
+ /** An instanced mesh's count and the tables (and their versions) last sent: one record, flat (each instanced mesh's
+ * was four objects, and the script engine's cycle collector walks every object). */
+ inst: { count: number; m: unknown; mv: number; c: unknown; cv: number; d: unknown; dv: number } | null;
/** Sync that last reached it in a walk of the graph. */
epoch: number;
/** Its rigid body in the engine, and what it was made from (a change makes it anew). */
@@ -586,7 +589,7 @@ export class SceneBinding {
const created = !b;
if (!b) {
const name = this.uniqueName(o);
- b = { id: this.nextId++, name, parent, kind, trs: new Float64Array(10).fill(NaN), visible: true, power: 1, custom: "0,0,0,0", sway: "", light: null, camera: "", anim: null, inst: null, epoch: 0, body: null, bodyFailed: null };
+ b = { id: this.nextId++, name, parent, kind, trs: new Array<number>(10).fill(NaN), visible: true, power: 1, custom: "0,0,0,0", sway: "", light: null, camera: "", anim: null, inst: null, epoch: 0, body: null, bodyFailed: null };
this.objects.set(o, b);
this.byName.set(name, o);
if (o instanceof Light) this.lights.set(o, b);
@@ -693,18 +696,18 @@ export class SceneBinding {
private sendInstances(o: InstancedMesh, b: Bound, stats: SyncStats): void {
const cap = o.instanceMatrix.count;
if (!Number.isInteger(o.count) || o.count < 0 || o.count > cap) throw new TypeError(`${b.name}: count must be an integer from 0 to ${cap}`);
- const s = (b.inst ??= { count: -1, m: [null, -1], c: [null, -1], d: [null, -1] });
- const fresh = (a: { version: number; array: Float32Array } | null, last: [unknown, number], size: number, what: string): Float32Array | null => {
- if (!a || (last[0] === a && last[1] === a.version)) return null;
+ const s = (b.inst ??= { count: -1, m: null, mv: -1, c: null, cv: -1, d: null, dv: -1 });
+ const fresh = (a: { version: number; array: Float32Array } | null, k: "m" | "c" | "d", v: "mv" | "cv" | "dv", size: number, what: string): Float32Array | null => {
+ if (!a || (s[k] === a && s[v] === a.version)) return null;
const arr = a.array;
if (arr.length !== cap * size) throw new TypeError(`${b.name}: ${what} must have ${size} numbers for each of the ${cap} instances`);
- last[0] = a;
- last[1] = a.version;
+ s[k] = a;
+ s[v] = a.version;
return arr;
};
- const m = fresh(o.instanceMatrix, s.m, 16, "instanceMatrix");
- const c = fresh(o.instanceColor, s.c, 3, "instanceColor");
- const d = fresh(o.instanceCustomData, s.d, 4, "instanceCustomData");
+ const m = fresh(o.instanceMatrix, "m", "mv", 16, "instanceMatrix");
+ const c = fresh(o.instanceColor, "c", "cv", 3, "instanceColor");
+ const d = fresh(o.instanceCustomData, "d", "dv", 4, "instanceCustomData");
if (m || c || d || o.count !== s.count) {
s.count = o.count;
this.engine.instances(b.id, o.count, m, c, d);
diff --git a/packages/scene/src/math.ts b/packages/scene/src/math.ts
index d82b940..6e60ae2 100644
--- a/packages/scene/src/math.ts
+++ b/packages/scene/src/math.ts
@@ -115,7 +115,10 @@ export class Quaternion {
_z: number;
/** @internal */
_w: number;
- _onChange: () => void = () => {};
+ /** Called after a change (an object's rotation / quaternion keep each other and the object in step). */
+ _onChange(): void {}
+ /** @internal The object whose rotation this is, if any (weakly: no cycle). */
+ declare _owner: WeakRef<object> | undefined;
constructor(x = 0, y = 0, z = 0, w = 1) {
this._x = x;
this._y = y;
@@ -257,7 +260,10 @@ export class Euler {
private _y: number;
private _z: number;
order: EulerOrder;
- _onChange: () => void = () => {};
+ /** Called after a change (an object's rotation / quaternion keep each other and the object in step). */
+ _onChange(): void {}
+ /** @internal The object whose rotation this is, if any (weakly: no cycle). */
+ declare _owner: WeakRef<object> | undefined;
constructor(x = 0, y = 0, z = 0, order: EulerOrder = "XYZ") {
this._x = x;
this._y = y;
diff --git a/packages/voxel/src/native.ts b/packages/voxel/src/native.ts
index cfe9212..086f4e8 100644
--- a/packages/voxel/src/native.ts
+++ b/packages/voxel/src/native.ts
@@ -172,7 +172,7 @@ export class VoxelBody extends Object3D {
this.asleep = r.asleep;
this.name = `voxel body ${r.body}`;
// (Known to the physics bindings by its body id: contacts and hits find it; it has no slot in the pose table.)
- bindBody(this, { id: r.body, slot: -1, epoch: 0, trs: new Float64Array(10), euler: false });
+ bindBody(this, { id: r.body, slot: -1, epoch: 0, trs: new Array<number>(10).fill(0), euler: false });
const p = this.position as Vector3 & { _x: number; _y: number; _z: number }, q = this.quaternion, e = this.rotation;
const place = (at: readonly number[], rot: readonly number[]) => {
[p._x, p._y, p._z] = at;
diff --git a/renderer/src/script.rs b/renderer/src/script.rs
index 52bbfe9..ac14c15 100644
--- a/renderer/src/script.rs
+++ b/renderer/src/script.rs
@@ -515,6 +515,12 @@ impl ScriptHost {
// 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);
+ // QuickJS collects cycles first at 256 KB of heap, then whenever the heap is half as large again as at the last
+ // collection; a collection walks every object (a streamed city: ~0.5 M of them, ~45 ms). The scene package
+ // makes no cycles of its own (its objects are freed as they go), so the first collection waits for 256 MB, or
+ // THREERT_SCRIPT_GC_MB; after it, QuickJS's own rule.
+ let gc_mb = std::env::var("THREERT_SCRIPT_GC_MB").ok().and_then(|v| v.parse::<usize>().ok()).unwrap_or(256);
+ rt.set_gc_threshold(gc_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) });