@threenative/three-native 0.3.21 → 0.3.23
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/browser-abi-types.ts +3 -0
- package/src/browser-backend.ts +130 -15
- package/src/browser-entry.ts +5 -1
- package/src/browser-renderer.ts +91 -9
- package/src/browser-tsl.ts +65 -2
- package/src/debug-telemetry.ts +10 -2
- package/src/reflector.ts +20 -1
- package/src/tsl-extras.ts +9 -0
- package/src/tsl-uniforms.ts +11 -3
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@threenative/three-native",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.23",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"description": "The native engine's machine-readable compatibility catalog and the generators that adapt it to TypeScript declarations and the C binding ABI.",
|
|
6
6
|
"keywords": [
|
package/src/browser-abi-types.ts
CHANGED
|
@@ -434,6 +434,7 @@ export function tslOf(
|
|
|
434
434
|
let candidateAt = 0;
|
|
435
435
|
let candidateRoom = 0;
|
|
436
436
|
let candidatesWritten = 0;
|
|
437
|
+
let graphVersion = 0;
|
|
437
438
|
// Writes tn_tsl_arg_t values; text is allocated first, since an allocation can grow the memory.
|
|
438
439
|
const writeArgs = (args: readonly TslArgValue[]): number => {
|
|
439
440
|
const pointer = h.alloc(Math.max(TSL_ARG, args.length * TSL_ARG));
|
|
@@ -479,8 +480,10 @@ export function tslOf(
|
|
|
479
480
|
release(context, BigInt(node), diag);
|
|
480
481
|
abi._tn_diagnostic_release(diag);
|
|
481
482
|
}),
|
|
483
|
+
graphVersion: () => graphVersion,
|
|
482
484
|
set: (material, path, node) =>
|
|
483
485
|
h.scoped(() => {
|
|
486
|
+
graphVersion += 1;
|
|
484
487
|
const diag = h.diagnostic();
|
|
485
488
|
h.check(
|
|
486
489
|
set(context, h.handleOf(material), h.string(path).pointer, BigInt(node), diag),
|
package/src/browser-backend.ts
CHANGED
|
@@ -154,6 +154,7 @@ function disposeObject(this: { dispatchEvent?(event: { type: string }): void }):
|
|
|
154
154
|
}
|
|
155
155
|
|
|
156
156
|
type TraverseCallback = (object: object) => void;
|
|
157
|
+
type EngineMethod = (this: object, ...args: unknown[]) => unknown;
|
|
157
158
|
|
|
158
159
|
/** The engine classes with their own raycast (`Mesh::raycast`, `Line::raycast`, `LOD::raycast`). */
|
|
159
160
|
const RAYCASTERS = new Set(["Mesh", "Line", "Sprite", "LOD"]);
|
|
@@ -523,6 +524,9 @@ export function defineBrowserClasses(
|
|
|
523
524
|
(binding.fixedMembers?.includes(property) === true || /^(map|[a-z]+Map)$/u.test(property)));
|
|
524
525
|
const labels = new WeakMap<object, Map<string, unknown>>();
|
|
525
526
|
let animated = new WeakMap<object, Map<string, unknown>>();
|
|
527
|
+
// The geometry JS last wrote on an object, which the shadow LOD sync compares with the next write to
|
|
528
|
+
// tell a LOD rung swap (same registered chain, no walk owed) from any other geometry change.
|
|
529
|
+
const assignedGeometries = new WeakMap<object, unknown>();
|
|
526
530
|
// An action's `isScheduled()`: the mixer's list of active actions, which only the action's own
|
|
527
531
|
// play/stop and the mixer's stopAllAction/uncache calls change (animation/mixer.cpp), never update,
|
|
528
532
|
// setTime or clipAction (a rifle asks clipAction each frame).
|
|
@@ -721,13 +725,76 @@ export function defineBrowserClasses(
|
|
|
721
725
|
|
|
722
726
|
const fromEngine = (value: EngineValue): unknown => {
|
|
723
727
|
if (isRef(value)) return wrap(value);
|
|
724
|
-
if (Array.isArray(value))
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
728
|
+
if (Array.isArray(value)) {
|
|
729
|
+
const out = new Array<unknown>(value.length);
|
|
730
|
+
for (let i = 0; i < value.length; i += 1) out[i] = fromEngine(value[i] as EngineValue);
|
|
731
|
+
return out;
|
|
732
|
+
}
|
|
733
|
+
if (typeof value === "object" && value !== null) {
|
|
734
|
+
const out: Record<string, unknown> = {};
|
|
735
|
+
for (const key in value) {
|
|
736
|
+
if (Object.hasOwn(value, key)) {
|
|
737
|
+
out[key] = fromEngine((value as Record<string, EngineValue>)[key] as EngineValue);
|
|
738
|
+
}
|
|
739
|
+
}
|
|
740
|
+
return out;
|
|
741
|
+
}
|
|
729
742
|
return value;
|
|
730
743
|
};
|
|
744
|
+
// The engine's flat ray hits (`__tnIntersectObject`): each vector is a number list, decoded here
|
|
745
|
+
// into a JS value, so a hit makes no engine vector. A wrapped vector still decodes as before.
|
|
746
|
+
const hitVectors = new Map([
|
|
747
|
+
["point", 3],
|
|
748
|
+
["barycoord", 3],
|
|
749
|
+
["normal", 3],
|
|
750
|
+
["uv", 2],
|
|
751
|
+
["uv1", 2],
|
|
752
|
+
]);
|
|
753
|
+
const { Vector2, Vector3 } = math as Record<
|
|
754
|
+
"Vector2" | "Vector3",
|
|
755
|
+
new (
|
|
756
|
+
...lanes: unknown[]
|
|
757
|
+
) => object
|
|
758
|
+
>;
|
|
759
|
+
const hitField = (key: string, field: EngineValue): unknown => {
|
|
760
|
+
const size = hitVectors.get(key);
|
|
761
|
+
if (size === undefined) return key === "face" ? hitRecord(field) : fromEngine(field);
|
|
762
|
+
if (!Array.isArray(field)) return fromEngine(field);
|
|
763
|
+
return size === 3 ? new Vector3(field[0], field[1], field[2]) : new Vector2(field[0], field[1]);
|
|
764
|
+
};
|
|
765
|
+
const hitRecord = (value: EngineValue): unknown => {
|
|
766
|
+
if (typeof value !== "object" || value === null || Array.isArray(value) || isRef(value))
|
|
767
|
+
return fromEngine(value);
|
|
768
|
+
const out: Record<string, unknown> = {};
|
|
769
|
+
for (const key in value)
|
|
770
|
+
if (Object.hasOwn(value, key))
|
|
771
|
+
out[key] = hitField(key, (value as Record<string, EngineValue>)[key] as EngineValue);
|
|
772
|
+
return out;
|
|
773
|
+
};
|
|
774
|
+
/** Whether every argument after the first crosses as itself: a number, flag, string or nothing. */
|
|
775
|
+
const scalarTail = (args: readonly unknown[]): boolean => {
|
|
776
|
+
for (let i = 1; i < args.length; i++) {
|
|
777
|
+
const kind = typeof args[i];
|
|
778
|
+
if (kind === "object" || kind === "function") return false;
|
|
779
|
+
}
|
|
780
|
+
return true;
|
|
781
|
+
};
|
|
782
|
+
// GroundSnap and Billboard3D call these once per object per frame with one engine object and
|
|
783
|
+
// scalars. Both are transform-only (the kept labels stay) and lend no value, so the call skips
|
|
784
|
+
// the generic wrapper's bookkeeping. Any other argument shape takes the generic path.
|
|
785
|
+
const scalarHook = (method: string, generic: EngineMethod): EngineMethod =>
|
|
786
|
+
function (this: object, ...args: unknown[]) {
|
|
787
|
+
const target = (args[0] as Partial<IWrapped> | null | undefined)?.[REF];
|
|
788
|
+
if (!caching || target === undefined || !scalarTail(args)) return generic.apply(this, args);
|
|
789
|
+
if (glueCounting) methodCalls += 1;
|
|
790
|
+
if (pending.size > 0 || dirty.size > 0) writeBack();
|
|
791
|
+
hold(args[0] as object); // as toEngine does for a wrapper passed into the engine
|
|
792
|
+
const engineArgs = args.map((arg, i) =>
|
|
793
|
+
i === 0 ? target : ((arg as EngineValue | undefined) ?? null),
|
|
794
|
+
);
|
|
795
|
+
const result = runtime.invoke(refOf(this), method, engineArgs);
|
|
796
|
+
return isRef(result) ? wrap(result) : result;
|
|
797
|
+
};
|
|
731
798
|
// A geometry bulk mutator (`translate`, `applyMatrix4`, `computeVertexNormals`, ...) writes the
|
|
732
799
|
// bytes of its attributes. The engine already keeps the geometry's current attribute list, so the
|
|
733
800
|
// wrapper enumerates it (one `__attributeNames` read, then a `getAttribute` each) rather than track
|
|
@@ -921,6 +988,14 @@ export function defineBrowserClasses(
|
|
|
921
988
|
: undefined;
|
|
922
989
|
// An action's clip and root are its construction arguments: kept like a geometry's attributes.
|
|
923
990
|
const lifelong = name === "AnimationAction" && (method === "getClip" || method === "getRoot");
|
|
991
|
+
const flatName =
|
|
992
|
+
method === "intersectObject"
|
|
993
|
+
? "__tnIntersectObject"
|
|
994
|
+
: method === "intersectObjects"
|
|
995
|
+
? "__tnIntersectObjects"
|
|
996
|
+
: undefined;
|
|
997
|
+
const flatHits =
|
|
998
|
+
flatName !== undefined && binding.methods.includes(flatName) ? flatName : undefined;
|
|
924
999
|
Object.defineProperty(prototype, method, {
|
|
925
1000
|
configurable: true,
|
|
926
1001
|
writable: true,
|
|
@@ -982,6 +1057,7 @@ export function defineBrowserClasses(
|
|
|
982
1057
|
if (!keeps && !(transforms && caching)) {
|
|
983
1058
|
labels.delete(this);
|
|
984
1059
|
animated.delete(this);
|
|
1060
|
+
assignedGeometries.delete(this);
|
|
985
1061
|
}
|
|
986
1062
|
// The item a mesh-level attribute write makes: read before the arguments cross, since a
|
|
987
1063
|
// Matrix4 is promoted in place, and written into the game's array once the call lands.
|
|
@@ -992,13 +1068,13 @@ export function defineBrowserClasses(
|
|
|
992
1068
|
const mark = loans.length;
|
|
993
1069
|
let result: unknown;
|
|
994
1070
|
try {
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
toEngineArgs(intersections ? args.slice(0, 2) : args),
|
|
1000
|
-
),
|
|
1071
|
+
const raw = runtime.invoke(
|
|
1072
|
+
refOf(this),
|
|
1073
|
+
flatHits ?? method,
|
|
1074
|
+
toEngineArgs(intersections ? args.slice(0, 2) : args),
|
|
1001
1075
|
);
|
|
1076
|
+
result =
|
|
1077
|
+
flatHits !== undefined && Array.isArray(raw) ? raw.map(hitRecord) : fromEngine(raw);
|
|
1002
1078
|
} finally {
|
|
1003
1079
|
if (loans.length > mark) result = repay(mark, result);
|
|
1004
1080
|
if (drives) animated = new WeakMap();
|
|
@@ -1015,6 +1091,11 @@ export function defineBrowserClasses(
|
|
|
1015
1091
|
const slots = shaderNodes.get(refOf(from as object).key);
|
|
1016
1092
|
if (slots === undefined) shaderNodes.delete(refOf(to as object).key);
|
|
1017
1093
|
else shaderNodes.set(refOf(to as object).key, new Map(slots));
|
|
1094
|
+
if (method === "copy") {
|
|
1095
|
+
const host = globalThis as Record<symbol, unknown>;
|
|
1096
|
+
const key = Symbol.for("threenative.materialGraphVersion");
|
|
1097
|
+
host[key] = ((host[key] as number | undefined) ?? 0) + 1;
|
|
1098
|
+
}
|
|
1018
1099
|
}
|
|
1019
1100
|
if (method === "copy") {
|
|
1020
1101
|
shapes.delete(this);
|
|
@@ -1050,6 +1131,14 @@ export function defineBrowserClasses(
|
|
|
1050
1131
|
return result;
|
|
1051
1132
|
},
|
|
1052
1133
|
});
|
|
1134
|
+
// Transform-only hooks with scalar arguments: see `scalarHook`.
|
|
1135
|
+
if (transforms && (method === "__tnGroundSnapApply" || method === "__tnBillboardFace")) {
|
|
1136
|
+
Object.defineProperty(prototype, method, {
|
|
1137
|
+
configurable: true,
|
|
1138
|
+
writable: true,
|
|
1139
|
+
value: scalarHook(method, prototype[method] as EngineMethod),
|
|
1140
|
+
});
|
|
1141
|
+
}
|
|
1053
1142
|
}
|
|
1054
1143
|
// three's `layers.test(other)` is one AND of two masks the engine holds in place (field `mask`): a
|
|
1055
1144
|
// game tests each light's layers against the camera's per callback, so it stays in JS.
|
|
@@ -1206,6 +1295,9 @@ export function defineBrowserClasses(
|
|
|
1206
1295
|
if (value === null) {
|
|
1207
1296
|
runtime.set(ref, property, null);
|
|
1208
1297
|
shaderNodes.get(ref.key)?.delete(property);
|
|
1298
|
+
const host = globalThis as Record<symbol, unknown>;
|
|
1299
|
+
const key = Symbol.for("threenative.materialGraphVersion");
|
|
1300
|
+
host[key] = ((host[key] as number | undefined) ?? 0) + 1;
|
|
1209
1301
|
return;
|
|
1210
1302
|
}
|
|
1211
1303
|
if (typeof value !== "object" || !(TSL_NODE in value) || !runtime.tsl)
|
|
@@ -1399,6 +1491,12 @@ export function defineBrowserClasses(
|
|
|
1399
1491
|
);
|
|
1400
1492
|
return;
|
|
1401
1493
|
}
|
|
1494
|
+
// The geometry the object held until this write: the mirror's answer, or the one JS
|
|
1495
|
+
// last wrote (a mesh nothing has read since).
|
|
1496
|
+
const prevGeometry =
|
|
1497
|
+
property === "geometry"
|
|
1498
|
+
? (labels.get(this)?.get("geometry") ?? assignedGeometries.get(this))
|
|
1499
|
+
: undefined;
|
|
1402
1500
|
if (caching && (mirrored(binding, property, setters) || bounds)) {
|
|
1403
1501
|
// A mirrored property's setter writes only that property: the others stay kept,
|
|
1404
1502
|
// and a write of the primitive the mirror holds changes nothing in the engine.
|
|
@@ -1418,11 +1516,25 @@ export function defineBrowserClasses(
|
|
|
1418
1516
|
labels.delete(this);
|
|
1419
1517
|
animated.delete(this);
|
|
1420
1518
|
}
|
|
1421
|
-
// The shadow LOD sync
|
|
1519
|
+
// The shadow LOD sync re-walks the light root when this or the hierarchy moves. The walk
|
|
1520
|
+
// already registered a chain for the caster, so a swap between two rungs of that same
|
|
1521
|
+
// chain owes no walk: core's ModelLod does it as the camera orbits.
|
|
1422
1522
|
if (property === "geometry") {
|
|
1423
1523
|
const host = globalThis as Record<symbol, unknown>;
|
|
1424
|
-
const
|
|
1425
|
-
|
|
1524
|
+
const chains = host[Symbol.for("threenative.discreteLodChains")] as
|
|
1525
|
+
| WeakMap<object, { chain?: object }>
|
|
1526
|
+
| undefined;
|
|
1527
|
+
const chainOf = (candidate: unknown): object | undefined =>
|
|
1528
|
+
candidate !== null && typeof candidate === "object"
|
|
1529
|
+
? chains?.get(candidate)?.chain
|
|
1530
|
+
: undefined;
|
|
1531
|
+
const prevChain = chainOf(prevGeometry);
|
|
1532
|
+
if (!caching || prevChain === undefined || prevChain !== chainOf(value)) {
|
|
1533
|
+
const key = Symbol.for("threenative.geometryAssignments");
|
|
1534
|
+
host[key] = ((host[key] as number | undefined) ?? 0) + 1;
|
|
1535
|
+
}
|
|
1536
|
+
if (caching) assignedGeometries.set(this, value);
|
|
1537
|
+
else assignedGeometries.delete(this);
|
|
1426
1538
|
}
|
|
1427
1539
|
runtime.set(refOf(this), property, toEngine(value));
|
|
1428
1540
|
if (shape) {
|
|
@@ -1438,7 +1550,10 @@ export function defineBrowserClasses(
|
|
|
1438
1550
|
: {}),
|
|
1439
1551
|
};
|
|
1440
1552
|
Object.defineProperty(accessors, property, accessor);
|
|
1441
|
-
|
|
1553
|
+
// three hides `id` (`Object.defineProperty(this, "id", { value })`), so a copy loop never
|
|
1554
|
+
// writes the getter-only field.
|
|
1555
|
+
if (materialClass)
|
|
1556
|
+
own.push({ key: property, descriptor: { ...accessor, enumerable: property !== "id" } });
|
|
1442
1557
|
}
|
|
1443
1558
|
// A dotted path whose head is no member of its own (three's plain `morphAttributes` object) is
|
|
1444
1559
|
// a holder made per read, as the V8 adapter makes it: each tail reads and writes the full path.
|
package/src/browser-entry.ts
CHANGED
|
@@ -347,7 +347,11 @@ export async function bindWebEngine(
|
|
|
347
347
|
updatePasses = passes.updateFramePasses;
|
|
348
348
|
Object.assign(bound, passes);
|
|
349
349
|
}
|
|
350
|
-
|
|
350
|
+
const exported = bindUpstreamExports(names, engineCatalog, bound);
|
|
351
|
+
// three/webgpu's `TSL` is the three/tsl namespace (`export * as TSL`); here one namespace serves
|
|
352
|
+
// all three modules, so it already holds every TSL name.
|
|
353
|
+
exported.TSL = exported;
|
|
354
|
+
return exported;
|
|
351
355
|
}
|
|
352
356
|
|
|
353
357
|
/**
|
package/src/browser-renderer.ts
CHANGED
|
@@ -153,6 +153,40 @@ function markBaked(environment: IBakedEnvironment): void {
|
|
|
153
153
|
bakedEnvironments.set(environment, environment.version);
|
|
154
154
|
}
|
|
155
155
|
|
|
156
|
+
/** A host message that names GPU memory running out (core's launch-diagnostics holds the same test). */
|
|
157
|
+
const GPU_MEMORY_EXHAUSTED = /vkAllocateMemory|OUT_OF_DEVICE_MEMORY|out of (?:device )?memory/iu;
|
|
158
|
+
|
|
159
|
+
type GpuRequest = (...args: unknown[]) => Promise<unknown>;
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Hands `onDevice` the GPUDevice the next `navigator.gpu.requestAdapter` leads to, then returns the
|
|
163
|
+
* restore. Dawn's bindings create the device in JS, and its handle is the only way JS can free it.
|
|
164
|
+
*/
|
|
165
|
+
function captureDevice(onDevice: (device: { destroy(): void }) => void): () => void {
|
|
166
|
+
const gpu = (globalThis.navigator as { gpu?: { requestAdapter?: GpuRequest } } | undefined)?.gpu;
|
|
167
|
+
const requestAdapter = gpu?.requestAdapter;
|
|
168
|
+
if (gpu === undefined || typeof requestAdapter !== "function") return () => undefined;
|
|
169
|
+
const own = Object.hasOwn(gpu, "requestAdapter");
|
|
170
|
+
gpu.requestAdapter = async (...args) => {
|
|
171
|
+
const adapter = (await requestAdapter.apply(gpu, args)) as {
|
|
172
|
+
requestDevice?: GpuRequest;
|
|
173
|
+
} | null;
|
|
174
|
+
const requestDevice = adapter?.requestDevice;
|
|
175
|
+
if (adapter !== null && typeof requestDevice === "function") {
|
|
176
|
+
adapter.requestDevice = async (...options) => {
|
|
177
|
+
const device = (await requestDevice.apply(adapter, options)) as { destroy(): void };
|
|
178
|
+
onDevice(device);
|
|
179
|
+
return device;
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
return adapter;
|
|
183
|
+
};
|
|
184
|
+
return () => {
|
|
185
|
+
if (own) gpu.requestAdapter = requestAdapter;
|
|
186
|
+
else Reflect.deleteProperty(gpu, "requestAdapter");
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
|
|
156
190
|
export function defineWebRenderer(
|
|
157
191
|
module: WebEngineModule,
|
|
158
192
|
Color: new (...args: unknown[]) => IColorLike,
|
|
@@ -173,6 +207,10 @@ export function defineWebRenderer(
|
|
|
173
207
|
// The engine starts once per page: one device, and one surface bound to the first renderer's canvas.
|
|
174
208
|
// A renderer built after that one was disposed (a hot update re-runs the game) adopts both.
|
|
175
209
|
let started: HTMLCanvasElement | undefined;
|
|
210
|
+
// The engine's device, as Dawn's bindings received it. A reload left it to the browser to free once
|
|
211
|
+
// it got to the old document; a reload storm stacked them until the GPU ran out of memory. `pagehide`
|
|
212
|
+
// destroys it at once. A page kept in the back-forward cache (`persisted`) keeps it.
|
|
213
|
+
let gpuDevice: { destroy(): void } | undefined;
|
|
176
214
|
const string = (text: string): number => {
|
|
177
215
|
const bytes = module.lengthBytesUTF8(text) + 1;
|
|
178
216
|
const pointer = module._malloc(bytes) >>> 0;
|
|
@@ -395,7 +433,18 @@ export function defineWebRenderer(
|
|
|
395
433
|
#frameOpen = false;
|
|
396
434
|
/** The draw in flight is renderOverlay's. */
|
|
397
435
|
#overlay = false;
|
|
398
|
-
#state:
|
|
436
|
+
#state:
|
|
437
|
+
| {
|
|
438
|
+
toneMapping: number;
|
|
439
|
+
toneMappingExposure: number;
|
|
440
|
+
outputColorSpace: string;
|
|
441
|
+
shadowEnabled: boolean;
|
|
442
|
+
shadowType: number;
|
|
443
|
+
samples: number;
|
|
444
|
+
renderScale: number;
|
|
445
|
+
trackTimestamp: boolean;
|
|
446
|
+
}
|
|
447
|
+
| undefined;
|
|
399
448
|
#gpuSamples = 0;
|
|
400
449
|
#holdsSlot = true;
|
|
401
450
|
#timestampFrames: number[] = [];
|
|
@@ -464,13 +513,21 @@ export function defineWebRenderer(
|
|
|
464
513
|
);
|
|
465
514
|
module.specialHTMLTargets[CANVAS_TARGET] = this.domElement;
|
|
466
515
|
const selector = string(CANVAS_TARGET);
|
|
516
|
+
// tnw_web_init asks navigator.gpu for the adapter before it returns, so the hook lasts one call.
|
|
517
|
+
const release = captureDevice((device) => {
|
|
518
|
+
gpuDevice = device;
|
|
519
|
+
});
|
|
467
520
|
try {
|
|
468
521
|
check(
|
|
469
522
|
module._tnw_web_init(selector, this.#drawWidth(), this.#drawHeight(), WEB_HOST_ABI),
|
|
470
523
|
);
|
|
471
524
|
} finally {
|
|
525
|
+
release();
|
|
472
526
|
module._free(selector);
|
|
473
527
|
}
|
|
528
|
+
globalThis.addEventListener?.("pagehide", (event) => {
|
|
529
|
+
if (!(event as PageTransitionEvent).persisted) gpuDevice?.destroy();
|
|
530
|
+
});
|
|
474
531
|
// Only a host that started owns this canvas. Marked before the init, a start that threw left the
|
|
475
532
|
// next renderer polling a host nobody started, Pending for ever (PRD-895).
|
|
476
533
|
started = this.domElement;
|
|
@@ -852,8 +909,22 @@ export function defineWebRenderer(
|
|
|
852
909
|
renderScale,
|
|
853
910
|
} = this;
|
|
854
911
|
this.library.apply(toneMapping);
|
|
855
|
-
const
|
|
856
|
-
|
|
912
|
+
const shadowEnabled = shadowMap.enabled;
|
|
913
|
+
const shadowType = shadowMap.type;
|
|
914
|
+
const trackTimestamp = this.backend.trackTimestamp;
|
|
915
|
+
const prev = this.#state;
|
|
916
|
+
if (
|
|
917
|
+
prev !== undefined &&
|
|
918
|
+
prev.toneMapping === toneMapping &&
|
|
919
|
+
prev.toneMappingExposure === toneMappingExposure &&
|
|
920
|
+
prev.outputColorSpace === outputColorSpace &&
|
|
921
|
+
prev.shadowEnabled === shadowEnabled &&
|
|
922
|
+
prev.shadowType === shadowType &&
|
|
923
|
+
prev.samples === samples &&
|
|
924
|
+
prev.renderScale === renderScale &&
|
|
925
|
+
prev.trackTimestamp === trackTimestamp
|
|
926
|
+
)
|
|
927
|
+
return;
|
|
857
928
|
const space = string(String(outputColorSpace));
|
|
858
929
|
try {
|
|
859
930
|
check(
|
|
@@ -861,17 +932,26 @@ export function defineWebRenderer(
|
|
|
861
932
|
toneMapping,
|
|
862
933
|
toneMappingExposure,
|
|
863
934
|
space,
|
|
864
|
-
|
|
865
|
-
|
|
935
|
+
shadowEnabled ? 1 : 0,
|
|
936
|
+
shadowType,
|
|
866
937
|
samples,
|
|
867
938
|
renderScale,
|
|
868
|
-
|
|
939
|
+
trackTimestamp ? 1 : 0,
|
|
869
940
|
),
|
|
870
941
|
);
|
|
871
942
|
} finally {
|
|
872
943
|
module._free(space);
|
|
873
944
|
}
|
|
874
|
-
this.#state =
|
|
945
|
+
this.#state = {
|
|
946
|
+
toneMapping,
|
|
947
|
+
toneMappingExposure,
|
|
948
|
+
outputColorSpace,
|
|
949
|
+
shadowEnabled,
|
|
950
|
+
shadowType,
|
|
951
|
+
samples,
|
|
952
|
+
renderScale,
|
|
953
|
+
trackTimestamp,
|
|
954
|
+
};
|
|
875
955
|
}
|
|
876
956
|
|
|
877
957
|
/**
|
|
@@ -888,7 +968,8 @@ export function defineWebRenderer(
|
|
|
888
968
|
if (this.#adapter === undefined)
|
|
889
969
|
throw new Error("TN_WASM_RENDERER: render() before init() finished.");
|
|
890
970
|
if (this.#lost) return;
|
|
891
|
-
|
|
971
|
+
if ((root as { isQuadMesh?: unknown } | null | undefined)?.isQuadMesh !== true)
|
|
972
|
+
syncVirtualShadowLods();
|
|
892
973
|
beforeRender({ camera, scene: root, renderer: this, frameId: this.info.frame });
|
|
893
974
|
this.#applyState();
|
|
894
975
|
writeHandle(0, root, "scene");
|
|
@@ -943,7 +1024,8 @@ export function defineWebRenderer(
|
|
|
943
1024
|
console.error(
|
|
944
1025
|
`TN_WASM_RENDERER_LOST: this renderer draws nothing after this call. ${message}`,
|
|
945
1026
|
);
|
|
946
|
-
|
|
1027
|
+
// A device out of memory draws nothing either, and core recovers it by a reload (TN_GPU_MEMORY_RELOAD).
|
|
1028
|
+
if (message.startsWith("TN_WASM_DEVICE_LOST") || GPU_MEMORY_EXHAUSTED.test(message))
|
|
947
1029
|
this.#deviceLost({ reason: "unknown", message });
|
|
948
1030
|
return true;
|
|
949
1031
|
}
|
package/src/browser-tsl.ts
CHANGED
|
@@ -44,6 +44,8 @@ export interface ITslRuntime {
|
|
|
44
44
|
setUniform(node: number, lanes: readonly number[]): void;
|
|
45
45
|
/** Many `setUniform`s in one crossing: node i takes `counts[i]` of the packed `lanes` (PRD-828). */
|
|
46
46
|
setUniforms?(nodes: readonly number[], counts: readonly number[], lanes: readonly number[]): void;
|
|
47
|
+
/** Monotonic counter bumped whenever any material shader node slot changes. */
|
|
48
|
+
graphVersion?(): number;
|
|
47
49
|
/**
|
|
48
50
|
* PRD-878, `tn_tsl_reads`: which of `candidates` (uniform node ids) a draw of `root` (a mesh and what is under it)
|
|
49
51
|
* or a dispatch of `kernels` reads, as indices into `candidates`.
|
|
@@ -264,6 +266,7 @@ const CONSTANTS = [
|
|
|
264
266
|
"materialEmissive",
|
|
265
267
|
"materialMetalness",
|
|
266
268
|
"materialRoughness",
|
|
269
|
+
"materialReferenceOpacity",
|
|
267
270
|
"diffuseColor",
|
|
268
271
|
"time",
|
|
269
272
|
"deltaTime",
|
|
@@ -478,6 +481,15 @@ export function defineTsl(
|
|
|
478
481
|
)
|
|
479
482
|
return { kind: "other" };
|
|
480
483
|
if (typeof value === "number") return { kind: "number", number: value };
|
|
484
|
+
// three's `.compute(count, [size])`: a one-element array is the 1D workgroup size, the number the engine takes.
|
|
485
|
+
if (
|
|
486
|
+
name === "compute" &&
|
|
487
|
+
index === 1 &&
|
|
488
|
+
Array.isArray(value) &&
|
|
489
|
+
value.length === 1 &&
|
|
490
|
+
typeof value[0] === "number"
|
|
491
|
+
)
|
|
492
|
+
return { kind: "number", number: value[0] };
|
|
481
493
|
if (typeof value === "string") return { kind: "string", text: value };
|
|
482
494
|
// setSampler(false) on a storage texture: its flag crosses as 0 or 1.
|
|
483
495
|
if (name === "setSampler" && typeof value === "boolean")
|
|
@@ -726,6 +738,26 @@ export function defineTsl(
|
|
|
726
738
|
statement(name);
|
|
727
739
|
return wrap(call(name, null, args));
|
|
728
740
|
};
|
|
741
|
+
// r187's workgroup memory (gpgpu/WorkgroupInfoNode.js, BarrierNode.js): workgroupArray(type, count).element(i) is a
|
|
742
|
+
// compute-stage array the workgroup shares, and the two barriers are statements. textureBarrier, and any other
|
|
743
|
+
// barrier form, has no engine mapping and fails by name.
|
|
744
|
+
exports.workgroupArray = (type: unknown, count: unknown) =>
|
|
745
|
+
wrap(call("workgroupArray", null, [type, count]));
|
|
746
|
+
for (const name of ["workgroupBarrier", "storageBarrier"])
|
|
747
|
+
exports[name] = () => {
|
|
748
|
+
statement(name);
|
|
749
|
+
return wrap(call(name, null, []));
|
|
750
|
+
};
|
|
751
|
+
exports.textureBarrier = () => {
|
|
752
|
+
throw new TypeError(
|
|
753
|
+
"TN_TSL_BARRIER_UNSUPPORTED: textureBarrier is not supported; use workgroupBarrier or storageBarrier",
|
|
754
|
+
);
|
|
755
|
+
};
|
|
756
|
+
// three's node.discard() (addMethodChaining): Discard(node), the node as the condition.
|
|
757
|
+
prototype.discard = function (this: ITslNode) {
|
|
758
|
+
statement("Discard");
|
|
759
|
+
return wrap(call("Discard", null, [this]));
|
|
760
|
+
};
|
|
729
761
|
exports.If = (condition: unknown, callback: unknown) => {
|
|
730
762
|
statement("If");
|
|
731
763
|
const test = argument("If", 0, condition);
|
|
@@ -883,9 +915,15 @@ export function defineTsl(
|
|
|
883
915
|
};
|
|
884
916
|
const setUniforms = runtime.setUniforms?.bind(runtime);
|
|
885
917
|
const engineReads = runtime.reads?.bind(runtime);
|
|
918
|
+
const engineGraphVersion = runtime.graphVersion?.bind(runtime);
|
|
919
|
+
const graphVersionKey = Symbol.for("threenative.materialGraphVersion");
|
|
886
920
|
const readsCache = new WeakMap<
|
|
887
921
|
readonly object[],
|
|
888
|
-
{
|
|
922
|
+
{
|
|
923
|
+
ids: number[];
|
|
924
|
+
kernelCache?: Map<string, ArrayLike<number> | undefined>;
|
|
925
|
+
materialCache?: WeakMap<object, { version: number; picked: ArrayLike<number> | undefined }>;
|
|
926
|
+
}
|
|
889
927
|
>();
|
|
890
928
|
const live = liveUniforms(
|
|
891
929
|
matrixUniform,
|
|
@@ -914,8 +952,9 @@ export function defineTsl(
|
|
|
914
952
|
if (entry.ids.length < hooked.length) {
|
|
915
953
|
for (let i = entry.ids.length; i < hooked.length; i += 1)
|
|
916
954
|
entry.ids.push((hooked[i] as ITslNode)[TSL_NODE]);
|
|
917
|
-
// Newly registered uniforms in the same array invalidate prior kernel read selections.
|
|
955
|
+
// Newly registered uniforms in the same array invalidate prior kernel and material read selections.
|
|
918
956
|
entry.kernelCache?.clear();
|
|
957
|
+
entry.materialCache = undefined;
|
|
919
958
|
}
|
|
920
959
|
const kernels = frame.kernels;
|
|
921
960
|
if (kernels !== undefined) {
|
|
@@ -930,6 +969,30 @@ export function defineTsl(
|
|
|
930
969
|
cache.set(kernelKey, picked);
|
|
931
970
|
return picked;
|
|
932
971
|
}
|
|
972
|
+
const mesh = root as { isMesh?: unknown; children?: unknown[]; material?: unknown };
|
|
973
|
+
const mat = mesh.material;
|
|
974
|
+
const children = mesh.children;
|
|
975
|
+
if (
|
|
976
|
+
mesh.isMesh === true &&
|
|
977
|
+
(children === undefined || children.length === 0) &&
|
|
978
|
+
typeof mat === "object" &&
|
|
979
|
+
mat !== null &&
|
|
980
|
+
!Array.isArray(mat)
|
|
981
|
+
) {
|
|
982
|
+
const version =
|
|
983
|
+
(engineGraphVersion?.() ?? 0) +
|
|
984
|
+
(((globalThis as Record<symbol, unknown>)[graphVersionKey] as number | undefined) ?? 0);
|
|
985
|
+
let cache = entry.materialCache;
|
|
986
|
+
if (cache === undefined) {
|
|
987
|
+
cache = new WeakMap();
|
|
988
|
+
entry.materialCache = cache;
|
|
989
|
+
}
|
|
990
|
+
const cached = cache.get(mat);
|
|
991
|
+
if (cached !== undefined && cached.version === version) return cached.picked;
|
|
992
|
+
const picked = engineReads(ref, [], entry.ids);
|
|
993
|
+
cache.set(mat, { version, picked });
|
|
994
|
+
return picked;
|
|
995
|
+
}
|
|
933
996
|
return engineReads(ref, [], entry.ids);
|
|
934
997
|
}),
|
|
935
998
|
);
|
package/src/debug-telemetry.ts
CHANGED
|
@@ -1,5 +1,10 @@
|
|
|
1
1
|
import { PLAYTEST_OBSERVING_GLOBAL, callerOf } from "./bridge-meter.js";
|
|
2
2
|
|
|
3
|
+
// The bridge meter and uniform sync ask every frame; parsing an unchanged `location.search` again
|
|
4
|
+
// cost 0.82% self CPU on the browser profile. A changed search string (pushState) reparses.
|
|
5
|
+
let cachedSearch: string | undefined;
|
|
6
|
+
let cachedSearchParam: string | null = null;
|
|
7
|
+
|
|
3
8
|
/**
|
|
4
9
|
* Kept local to the bridge so three-native does not depend on core, and held to core's rule by
|
|
5
10
|
* `scripts/__tests__/launch-flag-parity.spec.ts`: `0` and `false` are off, a named-but-empty value
|
|
@@ -17,8 +22,11 @@ export function debugRequested(): boolean {
|
|
|
17
22
|
if (typeof env === "string" && env !== "") values.push(env);
|
|
18
23
|
const search = globalThis.location?.search;
|
|
19
24
|
if (typeof search === "string") {
|
|
20
|
-
|
|
21
|
-
|
|
25
|
+
if (search !== cachedSearch) {
|
|
26
|
+
cachedSearchParam = new URLSearchParams(search).get("tnDebug");
|
|
27
|
+
cachedSearch = search;
|
|
28
|
+
}
|
|
29
|
+
if (cachedSearchParam !== null) values.push(cachedSearchParam);
|
|
22
30
|
}
|
|
23
31
|
const set = host.__THREENATIVE_DEBUG__;
|
|
24
32
|
if (typeof set === "string") values.push(set);
|
package/src/reflector.ts
CHANGED
|
@@ -21,6 +21,9 @@ export interface IReflectorParameters {
|
|
|
21
21
|
readonly bounces?: boolean;
|
|
22
22
|
readonly depth?: boolean;
|
|
23
23
|
readonly samples?: number;
|
|
24
|
+
readonly excludeInstancedAndSkinned?: boolean;
|
|
25
|
+
readonly minSize?: number;
|
|
26
|
+
readonly refreshInterval?: number;
|
|
24
27
|
}
|
|
25
28
|
|
|
26
29
|
/** The engine classes the reflector builds its target and virtual camera from. */
|
|
@@ -43,7 +46,17 @@ export function defineReflector(native: NativeReflector, classes: IReflectorClas
|
|
|
43
46
|
return function reflector(parameters: IReflectorParameters = {}): object {
|
|
44
47
|
const target = parameters.target ?? new classes.Object3D();
|
|
45
48
|
const resolutionScale = parameters.resolutionScale ?? parameters.resolution ?? 1;
|
|
46
|
-
const {
|
|
49
|
+
const {
|
|
50
|
+
generateMipmaps = false,
|
|
51
|
+
bounces = true,
|
|
52
|
+
depth = false,
|
|
53
|
+
samples = 0,
|
|
54
|
+
excludeInstancedAndSkinned = false,
|
|
55
|
+
minSize = 0,
|
|
56
|
+
refreshInterval = 1,
|
|
57
|
+
} = parameters;
|
|
58
|
+
if (!Number.isInteger(refreshInterval) || refreshInterval < 1)
|
|
59
|
+
throw new Error("defineReflector.refreshInterval must be a positive integer.");
|
|
47
60
|
const camera = new classes.PerspectiveCamera();
|
|
48
61
|
const node = native(
|
|
49
62
|
target,
|
|
@@ -53,6 +66,9 @@ export function defineReflector(native: NativeReflector, classes: IReflectorClas
|
|
|
53
66
|
generateMipmaps ? 1 : 0,
|
|
54
67
|
depth ? 1 : 0,
|
|
55
68
|
samples,
|
|
69
|
+
excludeInstancedAndSkinned ? 1 : 0,
|
|
70
|
+
minSize,
|
|
71
|
+
refreshInterval,
|
|
56
72
|
);
|
|
57
73
|
let getVirtualCamera: (camera?: object) => object = () => camera;
|
|
58
74
|
const base = {
|
|
@@ -62,6 +78,9 @@ export function defineReflector(native: NativeReflector, classes: IReflectorClas
|
|
|
62
78
|
bounces,
|
|
63
79
|
depth,
|
|
64
80
|
samples,
|
|
81
|
+
excludeInstancedAndSkinned,
|
|
82
|
+
minSize,
|
|
83
|
+
refreshInterval,
|
|
65
84
|
// three's NodeUpdateType.NONE: no JS update runs, so a caller can tell before it wraps one.
|
|
66
85
|
updateBeforeType: "none",
|
|
67
86
|
get getVirtualCamera() {
|
package/src/tsl-extras.ts
CHANGED
|
@@ -7,6 +7,7 @@ interface IExtrasTsl {
|
|
|
7
7
|
readonly clamp: (value: unknown, low: number, high: number) => unknown;
|
|
8
8
|
readonly float: (value: number) => IFogNode;
|
|
9
9
|
readonly linearDepth: () => IFogNode;
|
|
10
|
+
readonly materialReferenceOpacity: IFogNode;
|
|
10
11
|
// quality-allow: three's TSL export name.
|
|
11
12
|
// biome-ignore lint/style/useNamingConvention: three's TSL export name.
|
|
12
13
|
readonly mx_noise_float: (position: unknown) => IFogNode;
|
|
@@ -36,6 +37,14 @@ interface IFogNode {
|
|
|
36
37
|
*/
|
|
37
38
|
export function defineTslExtras(tsl: IExtrasTsl) {
|
|
38
39
|
return {
|
|
40
|
+
// three's materialReference(name, type) reads the drawn material's own uniform by name. The engine
|
|
41
|
+
// answers `opacity`, the one a vendored node graph reads (threejs-hair-shader); any other refuses by name.
|
|
42
|
+
materialReference: (name: string, type = "float") => {
|
|
43
|
+
if (name === "opacity" && type === "float") return tsl.materialReferenceOpacity;
|
|
44
|
+
throw new Error(
|
|
45
|
+
`TN_NATIVE_MATERIAL_REFERENCE: materialReference("${name}", "${type}") is not on the native engine; it reads "opacity" as a float`,
|
|
46
|
+
);
|
|
47
|
+
},
|
|
39
48
|
// r185's saturate(x) is clamp(x, 0, 1).
|
|
40
49
|
saturate: (value: unknown) => tsl.clamp(value, 0, 1),
|
|
41
50
|
// r185's densityFogFactor (nodes/fog/Fog.js): 1 - exp(-density^2 * viewZ^2). The fragment's view-space
|
package/src/tsl-uniforms.ts
CHANGED
|
@@ -520,11 +520,14 @@ export function liveUniforms<TNode extends object>(
|
|
|
520
520
|
// A nested render of a frame whose frame hooks already ran skips them without walking them.
|
|
521
521
|
const nested = rendererFrame !== undefined && rendererFrame === hookedFrame;
|
|
522
522
|
// A draw of one mesh or a dispatch runs only the hooks its graphs read (the engine answers which).
|
|
523
|
-
|
|
523
|
+
// When nested with no per-render hooks, frame hooks already ran for this frame, so skip both reads and hook walk.
|
|
524
|
+
const skipHooks = nested && renders.size === 0;
|
|
525
|
+
const picked = extra === undefined || skipHooks ? undefined : reads?.(extra, updating);
|
|
524
526
|
if (picked !== undefined)
|
|
525
527
|
for (let index = 0; index < picked.length; index += 1)
|
|
526
528
|
updateNode(updating[picked[index] as number] as TNode, rendererFrame);
|
|
527
|
-
else
|
|
529
|
+
else if (!skipHooks)
|
|
530
|
+
for (const node of nested ? renders : updating) updateNode(node, rendererFrame);
|
|
528
531
|
// Only once every hook returned: one that threw leaves later frame hooks to the next render. A picked
|
|
529
532
|
// sync ran some hooks only, so it does not stand for the frame's.
|
|
530
533
|
if (picked === undefined) hookedFrame = rendererFrame;
|
|
@@ -537,7 +540,12 @@ export function liveUniforms<TNode extends object>(
|
|
|
537
540
|
}
|
|
538
541
|
dirty.delete(ref);
|
|
539
542
|
}
|
|
540
|
-
|
|
543
|
+
const narrow =
|
|
544
|
+
extra?.kernels !== undefined ||
|
|
545
|
+
(typeof extra?.scene === "object" &&
|
|
546
|
+
extra.scene !== null &&
|
|
547
|
+
(extra.scene as { isScene?: unknown }).isScene !== true);
|
|
548
|
+
if (narrow && reads !== undefined) {
|
|
541
549
|
if (objects.size > 0) {
|
|
542
550
|
if (objectNodesVersion !== objectsVersion) {
|
|
543
551
|
const fresh: TNode[] = [];
|