@threenative/three-native 0.3.10 → 0.3.12

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.10",
3
+ "version": "0.3.12",
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": [
@@ -12,7 +12,7 @@
12
12
  ],
13
13
  "repository": {
14
14
  "type": "git",
15
- "url": "git+https://github.com/ThreeNativeHQ/threenative.git",
15
+ "url": "git+https://github.com/ThreeNativeHQ/threenative-engine.git",
16
16
  "directory": "packages/three-native"
17
17
  },
18
18
  "type": "module",
@@ -197,6 +197,33 @@ function hostPlugins(
197
197
  return { parser, plugins };
198
198
  }
199
199
 
200
+ /**
201
+ * One fetch per image file while it is in flight: models loaded together that share an image (ten
202
+ * spruce models and their 12 MB atlas in the Strata forest) wait on the same bytes instead of each
203
+ * downloading them. The engine copies the bytes, so sharing them is safe. Nothing is kept once the
204
+ * fetch lands. ponytail: a model loaded later fetches again; keep the bytes if that shows in a load.
205
+ */
206
+ const inFlight = new Map<string, Promise<Uint8Array>>();
207
+ function imageBytes(url: string): Promise<Uint8Array> {
208
+ const key = new URL(url, globalThis.location?.href ?? "http://localhost/").href;
209
+ let pending = inFlight.get(key);
210
+ if (pending === undefined) {
211
+ pending = (async () => {
212
+ const response = await fetch(url);
213
+ if (!response.ok) throw new Error(`TN_WASM_GLTF_FETCH: ${response.status} ${url}`);
214
+ // A dev server answers a missing file with its page and a 200 (Vite's SPA fallback); the
215
+ // engine would refuse those bytes only as "undecoded images", without the file's name.
216
+ if (response.headers.get("content-type")?.startsWith("text/html"))
217
+ throw new Error(`TN_WASM_GLTF_FETCH: text/html ${url}`);
218
+ return new Uint8Array(await response.arrayBuffer());
219
+ })();
220
+ inFlight.set(key, pending);
221
+ const settled = () => inFlight.delete(key);
222
+ pending.then(settled, settled);
223
+ }
224
+ return pending;
225
+ }
226
+
200
227
  export class GLTFLoader {
201
228
  path = "";
202
229
  /** A plugin defect (a chain the file declares and cannot deliver) rejects the load; core's plugin logs it on stock three. */
@@ -280,16 +307,8 @@ export class GLTFLoader {
280
307
  return;
281
308
  }
282
309
  Promise.all(
283
- uris.map(async (uri) => {
284
- const response = await fetch(path + uri);
285
- if (!response.ok) throw new Error(`TN_WASM_GLTF_FETCH: ${response.status} ${path + uri}`);
286
- // A dev server answers a missing file with its page and a 200 (Vite's SPA fallback); the
287
- // engine would refuse those bytes only as "undecoded images", without the file's name.
288
- if (response.headers.get("content-type")?.startsWith("text/html"))
289
- throw new Error(`TN_WASM_GLTF_FETCH: text/html ${path + uri}`);
290
- // The engine loader asks for the uri with its percent escapes decoded.
291
- return [decodeURIComponent(uri), new Uint8Array(await response.arrayBuffer())] as const;
292
- }),
310
+ // The engine loader asks for the uri with its percent escapes decoded.
311
+ uris.map(async (uri) => [decodeURIComponent(uri), await imageBytes(path + uri)] as const),
293
312
  ).then(
294
313
  (files) => settle(new Map(files)),
295
314
  (error: unknown) => {
@@ -47,6 +47,7 @@ export interface IScreenSpaceTsl {
47
47
  readonly min: (a: TslNode, b: TslNode) => TslNode;
48
48
  readonly mix: (a: TslNode, b: TslNode, t: TslNode) => TslNode;
49
49
  readonly normalize: (value: TslNode) => TslNode;
50
+ readonly pow: (base: TslNode, exponent: TslNode) => TslNode;
50
51
  readonly reflect: (incident: TslNode, normal: TslNode) => TslNode;
51
52
  readonly rtt: (
52
53
  source: TslNode,
@@ -470,7 +471,11 @@ const GI_MAX_LUMINANCE = 40;
470
471
  * multiplies it by the receiver's albedo (`mrt({ diffuseColor })`) and adds it to the lit frame.
471
472
  * rgb mean over the rays of hit x (hit radiance - fallback)
472
473
  * a the share of rays that hit
473
- * `getAONode()` answers 1: occlusion is the GTAO stage's, and hits already darken through `hit - fallback`.
474
+ * `getAONode()` answers that share as occlusion, in the form the caller applies: three's SSGINode averages the occluded
475
+ * share of its rays and answers `pow(clamp(1 - occludedShare), aoIntensity)` for the caller to multiply the lit frame
476
+ * by (SSGINode.js:637-638, 651). This answers the same quantity as `pow(clamp(1 - a), aoIntensity)` over rgb. A
477
+ * constant 1 dropped the term: the frame kept the light the occluder blocked and SSGI only added its gather
478
+ * (2026-11-02, PRD-617 AC-7).
474
479
  */
475
480
  export function defineScreenSpaceGi(tsl: IScreenSpaceTsl) {
476
481
  return function ssgi(
@@ -479,8 +484,23 @@ export function defineScreenSpaceGi(tsl: IScreenSpaceTsl) {
479
484
  normalNode: TslNode,
480
485
  cameraOrOptions: IScreenSpaceCamera | IScreenSpaceGiOptions,
481
486
  ): TslNode {
482
- const { Break, Fn, If, Loop, float, int, max, min, normalize, rtt, smoothstep, uniform, uv } =
483
- tsl;
487
+ const {
488
+ Break,
489
+ Fn,
490
+ If,
491
+ Loop,
492
+ clamp,
493
+ float,
494
+ int,
495
+ max,
496
+ min,
497
+ normalize,
498
+ pow,
499
+ rtt,
500
+ smoothstep,
501
+ uniform,
502
+ uv,
503
+ } = tsl;
484
504
  const { vec2, vec3, vec4 } = tsl;
485
505
  const options: IScreenSpaceGiOptions =
486
506
  "camera" in cameraOrOptions ? cameraOrOptions : { camera: cameraOrOptions };
@@ -491,9 +511,16 @@ export function defineScreenSpaceGi(tsl: IScreenSpaceTsl) {
491
511
  const sliceCount = uniform(2);
492
512
  const stepCount = uniform(12);
493
513
  const intensity = uniform(1);
514
+ // three's `aoIntensity`: the power applied to the occlusion (SSGINode.js:129, default 1). The caller reads the
515
+ // occlusion through `.r`, so it is broadcast over rgb for a denoise pass to carry.
516
+ const aoIntensity = uniform(1);
494
517
  const screenEdgeFade = uniform(0.1);
495
518
  const probeJitter = uniform(1);
496
519
  const probeDebug = uniform(0);
520
+ const occlusion = (gather: TslNode): TslNode => {
521
+ const ao = pow(clamp(float(1).sub(gather.a), float(0), float(1)), aoIntensity);
522
+ return vec4(ao, ao, ao, 1);
523
+ };
497
524
  const { march, shade } = defineGiTrace(tsl, {
498
525
  colorNode,
499
526
  depthNode,
@@ -521,13 +548,14 @@ export function defineScreenSpaceGi(tsl: IScreenSpaceTsl) {
521
548
  sliceCount,
522
549
  stepCount,
523
550
  intensity,
551
+ aoIntensity,
524
552
  screenEdgeFade,
525
553
  probeJitter,
526
554
  probeDebug,
527
555
  }).map(([name, value]) => [name, { value }]),
528
556
  ),
529
557
  getGINode: { value: () => node },
530
- getAONode: { value: () => tsl.vec4(1, 1, 1, 1) },
558
+ getAONode: { value: () => occlusion(node) },
531
559
  resolutionScale: {
532
560
  get: () => node.getResolutionScale(),
533
561
  set: (value: number) => node.setResolutionScale(value),
@@ -598,13 +626,21 @@ export function defineScreenSpaceGi(tsl: IScreenSpaceTsl) {
598
626
  })();
599
627
 
600
628
  const node = rtt(graph, null, null, { type: HALF_FLOAT_TYPE, gpuStage: GI_STAGE });
601
- const uniformObjects = { radius, thickness, sliceCount, stepCount, intensity, screenEdgeFade };
629
+ const uniformObjects = {
630
+ radius,
631
+ thickness,
632
+ sliceCount,
633
+ stepCount,
634
+ intensity,
635
+ aoIntensity,
636
+ screenEdgeFade,
637
+ };
602
638
  return Object.defineProperties(node, {
603
639
  ...Object.fromEntries(
604
640
  Object.entries(uniformObjects).map(([name, value]) => [name, { value }]),
605
641
  ),
606
642
  getGINode: { value: () => node },
607
- getAONode: { value: () => vec4(1, 1, 1, 1) },
643
+ getAONode: { value: () => occlusion(node) },
608
644
  resolutionScale: {
609
645
  get: () => node.getResolutionScale(),
610
646
  set: (value: number) => node.setResolutionScale(value),
@@ -73,10 +73,19 @@ export interface IBridgeMeter {
73
73
  frame(): void;
74
74
  }
75
75
 
76
+ /**
77
+ * The files a caller search looks through rather than names: the back end's own (`browser-backend.ts`
78
+ * and the modules it was split into, PRD-803) and this meter's two.
79
+ */
80
+ const BACK_END_FILE =
81
+ /(?:browser-backend|browser-abi-types|browser-marshal|browser-wasm-runtime|browser-value-views|browser-attribute-sync|debug-telemetry|bridge-meter)\.[jt]s(?:[:?]|$)/u;
82
+
76
83
  /**
77
84
  * The first frame of `stack` outside the back end and this meter (the files of its first two frames:
78
85
  * the stack call, then `record`), and the two after it: `fn (file:line) < fn (file:line)`. A bundle
79
86
  * that puts the game in the back end's file falls back to the fourth frame, the one above the accessor.
87
+ * Every file the back end was split into (PRD-803) belongs here: a crossing it makes for a game's call
88
+ * is attributed to the game, never to the back end.
80
89
  */
81
90
  export function callerOf(stack: string | undefined): string {
82
91
  const frames = (stack ?? "")
@@ -87,9 +96,7 @@ export function callerOf(stack: string | undefined): string {
87
96
  const fileOf = (frame: string) => /\(?([^()\s]+?)(?::\d+){1,2}\)?$/u.exec(frame)?.[1] ?? frame;
88
97
  const own = new Set(frames.slice(0, 2).map(fileOf));
89
98
  let at = frames.findIndex(
90
- (frame) =>
91
- !own.has(fileOf(frame)) &&
92
- !/(?:browser-backend|debug-telemetry|bridge-meter)\.[jt]s(?:[:?]|$)/u.test(fileOf(frame)),
99
+ (frame) => !own.has(fileOf(frame)) && !BACK_END_FILE.test(fileOf(frame)),
93
100
  );
94
101
  if (at < 0) at = Math.min(3, frames.length - 1);
95
102
  const short = (frame: string) =>
@@ -0,0 +1,427 @@
1
+ import type { TypedArray } from "./browser-marshal.js";
2
+ /**
3
+ * The engine's C ABI as the browser back end sees it (PRD-532, PRD-803): the runtime interface the
4
+ * classes call, the handle's packed words, the value layouts of `tn_abi.h`, and the two host
5
+ * integrations a module may carry (the glTF loader and TSL by name).
6
+ */
7
+ import type { ITslRuntime, TslArgValue } from "./browser-tsl.js";
8
+ import type { DebugTelemetry } from "./debug-telemetry.js";
9
+
10
+ /** A ref with its handle words kept (see `createWasmRuntime`): type | context << 16, index, generation. */
11
+ export interface IPackedRef extends IEngineRef {
12
+ w0: number;
13
+ w1: number;
14
+ w2: number;
15
+ }
16
+
17
+ /** An engine object as the back end sees it: an opaque key and its catalog type id. */
18
+ export interface IEngineRef {
19
+ readonly key: string;
20
+ readonly type: number;
21
+ }
22
+
23
+ export function isRef(value: unknown): value is IEngineRef {
24
+ return typeof value === "object" && value !== null && "key" in value && "type" in value;
25
+ }
26
+
27
+ export type EngineValue =
28
+ | null
29
+ | undefined
30
+ | number
31
+ | boolean
32
+ | string
33
+ | TypedArray
34
+ | readonly EngineValue[]
35
+ | IEngineRef
36
+ | { readonly [key: string]: EngineValue };
37
+
38
+ /** What the classes call; the Wasm ABI implements it, and a surface-only runtime refuses every call. */
39
+ export interface IBrowserRuntime {
40
+ readonly debugTelemetry?: DebugTelemetry;
41
+ typeId(className: string): number;
42
+ construct(className: string, args: readonly EngineValue[]): IEngineRef;
43
+ invoke(self: IEngineRef, method: string, args: readonly EngineValue[]): EngineValue;
44
+ get(self: IEngineRef, path: string): EngineValue;
45
+ set(self: IEngineRef, path: string, value: EngineValue): void;
46
+ release(self: IEngineRef): void;
47
+ /** For each ref, how many references other engine objects hold to its object; one call a batch. */
48
+ engineReferences?(refs: readonly IEngineRef[]): ArrayLike<number>;
49
+ /** A numeric typed array argument crosses as is, no boxed copy; Wasm only. */
50
+ readonly typedArrays?: boolean;
51
+ /** Doubles at `address` in the engine's memory (one as a number, more as an array); Wasm only. */
52
+ readDoubles?(address: number, count: number): number | number[];
53
+ /**
54
+ * The engine's memory as doubles, current: Emscripten replaces the view when the memory grows, so a caller
55
+ * reads it per operation and never keeps it. Wasm only.
56
+ */
57
+ heapF64?(): Float64Array;
58
+ /** The byte at `address` in the engine's memory; Wasm only. A registry field `[offset, 0]` is a byte flag. */
59
+ readByte?(address: number): number;
60
+ /** The 32-bit word at `address` in the engine's memory (the hierarchy counter's low word); Wasm only. */
61
+ readWord?(address: number): number;
62
+ /** Writes one double at `address` in the engine's memory; Wasm only. */
63
+ writeDouble?(address: number, value: number): void;
64
+ /** Writes the byte at `address` in the engine's memory (a flag field); Wasm only. */
65
+ writeByte?(address: number, value: number): void;
66
+ /**
67
+ * A copy of the attribute's data, of its scalar type; three's `attribute.array` is built on it.
68
+ * With `offset`/`count`, a copy of that scalar subrange only (a per-vertex setter syncs one item).
69
+ */
70
+ attributeArray?(self: IEngineRef, offset?: number, count?: number): TypedArray;
71
+ /**
72
+ * Writes `array` into the attribute's data; present with attributeArray. With `offset`, writes that
73
+ * subrange; without it, `array` must be the attribute's whole data.
74
+ */
75
+ attributeWrite?(self: IEngineRef, array: TypedArray, offset?: number): void;
76
+ /** Sets (or, with null, clears) a callback the engine runs; `handler` gets the engine's arguments. */
77
+ setCallback(
78
+ self: IEngineRef,
79
+ name: string,
80
+ handler: ((args: readonly EngineValue[]) => void) | null,
81
+ ): void;
82
+ /** TSL by name (PRD-540), when the module carries `tn_tsl_call`. */
83
+ readonly tsl?: ITslRuntime;
84
+ /** A GLB through the engine's own glTF loader (PRD-540), when the module carries the web host. */
85
+ loadGltf?(
86
+ bytes: Uint8Array,
87
+ files?: ReadonlyMap<string, Uint8Array>,
88
+ ): { readonly scene: IEngineRef; readonly animations: IEngineRef[] };
89
+ }
90
+
91
+ /**
92
+ * The engine's C ABI as built by `tn-native-engine-abi-module` (Emscripten, wasm32). The names are
93
+ * Emscripten's (`HEAPU8`, `_malloc`, `_tn_*`), so they are declared as record keys.
94
+ */
95
+ type AbiCall =
96
+ | "_malloc"
97
+ | "_free"
98
+ | "_tn_engine_version"
99
+ | "_tn_context_create"
100
+ | "_tn_type_id"
101
+ | "_tn_object_release"
102
+ | "_tn_object_engine_references"
103
+ | "_tn_construct"
104
+ | "_tn_invoke"
105
+ | "_tn_get"
106
+ | "_tn_set"
107
+ | "_tn_set_callback"
108
+ | "_tn_diagnostic_release";
109
+ export type TnAbiModule = Record<AbiCall, (...args: number[]) => number> &
110
+ Partial<
111
+ Record<"_tnw_attribute_view" | "_tnw_attribute_view_release", (...args: number[]) => number>
112
+ > &
113
+ Record<"HEAPU8", Uint8Array> &
114
+ Record<"HEAPF64", Float64Array> &
115
+ Record<"UTF8ToString", (pointer: number, maxBytes?: number) => string> &
116
+ Record<
117
+ "addFunction",
118
+ (fn: (...args: number[]) => number | undefined, signature: string) => number
119
+ > & {
120
+ stringToUTF8(text: string, pointer: number, maxBytes: number): void;
121
+ lengthBytesUTF8(text: string): number;
122
+ };
123
+
124
+ // wasm32 layouts of tn_abi.h, measured with offsetof under emcc: tn_handle_t 12 bytes; tn_value_t
125
+ // 56 bytes (kind 0, boolean 4, number 8, handle 16, text 32, count 40, numbers 48); tn_diagnostic_t
126
+ // 8 bytes (message 0, code 4); tn_version_info_t 32 bytes. A struct passed by value goes by pointer.
127
+ export const HANDLE = 12;
128
+ export const VALUE = 56;
129
+ export const KIND = {
130
+ null: 0,
131
+ number: 1,
132
+ bool: 2,
133
+ string: 3,
134
+ handle: 4,
135
+ numbers: 5,
136
+ array: 6,
137
+ record: 7,
138
+ undefined: 8,
139
+ bytes: 9,
140
+ } as const;
141
+
142
+ // wasm32 layout of tn_tsl_arg_t (tn_tsl.h): kind 0, lanes 4, node 8 (u64), number 16, text 24,
143
+ // numbers 32 (four f64); 64 bytes. A handle argument's 12 bytes start at lanes (4) and run through node.
144
+ const TSL_ARG = 64;
145
+ const TSL_KIND = {
146
+ node: 0,
147
+ number: 1,
148
+ string: 2,
149
+ named: 3,
150
+ rgb: 4,
151
+ vector: 5,
152
+ other: 6,
153
+ handle: 7,
154
+ } as const;
155
+ type TslCall =
156
+ | "_tn_tsl_call"
157
+ | "_tn_tsl_release"
158
+ | "_tn_tsl_set"
159
+ | "_tn_tsl_set_uniform"
160
+ | "_tn_tsl_effect_parameter"
161
+ | "_tnw_web_set_post"
162
+ | "_tnw_web_compute"
163
+ | "_tnw_web_compute_flush"
164
+ | "_tnw_web_read_storage"
165
+ | "_tnw_web_read_storage_size"
166
+ | "_tnw_web_read_storage_take"
167
+ | "_tnw_web_delete_storage"
168
+ | "_tnw_web_poll"
169
+ | "_tnw_web_error";
170
+
171
+ export interface IAbiHelpers {
172
+ scoped<T>(work: () => T): T;
173
+ alloc(size: number): number;
174
+ string(text: string): { pointer: number; bytes: number };
175
+ diagnostic(): number;
176
+ check(status: number, diag: number, what: string): void;
177
+ handleOf(ref: IEngineRef): number;
178
+ writeHandle(pointer: number, ref: IEngineRef): void;
179
+ view(): DataView;
180
+ }
181
+
182
+ /** The engine glTF loader over the product web host's `tnw_web_load_gltf`, when the module has it. */
183
+ export function gltfOf(
184
+ abi: TnAbiModule,
185
+ context: number,
186
+ h: Pick<IAbiHelpers, "scoped" | "alloc"> & { keyOf(pointer: number): IEngineRef },
187
+ ): Pick<IBrowserRuntime, "loadGltf"> {
188
+ // quality-allow: the Emscripten module is read through the exports this call site names, not its full surface.
189
+ const host = abi as unknown as Partial<
190
+ Record<
191
+ | "_tnw_web_load_gltf"
192
+ | "_tnw_web_load_error"
193
+ | "_tnw_web_gltf_file"
194
+ | "_tnw_web_gltf_files_clear",
195
+ (...args: number[]) => number
196
+ >
197
+ >;
198
+ const {
199
+ _tnw_web_load_gltf: load,
200
+ _tnw_web_load_error: error,
201
+ _tnw_web_gltf_file: file,
202
+ _tnw_web_gltf_files_clear: clearFiles,
203
+ } = host;
204
+ if (load === undefined || error === undefined) return {};
205
+ return {
206
+ loadGltf: (bytes, files) =>
207
+ h.scoped(() => {
208
+ // Files the model names by relative uri (shared images), read by the engine loader.
209
+ if (files !== undefined && files.size > 0) {
210
+ if (file === undefined || clearFiles === undefined)
211
+ throw new Error(
212
+ "TN_WASM_GLTF_FILES_UNAVAILABLE: this web engine cannot read a model's image files",
213
+ );
214
+ for (const [uri, content] of files) {
215
+ // tnw_web_gltf_file keeps its own copy, so this scratch is dead once it returns. One scope
216
+ // per file frees it at once: the peak is one file, not the sum of all of them.
217
+ h.scoped(() => {
218
+ const name = h.alloc(abi.lengthBytesUTF8(uri) + 1);
219
+ abi.stringToUTF8(uri, name, abi.lengthBytesUTF8(uri) + 1);
220
+ const copy = h.alloc(Math.max(1, content.byteLength));
221
+ abi.HEAPU8.set(content, copy);
222
+ file(name, copy, content.byteLength);
223
+ });
224
+ }
225
+ }
226
+ try {
227
+ const data = h.alloc(Math.max(1, bytes.byteLength));
228
+ abi.HEAPU8.set(bytes, data);
229
+ const count = h.alloc(4);
230
+ // Retried once with the exact size when the model has more clips than the first guess.
231
+ for (let capacity = 64; ; ) {
232
+ const out = h.alloc(HANDLE * capacity);
233
+ const status = load(context, data, bytes.byteLength, out, capacity, count);
234
+ const needed = new DataView(abi.HEAPU8.buffer).getUint32(count, true);
235
+ if (status === 0) {
236
+ const refs = Array.from({ length: needed }, (_, i) => h.keyOf(out + i * HANDLE));
237
+ return { scene: refs[0] as IEngineRef, animations: refs.slice(1) };
238
+ }
239
+ const reason = abi.UTF8ToString(error());
240
+ if (reason !== "TN_WASM_GLTF_CAPACITY" || needed <= capacity) throw new Error(reason);
241
+ capacity = needed;
242
+ }
243
+ } finally {
244
+ clearFiles?.();
245
+ }
246
+ }),
247
+ };
248
+ }
249
+
250
+ /** TSL by name over `tn_tsl_call`, when the module exports it (the product web host does). */
251
+ export function tslOf(
252
+ abi: TnAbiModule,
253
+ context: number,
254
+ h: IAbiHelpers,
255
+ ): { tsl: ITslRuntime } | undefined {
256
+ // Node ids are u64 in the C ABI; Emscripten passes a 64-bit parameter as a BigInt.
257
+ // quality-allow: the Emscripten module is read through the TSL call exports this call site names, not its full surface.
258
+ const calls = abi as unknown as Partial<
259
+ Record<TslCall, (...args: (number | bigint)[]) => number>
260
+ >;
261
+ const {
262
+ _tn_tsl_call: call,
263
+ _tn_tsl_release: release,
264
+ _tn_tsl_set: set,
265
+ _tn_tsl_set_uniform: setUniform,
266
+ _tn_tsl_effect_parameter: effectParameter,
267
+ _tnw_web_set_post: setPost,
268
+ _tnw_web_compute: computeNode,
269
+ _tnw_web_compute_flush: computeFlush,
270
+ _tnw_web_read_storage: readStorage,
271
+ _tnw_web_read_storage_size: readStorageSize,
272
+ _tnw_web_read_storage_take: readStorageTake,
273
+ _tnw_web_delete_storage: deleteStorage,
274
+ _tnw_web_poll: poll,
275
+ _tnw_web_error: webError,
276
+ } = calls;
277
+ if (
278
+ call === undefined ||
279
+ release === undefined ||
280
+ set === undefined ||
281
+ setUniform === undefined ||
282
+ effectParameter === undefined
283
+ )
284
+ return undefined;
285
+ // Writes tn_tsl_arg_t values; text is allocated first, since an allocation can grow the memory.
286
+ const writeArgs = (args: readonly TslArgValue[]): number => {
287
+ const pointer = h.alloc(Math.max(TSL_ARG, args.length * TSL_ARG));
288
+ args.forEach((arg, i) => {
289
+ const at = pointer + i * TSL_ARG;
290
+ const text = arg.kind === "string" || arg.kind === "named" ? h.string(arg.text).pointer : 0;
291
+ const v = h.view();
292
+ v.setUint32(at, TSL_KIND[arg.kind], true);
293
+ if (arg.kind === "node") v.setBigUint64(at + 8, BigInt(arg.node), true);
294
+ else if (arg.kind === "number") v.setFloat64(at + 16, arg.number, true);
295
+ else if (arg.kind === "rgb" || arg.kind === "vector") {
296
+ v.setUint32(at + 4, arg.numbers.length, true);
297
+ arg.numbers.forEach((c, j) => v.setFloat64(at + 32 + j * 8, c, true));
298
+ } else if (arg.kind === "handle") h.writeHandle(at + 4, arg.ref);
299
+ else v.setUint32(at + 24, text, true);
300
+ });
301
+ return pointer;
302
+ };
303
+ const nodeOf = (node: number | null): number => {
304
+ if (node === null) return 0;
305
+ const pointer = h.alloc(8);
306
+ h.view().setBigUint64(pointer, BigInt(node), true);
307
+ return pointer;
308
+ };
309
+ return {
310
+ tsl: {
311
+ call: (name, receiver, args) =>
312
+ h.scoped(() => {
313
+ const pointer = writeArgs(args);
314
+ const self = nodeOf(receiver);
315
+ const out = h.alloc(8);
316
+ const diag = h.diagnostic();
317
+ h.check(
318
+ call(context, h.string(name).pointer, self, pointer, args.length, out, diag),
319
+ diag,
320
+ `TSL ${name}`,
321
+ );
322
+ return Number(h.view().getBigUint64(out, true));
323
+ }),
324
+ release: (node) =>
325
+ h.scoped(() => {
326
+ const diag = h.diagnostic();
327
+ release(context, BigInt(node), diag);
328
+ abi._tn_diagnostic_release(diag);
329
+ }),
330
+ set: (material, path, node) =>
331
+ h.scoped(() => {
332
+ const diag = h.diagnostic();
333
+ h.check(
334
+ set(context, h.handleOf(material), h.string(path).pointer, BigInt(node), diag),
335
+ diag,
336
+ `set ${path}`,
337
+ );
338
+ }),
339
+ effectParameter: (node, name, value) =>
340
+ h.scoped(() => {
341
+ const self = nodeOf(node);
342
+ const input = value === undefined ? 0 : h.alloc(8);
343
+ if (value !== undefined) h.view().setFloat64(input, value, true);
344
+ const out = h.alloc(8);
345
+ const diag = h.diagnostic();
346
+ h.check(
347
+ effectParameter(context, self, h.string(name).pointer, input, out, diag),
348
+ diag,
349
+ `effect ${name}`,
350
+ );
351
+ return h.view().getFloat64(out, true);
352
+ }),
353
+ // three's RenderPipeline on the product web host: the graph between scene and output.
354
+ setPost: (node) =>
355
+ h.scoped(() => {
356
+ if (setPost === undefined) throw new Error("TN_WASM_POST: this module has no web host");
357
+ if (setPost(context, nodeOf(node), 0) !== 0) throw new Error("TN_WASM_POST: refused");
358
+ }),
359
+ setToneMapping: (node) =>
360
+ h.scoped(() => {
361
+ if (setPost === undefined)
362
+ throw new Error("TN_NATIVE_CUSTOM_TONEMAPPING_MISSING: no web output binding");
363
+ if (setPost(context, nodeOf(node), 1) !== 0)
364
+ throw new Error("TN_NATIVE_CUSTOM_TONEMAPPING_INVALID: refused output node");
365
+ }),
366
+ // PRD-620: renderer.compute and storage reads over the product web host.
367
+ compute: (node) =>
368
+ h.scoped(() => {
369
+ if (computeNode === undefined || webError === undefined)
370
+ throw new Error("TN_WASM_COMPUTE: this module has no web host");
371
+ if (computeNode(context, nodeOf(node)) !== 0)
372
+ throw new Error(abi.UTF8ToString(webError()));
373
+ }),
374
+ readStorage: async (attribute) => {
375
+ if (
376
+ readStorage === undefined ||
377
+ readStorageSize === undefined ||
378
+ readStorageTake === undefined ||
379
+ computeFlush === undefined ||
380
+ poll === undefined ||
381
+ webError === undefined
382
+ )
383
+ throw new Error("TN_WASM_COMPUTE: this module has no web host");
384
+ const id = h.scoped(() => {
385
+ const pointer = h.alloc(HANDLE);
386
+ h.writeHandle(pointer, attribute);
387
+ return readStorage(pointer);
388
+ });
389
+ if (id === 0) throw new Error(abi.UTF8ToString(webError()));
390
+ computeFlush();
391
+ for (;;) {
392
+ poll();
393
+ const size = readStorageSize(id);
394
+ if (size > 0 || readStorageTake(id, 0, 0) < 0) {
395
+ const out = abi._malloc(size) >>> 0;
396
+ try {
397
+ if (readStorageTake(id, out, size) === 1)
398
+ return abi.HEAPU8.slice(out, out + size).buffer;
399
+ } finally {
400
+ abi._free(out);
401
+ }
402
+ throw new Error("TN_NATIVE_READ_STORAGE: the read failed");
403
+ }
404
+ await new Promise((resolve) => setTimeout(resolve, 0));
405
+ }
406
+ },
407
+ deleteStorage: (attribute) =>
408
+ h.scoped(() => {
409
+ if (deleteStorage === undefined || webError === undefined)
410
+ throw new Error("TN_WASM_COMPUTE: this module has no web host");
411
+ const pointer = h.alloc(HANDLE);
412
+ h.writeHandle(pointer, attribute);
413
+ if (deleteStorage(pointer) !== 0) throw new Error(abi.UTF8ToString(webError()));
414
+ }),
415
+ setUniform: (node, lanes) =>
416
+ h.scoped(() => {
417
+ const pointer = h.alloc(8);
418
+ const values = h.alloc(Math.max(8, lanes.length * 8));
419
+ const v = h.view();
420
+ v.setBigUint64(pointer, BigInt(node), true);
421
+ lanes.forEach((lane, i) => v.setFloat64(values + i * 8, lane, true));
422
+ const diag = h.diagnostic();
423
+ h.check(setUniform(context, pointer, values, lanes.length, diag), diag, "uniform.value");
424
+ }),
425
+ },
426
+ };
427
+ }