@threenative/three-native 0.3.11 → 0.3.13

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.
@@ -10,8 +10,10 @@
10
10
  import catalogJson from "../api/catalog.json" with { type: "json" };
11
11
  import registry from "../api/native-registry.json" with { type: "json" };
12
12
  import { DataUtils } from "./addons/data-utils.js";
13
+ import { AnimationUtils, defineCreateInterpolant } from "./animation-utils.js";
13
14
  import { type IAudioEngine, defineAudioClasses } from "./audio.js";
14
15
  import { BlendMode } from "./blend-mode.js";
16
+ import { defineBox2 } from "./box2.js";
15
17
  import {
16
18
  type IBrowserRuntime,
17
19
  type IRegistryDump,
@@ -20,6 +22,7 @@ import {
20
22
  createWasmRuntime,
21
23
  defineBrowserClasses,
22
24
  } from "./browser-backend.js";
25
+ import { LOADERS } from "./browser-loaders.js";
23
26
  import { ColorManagement } from "./browser-math.js";
24
27
  import {
25
28
  PIPELINE_POST,
@@ -29,14 +32,24 @@ import {
29
32
  isWebHostModule,
30
33
  } from "./browser-renderer.js";
31
34
  import { type ITslRuntime, defineTsl, isTslNode } from "./browser-tsl.js";
35
+ import { defineTypedBufferAttribute } from "./buffer-attributes.js";
32
36
  import type { CatalogEntry, ICatalog } from "./catalog.js";
37
+ import { defineEdgesGeometry } from "./edges-geometry.js";
38
+ import { WEB_FRAME_FIELD } from "./generated/web-frame-fields.js";
33
39
  import { CPU_STAGE_FIELDS } from "./gpu-stages.js";
40
+ import { defineGridHelper } from "./grid-helper.js";
34
41
  import { withMathUtilsExtras } from "./math-utils.js";
35
- import { Material, defineObjectSurface, defineTypeFlags } from "./object-surface.js";
42
+ import {
43
+ Material,
44
+ defineObjectSurface,
45
+ defineReleaseNoops,
46
+ defineTypeFlags,
47
+ } from "./object-surface.js";
36
48
  import { type PassDraw, definePass } from "./pass-node.js";
37
49
  import { definePropertyBinding } from "./property-binding.js";
38
50
  import { defineQuadMesh } from "./quad-mesh.js";
39
51
  import { defineReflector } from "./reflector.js";
52
+ import { defineLayeredTargets } from "./render-target.js";
40
53
  import { defineRendererUtils } from "./renderer-utils.js";
41
54
  import { ShadowBaseNode } from "./shadow-node.js";
42
55
  import { ReadbackBuffer } from "./storage.js";
@@ -52,7 +65,8 @@ const UPSTREAM_SOURCES = new Set(["three", "three/webgpu", "three/tsl"]);
52
65
  /**
53
66
  * A value that throws `diagnostic` on any call, construction or property access. Its `prototype`
54
67
  * alone reads, so a module may declare a subclass (core's `VirtualShadowNode extends ShadowBaseNode`)
55
- * and fail only when it constructs one.
68
+ * and fail only when it constructs one. `Symbol.hasInstance` reads as absent, so `x instanceof Sub`
69
+ * is the ordinary prototype check (always false here) instead of a throw on every caller.
56
70
  */
57
71
  function refused(name: string, diagnostic: string): unknown {
58
72
  const fail = (): never => {
@@ -61,7 +75,8 @@ function refused(name: string, diagnostic: string): unknown {
61
75
  return new Proxy(function refusedExport() {}, {
62
76
  apply: fail,
63
77
  construct: fail,
64
- get: (target, key) => (key === "prototype" ? target.prototype : fail()),
78
+ get: (target, key) =>
79
+ key === "prototype" ? target.prototype : key === Symbol.hasInstance ? undefined : fail(),
65
80
  set: fail,
66
81
  has: fail,
67
82
  ownKeys: fail,
@@ -163,20 +178,14 @@ export async function bindWebEngine(
163
178
  ? () => {
164
179
  const totals = { ...counters() };
165
180
  // Off, the engine reads no clock and the totals stand at their last value: listing them would report a stale cost.
166
- if (module._tnw_web_frame(84) !== 0)
181
+ if (module._tnw_web_frame(WEB_FRAME_FIELD.cpuMetersActive) !== 0)
167
182
  for (const [name, field] of Object.entries(CPU_STAGE_FIELDS))
168
183
  totals[name] = module._tnw_web_frame(field);
169
184
  return totals;
170
185
  }
171
186
  : counters;
172
187
  defineTypeFlags(classes);
173
- // three's BatchedMesh/InstancedMesh.dispose frees the instance textures; the engine frees its instance
174
- // buffers with the object, so the call has nothing to release (core's projection mirror makes it).
175
- for (const name of ["BatchedMesh", "InstancedMesh"]) {
176
- const prototype = (classes[name] as { prototype: { dispose?: () => void } } | undefined)
177
- ?.prototype;
178
- if (prototype !== undefined) prototype.dispose ??= () => {};
179
- }
188
+ defineReleaseNoops(classes);
180
189
  // attributes/groups, shape.holes and the abstract Material, as on the V8 player (object-surface.ts).
181
190
  const entries = engineCatalog.entries;
182
191
  const extending = (base: string) =>
@@ -226,12 +235,30 @@ export async function bindWebEngine(
226
235
  Object.assign(bound, { AudioContext, AudioListener, Audio, PositionalAudio, AudioLoader });
227
236
  // three's QuadMesh over the engine Mesh (quad-mesh.ts), shared with the V8 player.
228
237
  bound.QuadMesh = defineQuadMesh(classes as never);
238
+ // three's GridHelper over the engine LineSegments (grid-helper.ts), shared with the V8 player.
239
+ bound.GridHelper = defineGridHelper(classes as never);
240
+ // three's CubeRenderTarget, RenderTarget3D and CubeCamera (render-target.ts), shared with the V8 player.
241
+ Object.assign(bound, defineLayeredTargets(classes as never));
242
+ // three's EdgesGeometry, Box2, typed BufferAttributes and AnimationUtils: JS ports shared with V8.
243
+ bound.EdgesGeometry = defineEdgesGeometry(classes as never);
244
+ bound.Box2 = defineBox2(classes as never);
245
+ const attribute = classes.BufferAttribute as Parameters<typeof defineTypedBufferAttribute>[0];
246
+ bound.Uint8BufferAttribute = defineTypedBufferAttribute(attribute, Uint8Array);
247
+ bound.Uint16BufferAttribute = defineTypedBufferAttribute(attribute, Uint16Array);
248
+ bound.Uint32BufferAttribute = defineTypedBufferAttribute(attribute, Uint32Array);
249
+ bound.AnimationUtils = AnimationUtils;
250
+ // three's track.createInterpolant over the engine tracks, shared with V8 (PRD-854).
251
+ defineCreateInterpolant(classes);
252
+ // three's viewportCoordinate is screenCoordinate minus viewport.xy, which is (0, 0) on a full-target pass.
253
+ if (bound.screenCoordinate !== undefined) bound.viewportCoordinate = bound.screenCoordinate;
229
254
  // three/webgpu's BlendMode, the record mrt().setBlendMode takes (data only, as on the engine's scene pass).
230
255
  bound.BlendMode = BlendMode;
231
256
  // The engine's four MathUtils functions, with the rest of three's number-only ones beside them.
232
257
  bound.MathUtils = withMathUtilsExtras(bound.MathUtils as new () => object);
233
258
  // Offscreen PassNodes (pass-node.ts) draw into their targets at the top of each frame; the TSL block below binds it.
234
259
  let drawSecondaryPasses: PassUpdate = () => {};
260
+ // A frame PassNode's updateBefore runs once a frame, as three's node update system runs it.
261
+ let updatePasses: (frame?: { frameId?: number }) => void = () => {};
235
262
  // The product host draws; a module without it (the ABI-only test module) keeps the refusal.
236
263
  // Before each frame: edited Color/VectorN uniform values reach the engine, world poses WebAudio,
237
264
  // and the wrapper safe point runs (collect: held while the engine references them).
@@ -243,11 +270,16 @@ export async function bindWebEngine(
243
270
  bound.WebGPURenderer = defineWebRenderer(
244
271
  module,
245
272
  classes.Color as never,
246
- (frame) => {
273
+ (frame, kernels) => {
274
+ // Each renderer render runs the live frame passes' updateBefore, as three's node update does;
275
+ // a render that advances no frame (a standing frame the runner asks for) still hears them.
276
+ updatePasses(frame);
247
277
  // A compute dispatch passes no frame: it belongs to the frame already collected.
248
278
  const frameId = frame?.frameId ?? collectedFrame;
249
279
  if (updating || (frameId !== undefined && frameId === collectedFrame)) {
250
- tsl?.sync(frame);
280
+ // A dispatch's sync carries that frame, so the frame hooks that already ran do not run again for it,
281
+ // and its kernels, so it runs only the hooks they read (PRD-878).
282
+ tsl?.sync(frame ?? (frameId === undefined ? undefined : { frameId, kernels }));
251
283
  return;
252
284
  }
253
285
  collectedFrame = frameId;
@@ -265,11 +297,18 @@ export async function bindWebEngine(
265
297
  bound.DataTexture as never,
266
298
  );
267
299
  // A GLB through the engine's own glTF loader, for the web GLTFLoader (addons/gltf-loader-web.ts).
268
- const { loadGltf } = runtime;
300
+ // Off the main thread when the engine has a loader thread (PRD-860), else in the call.
301
+ const { loadGltf, loadGltfAsync } = runtime;
269
302
  if (loadGltf !== undefined)
270
- bound.__tnLoadGltf = (bytes: Uint8Array, files?: ReadonlyMap<string, Uint8Array>) => {
271
- const loaded = loadGltf.call(runtime, bytes, files);
272
- return { scene: wrap(loaded.scene), animations: loaded.animations.map(wrap) };
303
+ bound.__tnLoadGltf = async (bytes: Uint8Array, files?: ReadonlyMap<string, Uint8Array>) => {
304
+ const loaded = await (loadGltfAsync !== undefined
305
+ ? loadGltfAsync.call(runtime, bytes, files)
306
+ : loadGltf.call(runtime, bytes, files));
307
+ return {
308
+ scene: wrap(loaded.scene),
309
+ scenes: loaded.scenes.map(wrap),
310
+ animations: loaded.animations.map(wrap),
311
+ };
273
312
  };
274
313
  if (tsl !== undefined && runtime.tsl !== undefined) {
275
314
  const native = tsl.exports.reflector as (...args: unknown[]) => object;
@@ -281,6 +320,8 @@ export async function bindWebEngine(
281
320
  // draws the scene and camera the pass points at.
282
321
  const target: { scene?: unknown; camera?: unknown } = {};
283
322
  bound.RenderPipeline = defineRenderPipeline(runtime.tsl, target);
323
+ // The frame counters a host module answers (0 from a module without one, before it draws).
324
+ const hostFrame = (module as Partial<WebHostModule>)._tnw_web_frame;
284
325
  const passes = definePass(
285
326
  tsl.exports as never,
286
327
  (scene, camera) => {
@@ -289,11 +330,21 @@ export async function bindWebEngine(
289
330
  },
290
331
  classes.RenderTarget === undefined
291
332
  ? undefined
292
- : // quality-allow: three's class name, so a back end passes its class map.
293
- // biome-ignore lint/style/useNamingConvention: three's class name, so a back end passes its class map.
294
- { RenderTarget: classes.RenderTarget as never },
333
+ : {
334
+ // quality-allow: three's class name, so a back end passes its class map.
335
+ // biome-ignore lint/style/useNamingConvention: three's class name, so a back end passes its class map.
336
+ RenderTarget: classes.RenderTarget as never,
337
+ // The frame pass draws at the engine's input size, at the frame's sample count (tnw_web_frame's
338
+ // 35, 36 and 18), so a game reads the size and MSAA the engine actually drew.
339
+ surface: () => ({
340
+ width: hostFrame?.call(module, WEB_FRAME_FIELD.inputWidth) ?? 0,
341
+ height: hostFrame?.call(module, WEB_FRAME_FIELD.inputHeight) ?? 0,
342
+ }),
343
+ samples: () => hostFrame?.call(module, WEB_FRAME_FIELD.sampleCount) ?? 0,
344
+ },
295
345
  );
296
346
  drawSecondaryPasses = passes.updateSecondaryPasses;
347
+ updatePasses = passes.updateFramePasses;
297
348
  Object.assign(bound, passes);
298
349
  }
299
350
  return bindUpstreamExports(names, engineCatalog, bound);
@@ -301,13 +352,19 @@ export async function bindWebEngine(
301
352
 
302
353
  /**
303
354
  * The engine classes plus what plain JS adds over them: three's texture sources (typed array,
304
- * canvas, image, ImageBitmapLoader), `DataUtils`, and the `ColorManagement` singleton.
355
+ * canvas, image, ImageBitmapLoader), three's loader base classes, `DataUtils`, and the `ColorManagement` singleton.
305
356
  */
306
357
  export function withTextureSources(
307
358
  classes: Readonly<Record<string, unknown>>,
308
359
  runtime: IBrowserRuntime,
309
360
  ): Record<string, unknown> {
310
- return { ...classes, ...defineTextureSources(classes, runtime), DataUtils, ColorManagement };
361
+ return {
362
+ ...classes,
363
+ ...defineTextureSources(classes, runtime),
364
+ ...LOADERS,
365
+ DataUtils,
366
+ ColorManagement,
367
+ };
311
368
  }
312
369
 
313
370
  interface IPipelineRenderer {
@@ -0,0 +1,12 @@
1
+ /**
2
+ * three's loader base classes in JavaScript (three's own modules, MIT), for the browser back end:
3
+ * `Loader`, `FileLoader`, `LoadingManager` and `Cache` only fetch and track requests, so they draw
4
+ * nothing and need no engine call. An upstream loader that extends them (KTX2Loader, PRD-867) runs
5
+ * over the engine's textures unchanged.
6
+ */
7
+ import { Cache } from "three/src/loaders/Cache.js";
8
+ import { FileLoader } from "three/src/loaders/FileLoader.js";
9
+ import { Loader } from "three/src/loaders/Loader.js";
10
+ import { DefaultLoadingManager, LoadingManager } from "three/src/loaders/LoadingManager.js";
11
+
12
+ export const LOADERS = { Cache, DefaultLoadingManager, FileLoader, Loader, LoadingManager };
@@ -0,0 +1,79 @@
1
+ /**
2
+ * What a JS value becomes on its way to the engine (PRD-532, PRD-803): three's typed arrays with the
3
+ * engine's scalar order they name, the symbol that keeps a value's storage type, the ref slot every
4
+ * engine wrapper carries, and the parameter rules three's own `Color.set` and `Material.setValues`
5
+ * apply to a constructor's parameters object.
6
+ */
7
+
8
+ export type TypedArray =
9
+ | Float32Array
10
+ | Float64Array
11
+ | Int8Array
12
+ | Uint8Array
13
+ | Int16Array
14
+ | Uint16Array
15
+ | Int32Array
16
+ | Uint32Array;
17
+
18
+ export const REF = Symbol("tn.engineRef");
19
+
20
+ /** A number list that came from a typed array names it, so the engine keeps three's storage type. */
21
+ export const TYPED = Symbol("tn.typedArray");
22
+ // The engine's Scalar order: F32, F64, I8, U8, I16, U16, I32, U32.
23
+ export const SCALARS = [
24
+ Float32Array,
25
+ Float64Array,
26
+ Int8Array,
27
+ Uint8Array,
28
+ Int16Array,
29
+ Uint16Array,
30
+ Int32Array,
31
+ Uint32Array,
32
+ ];
33
+
34
+ export function isPlainObject(value: unknown): boolean {
35
+ return (
36
+ typeof value === "object" && value !== null && Object.getPrototypeOf(value) === Object.prototype
37
+ );
38
+ }
39
+
40
+ export function isWrapperOf(
41
+ value: unknown,
42
+ className: string,
43
+ ): value is Record<string, (...args: unknown[]) => unknown> {
44
+ return (
45
+ typeof value === "object" &&
46
+ value !== null &&
47
+ REF in value &&
48
+ value.constructor.name === className
49
+ );
50
+ }
51
+
52
+ /** three's `Color.set`: a hex number, a CSS string, or another Color. */
53
+ export function setColor(
54
+ color: Record<string, (...args: unknown[]) => unknown>,
55
+ value: unknown,
56
+ ): void {
57
+ if (typeof value === "number") color.setHex?.(value);
58
+ else if (typeof value === "string") color.setStyle?.(value);
59
+ else color.copy?.(value);
60
+ }
61
+
62
+ /**
63
+ * three's `Material.setValues`: an undefined value is skipped, a Color member is set from a hex,
64
+ * a CSS string or another Color, a Vector3 member copies a Vector3, everything else is assigned.
65
+ * three warns and drops a key the object does not have; here that key fails.
66
+ */
67
+ export function setValues(target: object, className: string, values: object): void {
68
+ const self = target as Record<string, unknown>;
69
+ for (const [key, value] of Object.entries(values)) {
70
+ if (value === undefined) continue;
71
+ const current = self[key];
72
+ if (current === undefined)
73
+ throw new TypeError(`TN_BROWSER_PARAMETER_UNSUPPORTED: ${className} has no '${key}'`);
74
+ if (isWrapperOf(current, "Color")) setColor(current, value);
75
+ else if (isWrapperOf(current, "Vector3") && (value as { isVector3?: boolean }).isVector3)
76
+ current.copy?.(value);
77
+ else self[key] = value;
78
+ }
79
+ }