@threenative/three-native 0.0.0-stage → 0.3.6

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.
Files changed (45) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +24 -2
  3. package/package.json +42 -3
  4. package/src/addons/buffer-geometry-utils.ts +14 -0
  5. package/src/addons/data-utils.ts +63 -0
  6. package/src/addons/decal-geometry.ts +25 -0
  7. package/src/addons/decal.ts +218 -0
  8. package/src/addons/gltf-loader-web.ts +323 -0
  9. package/src/addons/hdr-loader.ts +71 -0
  10. package/src/addons/hdr.ts +139 -0
  11. package/src/addons/lut-cube-loader-web.ts +17 -0
  12. package/src/addons/lut-cube-loader.ts +149 -0
  13. package/src/addons/merge-geometries.ts +374 -0
  14. package/src/addons/mesh-bvh-webgpu.ts +13 -0
  15. package/src/addons/mesh-bvh.ts +50 -0
  16. package/src/addons/post-effects-web.ts +22 -0
  17. package/src/addons/post-effects.ts +173 -0
  18. package/src/audio.ts +564 -0
  19. package/src/blend-mode.ts +33 -0
  20. package/src/browser-backend.ts +2156 -0
  21. package/src/browser-entry.ts +305 -0
  22. package/src/browser-math.ts +448 -0
  23. package/src/browser-renderer.ts +527 -0
  24. package/src/browser-tsl.ts +650 -0
  25. package/src/catalog.ts +497 -0
  26. package/src/fixture-format.ts +721 -0
  27. package/src/fixture-native.ts +426 -0
  28. package/src/fixture-protocol.ts +315 -0
  29. package/src/math-utils.ts +65 -0
  30. package/src/object-surface.ts +250 -0
  31. package/src/pass-node.ts +286 -0
  32. package/src/property-binding.ts +93 -0
  33. package/src/quad-mesh.ts +54 -0
  34. package/src/reflector.ts +89 -0
  35. package/src/refused.ts +27 -0
  36. package/src/render-target.ts +107 -0
  37. package/src/rtt.ts +158 -0
  38. package/src/shadow-map.ts +21 -0
  39. package/src/storage.ts +206 -0
  40. package/src/texture-sources.ts +252 -0
  41. package/src/tsl-extras.ts +51 -0
  42. package/src/tsl-struct.ts +20 -0
  43. package/src/tsl-uniforms.ts +234 -0
  44. package/src/update-ranges.ts +109 -0
  45. package/src/wgsl-fn.ts +55 -0
