@threenative/three-native 0.3.6 → 0.3.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/src/addons/gltf-loader-web.ts +4 -0
- package/src/addons/mesh-bvh.ts +16 -0
- package/src/addons/post-effects-web.ts +10 -2
- package/src/addons/post-effects.ts +126 -16
- package/src/addons/screen-space.ts +849 -0
- package/src/bridge-meter.ts +237 -0
- package/src/browser-backend.ts +1329 -183
- package/src/browser-entry.ts +90 -11
- package/src/browser-math.ts +41 -8
- package/src/browser-renderer.ts +592 -36
- package/src/browser-tsl.ts +167 -10
- package/src/debug-telemetry.ts +115 -0
- package/src/fn-builder.ts +30 -0
- package/src/gpu-stages.ts +72 -0
- package/src/pass-node.ts +94 -4
- package/src/refused.ts +4 -2
- package/src/render-target.ts +12 -8
- package/src/renderer-utils.ts +65 -0
- package/src/rtt.ts +9 -1
- package/src/shadow-node.ts +192 -0
- package/src/sphere-reflection-capture.ts +123 -0
- package/src/storage.ts +37 -0
- package/src/temp-node.ts +141 -0
- package/src/texture-sources.ts +30 -8
- package/src/tone-mapping.ts +33 -0
- package/src/tsl-uniforms.ts +178 -25
- package/src/update-ranges.ts +33 -9
package/src/browser-backend.ts
CHANGED
|
@@ -12,8 +12,11 @@
|
|
|
12
12
|
* collected wrapper releases its object.
|
|
13
13
|
*/
|
|
14
14
|
|
|
15
|
-
import {
|
|
15
|
+
import { ENGINE_COST_KNOB, createBridgeMeter } from "./bridge-meter.js";
|
|
16
|
+
import { UpstreamVector3, defineMath } from "./browser-math.js";
|
|
16
17
|
import type { ITslRuntime, TslArgValue } from "./browser-tsl.js";
|
|
18
|
+
import { type DebugTelemetry, debugTelemetry } from "./debug-telemetry.js";
|
|
19
|
+
import { detachVirtualShadow, shadowFilterOptions, virtualShadowOptions } from "./shadow-node.js";
|
|
17
20
|
import { withUpdateRanges } from "./update-ranges.js";
|
|
18
21
|
|
|
19
22
|
export interface IRegistryClass {
|
|
@@ -55,12 +58,14 @@ export type EngineValue =
|
|
|
55
58
|
| number
|
|
56
59
|
| boolean
|
|
57
60
|
| string
|
|
61
|
+
| TypedArray
|
|
58
62
|
| readonly EngineValue[]
|
|
59
63
|
| IEngineRef
|
|
60
64
|
| { readonly [key: string]: EngineValue };
|
|
61
65
|
|
|
62
66
|
/** What the classes call; the Wasm ABI implements it, and a surface-only runtime refuses every call. */
|
|
63
67
|
export interface IBrowserRuntime {
|
|
68
|
+
readonly debugTelemetry?: DebugTelemetry;
|
|
64
69
|
typeId(className: string): number;
|
|
65
70
|
construct(className: string, args: readonly EngineValue[]): IEngineRef;
|
|
66
71
|
invoke(self: IEngineRef, method: string, args: readonly EngineValue[]): EngineValue;
|
|
@@ -69,6 +74,8 @@ export interface IBrowserRuntime {
|
|
|
69
74
|
release(self: IEngineRef): void;
|
|
70
75
|
/** For each ref, how many references other engine objects hold to its object; one call a batch. */
|
|
71
76
|
engineReferences?(refs: readonly IEngineRef[]): ArrayLike<number>;
|
|
77
|
+
/** A numeric typed array argument crosses as is, no boxed copy; Wasm only. */
|
|
78
|
+
readonly typedArrays?: boolean;
|
|
72
79
|
/** Doubles at `address` in the engine's memory (one as a number, more as an array); Wasm only. */
|
|
73
80
|
readDoubles?(address: number, count: number): number | number[];
|
|
74
81
|
/**
|
|
@@ -78,8 +85,12 @@ export interface IBrowserRuntime {
|
|
|
78
85
|
heapF64?(): Float64Array;
|
|
79
86
|
/** The byte at `address` in the engine's memory; Wasm only. A registry field `[offset, 0]` is a byte flag. */
|
|
80
87
|
readByte?(address: number): number;
|
|
88
|
+
/** The 32-bit word at `address` in the engine's memory (the hierarchy counter's low word); Wasm only. */
|
|
89
|
+
readWord?(address: number): number;
|
|
81
90
|
/** Writes one double at `address` in the engine's memory; Wasm only. */
|
|
82
91
|
writeDouble?(address: number, value: number): void;
|
|
92
|
+
/** Writes the byte at `address` in the engine's memory (a flag field); Wasm only. */
|
|
93
|
+
writeByte?(address: number, value: number): void;
|
|
83
94
|
/**
|
|
84
95
|
* A copy of the attribute's data, of its scalar type; three's `attribute.array` is built on it.
|
|
85
96
|
* With `offset`/`count`, a copy of that scalar subrange only (a per-vertex setter syncs one item).
|
|
@@ -120,6 +131,8 @@ export interface IBrowserEngine {
|
|
|
120
131
|
collect(): void;
|
|
121
132
|
/** Engine crossings so far (construct, get, set, invoke, engineReferences): a bench rung's bridgeCalls. */
|
|
122
133
|
crossings(): number;
|
|
134
|
+
/** Running work totals by name (this back end's and the engine's), for TN_FRAME_BUDGET.counters.engine. */
|
|
135
|
+
counters(): Record<string, number>;
|
|
123
136
|
/** The wrapper for an engine object the engine handed over (a loaded model's scene). */
|
|
124
137
|
wrap(ref: IEngineRef): object;
|
|
125
138
|
}
|
|
@@ -128,6 +141,8 @@ export interface IBrowserEngine {
|
|
|
128
141
|
const SETTLED_PASS = 64;
|
|
129
142
|
|
|
130
143
|
const REF = Symbol("tn.engineRef");
|
|
144
|
+
/** An engine object's address, kept on it after the first ask: every lane read and write needs it. */
|
|
145
|
+
const ADDRESS = Symbol("tn.engineAddress");
|
|
131
146
|
|
|
132
147
|
type TypedArray =
|
|
133
148
|
| Float32Array
|
|
@@ -163,6 +178,20 @@ interface IWrapped {
|
|
|
163
178
|
[REF]: IEngineRef;
|
|
164
179
|
}
|
|
165
180
|
|
|
181
|
+
/** One own, enumerable field of a material: its descriptor is built once per class and shared by every instance. */
|
|
182
|
+
interface IOwnField {
|
|
183
|
+
readonly key: string;
|
|
184
|
+
readonly descriptor: PropertyDescriptor;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* Define a class's own fields on one instance. A loop of `Object.defineProperty` takes about 12 us for the
|
|
189
|
+
* 40 fields of a standard material where one `Object.defineProperties` takes 17 us (node 20, 20000 builds).
|
|
190
|
+
*/
|
|
191
|
+
function defineOwn(target: object, own: readonly IOwnField[]): void {
|
|
192
|
+
for (const field of own) Object.defineProperty(target, field.key, field.descriptor);
|
|
193
|
+
}
|
|
194
|
+
|
|
166
195
|
/** The engine object behind a back-end wrapper, for a host that talks to the ABI directly. */
|
|
167
196
|
export function engineRef(object: object): IEngineRef | undefined {
|
|
168
197
|
return (object as Partial<IWrapped>)[REF];
|
|
@@ -236,11 +265,18 @@ export const LANGUAGE_MEMBERS = [
|
|
|
236
265
|
"traverse",
|
|
237
266
|
"traverseVisible",
|
|
238
267
|
"traverseAncestors",
|
|
268
|
+
"getObjectsByProperty",
|
|
269
|
+
"getObjectByProperty",
|
|
270
|
+
"getObjectByName",
|
|
271
|
+
"getObjectById",
|
|
239
272
|
"raycast",
|
|
240
273
|
] as const;
|
|
241
274
|
|
|
242
275
|
type TraverseCallback = (object: object) => void;
|
|
243
276
|
|
|
277
|
+
/** The engine classes with their own raycast (`Mesh::raycast`, `Line::raycast`, `LOD::raycast`). */
|
|
278
|
+
const RAYCASTERS = new Set(["Mesh", "Line", "Sprite", "LOD"]);
|
|
279
|
+
|
|
244
280
|
/**
|
|
245
281
|
* The `traverse` family, written over `children`, as three writes it. A class whose engine binding
|
|
246
282
|
* has no `children` refuses by name instead of visiting only the root.
|
|
@@ -250,20 +286,32 @@ function defineTraversal(
|
|
|
250
286
|
className: string,
|
|
251
287
|
hasChildren: boolean,
|
|
252
288
|
walks: boolean,
|
|
289
|
+
keep?: (object: object) => Record<string, unknown> | undefined,
|
|
290
|
+
visited?: (count: number) => void,
|
|
291
|
+
raycasts = true,
|
|
253
292
|
) {
|
|
254
293
|
const childrenOf = (object: object): object[] => {
|
|
255
294
|
if (!hasChildren) throw new TypeError(`TN_BROWSER_UNBOUND: ${className}.children`);
|
|
256
295
|
return (object as { children: object[] }).children;
|
|
257
296
|
};
|
|
258
|
-
// The engine's walk: one crossing for the whole subtree, in three's order (`__walk`).
|
|
259
|
-
|
|
260
|
-
|
|
297
|
+
// The engine's walk: one crossing for the whole subtree, in three's order (`__walk`). The whole walk
|
|
298
|
+
// depends on the hierarchy alone, so it is kept with `children` until the hierarchy counter moves;
|
|
299
|
+
// a visible-only walk reads the visible flags too, so it is asked each time.
|
|
300
|
+
const walk = (object: object, visibleOnly: boolean): object[] => {
|
|
301
|
+
const entry = visibleOnly ? undefined : keep?.(object);
|
|
302
|
+
if (entry !== undefined && entry.__walk !== undefined) return entry.__walk as object[];
|
|
303
|
+
const found = (object as { __walk(visibleOnly: boolean): object[] }).__walk(visibleOnly);
|
|
304
|
+
if (entry !== undefined) entry.__walk = found;
|
|
305
|
+
visited?.(found.length);
|
|
306
|
+
return found;
|
|
307
|
+
};
|
|
261
308
|
const methods: Record<string, (this: object, callback: TraverseCallback) => void> = {
|
|
262
309
|
traverse(callback) {
|
|
263
310
|
if (walks) {
|
|
264
311
|
for (const object of walk(this, false)) callback(object);
|
|
265
312
|
return;
|
|
266
313
|
}
|
|
314
|
+
visited?.(1);
|
|
267
315
|
callback(this);
|
|
268
316
|
for (const child of childrenOf(this))
|
|
269
317
|
(child as { traverse(c: TraverseCallback): void }).traverse(callback);
|
|
@@ -274,6 +322,7 @@ function defineTraversal(
|
|
|
274
322
|
return;
|
|
275
323
|
}
|
|
276
324
|
if ((this as { visible: boolean }).visible === false) return;
|
|
325
|
+
visited?.(1);
|
|
277
326
|
callback(this);
|
|
278
327
|
for (const child of childrenOf(this))
|
|
279
328
|
(child as { traverseVisible(c: TraverseCallback): void }).traverseVisible(callback);
|
|
@@ -287,18 +336,48 @@ function defineTraversal(
|
|
|
287
336
|
};
|
|
288
337
|
for (const [name, value] of Object.entries(methods))
|
|
289
338
|
Object.defineProperty(prototype, name, { configurable: true, writable: true, value });
|
|
339
|
+
// three's lookups, written over `traverse` as three writes them: the first match in walk order.
|
|
340
|
+
const lookups: Record<string, (this: object, ...args: never[]) => unknown> = {
|
|
341
|
+
getObjectsByProperty(this: object, name: string, value: unknown, result: object[] = []) {
|
|
342
|
+
(this as { traverse(c: TraverseCallback): void }).traverse((object) => {
|
|
343
|
+
if ((object as Record<string, unknown>)[name] === value) result.push(object);
|
|
344
|
+
});
|
|
345
|
+
return result;
|
|
346
|
+
},
|
|
347
|
+
getObjectByProperty(this: object, name: string, value: unknown) {
|
|
348
|
+
return (
|
|
349
|
+
this as { getObjectsByProperty(n: string, v: unknown): object[] }
|
|
350
|
+
).getObjectsByProperty(name, value)[0];
|
|
351
|
+
},
|
|
352
|
+
getObjectByName(this: object, name: string) {
|
|
353
|
+
return (this as { getObjectByProperty(n: string, v: unknown): object }).getObjectByProperty(
|
|
354
|
+
"name",
|
|
355
|
+
name,
|
|
356
|
+
);
|
|
357
|
+
},
|
|
358
|
+
getObjectById(this: object, id: number) {
|
|
359
|
+
return (this as { getObjectByProperty(n: string, v: unknown): object }).getObjectByProperty(
|
|
360
|
+
"id",
|
|
361
|
+
id,
|
|
362
|
+
);
|
|
363
|
+
},
|
|
364
|
+
};
|
|
365
|
+
for (const [name, value] of Object.entries(lookups))
|
|
366
|
+
Object.defineProperty(prototype, name, { configurable: true, writable: true, value });
|
|
290
367
|
// three's Object3D.raycast(raycaster, intersects): push this object's own hits, no recursion. The engine
|
|
291
|
-
// answers them through Raycaster.intersectObject (the object's native raycast
|
|
368
|
+
// answers them through Raycaster.intersectObject (the object's native raycast). A class the engine
|
|
369
|
+
// raycasts nothing for (a Group, a Bone, a light) keeps three's empty raycast and crosses nothing.
|
|
370
|
+
const raycast = function (
|
|
371
|
+
this: object,
|
|
372
|
+
raycaster: { intersectObject(object: object, recursive: boolean): unknown[] },
|
|
373
|
+
intersects: unknown[],
|
|
374
|
+
) {
|
|
375
|
+
intersects.push(...raycaster.intersectObject(this, false));
|
|
376
|
+
};
|
|
292
377
|
Object.defineProperty(prototype, "raycast", {
|
|
293
378
|
configurable: true,
|
|
294
379
|
writable: true,
|
|
295
|
-
value(
|
|
296
|
-
this: object,
|
|
297
|
-
raycaster: { intersectObject(object: object, recursive: boolean): unknown[] },
|
|
298
|
-
intersects: unknown[],
|
|
299
|
-
) {
|
|
300
|
-
intersects.push(...raycaster.intersectObject(this, false));
|
|
301
|
-
},
|
|
380
|
+
value: raycasts ? raycast : () => undefined,
|
|
302
381
|
});
|
|
303
382
|
}
|
|
304
383
|
|
|
@@ -312,38 +391,144 @@ export function defineBrowserClasses(
|
|
|
312
391
|
catalog?: ICatalogShape,
|
|
313
392
|
): IBrowserEngine {
|
|
314
393
|
// Every call into the engine counts, one increment each: the bench's crossing budget reads it per frame.
|
|
394
|
+
// A census frame (bridge-meter.ts) also records each one by name, so a redundant read is named.
|
|
315
395
|
let crossings = 0;
|
|
316
|
-
const
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
396
|
+
const debug = source.debugTelemetry ?? debugTelemetry(source);
|
|
397
|
+
let debugActivated = false;
|
|
398
|
+
let crossingMicros: number | undefined;
|
|
399
|
+
const typeNames = new Map<number, string>();
|
|
400
|
+
const calibratedCrossingMicros = (): number => {
|
|
401
|
+
if (crossingMicros === undefined) {
|
|
402
|
+
const ref = source.construct("Group", []);
|
|
403
|
+
const start = performance.now();
|
|
404
|
+
for (let i = 0; i < 1000; i++) source.get(ref, "name");
|
|
405
|
+
crossingMicros = performance.now() - start;
|
|
406
|
+
source.release(ref);
|
|
407
|
+
if (!Number.isFinite(crossingMicros) || crossingMicros < 0)
|
|
408
|
+
throw new Error("TN_DEBUG: invalid crossing calibration.");
|
|
409
|
+
}
|
|
410
|
+
return crossingMicros;
|
|
411
|
+
};
|
|
412
|
+
const meter = createBridgeMeter({
|
|
413
|
+
now: () => performance.now(),
|
|
414
|
+
// Getter-equivalent microseconds: a thousand crossings measured in milliseconds.
|
|
415
|
+
crossingMicros: calibratedCrossingMicros,
|
|
416
|
+
typeName: (type) => typeNames.get(type) ?? String(type),
|
|
417
|
+
stack: () => new Error().stack,
|
|
418
|
+
report: (line) => console.warn(line),
|
|
419
|
+
});
|
|
322
420
|
const runtime: IBrowserRuntime = {
|
|
323
421
|
...source,
|
|
324
|
-
construct:
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
422
|
+
construct: (className, args) => {
|
|
423
|
+
crossings++;
|
|
424
|
+
const ref = source.construct(className, args);
|
|
425
|
+
if (meter.counting) meter.record("construct", ref, className);
|
|
426
|
+
debug?.crossing("construct", ref, className, className);
|
|
427
|
+
return ref;
|
|
428
|
+
},
|
|
429
|
+
get: (self, path) => {
|
|
430
|
+
crossings++;
|
|
431
|
+
if (meter.counting) meter.record("get", self, path);
|
|
432
|
+
debug?.crossing("get", self, path, typeNames.get(self.type) ?? String(self.type));
|
|
433
|
+
return source.get(self, path);
|
|
434
|
+
},
|
|
435
|
+
set: (self, path, value) => {
|
|
436
|
+
crossings++;
|
|
437
|
+
if (meter.counting) meter.record("set", self, path);
|
|
438
|
+
debug?.crossing("set", self, path, typeNames.get(self.type) ?? String(self.type));
|
|
439
|
+
source.set(self, path, value);
|
|
440
|
+
},
|
|
441
|
+
invoke: (self, method, args) => {
|
|
442
|
+
crossings++;
|
|
443
|
+
if (meter.counting) meter.record("call", self, method);
|
|
444
|
+
debug?.crossing("call", self, method, typeNames.get(self.type) ?? String(self.type));
|
|
445
|
+
return source.invoke(self, method, args);
|
|
446
|
+
},
|
|
328
447
|
...(source.engineReferences === undefined
|
|
329
448
|
? {}
|
|
330
|
-
: {
|
|
449
|
+
: {
|
|
450
|
+
engineReferences: (refs: readonly IEngineRef[]) => {
|
|
451
|
+
crossings++;
|
|
452
|
+
const first = refs[0];
|
|
453
|
+
if (meter.counting && first !== undefined)
|
|
454
|
+
meter.record("engineReferences", first, "engineReferences");
|
|
455
|
+
if (debug !== undefined)
|
|
456
|
+
debug.crossing(
|
|
457
|
+
"engineReferences",
|
|
458
|
+
first ?? { key: "batch", type: 0 },
|
|
459
|
+
"engineReferences",
|
|
460
|
+
"Object3D",
|
|
461
|
+
);
|
|
462
|
+
return source.engineReferences?.(refs) ?? [];
|
|
463
|
+
},
|
|
464
|
+
}),
|
|
331
465
|
};
|
|
466
|
+
if (debug !== undefined) {
|
|
467
|
+
runtime.release = (self) => {
|
|
468
|
+
debug.crossing("release", self, "release", typeNames.get(self.type) ?? String(self.type));
|
|
469
|
+
source.release(self);
|
|
470
|
+
};
|
|
471
|
+
runtime.setCallback = (self, name, callback) => {
|
|
472
|
+
debug.crossing("callback", self, name, typeNames.get(self.type) ?? String(self.type));
|
|
473
|
+
source.setCallback(self, name, callback);
|
|
474
|
+
};
|
|
475
|
+
const attributeArray = source.attributeArray;
|
|
476
|
+
if (attributeArray !== undefined)
|
|
477
|
+
runtime.attributeArray = (self, offset, count) => {
|
|
478
|
+
debug.crossing(
|
|
479
|
+
"attributeRead",
|
|
480
|
+
self,
|
|
481
|
+
"array",
|
|
482
|
+
typeNames.get(self.type) ?? String(self.type),
|
|
483
|
+
);
|
|
484
|
+
return attributeArray(self, offset, count);
|
|
485
|
+
};
|
|
486
|
+
const attributeWrite = source.attributeWrite;
|
|
487
|
+
if (attributeWrite !== undefined)
|
|
488
|
+
runtime.attributeWrite = (self, value, offset) => {
|
|
489
|
+
debug.crossing(
|
|
490
|
+
"attributeWrite",
|
|
491
|
+
self,
|
|
492
|
+
"array",
|
|
493
|
+
typeNames.get(self.type) ?? String(self.type),
|
|
494
|
+
);
|
|
495
|
+
attributeWrite(self, value, offset);
|
|
496
|
+
};
|
|
497
|
+
}
|
|
332
498
|
const classes: Record<string, new (...args: unknown[]) => object> = {};
|
|
333
|
-
const byType = new Map<number, { prototype: object }>();
|
|
334
|
-
const typeNames = new Map<number, string>();
|
|
499
|
+
const byType = new Map<number, { prototype: object; own?: readonly IOwnField[] }>();
|
|
335
500
|
(globalThis as { __tnEngineTypes?: Map<number, string> }).__tnEngineTypes = typeNames;
|
|
336
501
|
// Reads that need no engine call: a field the engine holds in place is read from its memory (Wasm,
|
|
337
502
|
// `readDoubles`), and a fixed member (`position`, `matrixWorld`) is kept after its first answer.
|
|
338
503
|
// Writes still go through the engine's setters, which it reacts to.
|
|
339
|
-
|
|
340
|
-
// Each object's kept `rotation` Euler -> the object, whose quaternion a rotation write syncs.
|
|
504
|
+
// Each object's kept `rotation` Euler (or `quaternion`) -> the object, whose other form a write syncs.
|
|
341
505
|
const rotations = new WeakMap<object, object>();
|
|
506
|
+
const quaternions = new WeakMap<object, object>();
|
|
507
|
+
const sharedTransforms = debug === undefined ? undefined : new WeakSet<object>();
|
|
508
|
+
const sharedTransformWrite =
|
|
509
|
+
debug === undefined
|
|
510
|
+
? undefined
|
|
511
|
+
: (self: object, address: number, value: number): void => {
|
|
512
|
+
if (!sharedTransforms?.has(self)) return;
|
|
513
|
+
debug.add(
|
|
514
|
+
"sharedTransformWrites",
|
|
515
|
+
1,
|
|
516
|
+
"scene",
|
|
517
|
+
"browser-backend.ts:shared transform setter",
|
|
518
|
+
);
|
|
519
|
+
if (source.readDoubles !== undefined && Object.is(source.readDoubles(address, 1), value))
|
|
520
|
+
debug.add(
|
|
521
|
+
"unchangedSharedTransformWrites",
|
|
522
|
+
1,
|
|
523
|
+
"scene",
|
|
524
|
+
"browser-backend.ts:shared transform setter",
|
|
525
|
+
);
|
|
526
|
+
};
|
|
342
527
|
// Properties only the object's own setter or methods change: `name` and `type` (read per track and
|
|
343
528
|
// per bone while a game binds animations), an attribute's shape (read per merge), a mesh's
|
|
344
529
|
// geometry and material. The answer is kept until JS sets it or calls a method on that object.
|
|
345
530
|
// ponytail: an engine call on another object that changes one of these is missed; none does today.
|
|
346
|
-
const
|
|
531
|
+
const legacyLabelled = new Set([
|
|
347
532
|
"name",
|
|
348
533
|
"type",
|
|
349
534
|
"itemSize",
|
|
@@ -352,7 +537,147 @@ export function defineBrowserClasses(
|
|
|
352
537
|
"geometry",
|
|
353
538
|
"material",
|
|
354
539
|
]);
|
|
540
|
+
// The bridge-read mirror (PRD-748): more properties whose only writers are their own setter and the
|
|
541
|
+
// object's own methods, read from the bindings and every engine-side write (rg over src/engine), so
|
|
542
|
+
// a game that reads them per callback pays one crossing, not one a read. Object3D's flags
|
|
543
|
+
// (static_transform.cpp writes the two auto-update flags but nothing calls it), a light's shape and
|
|
544
|
+
// target, fog density, the scene's slots, and the material state no animation track drives.
|
|
545
|
+
// A fixed member with a setter (a light's or material's `color`) is a value the setter copies into,
|
|
546
|
+
// so its handle is kept too, and so is a material's texture slot (`map`, `normalMap`, ...).
|
|
547
|
+
const labelled = new Set([
|
|
548
|
+
...legacyLabelled,
|
|
549
|
+
"id",
|
|
550
|
+
"uuid",
|
|
551
|
+
"renderOrder",
|
|
552
|
+
"frustumCulled",
|
|
553
|
+
"matrixAutoUpdate",
|
|
554
|
+
"matrixWorldAutoUpdate",
|
|
555
|
+
"static",
|
|
556
|
+
"__alwaysRender",
|
|
557
|
+
"distance",
|
|
558
|
+
"decay",
|
|
559
|
+
"angle",
|
|
560
|
+
"penumbra",
|
|
561
|
+
"sourceRadius",
|
|
562
|
+
"target",
|
|
563
|
+
"density",
|
|
564
|
+
"fog",
|
|
565
|
+
"background",
|
|
566
|
+
"environment",
|
|
567
|
+
"backgroundIntensity",
|
|
568
|
+
"backgroundBlurriness",
|
|
569
|
+
"environmentIntensity",
|
|
570
|
+
"side",
|
|
571
|
+
"shadowSide",
|
|
572
|
+
"transparent",
|
|
573
|
+
"depthTest",
|
|
574
|
+
"depthWrite",
|
|
575
|
+
"blending",
|
|
576
|
+
"toneMapped",
|
|
577
|
+
"vertexColors",
|
|
578
|
+
"flatShading",
|
|
579
|
+
"colorWrite",
|
|
580
|
+
"alphaHash",
|
|
581
|
+
"forceSinglePass",
|
|
582
|
+
"polygonOffset",
|
|
583
|
+
"polygonOffsetFactor",
|
|
584
|
+
"polygonOffsetUnits",
|
|
585
|
+
"envMapIntensity",
|
|
586
|
+
"aoMapIntensity",
|
|
587
|
+
"bumpScale",
|
|
588
|
+
// AnimationClip only: no setter, and no engine call rewrites a clip's length.
|
|
589
|
+
"duration",
|
|
590
|
+
]);
|
|
591
|
+
// The numbers an animation track can also drive (animation/property_binding.cpp: a light's intensity,
|
|
592
|
+
// a perspective camera's lens, a material's numbers): kept like the rest, and dropped by any mixer or
|
|
593
|
+
// action call, since the mixer writes them in the engine. Colours are written in place, so they stay.
|
|
594
|
+
const animatedNames = new Set([
|
|
595
|
+
"intensity",
|
|
596
|
+
"fov",
|
|
597
|
+
"zoom",
|
|
598
|
+
"near",
|
|
599
|
+
"far",
|
|
600
|
+
"aspect",
|
|
601
|
+
"focus",
|
|
602
|
+
"opacity",
|
|
603
|
+
"alphaTest",
|
|
604
|
+
"emissiveIntensity",
|
|
605
|
+
"roughness",
|
|
606
|
+
"metalness",
|
|
607
|
+
"shininess",
|
|
608
|
+
"ior",
|
|
609
|
+
"specularIntensity",
|
|
610
|
+
// An action's and a mixer's own state (only these two classes carry the names): the mixer's update
|
|
611
|
+
// advances time, ends fades and warps, and finishes a clip, so the same rule holds.
|
|
612
|
+
"time",
|
|
613
|
+
"timeScale",
|
|
614
|
+
"weight",
|
|
615
|
+
"paused",
|
|
616
|
+
"enabled",
|
|
617
|
+
"loop",
|
|
618
|
+
"repetitions",
|
|
619
|
+
"clampWhenFinished",
|
|
620
|
+
]);
|
|
621
|
+
const mirrored = (binding: IRegistryClass, property: string, setters: Set<string>): boolean =>
|
|
622
|
+
labelled.has(property) ||
|
|
623
|
+
animatedNames.has(property) ||
|
|
624
|
+
(setters.has(property) &&
|
|
625
|
+
(binding.fixedMembers?.includes(property) === true || /^(map|[a-z]+Map)$/u.test(property)));
|
|
355
626
|
const labels = new WeakMap<object, Map<string, unknown>>();
|
|
627
|
+
let animated = new WeakMap<object, Map<string, unknown>>();
|
|
628
|
+
// An action's `isScheduled()`: the mixer's list of active actions, which only the action's own
|
|
629
|
+
// play/stop and the mixer's stopAllAction/uncache calls change (animation/mixer.cpp), never update,
|
|
630
|
+
// setTime or clipAction (a rifle asks clipAction each frame).
|
|
631
|
+
// core's AnimationPlayer asks it of every clip of every rig each step: 171 crossings a frame.
|
|
632
|
+
let scheduling = new WeakMap<object, unknown>();
|
|
633
|
+
// Object3D methods that move only the transform: the mirrored labels and numbers stay.
|
|
634
|
+
const transformOnly =
|
|
635
|
+
/^(updateMatrix|updateMatrixWorld|updateWorldMatrix|lookAt|rotate(X|Y|Z|OnAxis|OnWorldAxis)|translate(X|Y|Z|OnAxis)|apply(Matrix4|Quaternion)|setRotationFrom\w+|localToWorld|worldToLocal|updateProjectionMatrix)$/u;
|
|
636
|
+
// `__THREENATIVE_BRIDGE_CACHE__ = false` (a page global the worker host forwards) turns the mirror, the
|
|
637
|
+
// hierarchy cache and the JS Layers test off at the next safe point: the paired A/B knob.
|
|
638
|
+
const knob = "__THREENATIVE_BRIDGE_CACHE__";
|
|
639
|
+
const cacheWanted = () => (globalThis as Record<string, unknown>)[knob] !== false;
|
|
640
|
+
let caching = cacheWanted();
|
|
641
|
+
// Running totals a playtest bounds per frame (TN_FRAME_BUDGET.counters.engine): JS reads of
|
|
642
|
+
// `children` (core's auto batch read the scene's each still frame) and the objects a `traverse`
|
|
643
|
+
// visits (the projection window line walked 8,900 nodes every five seconds). One add each.
|
|
644
|
+
let childrenReads = 0;
|
|
645
|
+
let walkVisits = 0;
|
|
646
|
+
const walked = (count: number) => {
|
|
647
|
+
walkVisits += count;
|
|
648
|
+
};
|
|
649
|
+
// The glue's own entries, which the crossing count cannot see: a method wrapper and a property getter
|
|
650
|
+
// run whether the cache answers or the engine does, and the cache answers most of them. Counted only
|
|
651
|
+
// while a playtest bounds engine counters, so a shipped frame pays one branch and no store;
|
|
652
|
+
// `collect()` is the safe point that reads the flag.
|
|
653
|
+
let methodCalls = 0;
|
|
654
|
+
let propertyReads = 0;
|
|
655
|
+
let glueCounting = false;
|
|
656
|
+
// The hierarchy cache: `children`, `parent` and a whole-subtree walk are kept until the engine's
|
|
657
|
+
// process-wide hierarchy counter (Object3D::hierarchyVersion, read in place) moves. Every add,
|
|
658
|
+
// remove, attach, clear and destructor moves it, and nothing else in the engine writes a children
|
|
659
|
+
// list, so a kept answer is never stale. The table is replaced when the counter moves, so a kept
|
|
660
|
+
// array never holds a removed subtree alive past the next read or safe point.
|
|
661
|
+
let hierarchyAt: number | undefined;
|
|
662
|
+
let engineCountersAt: readonly (readonly [string, number])[] = [];
|
|
663
|
+
let keptVersion = -1;
|
|
664
|
+
let kept = new WeakMap<object, Record<string, unknown>>();
|
|
665
|
+
const readWord = source.readWord;
|
|
666
|
+
const hierarchyKept = (self: object): Record<string, unknown> | undefined => {
|
|
667
|
+
if (!caching || readWord === undefined) return undefined;
|
|
668
|
+
hierarchyAt ??= runtime.get(refOf(self), "__hierarchy") as number;
|
|
669
|
+
const version = readWord(hierarchyAt);
|
|
670
|
+
if (version !== keptVersion) {
|
|
671
|
+
keptVersion = version;
|
|
672
|
+
kept = new WeakMap();
|
|
673
|
+
}
|
|
674
|
+
let entry = kept.get(self);
|
|
675
|
+
if (entry === undefined) {
|
|
676
|
+
entry = {};
|
|
677
|
+
kept.set(self, entry);
|
|
678
|
+
}
|
|
679
|
+
return entry;
|
|
680
|
+
};
|
|
356
681
|
const mixerStats = new WeakMap<object, object>();
|
|
357
682
|
const fastGetter = (binding: IRegistryClass, property: string) => {
|
|
358
683
|
const field = binding.fields?.[property];
|
|
@@ -365,9 +690,11 @@ export function defineBrowserClasses(
|
|
|
365
690
|
return readByte === undefined
|
|
366
691
|
? undefined
|
|
367
692
|
: function (this: object) {
|
|
693
|
+
if (glueCounting) propertyReads += 1;
|
|
368
694
|
return readByte(addressOf(this) + offset) !== 0;
|
|
369
695
|
};
|
|
370
696
|
return function (this: object) {
|
|
697
|
+
if (glueCounting) propertyReads += 1;
|
|
371
698
|
return read(addressOf(this) + offset, count);
|
|
372
699
|
};
|
|
373
700
|
}
|
|
@@ -376,19 +703,28 @@ export function defineBrowserClasses(
|
|
|
376
703
|
// Object3D has it: every later read is a plain property load, never this getter (R5 reads
|
|
377
704
|
// position and rotation three times per cube per frame).
|
|
378
705
|
return function (this: object) {
|
|
706
|
+
if (glueCounting) propertyReads += 1;
|
|
379
707
|
const member = fromEngine(runtime.get(refOf(this), property));
|
|
380
708
|
Object.defineProperty(this, property, { value: member, writable: false });
|
|
709
|
+
if (
|
|
710
|
+
property === "position" ||
|
|
711
|
+
property === "scale" ||
|
|
712
|
+
property === "rotation" ||
|
|
713
|
+
property === "quaternion"
|
|
714
|
+
)
|
|
715
|
+
sharedTransforms?.add(member as object);
|
|
381
716
|
if (property === "rotation") rotations.set(member as object, this);
|
|
717
|
+
if (property === "quaternion") quaternions.set(member as object, this);
|
|
382
718
|
return member;
|
|
383
719
|
};
|
|
384
720
|
return undefined;
|
|
385
721
|
};
|
|
722
|
+
// An own property, not a WeakMap: `position.x` and every other lane access reads it (PRD-748).
|
|
386
723
|
const addressOf = (self: object): number => {
|
|
387
|
-
|
|
388
|
-
if (
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
}
|
|
724
|
+
const known = (self as { [ADDRESS]?: number })[ADDRESS];
|
|
725
|
+
if (known !== undefined) return known;
|
|
726
|
+
const address = runtime.get(refOf(self), "__address") as number;
|
|
727
|
+
Object.defineProperty(self, ADDRESS, { value: address });
|
|
392
728
|
return address;
|
|
393
729
|
};
|
|
394
730
|
// three's math values are JS (browser-math.ts): `new Vector3()` holds its own lanes. The engine's
|
|
@@ -396,21 +732,186 @@ export function defineBrowserClasses(
|
|
|
396
732
|
// An engine call takes a JS value by value: a method borrows a pooled engine object and copies
|
|
397
733
|
// the lanes back after the call (an output argument); a constructor or setter, which may keep the
|
|
398
734
|
// object, gets the value itself turned into an engine object in place, so identity survives.
|
|
735
|
+
//
|
|
736
|
+
// A class may store its lanes under three's private names (`Quaternion._x`, `Matrix4.elements`) or
|
|
737
|
+
// hold them in member vectors (`Box3.min`): its plan reads and writes those, and says which own
|
|
738
|
+
// properties a promoted value must drop so the engine accessors take over.
|
|
739
|
+
/** A value class's JS storage: its public lanes, three's private names, and member vectors. */
|
|
740
|
+
interface IValueLanes {
|
|
741
|
+
[key: string]: unknown;
|
|
742
|
+
_x?: number;
|
|
743
|
+
_y?: number;
|
|
744
|
+
_z?: number;
|
|
745
|
+
_w?: number;
|
|
746
|
+
_order?: string;
|
|
747
|
+
elements?: number[];
|
|
748
|
+
radius?: number;
|
|
749
|
+
min?: { x: number; y: number; z: number; set(x: number, y: number, z: number): unknown };
|
|
750
|
+
max?: { x: number; y: number; z: number; set(x: number, y: number, z: number): unknown };
|
|
751
|
+
center?: { x: number; y: number; z: number; set(x: number, y: number, z: number): unknown };
|
|
752
|
+
}
|
|
753
|
+
interface IValuePlan {
|
|
754
|
+
/** The engine's lane names, in the order its constructor takes them. */
|
|
755
|
+
lanes: readonly string[];
|
|
756
|
+
/** Own JS properties the class keeps its storage in; a promoted value drops them. */
|
|
757
|
+
drop: readonly string[];
|
|
758
|
+
/** The lanes of a JS value, in `lanes` order (Euler appends its order). */
|
|
759
|
+
read(value: IValueLanes): number[];
|
|
760
|
+
/** Writes engine lanes back into a JS value, as `lend` copies them back. */
|
|
761
|
+
write(value: IValueLanes, values: readonly number[]): void;
|
|
762
|
+
/** Engine constructor arguments; the lanes themselves by default. */
|
|
763
|
+
args?(values: number[], make: (name: string, values: number[]) => IEngineRef): EngineValue[];
|
|
764
|
+
/** A method argument becomes an engine object in place: whole-object lanes and output targets. */
|
|
765
|
+
promote?: boolean;
|
|
766
|
+
/** Copies the lanes from one value to another with no list between: a loan's two copies. */
|
|
767
|
+
copy?(target: IValueLanes, source: IValueLanes): void;
|
|
768
|
+
}
|
|
399
769
|
interface IValueClass {
|
|
400
770
|
name: string;
|
|
401
|
-
lanes: string[];
|
|
402
771
|
engine: object;
|
|
403
772
|
pool: object[];
|
|
404
773
|
top: number;
|
|
774
|
+
plan: IValuePlan;
|
|
405
775
|
}
|
|
406
|
-
const
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
776
|
+
const eulerOrders = ["XYZ", "YXZ", "ZXY", "ZYX", "YZX", "XZY"] as const;
|
|
777
|
+
const defaultPlan = (lanes: readonly string[]): IValuePlan => ({
|
|
778
|
+
lanes,
|
|
779
|
+
drop: lanes,
|
|
780
|
+
copy: (target, source) => {
|
|
781
|
+
for (const lane of lanes) target[lane] = source[lane];
|
|
782
|
+
},
|
|
783
|
+
read: (value) => lanes.map((lane) => value[lane] as number),
|
|
784
|
+
write: (value, values) => {
|
|
785
|
+
lanes.forEach((lane, index) => {
|
|
786
|
+
value[lane] = values[index] as number;
|
|
787
|
+
});
|
|
788
|
+
},
|
|
789
|
+
});
|
|
790
|
+
/** A value's member vector (`Box3.min`, `Sphere.center`): present on every real instance. */
|
|
791
|
+
const memberVector = (vector: IValueLanes["min"]): NonNullable<IValueLanes["min"]> => {
|
|
792
|
+
if (vector === undefined)
|
|
793
|
+
throw new TypeError("TN_BROWSER_VALUE_MEMBER: the value has no vector");
|
|
794
|
+
return vector;
|
|
795
|
+
};
|
|
796
|
+
// three's private storage names, and the classes whose lanes are not plain fields.
|
|
797
|
+
const valuePlans: Record<string, IValuePlan> = {
|
|
798
|
+
// quality-allow: the plan table is keyed by three's PascalCase class names, so the name rule cannot apply.
|
|
799
|
+
// biome-ignore lint/style/useNamingConvention: keyed by three's class name.
|
|
800
|
+
Color: defaultPlan(["r", "g", "b"]),
|
|
801
|
+
// quality-allow: the plan table is keyed by three's PascalCase class names, so the name rule cannot apply.
|
|
802
|
+
// biome-ignore lint/style/useNamingConvention: keyed by three's class name.
|
|
803
|
+
Vector4: defaultPlan(["x", "y", "z", "w"]),
|
|
804
|
+
// quality-allow: the plan table is keyed by three's PascalCase class names, so the name rule cannot apply.
|
|
805
|
+
// biome-ignore lint/style/useNamingConvention: keyed by three's class name.
|
|
806
|
+
Quaternion: {
|
|
807
|
+
lanes: ["x", "y", "z", "w"],
|
|
808
|
+
drop: ["_x", "_y", "_z", "_w"],
|
|
809
|
+
read: (value) => [value._x, value._y, value._z, value._w] as number[],
|
|
810
|
+
write: (value, values) => {
|
|
811
|
+
value._x = values[0];
|
|
812
|
+
value._y = values[1];
|
|
813
|
+
value._z = values[2];
|
|
814
|
+
value._w = values[3];
|
|
815
|
+
},
|
|
816
|
+
},
|
|
817
|
+
// quality-allow: the plan table is keyed by three's PascalCase class names, so the name rule cannot apply.
|
|
818
|
+
// biome-ignore lint/style/useNamingConvention: keyed by three's class name.
|
|
819
|
+
Euler: {
|
|
820
|
+
lanes: ["x", "y", "z"],
|
|
821
|
+
drop: ["_x", "_y", "_z", "_order"],
|
|
822
|
+
read: (value) =>
|
|
823
|
+
[
|
|
824
|
+
value._x,
|
|
825
|
+
value._y,
|
|
826
|
+
value._z,
|
|
827
|
+
eulerOrders.indexOf(value._order as (typeof eulerOrders)[number]),
|
|
828
|
+
] as number[],
|
|
829
|
+
write: (value, values) => {
|
|
830
|
+
value._x = values[0];
|
|
831
|
+
value._y = values[1];
|
|
832
|
+
value._z = values[2];
|
|
833
|
+
value._order = eulerOrders[values[3] as number] ?? "XYZ";
|
|
834
|
+
},
|
|
835
|
+
args: (values) => [
|
|
836
|
+
values[0],
|
|
837
|
+
values[1],
|
|
838
|
+
values[2],
|
|
839
|
+
eulerOrders[values[3] as number] ?? "XYZ",
|
|
840
|
+
],
|
|
841
|
+
},
|
|
842
|
+
// quality-allow: the plan table is keyed by three's PascalCase class names, so the name rule cannot apply.
|
|
843
|
+
// biome-ignore lint/style/useNamingConvention: keyed by three's class name.
|
|
844
|
+
Matrix3: {
|
|
845
|
+
promote: true,
|
|
846
|
+
lanes: ["elements"],
|
|
847
|
+
drop: ["elements"],
|
|
848
|
+
read: (value) => Array.from(value.elements as number[]),
|
|
849
|
+
write: (value, values) => {
|
|
850
|
+
value.elements = Array.from(values);
|
|
851
|
+
},
|
|
852
|
+
// `elements` is column-major; the engine constructor takes three's row-major set order.
|
|
853
|
+
args: (values) => [0, 3, 6, 1, 4, 7, 2, 5, 8].map((index) => values[index] as number),
|
|
854
|
+
},
|
|
855
|
+
// quality-allow: the plan table is keyed by three's PascalCase class names, so the name rule cannot apply.
|
|
856
|
+
// biome-ignore lint/style/useNamingConvention: keyed by three's class name.
|
|
857
|
+
Matrix4: {
|
|
858
|
+
promote: true,
|
|
859
|
+
lanes: ["elements"],
|
|
860
|
+
drop: ["elements"],
|
|
861
|
+
read: (value) => Array.from(value.elements as number[]),
|
|
862
|
+
write: (value, values) => {
|
|
863
|
+
value.elements = Array.from(values);
|
|
864
|
+
},
|
|
865
|
+
// `elements` is column-major; the engine constructor takes three's row-major set order.
|
|
866
|
+
args: (values) =>
|
|
867
|
+
[0, 4, 8, 12, 1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15].map(
|
|
868
|
+
(index) => values[index] as number,
|
|
869
|
+
),
|
|
870
|
+
},
|
|
871
|
+
// quality-allow: the plan table is keyed by three's PascalCase class names, so the name rule cannot apply.
|
|
872
|
+
// biome-ignore lint/style/useNamingConvention: keyed by three's class name.
|
|
873
|
+
Box3: {
|
|
874
|
+
promote: true,
|
|
875
|
+
lanes: [],
|
|
876
|
+
drop: ["min", "max"],
|
|
877
|
+
read: (value) => {
|
|
878
|
+
const min = memberVector(value.min);
|
|
879
|
+
const max = memberVector(value.max);
|
|
880
|
+
return [min.x, min.y, min.z, max.x, max.y, max.z];
|
|
881
|
+
},
|
|
882
|
+
write: (value, values) => {
|
|
883
|
+
memberVector(value.min).set(values[0] as number, values[1] as number, values[2] as number);
|
|
884
|
+
memberVector(value.max).set(values[3] as number, values[4] as number, values[5] as number);
|
|
885
|
+
},
|
|
886
|
+
args: (values, make) => [
|
|
887
|
+
make("Vector3", values.slice(0, 3).map(Number)),
|
|
888
|
+
make("Vector3", values.slice(3, 6).map(Number)),
|
|
889
|
+
],
|
|
890
|
+
},
|
|
891
|
+
// quality-allow: the plan table is keyed by three's PascalCase class names, so the name rule cannot apply.
|
|
892
|
+
// biome-ignore lint/style/useNamingConvention: keyed by three's class name.
|
|
893
|
+
Sphere: {
|
|
894
|
+
promote: true,
|
|
895
|
+
lanes: ["radius"],
|
|
896
|
+
drop: ["center", "radius"],
|
|
897
|
+
read: (value) => {
|
|
898
|
+
const center = memberVector(value.center);
|
|
899
|
+
return [center.x, center.y, center.z, value.radius as number];
|
|
900
|
+
},
|
|
901
|
+
write: (value, values) => {
|
|
902
|
+
memberVector(value.center).set(
|
|
903
|
+
values[0] as number,
|
|
904
|
+
values[1] as number,
|
|
905
|
+
values[2] as number,
|
|
906
|
+
);
|
|
907
|
+
value.radius = values[3] as number;
|
|
908
|
+
},
|
|
909
|
+
args: (values, make) => [make("Vector3", values.slice(0, 3).map(Number)), values[3]],
|
|
910
|
+
},
|
|
911
|
+
};
|
|
912
|
+
const math = defineMath() as Record<string, new (...args: unknown[]) => object>;
|
|
412
913
|
const valueClasses = new Map<object, IValueClass>(); // JS prototype -> its engine side
|
|
413
|
-
const loans: [
|
|
914
|
+
const loans: [IValueLanes, IValueLanes, IValueClass][] = [];
|
|
414
915
|
let borrowing = false;
|
|
415
916
|
const toEngineArgs = (args: readonly unknown[]): EngineValue[] => {
|
|
416
917
|
borrowing = true;
|
|
@@ -420,15 +921,36 @@ export function defineBrowserClasses(
|
|
|
420
921
|
borrowing = false;
|
|
421
922
|
}
|
|
422
923
|
};
|
|
423
|
-
|
|
924
|
+
// A plan's member-vector arguments (Box3's two, Sphere's one) are native temporaries: the engine
|
|
925
|
+
// copies them, so they are released as soon as the value that owns the lanes is constructed.
|
|
926
|
+
const engineArgs = (
|
|
927
|
+
info: IValueClass,
|
|
928
|
+
values: number[],
|
|
929
|
+
): { args: EngineValue[]; temporaries: IEngineRef[] } => {
|
|
930
|
+
if (info.plan.args === undefined) return { args: values, temporaries: [] };
|
|
931
|
+
const temporaries: IEngineRef[] = [];
|
|
932
|
+
const args = info.plan.args(values, (name, lanes) => {
|
|
933
|
+
const ref = runtime.construct(name, lanes);
|
|
934
|
+
temporaries.push(ref);
|
|
935
|
+
return ref;
|
|
936
|
+
});
|
|
937
|
+
return { args, temporaries };
|
|
938
|
+
};
|
|
939
|
+
const lend = (value: IValueLanes, info: IValueClass): IEngineRef => {
|
|
424
940
|
let scratch = info.pool[info.top];
|
|
425
941
|
if (scratch === undefined) {
|
|
426
|
-
|
|
942
|
+
const built = engineArgs(info, info.plan.read(value));
|
|
943
|
+
try {
|
|
944
|
+
scratch = wrap(runtime.construct(info.name, built.args));
|
|
945
|
+
} finally {
|
|
946
|
+
for (const temporary of built.temporaries) runtime.release(temporary);
|
|
947
|
+
}
|
|
427
948
|
info.pool.push(scratch);
|
|
428
949
|
}
|
|
429
950
|
info.top++;
|
|
430
|
-
const lanes = scratch as
|
|
431
|
-
|
|
951
|
+
const lanes = scratch as IValueLanes;
|
|
952
|
+
if (info.plan.copy !== undefined) info.plan.copy(lanes, value);
|
|
953
|
+
else info.plan.write(lanes, info.plan.read(value));
|
|
432
954
|
loans.push([value, lanes, info]);
|
|
433
955
|
return refOf(scratch);
|
|
434
956
|
};
|
|
@@ -437,18 +959,224 @@ export function defineBrowserClasses(
|
|
|
437
959
|
let result = returned;
|
|
438
960
|
for (let i = loans.length - 1; i >= mark; i--) {
|
|
439
961
|
const [value, scratch, info] = loans[i] as (typeof loans)[number];
|
|
440
|
-
|
|
962
|
+
if (info.plan.copy !== undefined) info.plan.copy(value, scratch);
|
|
963
|
+
else info.plan.write(value, info.plan.read(scratch));
|
|
441
964
|
info.top--;
|
|
442
965
|
if (result === scratch) result = value;
|
|
443
966
|
}
|
|
444
967
|
loans.length = mark;
|
|
445
968
|
return result;
|
|
446
969
|
};
|
|
447
|
-
const promote = (value:
|
|
448
|
-
const
|
|
449
|
-
for (const
|
|
970
|
+
const promote = (value: IValueLanes, info: IValueClass): void => {
|
|
971
|
+
const values = info.plan.read(value);
|
|
972
|
+
for (const key of info.plan.drop) delete value[key];
|
|
450
973
|
Object.setPrototypeOf(value, info.engine);
|
|
451
|
-
|
|
974
|
+
const built = engineArgs(info, values);
|
|
975
|
+
try {
|
|
976
|
+
adopt(value, runtime.construct(info.name, built.args));
|
|
977
|
+
} finally {
|
|
978
|
+
for (const temporary of built.temporaries) runtime.release(temporary);
|
|
979
|
+
}
|
|
980
|
+
};
|
|
981
|
+
// An engine-owned value reads and writes its lanes in the engine's memory through accessors named
|
|
982
|
+
// for the storage its class actually uses. Quaternion and Euler store `_x`, Matrix stores
|
|
983
|
+
// `elements`, and an Euler's order is a string over the engine's byte enum; Box3 and Sphere reach
|
|
984
|
+
// their vectors through the registry's fixed members, so they need nothing here.
|
|
985
|
+
const defineValueView = (
|
|
986
|
+
name: string,
|
|
987
|
+
accessors: Record<string, unknown>,
|
|
988
|
+
binding: IRegistryClass,
|
|
989
|
+
skip: Set<string>,
|
|
990
|
+
): void => {
|
|
991
|
+
const read = runtime.readDoubles;
|
|
992
|
+
const write = runtime.writeDouble;
|
|
993
|
+
const peek = runtime.readByte;
|
|
994
|
+
if (read === undefined || write === undefined) return;
|
|
995
|
+
const heap = runtime.heapF64;
|
|
996
|
+
const lane = heap
|
|
997
|
+
? (address: number): number => heap()[address / 8] as number
|
|
998
|
+
: (address: number): number => read(address, 1) as number;
|
|
999
|
+
if (name === "Quaternion" && binding.fields !== undefined) {
|
|
1000
|
+
const offsets = ["x", "y", "z", "w"].map((key) => binding.fields?.[key]?.[0] ?? 0);
|
|
1001
|
+
["_x", "_y", "_z", "_w"].forEach((key, index) => {
|
|
1002
|
+
const offset = offsets[index] as number;
|
|
1003
|
+
Object.defineProperty(accessors, key, {
|
|
1004
|
+
configurable: true,
|
|
1005
|
+
get(this: object): number {
|
|
1006
|
+
return lane(addressOf(this) + offset);
|
|
1007
|
+
},
|
|
1008
|
+
set(this: object, value: number): void {
|
|
1009
|
+
const address = addressOf(this) + offset;
|
|
1010
|
+
const next = Number(value);
|
|
1011
|
+
sharedTransformWrite?.(this, address, next);
|
|
1012
|
+
write(address, next);
|
|
1013
|
+
},
|
|
1014
|
+
});
|
|
1015
|
+
});
|
|
1016
|
+
skip.add("x").add("y").add("z").add("w");
|
|
1017
|
+
// three syncs an Object3D's rotation from its quaternion. Physics interpolation sets every body's
|
|
1018
|
+
// quaternion every frame, so a call per sync cost 1,732 crossings a frame on the stress lab. This is
|
|
1019
|
+
// Euler::setFromQuaternion with update off (Euler.cpp), written into the rotation's lanes: the same
|
|
1020
|
+
// formulas, and Math is V8's fdlibm, which the engine's ieee754 functions are, so the bits match.
|
|
1021
|
+
const eulerFields = registry.classes.Euler?.fields;
|
|
1022
|
+
const angles = ["x", "y", "z"].map((key) => eulerFields?.[key]?.[0]);
|
|
1023
|
+
const orderAt = eulerFields?.__order?.[0];
|
|
1024
|
+
const local =
|
|
1025
|
+
peek !== undefined && orderAt !== undefined && angles.every((at) => at !== undefined);
|
|
1026
|
+
const [ax, ay, az] = angles as [number, number, number];
|
|
1027
|
+
Object.defineProperty(accessors, "_onChangeCallback", {
|
|
1028
|
+
configurable: true,
|
|
1029
|
+
writable: true,
|
|
1030
|
+
value(this: object): void {
|
|
1031
|
+
const owner = quaternions.get(this) as
|
|
1032
|
+
| { rotation?: object & { _order?: string } }
|
|
1033
|
+
| undefined;
|
|
1034
|
+
if (owner?.rotation === undefined) return;
|
|
1035
|
+
if (!local) {
|
|
1036
|
+
// The rotation's own order; the engine refuses a missing one on this call.
|
|
1037
|
+
runtime.invoke(refOf(owner.rotation), "setFromQuaternion", [
|
|
1038
|
+
refOf(this),
|
|
1039
|
+
owner.rotation._order ?? "XYZ",
|
|
1040
|
+
]);
|
|
1041
|
+
return;
|
|
1042
|
+
}
|
|
1043
|
+
const q = addressOf(this);
|
|
1044
|
+
const e = addressOf(owner.rotation);
|
|
1045
|
+
const [ex, ey, ez] = eulerFromQuaternion(
|
|
1046
|
+
lane(q + (offsets[0] as number)),
|
|
1047
|
+
lane(q + (offsets[1] as number)),
|
|
1048
|
+
lane(q + (offsets[2] as number)),
|
|
1049
|
+
lane(q + (offsets[3] as number)),
|
|
1050
|
+
eulerOrders[(peek as (address: number) => number)(e + (orderAt as number))] ?? "XYZ",
|
|
1051
|
+
);
|
|
1052
|
+
write(e + ax, ex);
|
|
1053
|
+
write(e + ay, ey);
|
|
1054
|
+
write(e + az, ez);
|
|
1055
|
+
},
|
|
1056
|
+
});
|
|
1057
|
+
return;
|
|
1058
|
+
}
|
|
1059
|
+
if (name === "Euler" && binding.fields !== undefined && peek !== undefined) {
|
|
1060
|
+
const offsets = ["x", "y", "z"].map((key) => binding.fields?.[key]?.[0] ?? 0) as number[];
|
|
1061
|
+
const orderAt = binding.fields.__order?.[0] ?? 0;
|
|
1062
|
+
const quaternionFields = registry.classes.Quaternion?.fields;
|
|
1063
|
+
const targets = ["x", "y", "z", "w"].map((key) => quaternionFields?.[key]?.[0] ?? 0);
|
|
1064
|
+
// three's setFromEuler: each order only signs the second terms, in the engine enum's order.
|
|
1065
|
+
const signs = [
|
|
1066
|
+
[1, -1, 1, -1],
|
|
1067
|
+
[1, -1, -1, 1],
|
|
1068
|
+
[-1, 1, 1, -1],
|
|
1069
|
+
[-1, 1, -1, 1],
|
|
1070
|
+
[1, 1, -1, -1],
|
|
1071
|
+
[-1, -1, 1, 1],
|
|
1072
|
+
];
|
|
1073
|
+
const sync = (euler: object): void => {
|
|
1074
|
+
const owner = rotations.get(euler) as { quaternion?: object } | undefined;
|
|
1075
|
+
if (owner?.quaternion === undefined) return;
|
|
1076
|
+
const at = addressOf(euler);
|
|
1077
|
+
const q = addressOf(owner.quaternion);
|
|
1078
|
+
const x = lane(at + (offsets[0] as number)) / 2;
|
|
1079
|
+
const y = lane(at + (offsets[1] as number)) / 2;
|
|
1080
|
+
const z = lane(at + (offsets[2] as number)) / 2;
|
|
1081
|
+
const sign = signs[peek(at + orderAt)] ?? (signs[0] as number[]);
|
|
1082
|
+
const c1 = Math.cos(x);
|
|
1083
|
+
const c2 = Math.cos(y);
|
|
1084
|
+
const c3 = Math.cos(z);
|
|
1085
|
+
const s1 = Math.sin(x);
|
|
1086
|
+
const s2 = Math.sin(y);
|
|
1087
|
+
const s3 = Math.sin(z);
|
|
1088
|
+
write(q + (targets[0] as number), s1 * c2 * c3 + (sign[0] as number) * c1 * s2 * s3);
|
|
1089
|
+
write(q + (targets[1] as number), c1 * s2 * c3 + (sign[1] as number) * s1 * c2 * s3);
|
|
1090
|
+
write(q + (targets[2] as number), c1 * c2 * s3 + (sign[2] as number) * s1 * s2 * c3);
|
|
1091
|
+
write(q + (targets[3] as number), c1 * c2 * c3 + (sign[3] as number) * s1 * s2 * s3);
|
|
1092
|
+
};
|
|
1093
|
+
["_x", "_y", "_z"].forEach((key, index) => {
|
|
1094
|
+
const offset = offsets[index] as number;
|
|
1095
|
+
Object.defineProperty(accessors, key, {
|
|
1096
|
+
configurable: true,
|
|
1097
|
+
get(this: object): number {
|
|
1098
|
+
return lane(addressOf(this) + offset);
|
|
1099
|
+
},
|
|
1100
|
+
set(this: object, value: number): void {
|
|
1101
|
+
const address = addressOf(this) + offset;
|
|
1102
|
+
const next = Number(value);
|
|
1103
|
+
sharedTransformWrite?.(this, address, next);
|
|
1104
|
+
write(address, next);
|
|
1105
|
+
},
|
|
1106
|
+
});
|
|
1107
|
+
});
|
|
1108
|
+
Object.defineProperty(accessors, "_order", {
|
|
1109
|
+
configurable: true,
|
|
1110
|
+
get(this: object): string {
|
|
1111
|
+
return eulerOrders[peek(addressOf(this) + orderAt)] ?? "XYZ";
|
|
1112
|
+
},
|
|
1113
|
+
set(this: object, value: unknown): void {
|
|
1114
|
+
const index = eulerOrders.indexOf(value as (typeof eulerOrders)[number]);
|
|
1115
|
+
if (index < 0)
|
|
1116
|
+
throw new TypeError(
|
|
1117
|
+
`Euler order is not one of ${eulerOrders.join(", ")}: ${String(value)}`,
|
|
1118
|
+
);
|
|
1119
|
+
// The order is the engine's byte enum: its setter reorders and syncs, so only a change
|
|
1120
|
+
// crosses (four numbers are not worth a call on every `rotation.set`).
|
|
1121
|
+
if (index !== peek(addressOf(this) + orderAt))
|
|
1122
|
+
runtime.set(refOf(this), "order", value as string);
|
|
1123
|
+
},
|
|
1124
|
+
});
|
|
1125
|
+
Object.defineProperty(accessors, "_onChangeCallback", {
|
|
1126
|
+
configurable: true,
|
|
1127
|
+
writable: true,
|
|
1128
|
+
value(this: object): void {
|
|
1129
|
+
sync(this);
|
|
1130
|
+
},
|
|
1131
|
+
});
|
|
1132
|
+
skip.add("x").add("y").add("z").add("order");
|
|
1133
|
+
return;
|
|
1134
|
+
}
|
|
1135
|
+
if ((name === "Matrix3" || name === "Matrix4") && binding.fields?.elements !== undefined) {
|
|
1136
|
+
const [offset = 0, count = 0] = binding.fields.elements;
|
|
1137
|
+
// three keeps one `elements` array; this keeps one proxy per matrix over a mirrored array and
|
|
1138
|
+
// writes every element it sets straight to engine memory, so the array never detaches.
|
|
1139
|
+
const mirrors = new WeakMap<object, { values: number[]; view: number[] }>();
|
|
1140
|
+
// Off the heap view when there is one: a game reads `matrixWorld.elements` hundreds of times
|
|
1141
|
+
// a frame, and a copy call allocates two arrays a read.
|
|
1142
|
+
const refresh = heap
|
|
1143
|
+
? (address: number, values: number[]): void => {
|
|
1144
|
+
const memory = heap();
|
|
1145
|
+
for (let i = 0, at = address / 8; i < count; i++) values[i] = memory[at + i] as number;
|
|
1146
|
+
}
|
|
1147
|
+
: (address: number, values: number[]): void => {
|
|
1148
|
+
const memory = read(address, count) as number[];
|
|
1149
|
+
for (let i = 0; i < count; i++) values[i] = memory[i] as number;
|
|
1150
|
+
};
|
|
1151
|
+
Object.defineProperty(accessors, "elements", {
|
|
1152
|
+
configurable: true,
|
|
1153
|
+
get(this: object): number[] {
|
|
1154
|
+
const address = addressOf(this) + offset;
|
|
1155
|
+
let mirror = mirrors.get(this);
|
|
1156
|
+
if (mirror === undefined) {
|
|
1157
|
+
const values = new Array<number>(count);
|
|
1158
|
+
const view = new Proxy(values, {
|
|
1159
|
+
set: (target, key, value): boolean => {
|
|
1160
|
+
const index = typeof key === "string" ? Number(key) : Number.NaN;
|
|
1161
|
+
if (Number.isInteger(index) && index >= 0 && index < count)
|
|
1162
|
+
write(address + index * 8, Number(value));
|
|
1163
|
+
target[key as never] = value as never;
|
|
1164
|
+
return true;
|
|
1165
|
+
},
|
|
1166
|
+
});
|
|
1167
|
+
mirror = { values, view };
|
|
1168
|
+
mirrors.set(this, mirror);
|
|
1169
|
+
}
|
|
1170
|
+
refresh(address, mirror.values);
|
|
1171
|
+
return mirror.view;
|
|
1172
|
+
},
|
|
1173
|
+
set(this: object, value: ArrayLike<number>): void {
|
|
1174
|
+
const address = addressOf(this) + offset;
|
|
1175
|
+
for (let i = 0; i < count; i++) write(address + i * 8, Number(value[i]));
|
|
1176
|
+
},
|
|
1177
|
+
});
|
|
1178
|
+
skip.add("elements");
|
|
1179
|
+
}
|
|
452
1180
|
};
|
|
453
1181
|
const wrappers = new Map<string, WeakRef<object>>();
|
|
454
1182
|
// Callbacks: the function lives on its wrapper (a WeakMap entry), so wrapper -> closure is an edge
|
|
@@ -475,6 +1203,8 @@ export function defineBrowserClasses(
|
|
|
475
1203
|
const { attributeArray, attributeWrite } = runtime;
|
|
476
1204
|
const arrays = new WeakMap<object, { array: TypedArray }>();
|
|
477
1205
|
const itemSizes = new WeakMap<object, number>();
|
|
1206
|
+
// Shape survives data uploads and transform calls; only copy/replacement changes it.
|
|
1207
|
+
const shapes = new WeakMap<object, Map<string, unknown>>();
|
|
478
1208
|
const pending = new Set<object>();
|
|
479
1209
|
const writeBack = (): void => {
|
|
480
1210
|
for (const attribute of pending) {
|
|
@@ -536,8 +1266,42 @@ export function defineBrowserClasses(
|
|
|
536
1266
|
if (fresh.length === entry.array.length) entry.array.set(fresh);
|
|
537
1267
|
else entry.array = fresh;
|
|
538
1268
|
};
|
|
1269
|
+
// three's `InstancedMesh.setMatrixAt`/`setColorAt` write the mesh's own `instanceMatrix`/
|
|
1270
|
+
// `instanceColor` array item (`index * 16`, `index * 3`); the engine's mesh-level call writes only
|
|
1271
|
+
// its own store, so the shadow a game already holds (core's velocity capture reads one per mesh a
|
|
1272
|
+
// frame) would send its frozen snapshot back at `needsUpdate` and leave the mesh where it stood.
|
|
1273
|
+
// Take the item the call writes into that same array, as three does. No shadow, no work: this is
|
|
1274
|
+
// a pair of map lookups and an array copy, never an engine call.
|
|
1275
|
+
const instanceItem = (
|
|
1276
|
+
mesh: object,
|
|
1277
|
+
attribute: string,
|
|
1278
|
+
index: unknown,
|
|
1279
|
+
argument: unknown,
|
|
1280
|
+
): { array: TypedArray; at: number; values: ArrayLike<number> } | undefined => {
|
|
1281
|
+
const held = shapes.get(mesh)?.get(attribute);
|
|
1282
|
+
if (held === null || held === undefined) return undefined;
|
|
1283
|
+
const entry = arrays.get(held as object);
|
|
1284
|
+
if (entry === undefined) return undefined;
|
|
1285
|
+
const source = argument as {
|
|
1286
|
+
elements?: ArrayLike<number>;
|
|
1287
|
+
r?: number;
|
|
1288
|
+
g?: number;
|
|
1289
|
+
b?: number;
|
|
1290
|
+
} | null;
|
|
1291
|
+
const values =
|
|
1292
|
+
attribute === "instanceMatrix"
|
|
1293
|
+
? source?.elements
|
|
1294
|
+
: [Number(source?.r), Number(source?.g), Number(source?.b)];
|
|
1295
|
+
if (values === undefined) return undefined;
|
|
1296
|
+
const at = Number(index) * values.length;
|
|
1297
|
+
// three's `toArray` writes one lane at a time, so a lane outside the array is ignored, not an error.
|
|
1298
|
+
if (!Number.isSafeInteger(at) || at < 0 || at + values.length > entry.array.length)
|
|
1299
|
+
return undefined;
|
|
1300
|
+
return { array: entry.array, at, values };
|
|
1301
|
+
};
|
|
539
1302
|
const released = new FinalizationRegistry<IEngineRef>((ref) => {
|
|
540
1303
|
if (wrappers.get(ref.key)?.deref() === undefined) {
|
|
1304
|
+
debug?.add("bridgeWrappersReleased");
|
|
541
1305
|
wrappers.delete(ref.key);
|
|
542
1306
|
shaderNodes.delete(ref.key); // the engine material keeps its graph; the JS nodes may go
|
|
543
1307
|
for (const name of callbackNames.get(ref.key) ?? []) runtime.setCallback(ref, name, null);
|
|
@@ -547,12 +1311,14 @@ export function defineBrowserClasses(
|
|
|
547
1311
|
});
|
|
548
1312
|
|
|
549
1313
|
const adopt = (target: object, ref: IEngineRef): object => {
|
|
1314
|
+
debug?.add("bridgeWrappersCreated");
|
|
550
1315
|
(target as IWrapped)[REF] = ref;
|
|
551
1316
|
wrappers.set(ref.key, new WeakRef(target));
|
|
552
1317
|
released.register(target, ref);
|
|
553
1318
|
return target;
|
|
554
1319
|
};
|
|
555
1320
|
const wrap = (ref: IEngineRef): object => {
|
|
1321
|
+
debug?.add("bridgeWrapRequests");
|
|
556
1322
|
const live = wrappers.get(ref.key)?.deref();
|
|
557
1323
|
if (live !== undefined) return live;
|
|
558
1324
|
const cls = byType.get(ref.type);
|
|
@@ -560,6 +1326,7 @@ export function defineBrowserClasses(
|
|
|
560
1326
|
throw new TypeError(`TN_BROWSER_TYPE_UNKNOWN: no class for engine type ${ref.type}`);
|
|
561
1327
|
// Held until the next safe point decides: the engine may reference what it just handed out.
|
|
562
1328
|
const wrapper = adopt(Object.create(cls.prototype) as object, ref);
|
|
1329
|
+
if (cls.own !== undefined) defineOwn(wrapper, cls.own);
|
|
563
1330
|
hold(wrapper);
|
|
564
1331
|
return wrapper;
|
|
565
1332
|
};
|
|
@@ -576,6 +1343,12 @@ export function defineBrowserClasses(
|
|
|
576
1343
|
if (typeof value === "number" || typeof value === "boolean" || typeof value === "string")
|
|
577
1344
|
return value;
|
|
578
1345
|
if (ArrayBuffer.isView(value) && !(value instanceof DataView)) {
|
|
1346
|
+
// An image's `getImageData` pixels are a Uint8ClampedArray: boxed into a list, a 4096x2048 sky took 1.4 s.
|
|
1347
|
+
if (
|
|
1348
|
+
runtime.typedArrays === true &&
|
|
1349
|
+
(value instanceof Uint8ClampedArray || SCALARS.some((scalar) => value instanceof scalar))
|
|
1350
|
+
)
|
|
1351
|
+
return value as TypedArray;
|
|
579
1352
|
// quality-allow: a typed-array view read as its numeric index signature, which ArrayBufferView does not declare.
|
|
580
1353
|
const list = Array.from(value as unknown as ArrayLike<number>);
|
|
581
1354
|
Object.defineProperty(list, TYPED, { value: value.constructor.name });
|
|
@@ -584,8 +1357,8 @@ export function defineBrowserClasses(
|
|
|
584
1357
|
if (Array.isArray(value)) return Array.from(value as ArrayLike<unknown>, toEngine);
|
|
585
1358
|
const info = valueClasses.get(Object.getPrototypeOf(value) as object);
|
|
586
1359
|
if (info !== undefined) {
|
|
587
|
-
if (borrowing) return lend(value as
|
|
588
|
-
promote(value as
|
|
1360
|
+
if (borrowing && info.plan.promote !== true) return lend(value as IValueLanes, info);
|
|
1361
|
+
promote(value as IValueLanes, info);
|
|
589
1362
|
}
|
|
590
1363
|
if (typeof value === "object" && REF in value) {
|
|
591
1364
|
// A wrapper passed into the engine is held until the next safe point decides (collect()).
|
|
@@ -686,12 +1459,31 @@ export function defineBrowserClasses(
|
|
|
686
1459
|
"setIndex",
|
|
687
1460
|
]);
|
|
688
1461
|
|
|
1462
|
+
const entries = new Map((catalog?.entries ?? []).map((entry) => [entry.name, entry]));
|
|
1463
|
+
// The engine raycasts a Mesh, a Line, a Sprite (each a Mesh in C++) and a LOD, and every kind of
|
|
1464
|
+
// them; any other node answers no hits. Without a catalog the chain is unknown, so every node asks.
|
|
1465
|
+
const raycasts = (name: string): boolean => {
|
|
1466
|
+
if (catalog === undefined) return true;
|
|
1467
|
+
for (
|
|
1468
|
+
let link = entries.get(name);
|
|
1469
|
+
link !== undefined;
|
|
1470
|
+
link = link.extends ? entries.get(link.extends) : undefined
|
|
1471
|
+
)
|
|
1472
|
+
if (RAYCASTERS.has(link.name)) return true;
|
|
1473
|
+
return false;
|
|
1474
|
+
};
|
|
689
1475
|
for (const [name, binding] of Object.entries(registry.classes)) {
|
|
690
1476
|
const adopts =
|
|
691
1477
|
attributeWrite !== undefined &&
|
|
692
1478
|
(name === "BufferAttribute" || name === "InstancedBufferAttribute");
|
|
693
1479
|
const attributeClass = ATTRIBUTE_CLASSES.has(name);
|
|
694
1480
|
const geometryClass = name.endsWith("Geometry");
|
|
1481
|
+
// three keeps a material's slots as own, enumerable fields, and the desktop host gives each
|
|
1482
|
+
// material instance its accessors as own ones. `for...in`, `Object.keys` and `Object.values` find
|
|
1483
|
+
// them on the web too: core's node-twin copy loops and "dispose every texture" rely on that.
|
|
1484
|
+
const materialClass = name.endsWith("Material");
|
|
1485
|
+
const hierarchyClass = readWord !== undefined && binding.getters.includes("__hierarchy");
|
|
1486
|
+
const own: IOwnField[] = [];
|
|
695
1487
|
const engineClass = class {
|
|
696
1488
|
constructor(...args: unknown[]) {
|
|
697
1489
|
if (!binding.constructor) throw new TypeError(`TN_BROWSER_NOT_CONSTRUCTIBLE: ${name}`);
|
|
@@ -704,6 +1496,25 @@ export function defineBrowserClasses(
|
|
|
704
1496
|
: undefined;
|
|
705
1497
|
const engineArgs = parameters === undefined ? args : args.slice(0, -1);
|
|
706
1498
|
adopt(this, runtime.construct(name, engineArgs.map(toEngine)));
|
|
1499
|
+
if (
|
|
1500
|
+
debug !== undefined &&
|
|
1501
|
+
!debugActivated &&
|
|
1502
|
+
binding.setters.includes("__debugTelemetry")
|
|
1503
|
+
) {
|
|
1504
|
+
runtime.set(refOf(this), "__debugTelemetry", true);
|
|
1505
|
+
debugActivated = true;
|
|
1506
|
+
}
|
|
1507
|
+
// The hierarchy counter's address, asked once a process at the first scene node made, and the
|
|
1508
|
+
// engine's work counts ("name@address,..."), each read in place per frame by counters().
|
|
1509
|
+
if (hierarchyAt === undefined && hierarchyClass) {
|
|
1510
|
+
hierarchyAt = runtime.get(refOf(this), "__hierarchy") as number;
|
|
1511
|
+
if (binding.getters.includes("__engineCounters"))
|
|
1512
|
+
engineCountersAt = String(runtime.get(refOf(this), "__engineCounters"))
|
|
1513
|
+
.split(",")
|
|
1514
|
+
.map((entry) => entry.split("@"))
|
|
1515
|
+
.map(([counter, address]) => [String(counter), Number(address)] as const);
|
|
1516
|
+
}
|
|
1517
|
+
if (materialClass) defineOwn(this, own);
|
|
707
1518
|
if (parameters !== undefined) setValues(this, name, parameters);
|
|
708
1519
|
// three's BufferAttribute keeps the typed array it is handed; the typed subclasses copy.
|
|
709
1520
|
const handed = args[0];
|
|
@@ -723,14 +1534,22 @@ export function defineBrowserClasses(
|
|
|
723
1534
|
string,
|
|
724
1535
|
unknown
|
|
725
1536
|
>;
|
|
726
|
-
|
|
727
|
-
|
|
1537
|
+
// Engine properties a class's own view already names: the generic accessors stay off them.
|
|
1538
|
+
const skip = new Set<string>();
|
|
1539
|
+
if (valueClass !== undefined) {
|
|
1540
|
+
const info: IValueClass = {
|
|
728
1541
|
name,
|
|
729
|
-
lanes: Object.keys(binding.fields ?? {}),
|
|
730
1542
|
engine: accessors,
|
|
731
1543
|
pool: [],
|
|
732
1544
|
top: 0,
|
|
733
|
-
|
|
1545
|
+
plan: valuePlans[name] ?? defaultPlan(Object.keys(binding.fields ?? {})),
|
|
1546
|
+
};
|
|
1547
|
+
valueClasses.set(prototype, info);
|
|
1548
|
+
// Box3 and Sphere build their default members from three's own Vector3 module, not the
|
|
1549
|
+
// hand-written class; both are the same value and cross the same way.
|
|
1550
|
+
if (name === "Vector3") valueClasses.set(UpstreamVector3.prototype, info);
|
|
1551
|
+
defineValueView(name, accessors, binding, skip);
|
|
1552
|
+
}
|
|
734
1553
|
for (const method of binding.methods) {
|
|
735
1554
|
if (valueClass !== undefined && Object.hasOwn(prototype, method)) continue;
|
|
736
1555
|
// A geometry's attribute lookups are kept with its labels, until anything else runs on it.
|
|
@@ -744,13 +1563,53 @@ export function defineBrowserClasses(
|
|
|
744
1563
|
const rangeMethod = attributeClass && rangeMethods.has(method);
|
|
745
1564
|
const transformMethod = attributeClass && transformMethods.has(method);
|
|
746
1565
|
const geometryWrite = geometryClass && geometryWrites.has(method);
|
|
1566
|
+
// A mesh-level write into an attribute a game can hold a shadow of (see `instanceItem`).
|
|
1567
|
+
const instanceWrite =
|
|
1568
|
+
name !== "InstancedMesh"
|
|
1569
|
+
? undefined
|
|
1570
|
+
: method === "setMatrixAt"
|
|
1571
|
+
? "instanceMatrix"
|
|
1572
|
+
: method === "setColorAt"
|
|
1573
|
+
? "instanceColor"
|
|
1574
|
+
: undefined;
|
|
1575
|
+
// A mixer or action call may write the tracks' targets (update, stop restoring originals).
|
|
1576
|
+
const drives =
|
|
1577
|
+
/^Animation(Mixer|Action|ObjectGroup)$/u.test(name) && !keeps && !/^is[A-Z]/u.test(method);
|
|
1578
|
+
const transforms = hierarchyClass && transformOnly.test(method);
|
|
1579
|
+
const schedule =
|
|
1580
|
+
name === "AnimationAction" && method === "isScheduled"
|
|
1581
|
+
? "read"
|
|
1582
|
+
: name === "AnimationAction" && drives
|
|
1583
|
+
? "own"
|
|
1584
|
+
: drives && !/^(update|setTime|clipAction|existingAction)$/u.test(method)
|
|
1585
|
+
? "all"
|
|
1586
|
+
: undefined;
|
|
1587
|
+
// An action's clip and root are its construction arguments: kept like a geometry's attributes.
|
|
1588
|
+
const lifelong = name === "AnimationAction" && (method === "getClip" || method === "getRoot");
|
|
747
1589
|
Object.defineProperty(prototype, method, {
|
|
748
1590
|
configurable: true,
|
|
749
1591
|
writable: true,
|
|
750
1592
|
value(this: object, ...args: unknown[]) {
|
|
1593
|
+
if (glueCounting) methodCalls += 1;
|
|
1594
|
+
// three's toArray(array, offset) writes the lanes into the array it is given and answers that array; the
|
|
1595
|
+
// engine answers a new one, since a plain array crosses by value.
|
|
1596
|
+
if (method === "toArray" && args[0] !== undefined) {
|
|
1597
|
+
const target = args[0] as number[];
|
|
1598
|
+
const start = (args[1] as number | undefined) ?? 0;
|
|
1599
|
+
const lanes = (prototype.toArray as () => unknown[]).call(this);
|
|
1600
|
+
for (let i = 0; i < lanes.length; i++) target[start + i] = lanes[i] as number;
|
|
1601
|
+
return target;
|
|
1602
|
+
}
|
|
751
1603
|
const intersections = method === "intersectObject" || method === "intersectObjects";
|
|
752
|
-
const
|
|
753
|
-
|
|
1604
|
+
const kept = query || (lifelong && caching);
|
|
1605
|
+
const key = kept ? `${method} ${String(args[0])}` : "";
|
|
1606
|
+
if (kept && labels.get(this)?.has(key)) return labels.get(this)?.get(key);
|
|
1607
|
+
if (schedule === "read" && caching && scheduling.has(this)) return scheduling.get(this);
|
|
1608
|
+
if (schedule === "own") {
|
|
1609
|
+
scheduling.delete(this);
|
|
1610
|
+
for (const arg of args)
|
|
1611
|
+
if (typeof arg === "object" && arg !== null) scheduling.delete(arg);
|
|
1612
|
+
} else if (schedule === "all") scheduling = new WeakMap();
|
|
754
1613
|
// A per-vertex setter writes its own range and reads no kept array, so a whole-shadow flush
|
|
755
1614
|
// would cost O(N) a call; it syncs just its range back below. Anything else flushes edits.
|
|
756
1615
|
if (pending.size > 0 && !rangeMethod) writeBack();
|
|
@@ -779,7 +1638,16 @@ export function defineBrowserClasses(
|
|
|
779
1638
|
);
|
|
780
1639
|
}
|
|
781
1640
|
}
|
|
782
|
-
if (!keeps
|
|
1641
|
+
if (!keeps && !(transforms && caching)) {
|
|
1642
|
+
labels.delete(this);
|
|
1643
|
+
animated.delete(this);
|
|
1644
|
+
}
|
|
1645
|
+
// The item a mesh-level attribute write makes: read before the arguments cross, since a
|
|
1646
|
+
// Matrix4 is promoted in place, and written into the game's array once the call lands.
|
|
1647
|
+
const item =
|
|
1648
|
+
instanceWrite === undefined
|
|
1649
|
+
? undefined
|
|
1650
|
+
: instanceItem(this, instanceWrite, args[0], args[1]);
|
|
783
1651
|
const mark = loans.length;
|
|
784
1652
|
let result: unknown;
|
|
785
1653
|
try {
|
|
@@ -792,6 +1660,17 @@ export function defineBrowserClasses(
|
|
|
792
1660
|
);
|
|
793
1661
|
} finally {
|
|
794
1662
|
if (loans.length > mark) result = repay(mark, result);
|
|
1663
|
+
if (drives) animated = new WeakMap();
|
|
1664
|
+
}
|
|
1665
|
+
if (method === "copy") {
|
|
1666
|
+
shapes.delete(this);
|
|
1667
|
+
itemSizes.delete(this);
|
|
1668
|
+
} else if (instanceWrite !== undefined) {
|
|
1669
|
+
const known = shapes.get(this);
|
|
1670
|
+
// The engine creates `instanceColor` on the first setColorAt: a cached null is stale.
|
|
1671
|
+
if (instanceWrite === "instanceColor" && known?.get("instanceColor") === null)
|
|
1672
|
+
known.delete("instanceColor");
|
|
1673
|
+
if (item !== undefined) item.array.set(item.values, item.at);
|
|
795
1674
|
}
|
|
796
1675
|
// The engine wrote only this range: copy it back, so a later game edit to the shadow wins.
|
|
797
1676
|
if (rangeMethod) {
|
|
@@ -811,18 +1690,43 @@ export function defineBrowserClasses(
|
|
|
811
1690
|
args[2].sort((a, b) => a.distance - b.distance);
|
|
812
1691
|
return args[2];
|
|
813
1692
|
}
|
|
814
|
-
if (
|
|
1693
|
+
if (kept)
|
|
815
1694
|
labels.get(this)?.set(key, result) ?? labels.set(this, new Map([[key, result]]));
|
|
1695
|
+
if (schedule === "read" && caching) scheduling.set(this, result);
|
|
816
1696
|
return result;
|
|
817
1697
|
},
|
|
818
1698
|
});
|
|
819
1699
|
}
|
|
1700
|
+
// three's `layers.test(other)` is one AND of two masks the engine holds in place (field `mask`): a
|
|
1701
|
+
// game tests each light's layers against the camera's per callback, so it stays in JS.
|
|
1702
|
+
if (
|
|
1703
|
+
name === "Layers" &&
|
|
1704
|
+
binding.fields?.mask !== undefined &&
|
|
1705
|
+
Object.hasOwn(prototype, "test")
|
|
1706
|
+
) {
|
|
1707
|
+
const engineTest = prototype.test as (this: object, other: unknown) => boolean;
|
|
1708
|
+
Object.defineProperty(prototype, "test", {
|
|
1709
|
+
configurable: true,
|
|
1710
|
+
writable: true,
|
|
1711
|
+
value(this: { mask: number }, other: unknown) {
|
|
1712
|
+
if (!caching || other === null || typeof other !== "object")
|
|
1713
|
+
return engineTest.call(this, other);
|
|
1714
|
+
if (Object.getPrototypeOf(other) !== prototype) return engineTest.call(this, other);
|
|
1715
|
+
return (this.mask & (other as { mask: number }).mask) !== 0;
|
|
1716
|
+
},
|
|
1717
|
+
});
|
|
1718
|
+
}
|
|
820
1719
|
// A transform matrix (`mesh.matrixWorld`, a projection's kept copy) is 16 doubles at an engine address:
|
|
821
1720
|
// copy and equals between two engine matrices run over that memory, not as engine calls (PRD-573 web
|
|
822
1721
|
// cut 2, the web side of the desktop's TransformPage views). Anything else takes the engine method.
|
|
823
1722
|
const elements = binding.fields?.elements;
|
|
824
1723
|
const heapF64 = runtime.heapF64;
|
|
825
|
-
if (
|
|
1724
|
+
if (
|
|
1725
|
+
valueClass === undefined &&
|
|
1726
|
+
elements !== undefined &&
|
|
1727
|
+
heapF64 !== undefined &&
|
|
1728
|
+
binding.methods.includes("copy")
|
|
1729
|
+
) {
|
|
826
1730
|
const [offset = 0, count = 0] = elements;
|
|
827
1731
|
const engineCopy = prototype.copy as (this: object, other: unknown) => object;
|
|
828
1732
|
const engineEquals = prototype.equals as (this: object, other: unknown) => boolean;
|
|
@@ -872,6 +1776,37 @@ export function defineBrowserClasses(
|
|
|
872
1776
|
},
|
|
873
1777
|
set(this: object, value: unknown) {
|
|
874
1778
|
const ref = refOf(this);
|
|
1779
|
+
if (property === "filterNode") {
|
|
1780
|
+
runtime.set(ref, property, shadowFilterOptions(value));
|
|
1781
|
+
const slots = shaderNodes.get(ref.key) ?? new Map<string, unknown>();
|
|
1782
|
+
shaderNodes.set(ref.key, slots.set(property, value));
|
|
1783
|
+
return;
|
|
1784
|
+
}
|
|
1785
|
+
if (property === "shadowNode") {
|
|
1786
|
+
if (shaderNodes.get(ref.key)?.get(property) === value) return;
|
|
1787
|
+
const options = virtualShadowOptions(value, (command) =>
|
|
1788
|
+
runtime.set(
|
|
1789
|
+
ref,
|
|
1790
|
+
property,
|
|
1791
|
+
Object.fromEntries(
|
|
1792
|
+
Object.entries(command).map(([key, item]) => [key, toEngine(item)]),
|
|
1793
|
+
),
|
|
1794
|
+
),
|
|
1795
|
+
);
|
|
1796
|
+
runtime.set(
|
|
1797
|
+
ref,
|
|
1798
|
+
property,
|
|
1799
|
+
options === null
|
|
1800
|
+
? null
|
|
1801
|
+
: Object.fromEntries(
|
|
1802
|
+
Object.entries(options).map(([key, item]) => [key, toEngine(item)]),
|
|
1803
|
+
),
|
|
1804
|
+
);
|
|
1805
|
+
const slots = shaderNodes.get(ref.key) ?? new Map<string, unknown>();
|
|
1806
|
+
if (slots.get(property) !== value) detachVirtualShadow(slots.get(property));
|
|
1807
|
+
shaderNodes.set(ref.key, slots.set(property, value));
|
|
1808
|
+
return;
|
|
1809
|
+
}
|
|
875
1810
|
if (value === null) {
|
|
876
1811
|
runtime.set(ref, property, null);
|
|
877
1812
|
shaderNodes.get(ref.key)?.delete(property);
|
|
@@ -892,7 +1827,13 @@ export function defineBrowserClasses(
|
|
|
892
1827
|
(path) => path.startsWith(`${head}.`) && /^\d+$/u.test(path.slice(head.length + 1)),
|
|
893
1828
|
);
|
|
894
1829
|
for (const property of binding.getters) {
|
|
895
|
-
if (
|
|
1830
|
+
if (
|
|
1831
|
+
property.includes(".") ||
|
|
1832
|
+
setters.has(property) ||
|
|
1833
|
+
skip.has(property) ||
|
|
1834
|
+
!indexed(property)
|
|
1835
|
+
)
|
|
1836
|
+
continue;
|
|
896
1837
|
Object.defineProperty(prototype, property, {
|
|
897
1838
|
configurable: true,
|
|
898
1839
|
get(this: object) {
|
|
@@ -920,7 +1861,8 @@ export function defineBrowserClasses(
|
|
|
920
1861
|
if (
|
|
921
1862
|
property.includes(".") ||
|
|
922
1863
|
binding.methods.includes(property) ||
|
|
923
|
-
Object.hasOwn(accessors, property)
|
|
1864
|
+
Object.hasOwn(accessors, property) ||
|
|
1865
|
+
skip.has(property)
|
|
924
1866
|
)
|
|
925
1867
|
continue;
|
|
926
1868
|
// A value class's lane is written in place: its engine setter is a plain store.
|
|
@@ -931,9 +1873,36 @@ export function defineBrowserClasses(
|
|
|
931
1873
|
flagField !== undefined && flagField[1] === 0 && peek !== undefined
|
|
932
1874
|
? (self: object): boolean => peek(addressOf(self) + (flagField[0] ?? 0)) !== 0
|
|
933
1875
|
: undefined;
|
|
934
|
-
|
|
1876
|
+
// One flag is a plain store in the engine: `matrixWorldNeedsUpdate` has no revision and no deferred
|
|
1877
|
+
// transform behind its setter, and core's physics interpolation arms it on every body after the draw
|
|
1878
|
+
// (stress lab: 300 crossings a frame). It is written in place, as the engine's own walks write it. The
|
|
1879
|
+
// render flags keep their call: `visible`, `castShadow` and `receiveShadow` bump render revisions.
|
|
1880
|
+
const store = runtime.writeByte;
|
|
1881
|
+
const inPlace =
|
|
1882
|
+
property === "matrixWorldNeedsUpdate" && store !== undefined ? flagField : undefined;
|
|
1883
|
+
// A geometry's bounds, once present, are one engine object the engine recomputes in place
|
|
1884
|
+
// (BufferGeometry::computeBoundingSphere); only its setter, copy() or another method replaces it.
|
|
1885
|
+
const bounds = geometryClass && (property === "boundingSphere" || property === "boundingBox");
|
|
1886
|
+
const shape =
|
|
1887
|
+
(attributeClass && ["itemSize", "count", "normalized", "gpuType"].includes(property)) ||
|
|
1888
|
+
(name === "InstancedMesh" &&
|
|
1889
|
+
["count", "instanceMatrix", "instanceColor"].includes(property));
|
|
1890
|
+
const accessor: PropertyDescriptor = {
|
|
935
1891
|
configurable: true,
|
|
936
1892
|
get:
|
|
1893
|
+
(shape
|
|
1894
|
+
? function (this: object) {
|
|
1895
|
+
if (property === "itemSize") return itemSizeOf(this);
|
|
1896
|
+
let known = shapes.get(this);
|
|
1897
|
+
if (known === undefined) {
|
|
1898
|
+
known = new Map();
|
|
1899
|
+
shapes.set(this, known);
|
|
1900
|
+
}
|
|
1901
|
+
if (!known.has(property))
|
|
1902
|
+
known.set(property, fromEngine(runtime.get(refOf(this), property)));
|
|
1903
|
+
return known.get(property);
|
|
1904
|
+
}
|
|
1905
|
+
: undefined) ??
|
|
937
1906
|
fastGetter(binding, property) ??
|
|
938
1907
|
(name === "AnimationMixer" && property === "stats"
|
|
939
1908
|
? function (this: object) {
|
|
@@ -968,24 +1937,56 @@ export function defineBrowserClasses(
|
|
|
968
1937
|
return stats;
|
|
969
1938
|
}
|
|
970
1939
|
: undefined) ??
|
|
971
|
-
|
|
1940
|
+
// `children`, `parent` and an object's hierarchy revision are the kept hierarchy answers: every
|
|
1941
|
+
// add, remove and attach moves the engine's counter, and nothing else changes who is under whom or
|
|
1942
|
+
// when a subtree last did (`Object3D::subtreeVersion`, stamped from that same counter). Core's camera
|
|
1943
|
+
// pass reads each rate root's revision every frame to keep its rig index (stress lab: 120 a frame).
|
|
1944
|
+
((property === "children" ||
|
|
1945
|
+
property === "parent" ||
|
|
1946
|
+
property === "__hierarchyRevision") &&
|
|
1947
|
+
binding.getters.includes("__hierarchy")
|
|
972
1948
|
? function (this: object) {
|
|
973
|
-
|
|
974
|
-
if (
|
|
975
|
-
|
|
976
|
-
|
|
1949
|
+
if (glueCounting) propertyReads += 1;
|
|
1950
|
+
if (property === "children") {
|
|
1951
|
+
childrenReads += 1;
|
|
1952
|
+
// The census names who reads it, though the cache answers without a crossing.
|
|
1953
|
+
if (meter.counting) meter.record("read", refOf(this), "children");
|
|
977
1954
|
}
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
1955
|
+
const entry = hierarchyKept(this);
|
|
1956
|
+
if (entry === undefined) return fromEngine(runtime.get(refOf(this), property));
|
|
1957
|
+
if (!(property in entry))
|
|
1958
|
+
entry[property] = fromEngine(runtime.get(refOf(this), property));
|
|
1959
|
+
return entry[property];
|
|
981
1960
|
}
|
|
982
|
-
:
|
|
983
|
-
|
|
984
|
-
|
|
1961
|
+
: mirrored(binding, property, setters) || bounds
|
|
1962
|
+
? function (this: object) {
|
|
1963
|
+
if (glueCounting) propertyReads += 1;
|
|
1964
|
+
const legacy = legacyLabelled.has(property);
|
|
1965
|
+
if (!caching && !legacy) return fromEngine(runtime.get(refOf(this), property));
|
|
1966
|
+
const table = !legacy && animatedNames.has(property) ? animated : labels;
|
|
1967
|
+
let known = table.get(this);
|
|
1968
|
+
if (known === undefined) {
|
|
1969
|
+
known = new Map();
|
|
1970
|
+
table.set(this, known);
|
|
1971
|
+
}
|
|
1972
|
+
if (!known.has(property)) {
|
|
1973
|
+
const value = fromEngine(runtime.get(refOf(this), property));
|
|
1974
|
+
// The renderer computes a missing bound itself, so only a present one is kept.
|
|
1975
|
+
if (bounds && value === null) return value;
|
|
1976
|
+
known.set(property, value);
|
|
1977
|
+
}
|
|
1978
|
+
return known.get(property);
|
|
1979
|
+
}
|
|
1980
|
+
: function (this: object) {
|
|
1981
|
+
if (glueCounting) propertyReads += 1;
|
|
1982
|
+
return fromEngine(runtime.get(refOf(this), property));
|
|
1983
|
+
}),
|
|
985
1984
|
...(lane !== undefined && write !== undefined
|
|
986
1985
|
? {
|
|
987
1986
|
set(this: object, value: number) {
|
|
988
|
-
|
|
1987
|
+
const address = addressOf(this) + (lane[0] ?? 0);
|
|
1988
|
+
sharedTransformWrite?.(this, address, value);
|
|
1989
|
+
write(address, value);
|
|
989
1990
|
},
|
|
990
1991
|
}
|
|
991
1992
|
: setters.has(property)
|
|
@@ -995,101 +1996,53 @@ export function defineBrowserClasses(
|
|
|
995
1996
|
// writes `visible` on hundreds of nodes a frame, so those stay out of the bridge.
|
|
996
1997
|
if (flag !== undefined && typeof value === "boolean" && flag(this) === value)
|
|
997
1998
|
return;
|
|
998
|
-
|
|
1999
|
+
if (inPlace !== undefined && typeof value === "boolean") {
|
|
2000
|
+
(store as (address: number, byte: number) => void)(
|
|
2001
|
+
addressOf(this) + (inPlace[0] ?? 0),
|
|
2002
|
+
value ? 1 : 0,
|
|
2003
|
+
);
|
|
2004
|
+
return;
|
|
2005
|
+
}
|
|
2006
|
+
if (caching && (mirrored(binding, property, setters) || bounds)) {
|
|
2007
|
+
// A mirrored property's setter writes only that property: the others stay kept,
|
|
2008
|
+
// and a write of the primitive the mirror holds changes nothing in the engine.
|
|
2009
|
+
const legacy = legacyLabelled.has(property);
|
|
2010
|
+
const known = (!legacy && animatedNames.has(property) ? animated : labels).get(
|
|
2011
|
+
this,
|
|
2012
|
+
);
|
|
2013
|
+
if (
|
|
2014
|
+
(value === null || typeof value !== "object") &&
|
|
2015
|
+
known?.has(property) &&
|
|
2016
|
+
known.get(property) === value
|
|
2017
|
+
)
|
|
2018
|
+
return;
|
|
2019
|
+
labels.get(this)?.delete(property);
|
|
2020
|
+
animated.get(this)?.delete(property);
|
|
2021
|
+
} else {
|
|
2022
|
+
labels.delete(this);
|
|
2023
|
+
animated.delete(this);
|
|
2024
|
+
}
|
|
2025
|
+
// The shadow LOD sync skips its scene walk until this or the hierarchy moves.
|
|
2026
|
+
if (property === "geometry") {
|
|
2027
|
+
const host = globalThis as Record<symbol, unknown>;
|
|
2028
|
+
const key = Symbol.for("threenative.geometryAssignments");
|
|
2029
|
+
host[key] = ((host[key] as number | undefined) ?? 0) + 1;
|
|
2030
|
+
}
|
|
999
2031
|
runtime.set(refOf(this), property, toEngine(value));
|
|
2032
|
+
if (shape) {
|
|
2033
|
+
let known = shapes.get(this);
|
|
2034
|
+
if (known === undefined) {
|
|
2035
|
+
known = new Map();
|
|
2036
|
+
shapes.set(this, known);
|
|
2037
|
+
}
|
|
2038
|
+
known.set(property, value);
|
|
2039
|
+
}
|
|
1000
2040
|
},
|
|
1001
2041
|
}
|
|
1002
2042
|
: {}),
|
|
1003
|
-
});
|
|
1004
|
-
}
|
|
1005
|
-
// Games turn objects every frame: an object's `rotation` is written in place (the transform page's
|
|
1006
|
-
// rotation column), and its quaternion follows here, as three's onRotationChange does. Any other
|
|
1007
|
-
// Euler, or a set with a new order, still crosses, callback and all. Ported from feat/native-engine
|
|
1008
|
-
// 07297c986 and 5ef18a54f.
|
|
1009
|
-
const order = binding.fields?.__order;
|
|
1010
|
-
const quaternion = registry.classes.Quaternion?.fields;
|
|
1011
|
-
const readLane = runtime.readDoubles;
|
|
1012
|
-
const readByte = runtime.readByte;
|
|
1013
|
-
if (name === "Euler" && order && quaternion && readLane && readByte && write) {
|
|
1014
|
-
const angles = ["x", "y", "z"].map((lane) => binding.fields?.[lane]?.[0] ?? 0);
|
|
1015
|
-
const targets = ["x", "y", "z", "w"].map((lane) => quaternion[lane]?.[0] ?? 0);
|
|
1016
|
-
// three's setFromEuler: each order only signs the second terms, in the engine enum's order.
|
|
1017
|
-
const names = ["XYZ", "YXZ", "ZXY", "ZYX", "YZX", "XZY"];
|
|
1018
|
-
const signs = [
|
|
1019
|
-
[1, -1, 1, -1],
|
|
1020
|
-
[1, -1, -1, 1],
|
|
1021
|
-
[-1, 1, 1, -1],
|
|
1022
|
-
[-1, 1, -1, 1],
|
|
1023
|
-
[1, 1, -1, -1],
|
|
1024
|
-
[-1, -1, 1, 1],
|
|
1025
|
-
];
|
|
1026
|
-
// Two writes per object per frame land here (R5 turns x then y on 4,096 cubes), so the hot path
|
|
1027
|
-
// allocates nothing: offsets are numbers, the owner's quaternion address is kept per Euler (an
|
|
1028
|
-
// engine object never moves), and lanes are read off HEAPF64 when the runtime has it.
|
|
1029
|
-
const [ox = 0, oy = 0, oz = 0] = angles;
|
|
1030
|
-
const [qx = 0, qy = 0, qz = 0, qw = 0] = targets;
|
|
1031
|
-
const orderAt = order[0] ?? 0;
|
|
1032
|
-
const heap = runtime.heapF64;
|
|
1033
|
-
const lane = heap
|
|
1034
|
-
? (address: number) => heap()[address / 8] as number
|
|
1035
|
-
: (address: number) => readLane(address, 1) as number;
|
|
1036
|
-
// An object's rotation -> [its address, its owner's quaternion address]: one lookup per write.
|
|
1037
|
-
const places = new WeakMap<object, [number, number]>();
|
|
1038
|
-
const placeOf = (euler: object): [number, number] | undefined => {
|
|
1039
|
-
let place = places.get(euler);
|
|
1040
|
-
if (place === undefined) {
|
|
1041
|
-
const owner = rotations.get(euler);
|
|
1042
|
-
if (owner === undefined) return undefined;
|
|
1043
|
-
place = [addressOf(euler), addressOf((owner as { quaternion: object }).quaternion)];
|
|
1044
|
-
places.set(euler, place);
|
|
1045
|
-
}
|
|
1046
|
-
return place;
|
|
1047
2043
|
};
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
const y = lane(at + oy) / 2;
|
|
1051
|
-
const z = lane(at + oz) / 2;
|
|
1052
|
-
const sign = (signs[readByte(at + orderAt)] ?? signs[0]) as number[];
|
|
1053
|
-
const c1 = Math.cos(x);
|
|
1054
|
-
const c2 = Math.cos(y);
|
|
1055
|
-
const c3 = Math.cos(z);
|
|
1056
|
-
const s1 = Math.sin(x);
|
|
1057
|
-
const s2 = Math.sin(y);
|
|
1058
|
-
const s3 = Math.sin(z);
|
|
1059
|
-
write(q + qx, s1 * c2 * c3 + (sign[0] as number) * c1 * s2 * s3);
|
|
1060
|
-
write(q + qy, c1 * s2 * c3 + (sign[1] as number) * s1 * c2 * s3);
|
|
1061
|
-
write(q + qz, c1 * c2 * s3 + (sign[2] as number) * s1 * s2 * c3);
|
|
1062
|
-
write(q + qw, c1 * c2 * c3 + (sign[3] as number) * s1 * s2 * s3);
|
|
1063
|
-
};
|
|
1064
|
-
angles.forEach((offset, i) => {
|
|
1065
|
-
const lane = "xyz"[i] as string;
|
|
1066
|
-
const crossing = Object.getOwnPropertyDescriptor(prototype, lane);
|
|
1067
|
-
Object.defineProperty(prototype, lane, {
|
|
1068
|
-
...crossing,
|
|
1069
|
-
set(this: object, value: number) {
|
|
1070
|
-
const place = placeOf(this);
|
|
1071
|
-
if (place === undefined) return crossing?.set?.call(this, value);
|
|
1072
|
-
write(place[0] + offset, value);
|
|
1073
|
-
sync(place[0], place[1]);
|
|
1074
|
-
},
|
|
1075
|
-
});
|
|
1076
|
-
});
|
|
1077
|
-
const set = prototype.set as (...args: unknown[]) => unknown;
|
|
1078
|
-
Object.defineProperty(prototype, "set", {
|
|
1079
|
-
configurable: true,
|
|
1080
|
-
writable: true,
|
|
1081
|
-
value(this: object, ...args: unknown[]) {
|
|
1082
|
-
const place = placeOf(this);
|
|
1083
|
-
if (place === undefined) return set.apply(this, args);
|
|
1084
|
-
const [at, q] = place;
|
|
1085
|
-
// Games pass their one order on every set; only a new order goes to the engine.
|
|
1086
|
-
if (args[3] !== undefined && args[3] !== names[readByte(at + (order[0] ?? 0))])
|
|
1087
|
-
return set.apply(this, args);
|
|
1088
|
-
angles.forEach((offset, i) => write(at + offset, args[i] as number));
|
|
1089
|
-
sync(at, q);
|
|
1090
|
-
return this;
|
|
1091
|
-
},
|
|
1092
|
-
});
|
|
2044
|
+
Object.defineProperty(accessors, property, accessor);
|
|
2045
|
+
if (materialClass) own.push({ key: property, descriptor: { ...accessor, enumerable: true } });
|
|
1093
2046
|
}
|
|
1094
2047
|
// A dotted path whose head is no member of its own (three's plain `morphAttributes` object) is
|
|
1095
2048
|
// a holder made per read, as the V8 adapter makes it: each tail reads and writes the full path.
|
|
@@ -1138,7 +2091,8 @@ export function defineBrowserClasses(
|
|
|
1138
2091
|
// A write-only setter (three's `texture.needsUpdate`) is a property too: without an accessor
|
|
1139
2092
|
// the write lands on a plain JS property and never reaches the engine.
|
|
1140
2093
|
for (const property of binding.setters) {
|
|
1141
|
-
if (property.includes(".") || Object.hasOwn(accessors, property))
|
|
2094
|
+
if (property.includes(".") || Object.hasOwn(accessors, property) || skip.has(property))
|
|
2095
|
+
continue;
|
|
1142
2096
|
Object.defineProperty(accessors, property, {
|
|
1143
2097
|
configurable: true,
|
|
1144
2098
|
set(this: object, value: unknown) {
|
|
@@ -1267,7 +2221,10 @@ export function defineBrowserClasses(
|
|
|
1267
2221
|
},
|
|
1268
2222
|
});
|
|
1269
2223
|
}
|
|
1270
|
-
|
|
2224
|
+
const graphNode = binding.members.includes("parent") || binding.getters.includes("parent");
|
|
2225
|
+
// three gives Object3D, Material, Texture and BufferGeometry a `userData`; the engine classes
|
|
2226
|
+
// with a parent or a `dispose` are those.
|
|
2227
|
+
if (graphNode || binding.methods.includes("dispose")) {
|
|
1271
2228
|
Object.defineProperty(prototype, "userData", {
|
|
1272
2229
|
configurable: true,
|
|
1273
2230
|
get(this: object) {
|
|
@@ -1278,15 +2235,20 @@ export function defineBrowserClasses(
|
|
|
1278
2235
|
userData.set(this, value);
|
|
1279
2236
|
},
|
|
1280
2237
|
});
|
|
2238
|
+
}
|
|
2239
|
+
if (graphNode) {
|
|
1281
2240
|
defineTraversal(
|
|
1282
2241
|
prototype,
|
|
1283
2242
|
name,
|
|
1284
2243
|
binding.members.includes("children") || binding.getters.includes("children"),
|
|
1285
2244
|
binding.methods.includes("__walk"),
|
|
2245
|
+
binding.getters.includes("__hierarchy") ? hierarchyKept : undefined,
|
|
2246
|
+
walked,
|
|
2247
|
+
raycasts(name),
|
|
1286
2248
|
);
|
|
1287
2249
|
}
|
|
1288
2250
|
classes[name] = cls;
|
|
1289
|
-
byType.set(runtime.typeId(name), { prototype: accessors });
|
|
2251
|
+
byType.set(runtime.typeId(name), { prototype: accessors, ...(materialClass ? { own } : {}) });
|
|
1290
2252
|
typeNames.set(runtime.typeId(name), name);
|
|
1291
2253
|
}
|
|
1292
2254
|
for (const name of ATTRIBUTE_CLASSES) {
|
|
@@ -1332,7 +2294,6 @@ export function defineBrowserClasses(
|
|
|
1332
2294
|
});
|
|
1333
2295
|
}
|
|
1334
2296
|
}
|
|
1335
|
-
const entries = new Map((catalog?.entries ?? []).map((entry) => [entry.name, entry]));
|
|
1336
2297
|
const isFlag = (field: { name: string; type: string; mutable?: boolean }) =>
|
|
1337
2298
|
/^is[A-Z]/u.test(field.name) &&
|
|
1338
2299
|
(field.type === "true" || (field.type === "boolean" && field.mutable === false));
|
|
@@ -1346,14 +2307,85 @@ export function defineBrowserClasses(
|
|
|
1346
2307
|
link !== undefined;
|
|
1347
2308
|
link = link.extends ? entries.get(link.extends) : undefined
|
|
1348
2309
|
)
|
|
2310
|
+
// Writable: three's own value classes assign `this.isColor = true` in their constructors.
|
|
1349
2311
|
for (const field of (link.fields ?? []).filter(isFlag))
|
|
1350
|
-
Object.defineProperty(cls.prototype, field.name, {
|
|
2312
|
+
Object.defineProperty(cls.prototype, field.name, {
|
|
2313
|
+
configurable: true,
|
|
2314
|
+
writable: true,
|
|
2315
|
+
value: true,
|
|
2316
|
+
});
|
|
1351
2317
|
}
|
|
1352
2318
|
return {
|
|
1353
2319
|
classes,
|
|
1354
2320
|
wrap,
|
|
1355
2321
|
crossings: () => crossings,
|
|
2322
|
+
// The back end's running totals, for TN_FRAME_BUDGET.counters.engine. `hierarchyMoves` is the
|
|
2323
|
+
// engine's hierarchy counter itself: each move drops every cache keyed on it, here and in C++.
|
|
2324
|
+
counters: () => {
|
|
2325
|
+
// Crossings ride their own series, TN_FRAME_BUDGET.counters.bridgeCrossings (__tnCrossingCount).
|
|
2326
|
+
// `methodCalls` and `propertyReads` are the glue entries that series cannot see: every wrapper
|
|
2327
|
+
// entry, crossed or answered by the cache.
|
|
2328
|
+
const totals: Record<string, number> = {
|
|
2329
|
+
childrenReads,
|
|
2330
|
+
methodCalls,
|
|
2331
|
+
propertyReads,
|
|
2332
|
+
walkVisits,
|
|
2333
|
+
};
|
|
2334
|
+
if (debug !== undefined) {
|
|
2335
|
+
// Getter-equivalent estimate, calibrated on this host; no per-crossing timer.
|
|
2336
|
+
const estimated = ((debug.totals.bridgeCrossings ?? 0) * calibratedCrossingMicros()) / 1000;
|
|
2337
|
+
debug.add(
|
|
2338
|
+
"bridgeCrossingMs",
|
|
2339
|
+
Math.max(0, estimated - (debug.totals.bridgeCrossingMs ?? 0)),
|
|
2340
|
+
"bridge",
|
|
2341
|
+
"browser-backend.ts",
|
|
2342
|
+
"estimated-ms",
|
|
2343
|
+
);
|
|
2344
|
+
debug.add("bridgeLiveWrappers", 0, "bridge", "browser-backend.ts", "gauge");
|
|
2345
|
+
Object.assign(totals, debug.totals, { bridgeLiveWrappers: wrappers.size });
|
|
2346
|
+
}
|
|
2347
|
+
if (readWord === undefined) return totals;
|
|
2348
|
+
if (hierarchyAt !== undefined) totals.hierarchyMoves = readWord(hierarchyAt);
|
|
2349
|
+
// Debug uses coherent 64-bit totals; off retains the original single-word census.
|
|
2350
|
+
for (const [counter, address] of engineCountersAt) {
|
|
2351
|
+
let value: number;
|
|
2352
|
+
if (debug === undefined) value = readWord(address) >>> 0;
|
|
2353
|
+
else {
|
|
2354
|
+
let before: number;
|
|
2355
|
+
let high: number;
|
|
2356
|
+
let low: number;
|
|
2357
|
+
do {
|
|
2358
|
+
before = readWord(address + 4) >>> 0;
|
|
2359
|
+
low = readWord(address) >>> 0;
|
|
2360
|
+
high = readWord(address + 4) >>> 0;
|
|
2361
|
+
} while (before !== high);
|
|
2362
|
+
value = high * 0x100000000 + low;
|
|
2363
|
+
}
|
|
2364
|
+
if (counter.endsWith("Micros")) totals[`${counter.slice(0, -6)}Ms`] = value / 1000;
|
|
2365
|
+
else totals[counter] = value;
|
|
2366
|
+
}
|
|
2367
|
+
return totals;
|
|
2368
|
+
},
|
|
1356
2369
|
collect() {
|
|
2370
|
+
meter.frame();
|
|
2371
|
+
debug?.frame();
|
|
2372
|
+
glueCounting =
|
|
2373
|
+
debug !== undefined || (globalThis as Record<string, unknown>)[ENGINE_COST_KNOB] === true;
|
|
2374
|
+
const wanted = cacheWanted();
|
|
2375
|
+
// A setter or method drops an object's kept answers whether or not the cache is on, so turning it
|
|
2376
|
+
// back on keeps nothing stale; the two tables that other calls drop are emptied anyway.
|
|
2377
|
+
if (wanted !== caching) {
|
|
2378
|
+
caching = wanted;
|
|
2379
|
+
animated = new WeakMap();
|
|
2380
|
+
scheduling = new WeakMap();
|
|
2381
|
+
kept = new WeakMap();
|
|
2382
|
+
}
|
|
2383
|
+
if (
|
|
2384
|
+
hierarchyAt !== undefined &&
|
|
2385
|
+
readWord !== undefined &&
|
|
2386
|
+
readWord(hierarchyAt) !== keptVersion
|
|
2387
|
+
)
|
|
2388
|
+
kept = new WeakMap();
|
|
1357
2389
|
// A wrapper handed out since the last safe point is asked now: the engine either references it (it
|
|
1358
2390
|
// settles) or does not (JS alone keeps it). A settled wrapper is asked again a sixty-fourth of the
|
|
1359
2391
|
// settled set per safe point, round robin (a live Set iterator): Midway settles about 50,000
|
|
@@ -1440,6 +2472,7 @@ const KIND = {
|
|
|
1440
2472
|
array: 6,
|
|
1441
2473
|
record: 7,
|
|
1442
2474
|
undefined: 8,
|
|
2475
|
+
bytes: 9,
|
|
1443
2476
|
} as const;
|
|
1444
2477
|
|
|
1445
2478
|
// wasm32 layout of tn_tsl_arg_t (tn_tsl.h): kind 0, lanes 4, node 8 (u64), number 16, text 24,
|
|
@@ -1653,7 +2686,14 @@ function tslOf(
|
|
|
1653
2686
|
setPost: (node) =>
|
|
1654
2687
|
h.scoped(() => {
|
|
1655
2688
|
if (setPost === undefined) throw new Error("TN_WASM_POST: this module has no web host");
|
|
1656
|
-
if (setPost(context, nodeOf(node)) !== 0) throw new Error("TN_WASM_POST: refused");
|
|
2689
|
+
if (setPost(context, nodeOf(node), 0) !== 0) throw new Error("TN_WASM_POST: refused");
|
|
2690
|
+
}),
|
|
2691
|
+
setToneMapping: (node) =>
|
|
2692
|
+
h.scoped(() => {
|
|
2693
|
+
if (setPost === undefined)
|
|
2694
|
+
throw new Error("TN_NATIVE_CUSTOM_TONEMAPPING_MISSING: no web output binding");
|
|
2695
|
+
if (setPost(context, nodeOf(node), 1) !== 0)
|
|
2696
|
+
throw new Error("TN_NATIVE_CUSTOM_TONEMAPPING_INVALID: refused output node");
|
|
1657
2697
|
}),
|
|
1658
2698
|
// PRD-620: renderer.compute and storage reads over the product web host.
|
|
1659
2699
|
compute: (node) =>
|
|
@@ -1732,11 +2772,30 @@ function countCall(kind: string, self: IEngineRef, name: string): void {
|
|
|
1732
2772
|
}
|
|
1733
2773
|
|
|
1734
2774
|
export function createWasmRuntime(abi: TnAbiModule): IBrowserRuntime {
|
|
1735
|
-
|
|
2775
|
+
const debug = debugTelemetry(abi);
|
|
2776
|
+
let encoding = "arguments";
|
|
2777
|
+
// The heap's views, made again only when the memory grows: Emscripten replaces HEAPU8 then, so one
|
|
2778
|
+
// identity test per use stands in for reading two `.buffer`s, which every crossing paid (PRD-748).
|
|
2779
|
+
let heap = abi.HEAPU8;
|
|
2780
|
+
let heapBytes = heap.byteLength;
|
|
2781
|
+
let dataView = new DataView(heap.buffer);
|
|
2782
|
+
let words = new Uint32Array(heap.buffer);
|
|
2783
|
+
const grown = () => {
|
|
2784
|
+
debug?.add("wasmGrowthEvents");
|
|
2785
|
+
debug?.add("wasmGrowthBytes", Math.max(0, abi.HEAPU8.byteLength - heapBytes), "memory");
|
|
2786
|
+
heap = abi.HEAPU8;
|
|
2787
|
+
heapBytes = heap.byteLength;
|
|
2788
|
+
dataView = new DataView(heap.buffer);
|
|
2789
|
+
words = new Uint32Array(heap.buffer);
|
|
2790
|
+
};
|
|
1736
2791
|
const view = () => {
|
|
1737
|
-
if (
|
|
2792
|
+
if (abi.HEAPU8 !== heap) grown();
|
|
1738
2793
|
return dataView;
|
|
1739
2794
|
};
|
|
2795
|
+
const wordView = () => {
|
|
2796
|
+
if (abi.HEAPU8 !== heap) grown();
|
|
2797
|
+
return words;
|
|
2798
|
+
};
|
|
1740
2799
|
// Each call frees what it allocated, and only that: a callback can run a nested call.
|
|
1741
2800
|
// A call's scratch (its handle, arguments, result and diagnostic) comes from one arena that each
|
|
1742
2801
|
// scope rewinds, a stack as nested calls (a callback inside an invoke) need; a scope that outgrows
|
|
@@ -1747,16 +2806,23 @@ export function createWasmRuntime(abi: TnAbiModule): IBrowserRuntime {
|
|
|
1747
2806
|
const allocations: number[] = [];
|
|
1748
2807
|
const alloc = (size: number): number => {
|
|
1749
2808
|
const aligned = (size + 7) & ~7;
|
|
2809
|
+
debug?.add("bridgeScratchBytes", aligned);
|
|
1750
2810
|
let pointer: number;
|
|
1751
2811
|
if (arenaTop + aligned <= arenaBase + arenaSize) {
|
|
1752
2812
|
pointer = arenaTop;
|
|
1753
2813
|
arenaTop += aligned;
|
|
1754
2814
|
} else {
|
|
1755
2815
|
// `>>> 0`: the module addresses up to 4 GB, and an export returns a pointer as a signed i32.
|
|
1756
|
-
pointer = abi._malloc(
|
|
2816
|
+
pointer = abi._malloc(aligned) >>> 0;
|
|
1757
2817
|
allocations.push(pointer);
|
|
2818
|
+
debug?.add("bridgeOverflowAllocations");
|
|
2819
|
+
debug?.add("bridgeOverflowBytes", aligned);
|
|
1758
2820
|
}
|
|
1759
|
-
|
|
2821
|
+
// A call's scratch is a few words (a handle, a value, a diagnostic): word stores beat a fill call.
|
|
2822
|
+
// `wordView` first: a `_malloc` above may have grown the memory.
|
|
2823
|
+
const w = wordView();
|
|
2824
|
+
if (aligned > 64) heap.fill(0, pointer, pointer + aligned);
|
|
2825
|
+
else for (let at = pointer >>> 2, end = (pointer + aligned) >>> 2; at < end; at++) w[at] = 0;
|
|
1760
2826
|
return pointer;
|
|
1761
2827
|
};
|
|
1762
2828
|
const scoped = <T>(work: () => T): T => {
|
|
@@ -1765,7 +2831,7 @@ export function createWasmRuntime(abi: TnAbiModule): IBrowserRuntime {
|
|
|
1765
2831
|
try {
|
|
1766
2832
|
return work();
|
|
1767
2833
|
} finally {
|
|
1768
|
-
|
|
2834
|
+
while (allocations.length > mark) abi._free(allocations.pop() as number);
|
|
1769
2835
|
arenaTop = top;
|
|
1770
2836
|
}
|
|
1771
2837
|
};
|
|
@@ -1797,11 +2863,6 @@ export function createWasmRuntime(abi: TnAbiModule): IBrowserRuntime {
|
|
|
1797
2863
|
};
|
|
1798
2864
|
// A handle is three words in memory: type and context as two halves of the first, then index and
|
|
1799
2865
|
// generation. A ref made here keeps those words, so writing one back is three stores, no parse.
|
|
1800
|
-
let words = new Uint32Array(abi.HEAPU8.buffer);
|
|
1801
|
-
const wordView = () => {
|
|
1802
|
-
if (words.buffer !== abi.HEAPU8.buffer) words = new Uint32Array(abi.HEAPU8.buffer);
|
|
1803
|
-
return words;
|
|
1804
|
-
};
|
|
1805
2866
|
const keyOf = (pointer: number): IEngineRef => {
|
|
1806
2867
|
const v = view();
|
|
1807
2868
|
const type = v.getUint16(pointer, true);
|
|
@@ -1866,6 +2927,19 @@ export function createWasmRuntime(abi: TnAbiModule): IBrowserRuntime {
|
|
|
1866
2927
|
v.setUint32(pointer, KIND.handle, true);
|
|
1867
2928
|
return writeHandle(pointer + 16, value);
|
|
1868
2929
|
}
|
|
2930
|
+
if (ArrayBuffer.isView(value) && !(value instanceof DataView)) {
|
|
2931
|
+
// A forwarded typed array (see `toEngine`): one heap copy, its view bounds kept, no boxed list.
|
|
2932
|
+
const typed = value as TypedArray;
|
|
2933
|
+
debug?.widen(typed, encoding, typed.byteLength);
|
|
2934
|
+
const numbers = alloc(Math.max(8, typed.byteLength));
|
|
2935
|
+
abi.HEAPU8.set(new Uint8Array(typed.buffer, typed.byteOffset, typed.byteLength), numbers);
|
|
2936
|
+
const name = string(typed.constructor.name).pointer;
|
|
2937
|
+
const w = view();
|
|
2938
|
+
w.setUint32(pointer, KIND.bytes, true);
|
|
2939
|
+
w.setUint32(pointer + 32, name, true);
|
|
2940
|
+
w.setUint32(pointer + 48, numbers, true);
|
|
2941
|
+
return w.setBigUint64(pointer + 40, BigInt(typed.length), true);
|
|
2942
|
+
}
|
|
1869
2943
|
if (!Array.isArray(value)) {
|
|
1870
2944
|
// A record: count key/value pairs, each key a string value, as the engine returns one.
|
|
1871
2945
|
const entries = Object.entries(value as Record<string, EngineValue>);
|
|
@@ -2021,6 +3095,8 @@ export function createWasmRuntime(abi: TnAbiModule): IBrowserRuntime {
|
|
|
2021
3095
|
view,
|
|
2022
3096
|
}) ?? {}),
|
|
2023
3097
|
...gltfOf(abi, context, { scoped, alloc, keyOf }),
|
|
3098
|
+
...(debug === undefined ? {} : { debugTelemetry: debug }),
|
|
3099
|
+
typedArrays: true,
|
|
2024
3100
|
typeId: (className) => abi._tn_type_id(name(className)),
|
|
2025
3101
|
construct: (className, args) =>
|
|
2026
3102
|
scoped(() => {
|
|
@@ -2043,6 +3119,7 @@ export function createWasmRuntime(abi: TnAbiModule): IBrowserRuntime {
|
|
|
2043
3119
|
invoke: (self, method, args) =>
|
|
2044
3120
|
scoped(() => {
|
|
2045
3121
|
countCall("call", self, method);
|
|
3122
|
+
if (debug !== undefined) encoding = method;
|
|
2046
3123
|
const out = alloc(VALUE);
|
|
2047
3124
|
const diag = diagnostic();
|
|
2048
3125
|
check(
|
|
@@ -2062,9 +3139,13 @@ export function createWasmRuntime(abi: TnAbiModule): IBrowserRuntime {
|
|
|
2062
3139
|
return refs.map((_, i) => v.getUint32(out + i * 4, true));
|
|
2063
3140
|
}),
|
|
2064
3141
|
readByte: (address) => abi.HEAPU8[address] as number,
|
|
3142
|
+
readWord: (address) => view().getUint32(address, true),
|
|
2065
3143
|
writeDouble: (address, value) => {
|
|
2066
3144
|
abi.HEAPF64[address / 8] = value;
|
|
2067
3145
|
},
|
|
3146
|
+
writeByte: (address, value) => {
|
|
3147
|
+
abi.HEAPU8[address] = value;
|
|
3148
|
+
},
|
|
2068
3149
|
heapF64: () => abi.HEAPF64,
|
|
2069
3150
|
readDoubles: (address, count) => {
|
|
2070
3151
|
const at = address / 8;
|
|
@@ -2083,7 +3164,10 @@ export function createWasmRuntime(abi: TnAbiModule): IBrowserRuntime {
|
|
|
2083
3164
|
set: (self, path, value) =>
|
|
2084
3165
|
scoped(() => {
|
|
2085
3166
|
countCall("set", self, path);
|
|
2086
|
-
|
|
3167
|
+
if (debug !== undefined) encoding = path;
|
|
3168
|
+
// One value written in place: no one-item list per write.
|
|
3169
|
+
const pointer = alloc(VALUE);
|
|
3170
|
+
writeValue(pointer, value);
|
|
2087
3171
|
const diag = diagnostic();
|
|
2088
3172
|
check(abi._tn_set(handleOf(self), name(path), pointer, diag), diag, `set ${path}`);
|
|
2089
3173
|
}),
|
|
@@ -2154,3 +3238,65 @@ export function createWasmRuntime(abi: TnAbiModule): IBrowserRuntime {
|
|
|
2154
3238
|
}),
|
|
2155
3239
|
};
|
|
2156
3240
|
}
|
|
3241
|
+
|
|
3242
|
+
/**
|
|
3243
|
+
* three's `Euler.setFromQuaternion` (and the engine's Euler.cpp, whose ieee754 functions are V8's fdlibm, so the
|
|
3244
|
+
* bits match): the rotation matrix of a unit quaternion, then the angles of the given order.
|
|
3245
|
+
*/
|
|
3246
|
+
export function eulerFromQuaternion(
|
|
3247
|
+
x: number,
|
|
3248
|
+
y: number,
|
|
3249
|
+
z: number,
|
|
3250
|
+
w: number,
|
|
3251
|
+
order: string,
|
|
3252
|
+
): [number, number, number] {
|
|
3253
|
+
const x2 = x + x;
|
|
3254
|
+
const y2 = y + y;
|
|
3255
|
+
const z2 = z + z;
|
|
3256
|
+
const xx = x * x2;
|
|
3257
|
+
const xy = x * y2;
|
|
3258
|
+
const xz = x * z2;
|
|
3259
|
+
const yy = y * y2;
|
|
3260
|
+
const yz = y * z2;
|
|
3261
|
+
const zz = z * z2;
|
|
3262
|
+
const wx = w * x2;
|
|
3263
|
+
const wy = w * y2;
|
|
3264
|
+
const wz = w * z2;
|
|
3265
|
+
const m11 = 1 - (yy + zz);
|
|
3266
|
+
const m12 = xy - wz;
|
|
3267
|
+
const m13 = xz + wy;
|
|
3268
|
+
const m21 = xy + wz;
|
|
3269
|
+
const m22 = 1 - (xx + zz);
|
|
3270
|
+
const m23 = yz - wx;
|
|
3271
|
+
const m31 = xz - wy;
|
|
3272
|
+
const m32 = yz + wx;
|
|
3273
|
+
const m33 = 1 - (xx + yy);
|
|
3274
|
+
const asin = (value: number): number => Math.asin(Math.max(-1, Math.min(1, value)));
|
|
3275
|
+
const free = (value: number): boolean => Math.abs(value) < 0.9999999;
|
|
3276
|
+
switch (order) {
|
|
3277
|
+
case "YXZ":
|
|
3278
|
+
return free(m23)
|
|
3279
|
+
? [-asin(m23), Math.atan2(m13, m33), Math.atan2(m21, m22)]
|
|
3280
|
+
: [-asin(m23), Math.atan2(-m31, m11), 0];
|
|
3281
|
+
case "ZXY":
|
|
3282
|
+
return free(m32)
|
|
3283
|
+
? [asin(m32), Math.atan2(-m31, m33), Math.atan2(-m12, m22)]
|
|
3284
|
+
: [asin(m32), 0, Math.atan2(m21, m11)];
|
|
3285
|
+
case "ZYX":
|
|
3286
|
+
return free(m31)
|
|
3287
|
+
? [Math.atan2(m32, m33), -asin(m31), Math.atan2(m21, m11)]
|
|
3288
|
+
: [0, -asin(m31), Math.atan2(-m12, m22)];
|
|
3289
|
+
case "YZX":
|
|
3290
|
+
return free(m21)
|
|
3291
|
+
? [Math.atan2(-m23, m22), Math.atan2(-m31, m11), asin(m21)]
|
|
3292
|
+
: [0, Math.atan2(m13, m33), asin(m21)];
|
|
3293
|
+
case "XZY":
|
|
3294
|
+
return free(m12)
|
|
3295
|
+
? [Math.atan2(m32, m22), Math.atan2(m13, m11), -asin(m12)]
|
|
3296
|
+
: [Math.atan2(-m23, m33), 0, -asin(m12)];
|
|
3297
|
+
default:
|
|
3298
|
+
return free(m13)
|
|
3299
|
+
? [Math.atan2(-m23, m33), asin(m13), Math.atan2(-m12, m11)]
|
|
3300
|
+
: [Math.atan2(m32, m22), asin(m13), 0];
|
|
3301
|
+
}
|
|
3302
|
+
}
|