@threenative/three-native 0.3.13 → 0.3.15

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@threenative/three-native",
3
- "version": "0.3.13",
3
+ "version": "0.3.15",
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": [
@@ -428,6 +428,16 @@ export interface IScreenSpaceGiOptions {
428
428
  * the shadowed walls nearby while its bright directions leave the screen. Missing means 0, as three's SSGINode.
429
429
  */
430
430
  readonly fallback?: (position: TslNode, direction: TslNode, normal: TslNode) => TslNode;
431
+ /**
432
+ * What a ray that leaves the screen finds in the tier past the screen: Unreal continues the ray in the distance field
433
+ * up to the radiance cache's coverage and reads the cache there, so a miss is a direction's radiance and not the
434
+ * pixel's mean (`ScreenProbeGather` composes that walk). Called for each ray that found nothing on screen, with the
435
+ * receiver's view-space position, the ray's unit view-space direction and its normal, and answers the light that
436
+ * arrives from off screen minus what the frame already holds at the pixel: the composite adds the pixel's own
437
+ * indirect diffuse, so a value that did not take it out would count it twice. Missing means 0, as three's SSGINode
438
+ * and this gather before PRD-640 Phase 2: a miss then leaves the pixel's cache average in place.
439
+ */
440
+ readonly miss?: (position: TslNode, direction: TslNode, normal: TslNode) => TslNode;
431
441
  /**
432
442
  * Gather with screen probes instead of per-pixel rays (Unreal's ScreenProbeGather): one probe per
433
443
  * `downsampleFactor` pixel tile traces an octahedron of rays, the probe radiance is turned into an irradiance
@@ -625,6 +635,11 @@ export function defineScreenSpaceGi(tsl: IScreenSpaceTsl) {
625
635
  const fallback = options.fallback?.(position, direction, normal) ?? vec3(0, 0, 0);
626
636
  gathered.assign(gathered.add(hit.radiance.sub(fallback).mul(hit.weight)));
627
637
  hits.assign(hits.add(hit.weight));
638
+ }).Else(() => {
639
+ // A ray the screen cannot answer reaches the tier past it (the world-space trace and the radiance cache):
640
+ // the delta over what the pixel's own indirect diffuse already holds, at the ray's weight.
641
+ const past = options.miss?.(position, direction, normal);
642
+ if (past !== undefined) gathered.assign(gathered.add(past));
628
643
  });
629
644
  },
630
645
  );
@@ -690,10 +705,11 @@ function octahedronEncode(tsl: IScreenSpaceTsl, direction: TslNode): TslNode {
690
705
  /**
691
706
  * The screen-probe gather (PRD-640). Three passes, none per pixel until the last:
692
707
  * 1. trace one texel per ray: a probe per tile traces an `n x n` octahedron of rays (view space) and keeps the lit
693
- * colour each hit found and its weight.
708
+ * colour each hit found and its weight, or, where the screen has nothing, what the tier past it answers
709
+ * (`miss`: the world-space trace and the radiance cache).
694
710
  * 2. filter each probe turns its rays into an irradiance octahedron: per direction, the cosine-weighted mean of
695
- * `hit - fallback` (the trace subtracts the cache along each ray), so a ray that leaves the screen keeps
696
- * the cache. A pixel then reads one bilinear tap instead of 64 rays.
711
+ * `hit - fallback` (the trace subtracts the cache along each ray), so a ray that hits keeps the screen's
712
+ * light and a ray that misses keeps the tier beyond it. A pixel then reads one bilinear tap, not 64 rays.
697
713
  * 3. gather each pixel blends the four nearest probes by position, depth-plane distance and normal agreement, and
698
714
  * reads each probe's irradiance along the pixel normal. A pixel no probe can see gets the cache alone.
699
715
  */
@@ -776,6 +792,11 @@ function defineScreenProbes(
776
792
  const hit = shade(trace.hitCoordinate, trace.hitDistance, direction);
777
793
  const believed = options.fallback?.(position, direction, normal) ?? vec3(0, 0, 0);
778
794
  result.assign(vec4(hit.radiance.sub(believed).mul(hit.weight), hit.weight));
795
+ }).Else(() => {
796
+ // A ray the screen cannot answer carries the tier past it: the filter mixes it with the probe's other rays, so a
797
+ // probe keeps a direction's radiance where the frame ends (the `a` channel stays the hit share).
798
+ const past = options.miss?.(position, direction, normal);
799
+ if (past !== undefined) result.assign(vec4(past, 0));
779
800
  });