@@ -0,0 +1,527 @@
1
+ /**
2
+ * `WebGPURenderer` on the Wasm engine (PRD-540): three's renderer surface over the product host
3
+ * (`packages/runtime-native/src/engine/wasm/web_host.cpp`). The engine owns the device, the canvas
4
+ * surface and every draw; this class turns three's calls into host calls and reports what the
5
+ * engine did. What it does not implement throws its diagnostic rather than doing nothing.
6
+ */
7
+ import { TSL_NODE, type TnAbiModule, engineRef } from "./browser-backend.js";
8
+ import { type ITslRuntime, isTslNode } from "./browser-tsl.js";
9
+ import type { PassDraw } from "./pass-node.js";
10
+ import { defineRenderTargets } from "./render-target.js";
11
+ import { ShadowMap } from "./shadow-map.js";
12
+ import { readStorageBytes } from "./storage.js";
13
+
14
+ /** The product host's exports beside the catalog ABI (all numbers: pointers, sizes, status). */
15
+ type HostCall =
16
+ | "_tnw_web_init"
17
+ | "_tnw_web_poll"
18
+ | "_tnw_web_error"
19
+ | "_tnw_web_adapter"
20
+ | "_tnw_web_resize"
21
+ | "_tnw_web_render"
22
+ | "_tnw_web_renderer_state"
23
+ | "_tnw_web_frame"
24
+ | "_tnw_web_render_target"
25
+ | "_tnw_web_read_target"
26
+ | "_tnw_web_read_target_take";
27
+
28
+ export type WebHostModule = Record<HostCall, (...args: number[]) => number> & {
29
+ readonly specialHTMLTargets: Record<string, unknown>;
30
+ };
31
+
32
+ export type WebEngineModule = TnAbiModule & WebHostModule;
33
+
34
+ export function isWebHostModule(module: TnAbiModule): module is WebEngineModule {
35
+ return typeof (module as Partial<WebHostModule>)._tnw_web_init === "function";
36
+ }
37
+
38
+ /** The canvas key the host's surface looks up; Emscripten resolves it before any DOM query. */
39
+ const CANVAS_TARGET = "!threenative-canvas";
40
+ const READY = 1;
41
+ /** The facade's own redraw, for RenderPipeline (browser-entry.ts). */
42
+ export const RENDER_AGAIN = Symbol("tn.renderAgain");
43
+ const DRAW_TARGET = Symbol("tn.drawTarget");
44
+ const FAILED = 2;
45
+
46
+ interface IAdapterInfo {
47
+ readonly vendor: string;
48
+ readonly architecture: string;
49
+ readonly description: string;
50
+ readonly device: string;
51
+ }
52
+
53
+ interface IColorLike {
54
+ readonly r: number;
55
+ readonly g: number;
56
+ readonly b: number;
57
+ }
58
+
59
+ function unsupported(name: string): never {
60
+ throw new Error(`TN_NATIVE_UNSUPPORTED_${name.toUpperCase()}: not available on the Wasm engine.`);
61
+ }
62
+
63
+ /** Defines the renderer class over one loaded module; the module owns one device and one canvas. */
64
+ export function defineWebRenderer(
65
+ module: WebEngineModule,
66
+ Color: new (...args: unknown[]) => IColorLike,
67
+ beforeRender: (frame?: { camera?: unknown; scene?: unknown }) => void = () => {},
68
+ tsl?: ITslRuntime,
69
+ /** Draws the offscreen PassNodes into their targets (pass-node.ts); given the drawing buffer and the target draw. */
70
+ drawSecondaryPasses: (
71
+ surface: () => { width: number; height: number },
72
+ draw: PassDraw,
73
+ ) => void = () => {},
74
+ ): new (
75
+ parameters?: Record<string, unknown>,
76
+ ) => object {
77
+ let claimed = false;
78
+ // The engine starts once per page: one device, and one surface bound to the first renderer's canvas.
79
+ // A renderer built after that one was disposed (a hot update re-runs the game) adopts both.
80
+ let started: HTMLCanvasElement | undefined;
81
+ const string = (text: string): number => {
82
+ const bytes = module.lengthBytesUTF8(text) + 1;
83
+ const pointer = module._malloc(bytes) >>> 0;
84
+ module.stringToUTF8(text, pointer, bytes);
85
+ return pointer;
86
+ };
87
+ const check = (status: number): void => {
88
+ if (status !== 0) throw new Error(module.UTF8ToString(module._tnw_web_error()));
89
+ };
90
+ // Three tn_handle_t (12 bytes each): the scene, the camera and the render target of the current call.
91
+ let handles = 0;
92
+ const writeHandle = (offset: number, object: unknown, what: string): void => {
93
+ const ref = typeof object === "object" && object !== null ? engineRef(object) : undefined;
94
+ if (ref === undefined)
95
+ throw new TypeError(`TN_WASM_RENDER: the ${what} is not an engine object.`);
96
+ const [type, context, slot, generation] = ref.key.split(":").map(Number) as [
97
+ number,
98
+ number,
99
+ number,
100
+ number,
101
+ ];
102
+ const view = new DataView(module.HEAPU8.buffer);
103
+ view.setUint16(handles + offset, type, true);
104
+ view.setUint16(handles + offset + 2, context, true);
105
+ view.setUint32(handles + offset + 4, slot, true);
106
+ view.setUint32(handles + offset + 8, generation, true);
107
+ };
108
+
109
+ const Renderer = class WebGPURenderer {
110
+ readonly isWebGPURenderer = true;
111
+ /** The native scene pass draws to the surface; there is no frame RenderTarget to retain. */
112
+ readonly supportsRetainedTargetSubrect = false;
113
+ readonly domElement: HTMLCanvasElement;
114
+ readonly info = {
115
+ autoReset: true,
116
+ frame: 0,
117
+ calls: 0,
118
+ render: { calls: 0, drawCalls: 0, frameCalls: 0, triangles: 0, timestamp: 0 },
119
+ compute: { calls: 0, frameCalls: 0, timestamp: 0 },
120
+ memory: { geometries: 0, textures: 0 },
121
+ // Not three's: the setup work the engine has done so far. A steady frame adds none of it, so a
122
+ // playtest holds each count still across frames (examples/wasm-engine-boot renderer scenario).
123
+ // `frameGateSkips` is the exception: render() calls the frame gate declined, which only grows.
124
+ engine: {
125
+ compiles: 0,
126
+ textLookups: 0,
127
+ bindGroups: 0,
128
+ graphKeys: 0,
129
+ programs: 0,
130
+ frameGateSkips: 0,
131
+ },
132
+ reset(): void {},
133
+ };
134
+ /** three's WebGPURenderer: `antialias` is 4x MSAA, `samples` 0 or 1 is none; the engine draws 1 or 4. */
135
+ readonly samples: number;
136
+ autoClear = true;
137
+ toneMapping = 0;
138
+ toneMappingExposure = 1;
139
+ outputColorSpace = "srgb";
140
+ readonly shadowMap = new ShadowMap();
141
+ /**
142
+ * What core reads to name the adapter: the engine's own device, not a second request. `pipelineCompiles`
143
+ * is the engine's own pipeline cache count, as the V8 player's facade exposes it to the bench harness.
144
+ */
145
+ readonly backend: {
146
+ readonly gpu: { requestAdapter(): Promise<{ info: IAdapterInfo }> };
147
+ trackTimestamp: boolean;
148
+ getTimestampFrames(type: string): number[];
149
+ pipelineCompiles(): number;
150
+ };
151
+ #pixelRatio = 1;
152
+ #width: number;
153
+ #height: number;
154
+ #clear: [number, number, number, number] = [0, 0, 0, 1];
155
+ #initialized: Promise<this> | undefined;
156
+ #adapter: IAdapterInfo | undefined;
157
+ #last: [unknown, unknown] | undefined;
158
+ #state: string | undefined;
159
+ #gpuSamples = 0;
160
+ #holdsSlot = true;
161
+ #timestampFrames: number[] = [];
162
+
163
+ constructor(parameters: Record<string, unknown> = {}) {
164
+ if (claimed)
165
+ throw new Error("TN_WASM_RENDERER_SINGLE: the Wasm engine drives one renderer per page.");
166
+ claimed = true;
167
+ // The surface cannot move to another canvas, so the engine's own canvas stays the one core mounts
168
+ // (it mounts `renderer.domElement`, not the canvas it asked for).
169
+ this.domElement =
170
+ started ??
171
+ (parameters.canvas as HTMLCanvasElement | undefined) ??
172
+ document.createElement("canvas");
173
+ // three's WebGPURenderer marks its canvas `three.js r<rev> webgpu`; tools read the backend there.
174
+ this.domElement.setAttribute("data-engine", "threenative wasm webgpu");
175
+ const samples = parameters.samples ?? (parameters.antialias ? 4 : 1);
176
+ this.samples = Math.max(1, Number(samples));
177
+ this.#width = this.domElement.width || 300;
178
+ this.#height = this.domElement.height || 150;
179
+ const adapter = () => this.#adapter;
180
+ const timestampFrames = (type: string) => (type === "render" ? this.#timestampFrames : []);
181
+ this.backend = {
182
+ gpu: {
183
+ async requestAdapter() {
184
+ const info = adapter();
185
+ if (info === undefined) throw new Error("TN_WASM_RENDERER: init() has not finished.");
186
+ return { info };
187
+ },
188
+ },
189
+ trackTimestamp: Boolean(parameters.trackTimestamp ?? true),
190
+ getTimestampFrames: timestampFrames,
191
+ pipelineCompiles: () => module._tnw_web_frame(2),
192
+ };
193
+ }
194
+
195
+ init(): Promise<this> {
196
+ this.#initialized ??= (async () => {
197
+ if (started === undefined) {
198
+ started = this.domElement;
199
+ module.specialHTMLTargets[CANVAS_TARGET] = this.domElement;
200
+ handles = module._malloc(36) >>> 0;
201
+ const selector = string(CANVAS_TARGET);
202
+ try {
203
+ check(module._tnw_web_init(selector, this.#drawWidth(), this.#drawHeight()));
204
+ } finally {
205
+ module._free(selector);
206
+ }
207
+ } else {
208
+ // The disposed renderer's post graph must not outlive its game.
209
+ tsl?.setPost(null);
210
+ }
211
+ for (;;) {
212
+ const state = module._tnw_web_poll();
213
+ if (state === READY) break;
214
+ if (state === FAILED) check(1);
215
+ await new Promise((resolve) => setTimeout(resolve, 0));
216
+ }
217
+ const field = (index: number) => module.UTF8ToString(module._tnw_web_adapter(index));
218
+ this.#adapter = {
219
+ vendor: field(0),
220
+ architecture: field(1),
221
+ description: field(2),
222
+ device: field(2),
223
+ };
224
+ // Honest, like the engine: a device without timestamp-query times no frame, so no caller
225
+ // may be told timestamps are enabled. An explicit opt-out stays off.
226
+ if (module._tnw_web_frame(10) === 0) this.backend.trackTimestamp = false;
227
+ return this;
228
+ })();
229
+ return this.#initialized;
230
+ }
231
+
232
+ #drawWidth(): number {
233
+ return Math.max(1, Math.floor(this.#width * this.#pixelRatio));
234
+ }
235
+
236
+ #drawHeight(): number {
237
+ return Math.max(1, Math.floor(this.#height * this.#pixelRatio));
238
+ }
239
+
240
+ #resize(): void {
241
+ this.domElement.width = this.#drawWidth();
242
+ this.domElement.height = this.#drawHeight();
243
+ if (handles !== 0) check(module._tnw_web_resize(this.#drawWidth(), this.#drawHeight()));
244
+ }
245
+
246
+ setSize(width: number, height: number, updateStyle = true): void {
247
+ this.#width = width;
248
+ this.#height = height;
249
+ if (updateStyle) {
250
+ this.domElement.style.width = `${width}px`;
251
+ this.domElement.style.height = `${height}px`;
252
+ }
253
+ this.#resize();
254
+ }
255
+
256
+ getSize<T extends { set(x: number, y: number): T }>(target: T): T {
257
+ return target.set(this.#width, this.#height);
258
+ }
259
+
260
+ setPixelRatio(ratio = 1): void {
261
+ this.#pixelRatio = ratio;
262
+ this.#resize();
263
+ }
264
+
265
+ getPixelRatio(): number {
266
+ return this.#pixelRatio;
267
+ }
268
+
269
+ getDrawingBufferSize<T extends { set(x: number, y: number): T }>(target: T): T {
270
+ return target.set(this.#drawWidth(), this.#drawHeight());
271
+ }
272
+
273
+ setClearColor(color: unknown, alpha = 1): void {
274
+ const value = (
275
+ typeof color === "object" && color !== null ? color : new Color(color)
276
+ ) as IColorLike;
277
+ this.#clear = [value.r, value.g, value.b, alpha];
278
+ }
279
+
280
+ getClearAlpha(): number {
281
+ return this.#clear[3];
282
+ }
283
+
284
+ setClearAlpha(alpha: number): void {
285
+ this.#clear[3] = alpha;
286
+ }
287
+
288
+ render(scene: unknown, camera: unknown): void {
289
+ if (this.#adapter === undefined)
290
+ throw new Error("TN_WASM_RENDERER: render() before init() finished.");
291
+ // Chromium queues a submitted frame without bound. When rAF outruns the GPU (an unthrottled
292
+ // loop, a heavy scene) the page blocks until the GPU drains and the GPU process is killed.
293
+ // The host says 1 while two drawn frames are still on the GPU: draw nothing this call.
294
+ if (module._tnw_web_frame(11) === 1) {
295
+ // Counted, never hidden: the loop's render phase for this frame is near zero, and a meter that
296
+ // averages it with drawn frames reads cheaper than the work that was done (core's `renderSkips`).
297
+ this.info.engine.frameGateSkips += 1;
298
+ return;
299
+ }
300
+ beforeRender({ camera, scene });
301
+ drawSecondaryPasses(
302
+ () => ({ width: this.#drawWidth(), height: this.#drawHeight() }),
303
+ (target, root, view) => this[DRAW_TARGET](target, root, view, true),
304
+ );
305
+ this.#last = [scene, camera];
306
+ this.#applyState();
307
+ writeHandle(0, scene, "scene");
308
+ writeHandle(12, camera, "camera");
309
+ const renderFrame = this.info.frame;
310
+ check(module._tnw_web_render(handles, handles + 12, ...this.#clear, renderFrame));
311
+ this.info.frame += 1;
312
+ this.info.render.frameCalls = module._tnw_web_frame(0);
313
+ this.info.render.calls += this.info.render.frameCalls;
314
+ this.info.render.drawCalls = this.info.render.frameCalls;
315
+ this.info.render.triangles = module._tnw_web_frame(1);
316
+ const gpuSamples = module._tnw_web_frame(8);
317
+ if (gpuSamples > this.#gpuSamples) {
318
+ this.#gpuSamples = gpuSamples;
319
+ const gpuMs = module._tnw_web_frame(7);
320
+ // The engine reports which submitted frame this sample belongs to; the readback can land
321
+ // many frames later, so the arrival frame is never the sample's age.
322
+ if (Number.isFinite(gpuMs) && gpuMs > 0) {
323
+ this.info.render.timestamp = gpuMs;
324
+ this.#timestampFrames = [module._tnw_web_frame(9)];
325
+ }
326
+ }
327
+ const engine = this.info.engine;
328
+ engine.compiles = module._tnw_web_frame(2);
329
+ engine.textLookups = module._tnw_web_frame(3);
330
+ engine.bindGroups = module._tnw_web_frame(4);
331
+ engine.graphKeys = module._tnw_web_frame(5);
332
+ engine.programs = module._tnw_web_frame(6);
333
+ }
334
+
335
+ /** three's output and shadow settings, handed to the engine when they change. */
336
+ #applyState(): void {
337
+ const { toneMapping, toneMappingExposure, outputColorSpace, shadowMap, samples } = this;
338
+ const key = `${toneMapping}|${toneMappingExposure}|${outputColorSpace}|${shadowMap.enabled}|${shadowMap.type}|${samples}`;
339
+ if (key === this.#state) return;
340
+ const space = string(String(outputColorSpace));
341
+ try {
342
+ check(
343
+ module._tnw_web_renderer_state(
344
+ toneMapping,
345
+ toneMappingExposure,
346
+ space,
347
+ shadowMap.enabled ? 1 : 0,
348
+ shadowMap.type,
349
+ samples,
350
+ ),
351
+ );
352
+ } finally {
353
+ module._free(space);
354
+ }
355
+ this.#state = key;
356
+ }
357
+
358
+ /**
359
+ * render() while a render target is set (render-target.ts): draws into the target. `deferred` (an offscreen PassNode)
360
+ * plans the draw and has the engine record it in the frame that samples the target.
361
+ */
362
+ [DRAW_TARGET](target: unknown, root: unknown, camera: unknown, deferred = false): void {
363
+ if (this.#adapter === undefined)
364
+ throw new Error("TN_WASM_RENDERER: render() before init() finished.");
365
+ beforeRender({ camera, scene: root });
366
+ this.#applyState();
367
+ writeHandle(0, root, "scene");
368
+ writeHandle(12, camera, "camera");
369
+ writeHandle(24, target, "render target");
370
+ check(
371
+ module._tnw_web_render_target(
372
+ handles + 24,
373
+ handles,
374
+ handles + 12,
375
+ ...this.#clear,
376
+ deferred ? 1 : 0,
377
+ ),
378
+ );
379
+ }
380
+
381
+ /** The last scene and camera again: RenderPipeline.render() draws through its post graph. */
382
+ [RENDER_AGAIN](): void {
383
+ if (this.#last !== undefined) this.render(...this.#last);
384
+ }
385
+
386
+ /** WebGPUCapabilities.getMaxAnisotropy, as on the V8 player: WebGPU samplers clamp to 16. */
387
+ getMaxAnisotropy(): number {
388
+ return 16;
389
+ }
390
+
391
+ compileAsync(): Promise<void> {
392
+ return Promise.resolve();
393
+ }
394
+
395
+ /**
396
+ * Startup warm-up's native counterpart of three's PMREM preparer: the engine bakes an environment
397
+ * a retained packet per render and skips every frame until it is done, so draw the held scene
398
+ * (behind the loading cover) until a render is no longer skipped for it. True when it drew;
399
+ * false at `deadlineMs` (a `performance.now()` time), so a bake that never finishes cannot
400
+ * hold the caller or keep drawing after it gave up.
401
+ */
402
+ async prepareEnvironmentAsync(
403
+ scene: unknown,
404
+ camera: unknown,
405
+ deadlineMs = Number.POSITIVE_INFINITY,
406
+ ): Promise<boolean> {
407
+ while (performance.now() < deadlineMs) {
408
+ const gated = this.info.engine.frameGateSkips;
409
+ this.render(scene, camera);
410
+ if (this.info.engine.frameGateSkips === gated && module._tnw_web_frame(12) === 0)
411
+ return true;
412
+ // A macrotask, not a frame: the work-done callbacks that advance the bake arrive between tasks.
413
+ await new Promise((resolve) => setTimeout(resolve, 0));
414
+ }
415
+ return false;
416
+ }
417
+
418
+ async resolveTimestampsAsync(type = "render"): Promise<number | undefined> {
419
+ if (type !== "render") return undefined;
420
+ return this.info.render.timestamp > 0 ? this.info.render.timestamp : undefined;
421
+ }
422
+
423
+ /**
424
+ * three's renderer.compute(node | node[]) (PRD-620): the kernels queue in call order, each with the uniform
425
+ * values it was called with, and run ahead of the next draw or read. A kernel the engine cannot lower
426
+ * refuses here, by name.
427
+ */
428
+ compute(computeNodes: unknown, dispatchSize: unknown = null): void {
429
+ if (tsl === undefined) unsupported("compute");
430
+ if (dispatchSize !== null)
431
+ throw new Error(
432
+ "TN_COMPUTE_DISPATCH_SIZE: renderer.compute(nodes, dispatchSize) is not available on the Wasm engine; give the node its count.",
433
+ );
434
+ beforeRender();
435
+ for (const node of Array.isArray(computeNodes) ? computeNodes : [computeNodes]) {
436
+ if (!isTslNode(node))
437
+ throw new TypeError(
438
+ "TN_COMPUTE_NODE: renderer.compute takes the node Fn(() => { ... })().compute(count) makes",
439
+ );
440
+ tsl.compute(node[TSL_NODE]);
441
+ }
442
+ }
443
+
444
+ async computeAsync(computeNodes: unknown, dispatchSize: unknown = null): Promise<void> {
445
+ this.compute(computeNodes, dispatchSize);
446
+ }
447
+
448
+ /** The attribute's storage bytes after every kernel queued before this call (three's resolved forms). */
449
+ getArrayBufferAsync(
450
+ attribute: object,
451
+ target: ArrayBuffer | { isReadbackBuffer?: boolean; buffer: unknown } | null = null,
452
+ offset = 0,
453
+ count = -1,
454
+ ): Promise<ArrayBuffer | { isReadbackBuffer?: boolean; buffer: unknown }> {
455
+ const runtime = tsl;
456
+ if (runtime === undefined) return unsupported("getArrayBufferAsync");
457
+ const ref = engineRef(attribute);
458
+ if (ref === undefined)
459
+ throw new TypeError(
460
+ "TN_NATIVE_READ_STORAGE: expected the BufferAttribute of a storage buffer",
461
+ );
462
+ return readStorageBytes(
463
+ (a) => runtime.readStorage(engineRef(a as object) ?? ref),
464
+ attribute,
465
+ target,
466
+ offset,
467
+ count,
468
+ );
469
+ }
470
+
471
+ /** Drops the attribute's GPU copy; the next use uploads its CPU contents again. */
472
+ deleteAttribute(attribute: object): this {
473
+ const ref = engineRef(attribute);
474
+ if (tsl === undefined || ref === undefined)
475
+ throw new TypeError("TN_NATIVE_DELETE_ATTRIBUTE: expected a BufferAttribute");
476
+ tsl.deleteStorage(ref);
477
+ return this;
478
+ }
479
+
480
+ getRenderTarget(): null {
481
+ return null;
482
+ }
483
+
484
+ setRenderTarget(target: unknown): void {
485
+ if (target !== null) unsupported("RenderTarget");
486
+ }
487
+
488
+ setAnimationLoop(): never {
489
+ return unsupported("setAnimationLoop");
490
+ }
491
+
492
+ /** Releases the page's one renderer slot; the engine and its canvas stay for the next renderer. */
493
+ dispose(): void {
494
+ if (!this.#holdsSlot) return;
495
+ this.#holdsSlot = false;
496
+ claimed = false;
497
+ }
498
+ };
499
+ const read = async (target: unknown, x: number, y: number, width: number, height: number) => {
500
+ writeHandle(24, target, "render target");
501
+ const id = module._tnw_web_read_target(handles + 24, x, y, width, height);
502
+ if (id === 0) check(1);
503
+ const size = width * height * 8;
504
+ const out = module._malloc(size) >>> 0;
505
+ try {
506
+ for (;;) {
507
+ module._tnw_web_poll();
508
+ const status = module._tnw_web_read_target_take(id, out, size);
509
+ if (status === 1) return module.HEAPU8.slice(out, out + size);
510
+ if (status < 0) throw new Error("TN_WASM_READ_TARGET: the read failed");
511
+ await new Promise((resolve) => setTimeout(resolve, 0));
512
+ }
513
+ } finally {
514
+ module._free(out);
515
+ }
516
+ };
517
+ defineRenderTargets(Renderer.prototype, (renderer) => ({
518
+ draw: (target, root, camera) =>
519
+ (renderer as { [DRAW_TARGET](t: unknown, r: unknown, c: unknown): void })[DRAW_TARGET](
520
+ target,
521
+ root,
522
+ camera,
523
+ ),
524
+ read,
525
+ }));
526
+ return Renderer;
527
+ }