@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,305 @@
1
+ /**
2
+ * What a web game's `three`, `three/webgpu` and `three/tsl` imports become under
3
+ * `engine: "threenative"` (PRD-540): every upstream export name, bound to the Wasm engine or refused.
4
+ *
5
+ * Registry classes come from the browser-JS back end and catalog constants keep their values. Every
6
+ * other name is a stub that throws its catalog diagnostic the moment it is called, constructed or
7
+ * read through, so a game bundles and an unbound symbol fails loudly. Nothing here imports upstream
8
+ * three, so no name can fall back to it.
9
+ */
10
+ import catalogJson from "../api/catalog.json" with { type: "json" };
11
+ import registry from "../api/native-registry.json" with { type: "json" };
12
+ import { DataUtils } from "./addons/data-utils.js";
13
+ import { type IAudioEngine, defineAudioClasses } from "./audio.js";
14
+ import { BlendMode } from "./blend-mode.js";
15
+ import {
16
+ type IBrowserRuntime,
17
+ type IRegistryDump,
18
+ TSL_NODE,
19
+ type TnAbiModule,
20
+ createWasmRuntime,
21
+ defineBrowserClasses,
22
+ } from "./browser-backend.js";
23
+ import { RENDER_AGAIN, defineWebRenderer, isWebHostModule } from "./browser-renderer.js";
24
+ import { type ITslRuntime, defineTsl, isTslNode } from "./browser-tsl.js";
25
+ import type { CatalogEntry, ICatalog } from "./catalog.js";
26
+ import { withMathUtilsExtras } from "./math-utils.js";
27
+ import { Material, defineObjectSurface, defineTypeFlags } from "./object-surface.js";
28
+ import { type PassDraw, definePass } from "./pass-node.js";
29
+ import { definePropertyBinding } from "./property-binding.js";
30
+ import { defineQuadMesh } from "./quad-mesh.js";
31
+ import { defineReflector } from "./reflector.js";
32
+ import { ReadbackBuffer } from "./storage.js";
33
+ import { defineTextureSources } from "./texture-sources.js";
34
+
35
+ // quality-allow: the JSON import is typed by its literal values, which ICatalog does not accept.
36
+ const engineCatalog = catalogJson as unknown as ICatalog;
37
+
38
+ type PassUpdate = (surface: () => { width: number; height: number }, draw: PassDraw) => void;
39
+
40
+ const UPSTREAM_SOURCES = new Set(["three", "three/webgpu", "three/tsl"]);
41
+
42
+ /**
43
+ * A value that throws `diagnostic` on any call, construction or property access. Its `prototype`
44
+ * alone reads, so a module may declare a subclass (core's `VirtualShadowNode extends ShadowBaseNode`)
45
+ * and fail only when it constructs one.
46
+ */
47
+ function refused(name: string, diagnostic: string): unknown {
48
+ const fail = (): never => {
49
+ throw new Error(`${diagnostic}: ${name} is not available on the Wasm engine.`);
50
+ };
51
+ return new Proxy(function refusedExport() {}, {
52
+ apply: fail,
53
+ construct: fail,
54
+ get: (target, key) => (key === "prototype" ? target.prototype : fail()),
55
+ set: fail,
56
+ has: fail,
57
+ ownKeys: fail,
58
+ getPrototypeOf: fail,
59
+ defineProperty: fail,
60
+ deleteProperty: fail,
61
+ getOwnPropertyDescriptor: fail,
62
+ });
63
+ }
64
+
65
+ function constantValue(entry: CatalogEntry): unknown {
66
+ if (entry.kind !== "constant" || entry.status.kind === "unsupported") return undefined;
67
+ return typeof entry.value === "string" ? JSON.parse(entry.value) : entry.value;
68
+ }
69
+
70
+ const NAMESPACES = new Set(["MathUtils", "SkeletonUtils"]);
71
+
72
+ /** Binds each upstream export name to an engine class, a catalog constant, or a refusal. */
73
+ export function bindUpstreamExports(
74
+ names: readonly string[],
75
+ catalog: Pick<ICatalog, "entries">,
76
+ classes: Readonly<Record<string, unknown>>,
77
+ ): Record<string, unknown> {
78
+ const entries = new Map(
79
+ catalog.entries
80
+ .filter((entry) => UPSTREAM_SOURCES.has(entry.source))
81
+ .map((entry) => [entry.name, entry]),
82
+ );
83
+ const bound: Record<string, unknown> = {};
84
+ for (const name of names) {
85
+ const entry = entries.get(name);
86
+ // three's MathUtils and SkeletonUtils are namespace objects: the engine binds each as a class,
87
+ // exported as its one instance (as the V8 player's core-three.mjs does).
88
+ if (Object.hasOwn(classes, name))
89
+ bound[name] = NAMESPACES.has(name)
90
+ ? new (classes[name] as new () => object)()
91
+ : classes[name];
92
+ else if (entry !== undefined && constantValue(entry) !== undefined)
93
+ bound[name] = constantValue(entry);
94
+ else
95
+ bound[name] = refused(
96
+ name,
97
+ entry?.status.kind === "unsupported"
98
+ ? entry.status.diagnostic
99
+ : `TN_NATIVE_${entry === undefined ? "UNCATALOGUED" : "UNBOUND"}_${name.toUpperCase()}`,
100
+ );
101
+ }
102
+ return bound;
103
+ }
104
+
105
+ /** Boots the Wasm module and returns every upstream export name bound over it. */
106
+ export async function bindWebEngine(
107
+ createModule: () => Promise<TnAbiModule>,
108
+ names: readonly string[],
109
+ ): Promise<Record<string, unknown>> {
110
+ const module = await createModule();
111
+ // The engine's linear memory, for a bench page's memory report (`memory.buffer` survives growth).
112
+ const memory = (module as { wasmMemory?: WebAssembly.Memory }).wasmMemory;
113
+ if (memory !== undefined)
114
+ (globalThis as { __tnWasmMemoryBytes?: () => number }).__tnWasmMemoryBytes = () =>
115
+ memory.buffer.byteLength;
116
+ const runtime = createWasmRuntime(module);
117
+ const { classes, wrap, collect, crossings } = defineBrowserClasses(
118
+ registry as IRegistryDump,
119
+ runtime,
120
+ engineCatalog,
121
+ );
122
+ // Engine crossings so far, for a bench page's per-frame bridgeCalls (the pair's crossing budget).
123
+ (globalThis as { __tnCrossingCount?: () => number }).__tnCrossingCount = crossings;
124
+ defineTypeFlags(classes);
125
+ // three's BatchedMesh/InstancedMesh.dispose frees the instance textures; the engine frees its instance
126
+ // buffers with the object, so the call has nothing to release (core's projection mirror makes it).
127
+ for (const name of ["BatchedMesh", "InstancedMesh"]) {
128
+ const prototype = (classes[name] as { prototype: { dispose?: () => void } } | undefined)
129
+ ?.prototype;
130
+ if (prototype !== undefined) prototype.dispose ??= () => {};
131
+ }
132
+ // attributes/groups, shape.holes and the abstract Material, as on the V8 player (object-surface.ts).
133
+ const entries = engineCatalog.entries;
134
+ const extending = (base: string) =>
135
+ entries
136
+ .filter(
137
+ (entry) =>
138
+ entry.kind === "class" && entry.extends === base && classes[entry.name] !== undefined,
139
+ )
140
+ .map((entry) => classes[entry.name] as new (...args: never[]) => object);
141
+ if (classes.BufferGeometry !== undefined)
142
+ defineObjectSurface({
143
+ bufferGeometry: classes.BufferGeometry,
144
+ // Every geometry class that binds its own setAttribute, not only BufferGeometry's children.
145
+ geometries: Object.values(classes).filter(
146
+ (cls) => cls !== classes.BufferGeometry && Object.hasOwn(cls.prototype, "setAttribute"),
147
+ ) as (new (
148
+ ...args: never[]
149
+ ) => object)[],
150
+ ...(classes.Shape === undefined ? {} : { shape: classes.Shape }),
151
+ materials: extending("Material"),
152
+ });
153
+ // TSL through the engine's shared name table (tn_tsl_call), when the module carries it.
154
+ const tsl = runtime.tsl ? defineTsl(runtime.tsl, classes as never) : undefined;
155
+ const bound: Record<string, unknown> = {
156
+ ...withTextureSources(classes, runtime),
157
+ ...tsl?.exports,
158
+ };
159
+ bound.Material = Material;
160
+ bound.ReadbackBuffer = ReadbackBuffer;
161
+ // three's PropertyBinding statics and console function over the engine class (shared with V8).
162
+ if (classes.PropertyBinding !== undefined)
163
+ Object.assign(bound, definePropertyBinding(classes.PropertyBinding as never));
164
+ // three's audio classes over the engine Object3D and the page's WebAudio; the renderer pushes
165
+ // world poses to WebAudio each frame, where three's own render calls updateMatrixWorld.
166
+ const audio = defineAudioClasses({
167
+ // quality-allow: the registry classes are read as the audio engine surface, which declares only the classes it uses.
168
+ ...(classes as unknown as Omit<IAudioEngine, "read">),
169
+ read: async (url) => {
170
+ const response = await fetch(url);
171
+ if (!response.ok) throw new Error(`TN_AUDIO_FETCH: ${String(response.status)} ${url}`);
172
+ return response.arrayBuffer();
173
+ },
174
+ });
175
+ const { AudioContext, AudioListener, Audio, PositionalAudio, AudioLoader } = audio;
176
+ Object.assign(bound, { AudioContext, AudioListener, Audio, PositionalAudio, AudioLoader });
177
+ // three's QuadMesh over the engine Mesh (quad-mesh.ts), shared with the V8 player.
178
+ bound.QuadMesh = defineQuadMesh(classes as never);
179
+ // three/webgpu's BlendMode, the record mrt().setBlendMode takes (data only, as on the engine's scene pass).
180
+ bound.BlendMode = BlendMode;
181
+ // The engine's four MathUtils functions, with the rest of three's number-only ones beside them.
182
+ bound.MathUtils = withMathUtilsExtras(bound.MathUtils as new () => object);
183
+ // Offscreen PassNodes (pass-node.ts) draw into their targets at the top of each frame; the TSL block below binds it.
184
+ let drawSecondaryPasses: PassUpdate = () => {};
185
+ // The product host draws; a module without it (the ABI-only test module) keeps the refusal.
186
+ // Before each frame: edited Color/VectorN uniform values reach the engine, world poses WebAudio,
187
+ // and the wrapper safe point runs (collect: held while the engine references them).
188
+ if (isWebHostModule(module))
189
+ bound.WebGPURenderer = defineWebRenderer(
190
+ module,
191
+ classes.Color as never,
192
+ (frame) => {
193
+ collect();
194
+ tsl?.sync(frame);
195
+ audio.updateAudio();
196
+ },
197
+ runtime.tsl,
198
+ (surface, draw) => drawSecondaryPasses(surface, draw),
199
+ );
200
+ // A GLB through the engine's own glTF loader, for the web GLTFLoader (addons/gltf-loader-web.ts).
201
+ const { loadGltf } = runtime;
202
+ if (loadGltf !== undefined)
203
+ bound.__tnLoadGltf = (bytes: Uint8Array, files?: ReadonlyMap<string, Uint8Array>) => {
204
+ const loaded = loadGltf.call(runtime, bytes, files);
205
+ return { scene: wrap(loaded.scene), animations: loaded.animations.map(wrap) };
206
+ };
207
+ if (tsl !== undefined && runtime.tsl !== undefined) {
208
+ const native = tsl.exports.reflector as (...args: unknown[]) => object;
209
+ bound.reflector = defineReflector(native, classes as never);
210
+ // The engine's TSL functions three does not export by name (ao, bloom, ...), for the shared post
211
+ // effects (addons/post-effects-web.ts), and three's RenderPipeline over the web host.
212
+ bound.__tnTsl = tsl.exports;
213
+ // three's pass() and mrt() over the engine's scene pass, as on the V8 player: RenderPipeline
214
+ // draws the scene and camera the pass points at.
215
+ const target: { scene?: unknown; camera?: unknown } = {};
216
+ bound.RenderPipeline = defineRenderPipeline(runtime.tsl, target);
217
+ const passes = definePass(
218
+ tsl.exports as never,
219
+ (scene, camera) => {
220
+ target.scene = scene;
221
+ target.camera = camera;
222
+ },
223
+ classes.RenderTarget === undefined
224
+ ? undefined
225
+ : // quality-allow: three's class name, so a back end passes its class map.
226
+ // biome-ignore lint/style/useNamingConvention: three's class name, so a back end passes its class map.
227
+ { RenderTarget: classes.RenderTarget as never },
228
+ );
229
+ drawSecondaryPasses = passes.updateSecondaryPasses;
230
+ Object.assign(bound, passes);
231
+ }
232
+ return bindUpstreamExports(names, engineCatalog, bound);
233
+ }
234
+
235
+ /**
236
+ * The engine classes plus what plain JS adds over them: three's texture sources (typed array,
237
+ * canvas, image, ImageBitmapLoader) and `DataUtils`, which touches no engine object at all.
238
+ */
239
+ export function withTextureSources(
240
+ classes: Readonly<Record<string, unknown>>,
241
+ runtime: IBrowserRuntime,
242
+ ): Record<string, unknown> {
243
+ return { ...classes, ...defineTextureSources(classes, runtime), DataUtils };
244
+ }
245
+
246
+ interface IPipelineRenderer {
247
+ [RENDER_AGAIN]?: () => void;
248
+ render?(scene: unknown, camera: unknown): void;
249
+ }
250
+
251
+ /**
252
+ * three's RenderPipeline on the Wasm engine, as on the V8 player: render() hands the output graph to
253
+ * the web host, which draws it between the scene and the output, over the scene and camera the
254
+ * graph's `pass(scene, camera)` points at (`target`), else the renderer's last scene.
255
+ */
256
+ function defineRenderPipeline(tsl: ITslRuntime, target: { scene?: unknown; camera?: unknown }) {
257
+ return class RenderPipeline {
258
+ outputNode: unknown;
259
+ outputColorTransform = true;
260
+ readonly context: { onBeforeRenderPipeline?: () => void; onAfterRenderPipeline?: () => void } =
261
+ {};
262
+ private outputSource?: number;
263
+ private outputGraph?: number;
264
+ readonly renderer: IPipelineRenderer;
265
+
266
+ constructor(renderer: IPipelineRenderer, outputNode?: unknown) {
267
+ this.renderer = renderer;
268
+ this.outputNode = outputNode;
269
+ }
270
+
271
+ render(): void {
272
+ if (!isTslNode(this.outputNode))
273
+ throw new TypeError("TN_WASM_POST: RenderPipeline.outputNode is not a TSL node");
274
+ this.context.onBeforeRenderPipeline?.();
275
+ try {
276
+ tsl.setPost(this.graph(this.outputNode[TSL_NODE]));
277
+ if (target.scene !== undefined && target.camera !== undefined && this.renderer.render)
278
+ this.renderer.render(target.scene, target.camera);
279
+ else this.renderer[RENDER_AGAIN]?.();
280
+ } finally {
281
+ this.context.onAfterRenderPipeline?.();
282
+ }
283
+ }
284
+
285
+ private graph(source: number): number {
286
+ if (this.outputSource !== source) {
287
+ if (this.outputGraph !== undefined) tsl.release(this.outputGraph);
288
+ this.outputSource = source;
289
+ this.outputGraph = undefined;
290
+ }
291
+ if (!this.outputColorTransform)
292
+ this.outputGraph ??= tsl.call("pipelineOutput", null, [
293
+ { kind: "node", node: source },
294
+ { kind: "number", number: 0 },
295
+ ]);
296
+ return this.outputColorTransform ? source : (this.outputGraph ?? source);
297
+ }
298
+
299
+ dispose(): void {
300
+ tsl.setPost(null);
301
+ if (this.outputGraph !== undefined) tsl.release(this.outputGraph);
302
+ this.outputGraph = undefined;
303
+ }
304
+ };
305
+ }