780
801
  });
781
802
  return result;
@@ -83,10 +83,10 @@ export interface IBrowserRuntime {
83
83
  /** Doubles at `address` in the engine's memory (one as a number, more as an array); Wasm only. */
84
84
  readDoubles?(address: number, count: number): number | number[];
85
85
  /**
86
- * The engine's memory as doubles, current: Emscripten replaces the view when the memory grows, so a caller
87
- * reads it per operation and never keeps it. Wasm only.
86
+ * The engine's memory as doubles, current and reaching at least byte `end`: the view is replaced
87
+ * when the memory grows, so a caller reads it per operation and never keeps it. Wasm only.
88
88
  */
89
- heapF64?(): Float64Array;
89
+ heapF64?(end: number): Float64Array;
90
90
  /** The byte at `address` in the engine's memory; Wasm only. A registry field `[offset, 0]` is a byte flag. */
91
91
  readByte?(address: number): number;
92
92
  /** The 32-bit word at `address` in the engine's memory (the hierarchy counter's low word); Wasm only. */
@@ -169,6 +169,28 @@ export type TnAbiModule = Record<AbiCall, (...args: number[]) => number> &
169
169
  lengthBytesUTF8(text: string): number;
170
170
  };
171
171
 
172
+ /**
173
+ * The engine's memory as bytes, reaching at least `end`. Shared memory (the threaded build) grows from
174
+ * any thread, and Emscripten refreshes a thread's views only inside its own glue: after a pool worker
175
+ * grew it, HEAPU8 here stayed short and a pointer past it threw "Offset is outside the bounds of the
176
+ * DataView". A shared buffer never detaches, so a short view is right below its end: only an access
177
+ * past it reads `memory.buffer`, and the fresh views go onto the module for every other reader.
178
+ */
179
+ export function heapFor(abi: TnAbiModule, end: number): Uint8Array {
180
+ if (end <= abi.HEAPU8.byteLength) return abi.HEAPU8;
181
+ const buffer = (abi as { wasmMemory?: WebAssembly.Memory }).wasmMemory?.buffer;
182
+ if (
183
+ buffer !== undefined &&
184
+ buffer.byteLength > abi.HEAPU8.byteLength &&
185
+ typeof SharedArrayBuffer !== "undefined" &&
186
+ buffer instanceof SharedArrayBuffer
187
+ ) {
188
+ abi.HEAPU8 = new Uint8Array(buffer);
189
+ abi.HEAPF64 = new Float64Array(buffer);
190
+ }
191
+ return abi.HEAPU8;
192
+ }
193
+
172
194
  // wasm32 layouts of tn_abi.h, measured with offsetof under emcc: tn_handle_t 12 bytes; tn_value_t
173
195
  // 56 bytes (kind 0, boolean 4, number 8, handle 16, text 32, count 40, numbers 48); tn_diagnostic_t
174
196
  // 8 bytes (message 0, code 4); tn_version_info_t 32 bytes. A struct passed by value goes by pointer.
@@ -226,7 +248,8 @@ export interface IAbiHelpers {
226
248
  check(status: number, diag: number, what: string): void;
227
249
  handleOf(ref: IEngineRef): number;
228
250
  writeHandle(pointer: number, ref: IEngineRef): void;
229
- view(): DataView;
251
+ /** The heap's DataView, reaching at least byte `end` (pass it for a pointer `alloc` did not make). */
252
+ view(end?: number): DataView;
230
253
  }
231
254
 
232
255
  /** `tnw_web_load_gltf`'s handles: the default scene, the clips, then every scene in file order. */
