@threenative/three-native 0.3.12 → 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.
@@ -4,9 +4,11 @@
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 { heapFor, packedRef } from "./browser-abi-types.js";
7
8
  import { TSL_NODE, type TnAbiModule, engineRef } from "./browser-backend.js";
8
9
  import { type ITslRuntime, defineTsl, isTslNode } from "./browser-tsl.js";
9
10
  import { debugTelemetry } from "./debug-telemetry.js";
11
+ import { WEB_FRAME_FIELD } from "./generated/web-frame-fields.js";
10
12
  import {
11
13
  CPU_STAGE_ENTRIES,
12
14
  type CpuStageName,
@@ -18,9 +20,15 @@ import {
18
20
  } from "./gpu-stages.js";
19
21
  import type { PassDraw } from "./pass-node.js";
20
22
  import { frameAttachmentName } from "./pass-node.js";
21
- import { defineRenderTargets, targetTexelBytes } from "./render-target.js";
23
+ import {
24
+ type IPositionLike,
25
+ type IRegionLike,
26
+ defineRenderTargets,
27
+ targetTexelBytes,
28
+ textureCopyArguments,
29
+ } from "./render-target.js";
22
30
  import { ShadowMap } from "./shadow-map.js";
23
- import { syncVirtualShadowLods } from "./shadow-node.js";
31
+ import { reportVirtualShadowFrame, syncVirtualShadowLods } from "./shadow-node.js";
24
32
  import { defineSphereReflectionCapture } from "./sphere-reflection-capture.js";
25
33
  import { readStorageBytes } from "./storage.js";
26
34
  import type { INodeFrame } from "./temp-node.js";
@@ -50,6 +58,7 @@ type HostCall =
50
58
  | "_tnw_web_copy_texture"
51
59
  | "_tnw_web_read_mrt"
52
60
  | "_tnw_web_device_limit"
61
+ | "_tnw_web_device_feature"
53
62
  | "_tnw_web_threads";
54
63
 
55
64
  export type WebHostModule = Record<HostCall, (...args: number[]) => number> & {
@@ -66,7 +75,16 @@ export function isWebHostModule(module: TnAbiModule): module is WebEngineModule
66
75
  * The tnw_* contract this facade speaks (web_host.cpp `kWebHostAbi`). Bump both on every tnw_*
67
76
  * signature change: web-host-abi.spec.ts pins the signatures per number, and a mismatch fails init.
68
77
  */
69
- export const WEB_HOST_ABI = 11;
78
+ export const WEB_HOST_ABI = 13;
79
+
80
+ /**
81
+ * The device features three reads by name, as `tnw_web_device_feature`'s argument (web_host.cpp): every
82
+ * other name answers false, as a WebGPU GPUSupportedFeatures without it does.
83
+ */
84
+ const WEB_DEVICE_FEATURES: Readonly<Record<string, number>> = {
85
+ "core-features-and-limits": 0,
86
+ "indirect-first-instance": 1,
87
+ };
70
88
 
71
89
  /** The canvas key the host's surface looks up; Emscripten resolves it before any DOM query. */
72
90
  const CANVAS_TARGET = "!threenative-canvas";
@@ -82,7 +100,12 @@ const FAILED = 2;
82
100
  * `tnw_web_frame` field of the first named stage's segment (web_host.cpp): 19 + 4 shadow, scene, other and output
83
101
  * passes. `GPU_STAGES` counts on from there, one segment per stage.
84
102
  */
85
- const GPU_STAGE_FIELD = 23;
103
+ const GPU_STAGE_FIELD: number = WEB_FRAME_FIELD.gpuSegmentGather;
104
+
105
+ /** One number of the frame snapshot (`tnw_web_frame` 89), read in place at the block's index plus the field id. */
106
+ function frameField(heap: Float64Array, block: number, field: number): number {
107
+ return heap[block + field] ?? Number.NaN;
108
+ }
86
109
 
87
110
  interface IAdapterInfo {
88
111
  readonly vendor: string;
@@ -91,20 +114,6 @@ interface IAdapterInfo {
91
114
  readonly device: string;
92
115
  }
93
116
 
94
- /** three's Box2 and Box3 as a texture copy reads them: a region by its corners. */
95
- interface IRegionLike {
96
- readonly isBox3?: boolean;
97
- readonly min: { readonly x: number; readonly y: number; readonly z?: number };
98
- readonly max: { readonly x: number; readonly y: number; readonly z?: number };
99
- }
100
-
101
- /** A Vector2 or Vector3: the destination origin of a texture copy, z the array layer. */
102
- interface IPositionLike {
103
- readonly x: number;
104
- readonly y: number;
105
- readonly z?: number;
106
- }
107
-
108
117
  interface IColorLike {
109
118
  readonly r: number;
110
119
  readonly g: number;
@@ -147,7 +156,8 @@ function markBaked(environment: IBakedEnvironment): void {
147
156
  export function defineWebRenderer(
148
157
  module: WebEngineModule,
149
158
  Color: new (...args: unknown[]) => IColorLike,
150
- beforeRender: (frame?: INodeFrame) => void = () => {},
159
+ /** The frame hook: a draw passes its frame; a dispatch passes none, with its kernels' engine node ids. */
160
+ beforeRender: (frame?: INodeFrame, kernels?: readonly number[]) => void = () => {},
151
161
  tsl?: ITslRuntime,
152
162
  /** Draws the offscreen PassNodes into their targets (pass-node.ts); given the drawing buffer and the target draw. */
153
163
  drawSecondaryPasses: (
@@ -178,17 +188,11 @@ export function defineWebRenderer(
178
188
  const ref = typeof object === "object" && object !== null ? engineRef(object) : undefined;
179
189
  if (ref === undefined)
180
190
  throw new TypeError(`TN_WASM_RENDER: the ${what} is not an engine object.`);
181
- const [type, context, slot, generation] = ref.key.split(":").map(Number) as [
182
- number,
183
- number,
184
- number,
185
- number,
186
- ];
187
- const view = new DataView(module.HEAPU8.buffer);
188
- view.setUint16(handles + offset, type, true);
189
- view.setUint16(handles + offset + 2, context, true);
190
- view.setUint32(handles + offset + 4, slot, true);
191
- view.setUint32(handles + offset + 8, generation, true);
191
+ const { w0, w1, w2 } = packedRef(ref);
192
+ const view = new DataView(heapFor(module, handles + offset + 12).buffer);
193
+ view.setUint32(handles + offset, w0, true);
194
+ view.setUint32(handles + offset + 4, w1, true);
195
+ view.setUint32(handles + offset + 8, w2, true);
192
196
  };
193
197
 
194
198
  const Renderer = class WebGPURenderer {
@@ -197,7 +201,7 @@ export function defineWebRenderer(
197
201
  readonly supportsRetainedTargetSubrect = false;
198
202
  renderScale = 1;
199
203
  get temporalUpscale(): boolean {
200
- return module._tnw_web_frame(34) === 1;
204
+ return module._tnw_web_frame(WEB_FRAME_FIELD.temporalUpscale) === 1;
201
205
  }
202
206
  #stageMeters = true;
203
207
  /** Address of the host's stage-total array (`tnw_web_frame` 78), 0 until `init` asks. */
@@ -208,7 +212,7 @@ export function defineWebRenderer(
208
212
  */
209
213
  setStageMeters(enabled: boolean): void {
210
214
  this.#stageMeters = enabled;
211
- module._tnw_web_frame(enabled ? -3 : -4);
215
+ module._tnw_web_frame(enabled ? WEB_FRAME_FIELD.cpuMetersOn : WEB_FRAME_FIELD.cpuMetersOff);
212
216
  }
213
217
  setRenderScale(scale: number): void {
214
218
  if (!Number.isFinite(scale) || scale < 0.25 || scale > 1)
@@ -275,6 +279,10 @@ export function defineWebRenderer(
275
279
  // The GPU milliseconds of the sample `render.timestamp` reports, by named stage (gpu-stages.ts). A stage that
276
280
  // drew no pass is absent; core's `stageGpuReading` hands it to the GI and shadow budgets.
277
281
  gpuStages: {} as Record<string, number>,
282
+ // The same sample split by pass (frame_gpu_timer.h segments): the scene pass, every shadow map, and the rest
283
+ // (other passes, output, gather). `frame` is the sample's source frame, -1 until one resolves; core's
284
+ // `gpuFrameSample` hands the split to the frame budget's `gpuMain`, `gpuShadow` and `gpuOther`.
285
+ gpuSplit: { frame: -1, main: 0, shadow: 0, other: 0 },
278
286
  // The last frame's shadow passes, the spot and point light maps apart from the sun's (PRD-650):
279
287
  // lamp maps redrawn and their draws, every shadow draw (the sun's are the rest), and the GPU
280
288
  // milliseconds of each part in the sample `render.timestamp` reports, -1 until one resolves.
@@ -352,6 +360,11 @@ export function defineWebRenderer(
352
360
  trackTimestamp: boolean;
353
361
  getTimestampFrames(type: string): number[];
354
362
  pipelineCompiles(): number;
363
+ /**
364
+ * three's GPUSupportedFeatures.has, which core reads to gate its GPU world scene
365
+ * (world-gpu-scene.ts `gpuSceneUnsupported`): the device's own answer, asked of the host.
366
+ */
367
+ hasFeature(name: string): boolean;
355
368
  /** Resolves as three's GPUDevice.lost does once the host loses its device; core reports it (TN_DEVICE_LOST). */
356
369
  readonly device: {
357
370
  readonly lost: Promise<{ reason: string; message: string }>;
@@ -418,7 +431,11 @@ export function defineWebRenderer(
418
431
  },
419
432
  trackTimestamp: Boolean(parameters.trackTimestamp ?? true),
420
433
  getTimestampFrames: timestampFrames,
421
- pipelineCompiles: () => module._tnw_web_frame(2),
434
+ pipelineCompiles: () => module._tnw_web_frame(WEB_FRAME_FIELD.pipelineCompiles),
435
+ hasFeature(name: string): boolean {
436
+ const feature = WEB_DEVICE_FEATURES[name];
437
+ return feature !== undefined && module._tnw_web_device_feature(feature) === 1;
438
+ },
422
439
  device: {
423
440
  lost: new Promise((resolve) => {
424
441
  this.#deviceLost = resolve;
@@ -445,9 +462,7 @@ export function defineWebRenderer(
445
462
  throw new Error(
446
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`,
447
464
  );
448
- started = this.domElement;
449
465
  module.specialHTMLTargets[CANVAS_TARGET] = this.domElement;
450
- handles = module._malloc(36) >>> 0;
451
466
  const selector = string(CANVAS_TARGET);
452
467
  try {
453
468
  check(
@@ -456,6 +471,10 @@ export function defineWebRenderer(
456
471
  } finally {
457
472
  module._free(selector);
458
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;
459
478
  } else {
460
479
  // The disposed renderer's post graph must not outlive its game.
461
480
  tsl?.setPost(null);
@@ -476,8 +495,9 @@ export function defineWebRenderer(
476
495
  };
477
496
  // Honest, like the engine: a device without timestamp-query times no frame, so no caller
478
497
  // may be told timestamps are enabled. An explicit opt-out stays off.
479
- if (module._tnw_web_frame(10) === 0) this.backend.trackTimestamp = false;
480
- this.#stageBase = module._tnw_web_frame(78);
498
+ if (module._tnw_web_frame(WEB_FRAME_FIELD.gpuTimerAvailable) === 0)
499
+ this.backend.trackTimestamp = false;
500
+ this.#stageBase = module._tnw_web_frame(WEB_FRAME_FIELD.stageTotalsAddress);
481
501
  if (this.#stageBase > 0) {
482
502
  this.info.engine.cpuMs = Object.fromEntries(
483
503
  CPU_STAGE_ENTRIES.map(([name]) => [name, 0]),
@@ -487,7 +507,12 @@ export function defineWebRenderer(
487
507
  ) as Record<WorkCountName, number>;
488
508
  }
489
509
  return this;
490
- })();
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
+ });
491
516
  return this.#initialized;
492
517
  }
493
518
 
@@ -581,6 +606,20 @@ export function defineWebRenderer(
581
606
  }
582
607
  }
583
608
 
609
+ /**
610
+ * three's `hasFeature`, which KTX2Loader.detectSupport reads (PRD-867): the block formats the engine
611
+ * uploads on this device. BC7 answers from the device; ETC2 answers false until the engine uploads
612
+ * three's opaque `RGB_ETC2_Format`, which KTX2Loader picks there, so a KTX2 falls back to RGBA instead.
613
+ */
614
+ hasFeature(name: string): boolean {
615
+ if (this.#adapter === undefined)
616
+ throw new Error("TN_WASM_RENDERER: hasFeature() before init() finished.");
617
+ return (
618
+ name === "texture-compression-bc" &&
619
+ module._tnw_web_frame(WEB_FRAME_FIELD.textureCompressionBc) === 1
620
+ );
621
+ }
622
+
584
623
  render(scene: unknown, camera: unknown): void {
585
624
  if (this.#adapter === undefined)
586
625
  throw new Error("TN_WASM_RENDERER: render() before init() finished.");
@@ -593,7 +632,7 @@ export function defineWebRenderer(
593
632
  // texture already taken, so refusing it saves no frame and presents the world without it.
594
633
  // Measured on Lantern Vale: every cover over a drawn frame was refused, so the loading screen
595
634
  // flickered black for the whole environment bake and then showed the unfinished world.
596
- if (!this.#frameOpen && module._tnw_web_frame(11) === 1) {
635
+ if (!this.#frameOpen && module._tnw_web_frame(WEB_FRAME_FIELD.gpuBusy) === 1) {
597
636
  // A lost device leaves its frames on the GPU for good, so the gate declines every later frame
598
637
  // and no draw ever returns a status: name the loss here, where the frame poll just ran.
599
638
  if (this.#noticeLost()) return;
@@ -623,7 +662,11 @@ export function defineWebRenderer(
623
662
  const renderFrame = this.info.frame;
624
663
  if (debug !== undefined) {
625
664
  // Observation only: native captures this request with each submitted sample.
626
- module._tnw_web_frame(this.backend.trackTimestamp ? -1 : -2);
665
+ module._tnw_web_frame(
666
+ this.backend.trackTimestamp
667
+ ? WEB_FRAME_FIELD.debugTimestampOn
668
+ : WEB_FRAME_FIELD.debugTimestampOff,
669
+ );
627
670
  debug?.add(
628
671
  "gpuTimestampRequests",
629
672
  this.backend.trackTimestamp ? 1 : 0,
@@ -641,32 +684,42 @@ export function defineWebRenderer(
641
684
  ),
642
685
  );
643
686
  this.info.frame += 1;
644
- if (this.#bakingEnvironment !== undefined && module._tnw_web_frame(12) === 0) {
687
+ // PRD-878: one host call copies every number of the frame into a block, read in place below.
688
+ const block = module._tnw_web_frame(WEB_FRAME_FIELD.frameSnapshot) / 8;
689
+ const heap = module.HEAPF64; // after the call: a grown memory replaces the view
690
+ if (!this.#overlay)
691
+ reportVirtualShadowFrame(
692
+ frameField(heap, block, WEB_FRAME_FIELD.virtualShadowPendingLevels),
693
+ );
694
+ if (
695
+ this.#bakingEnvironment !== undefined &&
696
+ frameField(heap, block, WEB_FRAME_FIELD.environmentPending) === 0
697
+ ) {
645
698
  // An overlay draw has no environment and says nothing; another sky ends the watch.
646
699
  const drawnEnvironment = (scene as { environment?: unknown }).environment;
647
700
  if (drawnEnvironment === this.#bakingEnvironment) markBaked(this.#bakingEnvironment);
648
701
  if (drawnEnvironment != null) this.#bakingEnvironment = undefined;
649
702
  }
650
- this.info.render.frameCalls = module._tnw_web_frame(0);
703
+ this.info.render.frameCalls = frameField(heap, block, WEB_FRAME_FIELD.draws);
651
704
  this.info.render.calls += this.info.render.frameCalls;
652
705
  this.info.render.drawCalls += this.info.render.frameCalls;
653
- const lastTriangles = module._tnw_web_frame(1);
706
+ const lastTriangles = frameField(heap, block, WEB_FRAME_FIELD.triangles);
654
707
  this.info.render.triangles += lastTriangles;
655
708
  const shadows = this.info.engine.shadows;
656
- shadows.lampRedraws = module._tnw_web_frame(25);
657
- shadows.lampDraws = module._tnw_web_frame(26);
658
- shadows.shadowDraws = module._tnw_web_frame(27);
659
- shadows.lampMapMin = module._tnw_web_frame(28);
660
- shadows.lampMapMax = module._tnw_web_frame(29);
661
- shadows.keptMaps = module._tnw_web_frame(40);
662
- this.info.engine.uniformBytes = module._tnw_web_frame(41);
709
+ shadows.lampRedraws = frameField(heap, block, WEB_FRAME_FIELD.lampRedraws);
710
+ shadows.lampDraws = frameField(heap, block, WEB_FRAME_FIELD.lampShadowDraws);
711
+ shadows.shadowDraws = frameField(heap, block, WEB_FRAME_FIELD.shadowDraws);
712
+ shadows.lampMapMin = frameField(heap, block, WEB_FRAME_FIELD.lampMapMin);
713
+ shadows.lampMapMax = frameField(heap, block, WEB_FRAME_FIELD.lampMapMax);
714
+ shadows.keptMaps = frameField(heap, block, WEB_FRAME_FIELD.keptShadowMaps);
715
+ this.info.engine.uniformBytes = frameField(heap, block, WEB_FRAME_FIELD.uniformBytes);
663
716
  const split = this.info.engine.frameSplit;
664
717
  // Field 0 answers for the renderer that drew last and field 27 for the world's: an overlay has no shadow pass of its own.
665
718
  split.shadowDraws = this.#overlay ? 0 : shadows.shadowDraws;
666
- split.shadowTriangles = module._tnw_web_frame(85);
719
+ split.shadowTriangles = frameField(heap, block, WEB_FRAME_FIELD.shadowTriangles);
667
720
  split.mainDraws = this.info.render.frameCalls - split.shadowDraws;
668
721
  split.mainTriangles = lastTriangles - split.shadowTriangles;
669
- const gpuSamples = module._tnw_web_frame(8);
722
+ const gpuSamples = frameField(heap, block, WEB_FRAME_FIELD.gpuSamples);
670
723
  if (gpuSamples > this.#gpuSamples) {
671
724
  debug?.add(
672
725
  "gpuTimestampSamples",
@@ -675,51 +728,77 @@ export function defineWebRenderer(
675
728
  "native timestamp readback",
676
729
  );
677
730
  this.#gpuSamples = gpuSamples;
678
- const gpuMs = module._tnw_web_frame(7);
731
+ const gpuMs = frameField(heap, block, WEB_FRAME_FIELD.gpuMs);
679
732
  // The engine reports which submitted frame this sample belongs to; the readback can land
680
733
  // many frames later, so the arrival frame is never the sample's age.
681
734
  if (Number.isFinite(gpuMs) && gpuMs > 0) {
682
735
  this.info.render.timestamp = gpuMs;
683
- this.#timestampFrames = [module._tnw_web_frame(9)];
736
+ this.#timestampFrames = [frameField(heap, block, WEB_FRAME_FIELD.gpuSourceFrame)];
684
737
  const stages: Record<string, number> = {};
685
738
  GPU_STAGES.forEach((name, index) => {
686
- const stageMs = module._tnw_web_frame(GPU_STAGE_FIELD + index);
739
+ const stageMs = frameField(heap, block, GPU_STAGE_FIELD + index);
687
740
  if (stageMs > 0) stages[name] = stageMs;
688
741
  });
689
- const shadowMs = module._tnw_web_frame(SHADOW_SEGMENT_FIELD);
742
+ const shadowMs = frameField(heap, block, SHADOW_SEGMENT_FIELD);
690
743
  if (shadowMs > 0) stages[SHADOW_STAGE] = shadowMs;
691
744
  this.info.engine.gpuStages = stages;
692
- this.info.engine.shadows.sunGpuMs = module._tnw_web_frame(19);
693
- this.info.engine.shadows.lampGpuMs = module._tnw_web_frame(24);
745
+ this.info.engine.shadows.sunGpuMs = frameField(
746
+ heap,
747
+ block,
748
+ WEB_FRAME_FIELD.gpuSegmentShadow,
749
+ );
750
+ this.info.engine.shadows.lampGpuMs = frameField(
751
+ heap,
752
+ block,
753
+ WEB_FRAME_FIELD.gpuSegmentLampShadow,
754
+ );
755
+ const segment = (field: number): number => Math.max(0, frameField(heap, block, field));
756
+ const split = this.info.engine.gpuSplit;
757
+ split.frame = this.#timestampFrames[0] ?? -1;
758
+ split.main = segment(WEB_FRAME_FIELD.gpuSegmentScene);
759
+ split.shadow =
760
+ segment(WEB_FRAME_FIELD.gpuSegmentShadow) +
761
+ segment(WEB_FRAME_FIELD.gpuSegmentLampShadow);
762
+ split.other =
763
+ segment(WEB_FRAME_FIELD.gpuSegmentOther) +
764
+ segment(WEB_FRAME_FIELD.gpuSegmentOutput) +
765
+ segment(WEB_FRAME_FIELD.gpuSegmentGather);
694
766
  // Opt-in, as `__tnPassLog`: a probe that sets `__tnGpuSegments` to an array gets each resolved sample's
695
767
  // split (frame_gpu_timer.h segments: sun shadow, scene, other passes, output, gather, lamp shadow).
696
768
  (globalThis as { __tnGpuSegments?: number[][] }).__tnGpuSegments?.push([
697
769
  gpuMs,
698
- ...[19, 20, 21, 22, 23, 24].map((field) => module._tnw_web_frame(field)),
770
+ ...[
771
+ WEB_FRAME_FIELD.gpuSegmentShadow,
772
+ WEB_FRAME_FIELD.gpuSegmentScene,
773
+ WEB_FRAME_FIELD.gpuSegmentOther,
774
+ WEB_FRAME_FIELD.gpuSegmentOutput,
775
+ WEB_FRAME_FIELD.gpuSegmentGather,
776
+ WEB_FRAME_FIELD.gpuSegmentLampShadow,
777
+ ].map((field) => frameField(heap, block, field)),
699
778
  ]);
700
779
  }
701
780
  }
702
781
  const engine = this.info.engine;
703
- engine.compiles = module._tnw_web_frame(2);
704
- engine.textLookups = module._tnw_web_frame(3);
705
- engine.bindGroups = module._tnw_web_frame(4);
706
- engine.graphKeys = module._tnw_web_frame(5);
707
- engine.programs = module._tnw_web_frame(6);
782
+ engine.compiles = frameField(heap, block, WEB_FRAME_FIELD.pipelineCompiles);
783
+ engine.textLookups = frameField(heap, block, WEB_FRAME_FIELD.pipelineLookups);
784
+ engine.bindGroups = frameField(heap, block, WEB_FRAME_FIELD.bindGroupsCreated);
785
+ engine.graphKeys = frameField(heap, block, WEB_FRAME_FIELD.graphKeyBuilds);
786
+ engine.programs = frameField(heap, block, WEB_FRAME_FIELD.programs);
708
787
  const temporal = engine.temporal;
709
- temporal.active = module._tnw_web_frame(13) === 1;
710
- temporal.frame = module._tnw_web_frame(14);
711
- temporal.historyValid = module._tnw_web_frame(15) === 1;
712
- temporal.jitter[0] = module._tnw_web_frame(16);
713
- temporal.jitter[1] = module._tnw_web_frame(17);
714
- temporal.rejected = module._tnw_web_frame(30);
715
- temporal.clamped = module._tnw_web_frame(31);
716
- temporal.pixels = module._tnw_web_frame(32);
717
- temporal.countedFrame = module._tnw_web_frame(33);
718
- temporal.inputWidth = module._tnw_web_frame(35);
719
- temporal.inputHeight = module._tnw_web_frame(36);
720
- temporal.jitterLength = module._tnw_web_frame(37);
721
- temporal.outputWidth = module._tnw_web_frame(38);
722
- temporal.outputHeight = module._tnw_web_frame(39);
788
+ temporal.active = frameField(heap, block, WEB_FRAME_FIELD.temporalActive) === 1;
789
+ temporal.frame = frameField(heap, block, WEB_FRAME_FIELD.temporalFrame);
790
+ temporal.historyValid = frameField(heap, block, WEB_FRAME_FIELD.temporalHistoryValid) === 1;
791
+ temporal.jitter[0] = frameField(heap, block, WEB_FRAME_FIELD.temporalJitterX);
792
+ temporal.jitter[1] = frameField(heap, block, WEB_FRAME_FIELD.temporalJitterY);
793
+ temporal.rejected = frameField(heap, block, WEB_FRAME_FIELD.temporalRejected);
794
+ temporal.clamped = frameField(heap, block, WEB_FRAME_FIELD.temporalClamped);
795
+ temporal.pixels = frameField(heap, block, WEB_FRAME_FIELD.temporalPixels);
796
+ temporal.countedFrame = frameField(heap, block, WEB_FRAME_FIELD.temporalCountedFrame);
797
+ temporal.inputWidth = frameField(heap, block, WEB_FRAME_FIELD.inputWidth);
798
+ temporal.inputHeight = frameField(heap, block, WEB_FRAME_FIELD.inputHeight);
799
+ temporal.jitterLength = frameField(heap, block, WEB_FRAME_FIELD.temporalJitterLength);
800
+ temporal.outputWidth = frameField(heap, block, WEB_FRAME_FIELD.width);
801
+ temporal.outputHeight = frameField(heap, block, WEB_FRAME_FIELD.height);
723
802
  if (debug !== undefined && temporal.active) {
724
803
  // The native renderer counts the active/history/rejected/clamped pixel totals under these
725
804
  // exact names (foundation/waste_counters.h, renderer.cpp); a JS series beside them would be
@@ -728,12 +807,11 @@ export function defineWebRenderer(
728
807
  debug.add("temporalInputPixels", temporal.inputWidth * temporal.inputHeight, "temporal");
729
808
  debug.add("temporalOutputPixels", temporal.outputWidth * temporal.outputHeight, "temporal");
730
809
  }
731
- engine.samples = module._tnw_web_frame(18);
810
+ engine.samples = frameField(heap, block, WEB_FRAME_FIELD.sampleCount);
732
811
  const cpu = engine.cpuMs;
733
812
  const work = engine.work;
734
813
  if (this.#stageMeters && cpu !== undefined && work !== undefined) {
735
814
  // In place, from the array the host fills at the end of every render: the ABI census above stays as it was.
736
- const heap = module.HEAPF64;
737
815
  const first = this.#stageBase / 8;
738
816
  for (let index = 0; index < CPU_STAGE_ENTRIES.length; index += 1)
739
817
  cpu[(CPU_STAGE_ENTRIES[index] as readonly [CpuStageName, number])[0]] =
@@ -743,19 +821,21 @@ export function defineWebRenderer(
743
821
  heap[first + CPU_STAGE_ENTRIES.length + index] ?? 0;
744
822
  }
745
823
  const passes = engine.passes;
746
- passes.mainRecorded = module._tnw_web_frame(60);
747
- passes.recordCause = module._tnw_web_frame(61);
748
- passes.auxRecorded = module._tnw_web_frame(62);
749
- passes.recordMs = module._tnw_web_frame(63);
750
- passes.shadowEncodeMs = module._tnw_web_frame(64);
751
- passes.shadowRecorded = module._tnw_web_frame(65);
824
+ passes.mainRecorded = frameField(heap, block, WEB_FRAME_FIELD.mainRecorded);
825
+ passes.recordCause = frameField(heap, block, WEB_FRAME_FIELD.recordCause);
826
+ passes.auxRecorded = frameField(heap, block, WEB_FRAME_FIELD.auxRecorded);
827
+ passes.recordMs = frameField(heap, block, WEB_FRAME_FIELD.recordMs);
828
+ passes.shadowEncodeMs = frameField(heap, block, WEB_FRAME_FIELD.shadowEncodeMs);
829
+ passes.shadowRecorded = frameField(heap, block, WEB_FRAME_FIELD.shadowRecorded);
752
830
  // The startup's own report, read only while the cover is up so a held frame sees the one it just made. After
753
831
  // the release nothing reads it, so a steady frame pays no host call for it and the last values stand.
754
832
  if (this.#presentationHeld) {
755
- engine.startup.worldSubmissions = module._tnw_web_frame(71);
756
- engine.startup.shadowInputsReady = module._tnw_web_frame(72) === 1;
833
+ engine.startup.worldSubmissions = frameField(heap, block, WEB_FRAME_FIELD.worldSubmissions);
834
+ engine.startup.shadowInputsReady =
835
+ frameField(heap, block, WEB_FRAME_FIELD.shadowInputsReady) === 1;
757
836
  } else if (!engine.startup.worldPresented) {
758
- engine.startup.worldPresented = module._tnw_web_frame(86) === 1;
837
+ engine.startup.worldPresented =
838
+ module._tnw_web_frame(WEB_FRAME_FIELD.firstWorldFrameDrawn) === 1;
759
839
  }
760
840
  // Opt-in, as `__tnCallCounts`: a probe that sets `__tnPassLog` to an array gets every frame's counters.
761
841
  (globalThis as { __tnPassLog?: unknown[] }).__tnPassLog?.push({ ...passes });
@@ -798,7 +878,13 @@ export function defineWebRenderer(
798
878
  * render() while a render target is set (render-target.ts): draws into the target. `deferred` (an offscreen PassNode)
799
879
  * plans the draw and has the engine record it in the frame that samples the target.
800
880
  */
801
- [DRAW_TARGET](target: unknown, root: unknown, camera: unknown, deferred = false): void {
881
+ [DRAW_TARGET](
882
+ target: unknown,
883
+ root: unknown,
884
+ camera: unknown,
885
+ deferred = false,
886
+ layer = 0,
887
+ ): void {
802
888
  if (this.#adapter === undefined)
803
889
  throw new Error("TN_WASM_RENDERER: render() before init() finished.");
804
890
  if (this.#lost) return;
@@ -814,7 +900,8 @@ export function defineWebRenderer(
814
900
  handles,
815
901
  handles + 12,
816
902
  ...this.#clear,
817
- (deferred ? 1 : 0) | (this.autoClear ? 0 : 2),
903
+ // Bits 8 and up: the layer of an array target (tnw_web_render_target).
904
+ (deferred ? 1 : 0) | (this.autoClear ? 0 : 2) | (layer << 8),
818
905
  ),
819
906
  );
820
907
  }
@@ -1001,14 +1088,15 @@ export function defineWebRenderer(
1001
1088
  throw new Error(
1002
1089
  "TN_COMPUTE_DISPATCH_SIZE: renderer.compute(nodes, dispatchSize) is not available on the Wasm engine; give the node its count.",
1003
1090
  );
1004
- beforeRender();
1005
- for (const node of Array.isArray(computeNodes) ? computeNodes : [computeNodes]) {
1091
+ const kernels = (Array.isArray(computeNodes) ? computeNodes : [computeNodes]).map((node) => {
1006
1092
  if (!isTslNode(node))
1007
1093
  throw new TypeError(
1008
1094
  "TN_COMPUTE_NODE: renderer.compute takes the node Fn(() => { ... })().compute(count) makes",
1009
1095
  );
1010
- tsl.compute(node[TSL_NODE]);
1011
- }
1096
+ return node[TSL_NODE];
1097
+ });
1098
+ beforeRender(undefined, kernels);
1099
+ for (const kernel of kernels) tsl.compute(kernel);
1012
1100
  }
1013
1101
 
1014
1102
  async computeAsync(computeNodes: unknown, dispatchSize: unknown = null): Promise<void> {
@@ -1075,25 +1163,11 @@ export function defineWebRenderer(
1075
1163
  throw new Error("TN_WASM_RENDERER: copyTextureToTexture() before init() finished.");
1076
1164
  writeHandle(0, source, "source texture");
1077
1165
  writeHandle(12, destination, "destination texture");
1078
- const { min, max } = srcRegion ?? {};
1079
- // A Box2 has no z: its depth is one layer, a Box3's its own.
1080
- const size =
1081
- min && max ? [max.x - min.x, max.y - min.y, (max.z ?? 1) - (min.z ?? 0)] : [-1, -1, 1];
1082
1166
  check(
1083
1167
  module._tnw_web_copy_texture(
1084
1168
  handles,
1085
1169
  handles + 12,
1086
- min?.x ?? 0,
1087
- min?.y ?? 0,
1088
- min?.z ?? 0,
1089
- size[0] as number,
1090
- size[1] as number,
1091
- srcRegion?.isBox3 ? (size[2] as number) : 1,
1092
- dstPosition?.x ?? 0,
1093
- dstPosition?.y ?? 0,
1094
- dstPosition?.z ?? 0,
1095
- srcLevel,
1096
- dstLevel,
1170
+ ...textureCopyArguments(srcRegion, dstPosition, srcLevel, dstLevel),
1097
1171
  ),
1098
1172
  );
1099
1173
  }
@@ -1126,7 +1200,7 @@ export function defineWebRenderer(
1126
1200
  for (;;) {
1127
1201
  module._tnw_web_poll();
1128
1202
  const status = module._tnw_web_read_target_take(id, out, size);
1129
- if (status === 1) return module.HEAPU8.slice(out, out + size);
1203
+ if (status === 1) return heapFor(module, out + size).slice(out, out + size);
1130
1204
  // A read the lost device dropped says so, so the caller's report is read as that one loss.
1131
1205
  if (status < 0)
1132
1206
  throw new Error(
@@ -1196,7 +1270,9 @@ export function defineWebRenderer(
1196
1270
  module._tnw_web_poll();
1197
1271
  const status = module._tnw_web_read_target_take(id, out, bytes);
1198
1272
  if (status === 1)
1199
- 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
+ );
1200
1276
  if (status < 0) throw new Error("TN_REFLECTION_CAPTURE_READ");
1201
1277
  await new Promise((resolve) => setTimeout(resolve, 0));
1202
1278
  }
@@ -1208,12 +1284,12 @@ export function defineWebRenderer(
1208
1284
  ),
1209
1285
  });
1210
1286
  defineRenderTargets(Renderer.prototype, (renderer) => ({
1211
- draw: (target, root, camera) =>
1212
- (renderer as { [DRAW_TARGET](t: unknown, r: unknown, c: unknown): void })[DRAW_TARGET](
1213
- target,
1214
- root,
1215
- camera,
1216
- ),
1287
+ draw: (target, root, camera, layer) =>
1288
+ (
1289
+ renderer as {
1290
+ [DRAW_TARGET](t: unknown, r: unknown, c: unknown, d: boolean, l: number): void;
1291
+ }
1292
+ )[DRAW_TARGET](target, root, camera, false, layer),
1217
1293
  clear: (target, color, depth) =>
1218
1294
  (renderer as { [CLEAR_TARGET](t: unknown, c: boolean, d: boolean): void })[CLEAR_TARGET](
1219
1295
  target,