@@ -508,7 +531,7 @@ export function tslOf(
508
531
  const out = abi._malloc(size) >>> 0;
509
532
  try {
510
533
  if (readStorageTake(id, out, size) === 1)
511
- return abi.HEAPU8.slice(out, out + size).buffer;
534
+ return heapFor(abi, out + size).slice(out, out + size).buffer;
512
535
  } finally {
513
536
  abi._free(out);
514
537
  }
@@ -550,7 +573,7 @@ export function tslOf(
550
573
  candidateAt = abi._malloc(candidateRoom * 12) >>> 0;
551
574
  candidatesWritten = 0;
552
575
  }
553
- const ids = h.view();
576
+ const ids = h.view(candidateAt + candidateRoom * 12);
554
577
  for (; candidatesWritten < candidates.length; candidatesWritten += 1)
555
578
  ids.setBigUint64(
556
579
  candidateAt + candidatesWritten * 8,
@@ -1069,8 +1069,9 @@ export function defineBrowserClasses(
1069
1069
  Object.getPrototypeOf(other) !== prototype
1070
1070
  )
1071
1071
  return engineCopy.call(this, other);
1072
- const from = (addressOf(other) + offset) / 8;
1073
- heapF64().copyWithin((addressOf(this) + offset) / 8, from, from + count);
1072
+ const to = addressOf(this) + offset;
1073
+ const from = addressOf(other) + offset;
1074
+ heapF64(Math.max(to, from) + count * 8).copyWithin(to / 8, from / 8, from / 8 + count);
1074
1075
  return this;
1075
1076
  },
1076
1077
  },
@@ -1084,9 +1085,9 @@ export function defineBrowserClasses(
1084
1085
  Object.getPrototypeOf(other) !== prototype
1085
1086
  )
1086
1087
  return engineEquals.call(this, other);
1087
- const heap = heapF64();
1088
1088
  const a = (addressOf(this) + offset) / 8;
1089
1089
  const b = (addressOf(other) + offset) / 8;
1090
+ const heap = heapF64((Math.max(a, b) + count) * 8);
1090
1091
  for (let i = 0; i < count; i++) if (heap[a + i] !== heap[b + i]) return false;
1091
1092
  return true;
1092
1093
  },
@@ -4,7 +4,7 @@
4
4
  * surface and every draw; this class turns three's calls into host calls and reports what the
5
5
  * engine did. What it does not implement throws its diagnostic rather than doing nothing.
6
6
  */
7
- import { packedRef } from "./browser-abi-types.js";
7
+ import { heapFor, packedRef } from "./browser-abi-types.js";
8
8
  import { TSL_NODE, type TnAbiModule, engineRef } from "./browser-backend.js";
9
9
  import { type ITslRuntime, defineTsl, isTslNode } from "./browser-tsl.js";
10
10
  import { debugTelemetry } from "./debug-telemetry.js";
@@ -189,7 +189,7 @@ export function defineWebRenderer(
189
189
  if (ref === undefined)
190
190
  throw new TypeError(`TN_WASM_RENDER: the ${what} is not an engine object.`);
191
191
  const { w0, w1, w2 } = packedRef(ref);
192
- const view = new DataView(module.HEAPU8.buffer);
192
+ const view = new DataView(heapFor(module, handles + offset + 12).buffer);
193
193
  view.setUint32(handles + offset, w0, true);
194
194
  view.setUint32(handles + offset + 4, w1, true);
195
195
  view.setUint32(handles + offset + 8, w2, true);
@@ -462,9 +462,7 @@ export function defineWebRenderer(
462
462
  throw new Error(
463
463
  `TN_WASM_ABI_MISMATCH: this facade speaks web host ABI ${WEB_HOST_ABI}, the engine ${engine ?? "none (older than ABI 2)"}: install create-threenative and @threenative/runtime-native from one build`,
464
464
  );
465
- started = this.domElement;
466
465
  module.specialHTMLTargets[CANVAS_TARGET] = this.domElement;
467
- handles = module._malloc(36) >>> 0;
468
466
  const selector = string(CANVAS_TARGET);
469
467
  try {
470
468
  check(
@@ -473,6 +471,10 @@ export function defineWebRenderer(
473
471
  } finally {
474
472
  module._free(selector);
475
473
  }
474
+ // Only a host that started owns this canvas. Marked before the init, a start that threw left the
475
+ // next renderer polling a host nobody started, Pending for ever (PRD-895).
476
+ started = this.domElement;
477
+ handles = module._malloc(36) >>> 0;
476
478
  } else {
477
479
  // The disposed renderer's post graph must not outlive its game.
478
480
  tsl?.setPost(null);
@@ -505,7 +507,12 @@ export function defineWebRenderer(
505
507
  ) as Record<WorkCountName, number>;
506
508
  }
507
509
  return this;
508
- })();
510
+ })().catch((error: unknown) => {
511
+ // A start that failed gives the page's one slot back, so the next start in this page (a hot
512
+ // reload) reports its own result instead of TN_WASM_RENDERER_SINGLE (PRD-894).
513
+ this.dispose();
514
+ throw error;
515
+ });
509
516
  return this.#initialized;
510
517
  }
511
518
 
@@ -1193,7 +1200,7 @@ export function defineWebRenderer(
1193
1200
  for (;;) {
1194
1201
  module._tnw_web_poll();
1195
1202
  const status = module._tnw_web_read_target_take(id, out, size);
1196
- if (status === 1) return module.HEAPU8.slice(out, out + size);
1203
+ if (status === 1) return heapFor(module, out + size).slice(out, out + size);
1197
1204
  // A read the lost device dropped says so, so the caller's report is read as that one loss.
1198
1205
  if (status < 0)
1199
1206
  throw new Error(
@@ -1263,7 +1270,9 @@ export function defineWebRenderer(
1263
1270
  module._tnw_web_poll();
1264
1271
  const status = module._tnw_web_read_target_take(id, out, bytes);
1265
1272
  if (status === 1)
1266
- return new Float32Array(module.HEAPU8.slice(out, out + bytes).buffer);
1273
+ return new Float32Array(
1274
+ heapFor(module, out + bytes).slice(out, out + bytes).buffer,
1275
+ );
1267
1276
  if (status < 0) throw new Error("TN_REFLECTION_CAPTURE_READ");
1268
1277
  await new Promise((resolve) => setTimeout(resolve, 0));
1269
1278
  }
@@ -311,7 +311,7 @@ export function defineValueViews(host: IValueViewHost): IValueViews {
311
311
  if (read === undefined || write === undefined) return;
312
312
  const heap = runtime.heapF64;
313
313
  const lane = heap
314
- ? (address: number): number => heap()[address / 8] as number
314
+ ? (address: number): number => heap(address + 8)[address / 8] as number
315
315
  : (address: number): number => read(address, 1) as number;
316
316
  if (name === "Quaternion" && binding.fields !== undefined) {
317
317
  const offsets = ["x", "y", "z", "w"].map((key) => binding.fields?.[key]?.[0] ?? 0);
@@ -458,7 +458,7 @@ export function defineValueViews(host: IValueViewHost): IValueViews {
458
458
  // a frame, and a copy call allocates two arrays a read.
459
459
  const refresh = heap
460
460
  ? (address: number, values: number[]): void => {
461
- const memory = heap();
461
+ const memory = heap(address + count * 8);
462
462
  for (let i = 0, at = address / 8; i < count; i++) values[i] = memory[at + i] as number;
463
463
  }
464
464
  : (address: number, values: number[]): void => {
@@ -472,7 +472,7 @@ export function defineValueViews(host: IValueViewHost): IValueViews {
472
472
  configurable: true,
473
473
  get(this: object): number[] {
474
474
  const address = addressOf(this) + offset;
475
- const memory = heap?.();
475
+ const memory = heap?.(address + count * 8);
476
476
  if (
477
477
  typeof SharedArrayBuffer !== "undefined" &&
478
478
  memory?.buffer instanceof SharedArrayBuffer
@@ -13,6 +13,7 @@ import {
13
13
  type TnAbiModule,
14
14
  VALUE,
15
15
  gltfOf,
16
+ heapFor,
16
17
  isRef,
17
18
  packedRef,
18
19
  tslOf,
@@ -37,24 +38,30 @@ export function createWasmRuntime(abi: TnAbiModule): IBrowserRuntime {
37
38
  let encoding = "arguments";
38
39
  // The heap's views, made again only when the memory grows: Emscripten replaces HEAPU8 then, so one
39
40
  // identity test per use stands in for reading two `.buffer`s, which every crossing paid (PRD-748).
41
+ // Shared memory can grow from another thread with no replacement here, but it never detaches: an
42
+ // access past `heapBytes` (an engine pointer's `end`) refreshes through `heapFor`.
40
43
  let heap = abi.HEAPU8;
41
44
  let heapBytes = heap.byteLength;
42
45
  let dataView = new DataView(heap.buffer);
43
46
  let words = new Uint32Array(heap.buffer);
44
- const grown = () => {
45
- debug?.add("wasmGrowthEvents", 1, "bridge");
46
- debug?.add("wasmGrowthBytes", Math.max(0, abi.HEAPU8.byteLength - heapBytes), "memory");
47
- heap = abi.HEAPU8;
47
+ const grown = (end: number) => {
48
+ const before = heapBytes;
49
+ heap = heapFor(abi, end);
48
50
  heapBytes = heap.byteLength;
49
51
  dataView = new DataView(heap.buffer);
50
52
  words = new Uint32Array(heap.buffer);
53
+ debug?.add("wasmGrowthEvents", 1, "bridge");
54
+ debug?.add("wasmGrowthBytes", Math.max(0, heapBytes - before), "memory");
51
55
  };
52
- const view = () => {
53
- if (abi.HEAPU8 !== heap) grown();
56
+ const reach = (end: number) => {
57
+ if (end > heapBytes) grown(end);
58
+ };
59
+ const view = (end = 0) => {
60
+ if (end > heapBytes || abi.HEAPU8 !== heap) grown(end);
54
61
  return dataView;
55
62
  };
56
- const wordView = () => {
57
- if (abi.HEAPU8 !== heap) grown();
63
+ const wordView = (end = 0) => {
64
+ if (end > heapBytes || abi.HEAPU8 !== heap) grown(end);
58
65
  return words;
59
66
  };
60
67
  // Each call frees what it allocated, and only that: a callback can run a nested call.
@@ -80,8 +87,8 @@ export function createWasmRuntime(abi: TnAbiModule): IBrowserRuntime {
80
87
  debug?.add("bridgeOverflowBytes", aligned, "bridge");
81
88
  }
82
89
  // A call's scratch is a few words (a handle, a value, a diagnostic): word stores beat a fill call.
83
- // `wordView` first: a `_malloc` above may have grown the memory.
84
- const w = wordView();
90
+ // `wordView` first: a `_malloc` above may have grown the memory, on this thread or another.
91
+ const w = wordView(pointer + aligned);
85
92
  if (aligned > 64) heap.fill(0, pointer, pointer + aligned);
86
93
  else for (let at = pointer >>> 2, end = (pointer + aligned) >>> 2; at < end; at++) w[at] = 0;
87
94
  return pointer;
@@ -228,7 +235,7 @@ export function createWasmRuntime(abi: TnAbiModule): IBrowserRuntime {
228
235
  return pointer;
229
236
  };
230
237
  const readValue = (pointer: number): EngineValue => {
231
- const v = view();
238
+ const v = view(pointer + VALUE);
232
239
  switch (v.getUint32(pointer, true)) {
233
240
  case KIND.undefined:
234
241
  return undefined;
@@ -261,9 +268,9 @@ export function createWasmRuntime(abi: TnAbiModule): IBrowserRuntime {
261
268
  }
262
269
  case KIND.numbers: {
263
270
  const at = v.getUint32(pointer + 48, true) / 8;
264
- return Array.from(
265
- abi.HEAPF64.subarray(at, at + Number(v.getBigUint64(pointer + 40, true))),
266
- );
271
+ const count = Number(v.getBigUint64(pointer + 40, true));
272
+ reach((at + count) * 8);
273
+ return Array.from(abi.HEAPF64.subarray(at, at + count));
267
274
  }
268
275
  default:
269
276
  return null;
@@ -323,6 +330,7 @@ export function createWasmRuntime(abi: TnAbiModule): IBrowserRuntime {
323
330
  const Typed = SCALARS[scalar ?? -1];
324
331
  if (Typed === undefined)
325
332
  throw new TypeError(`TN_NATIVE_UNSUPPORTED array: scalar ${String(scalar)}`);
333
+ reach((address ?? 0) + (count ?? 0) * Typed.BYTES_PER_ELEMENT);
326
334
  return use(new Typed(abi.HEAPU8.buffer as ArrayBuffer, address ?? 0, count ?? 0));
327
335
  } finally {
328
336
  abi._tnw_attribute_view_release?.(lease);
@@ -423,16 +431,25 @@ export function createWasmRuntime(abi: TnAbiModule): IBrowserRuntime {
423
431
  batch.status[i] = after.getFloat64(status + i * 8, true);
424
432
  });
425
433
  },
426
- readByte: (address) => abi.HEAPU8[address] as number,
427
- readWord: (address) => view().getUint32(address, true),
434
+ readByte: (address) => {
435
+ reach(address + 1);
436
+ return abi.HEAPU8[address] as number;
437
+ },
438
+ readWord: (address) => view(address + 4).getUint32(address, true),
428
439
  writeDouble: (address, value) => {
440
+ reach(address + 8);
429
441
  abi.HEAPF64[address / 8] = value;
430
442
  },
431
443
  writeByte: (address, value) => {
444
+ reach(address + 1);
432
445
  abi.HEAPU8[address] = value;
433
446
  },
434
- heapF64: () => abi.HEAPF64,
447
+ heapF64: (end) => {
448
+ reach(end);
449
+ return abi.HEAPF64;
450
+ },
435
451
  readDoubles: (address, count) => {
452
+ reach(address + count * 8);
436
453
  const at = address / 8;
437
454
  return count === 1
438
455
  ? (abi.HEAPF64[at] as number)
@@ -3,6 +3,7 @@
3
3
  // The `TN_*` console markers the perf tooling parses. Add the colon where a line is matched.
4
4
  export const CONSOLE_MARKER = {
5
5
  bridgeCensus: "TN_BRIDGE_CENSUS",
6
+ firstFrame: "TN_FIRST_FRAME",
6
7
  frameBudget: "TN_FRAME_BUDGET",
7
8
  frameHitch: "TN_FRAME_HITCH",
8
9
  hostGap: "TN_HOST_GAP",
@@ -79,6 +79,7 @@ export const WEB_FRAME_FIELD = {
79
79
  textureCompressionBc: 87,
80
80
  virtualShadowPendingLevels: 88,
81
81
  frameSnapshot: 89,
82
+ prepassDraws: 90,
82
83
  } as const;
83
84
 
84
85
  export type WebFrameField = (typeof WEB_FRAME_FIELD)[keyof typeof WEB_FRAME_FIELD];
@@ -41,6 +41,8 @@ interface IGeometry {
41
41
  getAttribute(name: string): unknown;
42
42
  }
43
43
 
44
+ const undefinedOnMissing = new WeakSet<object>();
45
+
44
46
  function defineGeometrySurface(
45
47
  BufferGeometry: Constructor,
46
48
  geometries: readonly Constructor[],
@@ -82,6 +84,23 @@ function defineGeometrySurface(
82
84
  ).map(({ start, count, materialIndex }) => ({ start, count, materialIndex }));
83
85
  },
84
86
  });
87
+ // three answers a missing attribute with undefined and the engine with null, so a game's
88
+ // `getAttribute(name) === undefined` (a sway material picking its geometry) misread every
89
+ // geometry as carrying it and the draw failed TN_NATIVE_ATTRIBUTE_MISSING. The engine may define
90
+ // it on a shared base, so the method each class resolves is wrapped on that class.
91
+ const read = (prototype as { getAttribute?: unknown }).getAttribute;
92
+ if (typeof read === "function" && !undefinedOnMissing.has(read)) {
93
+ const answer = function (this: unknown, name: string): unknown {
94
+ return (read as (this: unknown, name: string) => unknown).call(this, name) ?? undefined;
95
+ };
96
+ undefinedOnMissing.add(answer);
97
+ Object.defineProperty(prototype, "getAttribute", {
98
+ configurable: true,
99
+ enumerable: false,
100
+ value: answer,
101
+ writable: true,
102
+ });
103
+ }
85
104
  // Each geometry class carries its own `attributes` accessor, so every one gets the view.
86
105
  Object.defineProperty(prototype, "attributes", {
87
106
  configurable: true,