@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.
@@ -264,6 +264,11 @@ function defineTraversal(
264
264
  * Defines every registry class over `runtime`. With `catalog`, classes chain as three's do
265
265
  * (`mesh instanceof Object3D`) and carry three's `is*` flags.
266
266
  */
267
+ /** A catalog field that is one of three's `is<Class>` type flags, which the back end sets to true. */
268
+ export const isTypeFlagField = (field: { name: string; type: string; mutable?: boolean }) =>
269
+ /^is[A-Z]/u.test(field.name) &&
270
+ (field.type === "true" || (field.type === "boolean" && field.mutable === false));
271
+
267
272
  export function defineBrowserClasses(
268
273
  registry: IRegistryDump,
269
274
  source: IBrowserRuntime,
@@ -683,12 +688,14 @@ export function defineBrowserClasses(
683
688
  itemSizes,
684
689
  shapes,
685
690
  pending,
691
+ dirty,
686
692
  writeBack,
687
693
  itemSizeOf,
688
694
  rangeOf,
689
695
  syncRange,
690
696
  syncFull,
691
697
  instanceItem,
698
+ writeItemAt,
692
699
  } = defineAttributeSync({ runtime, refOf });
693
700
 
694
701
  const fromEngine = (value: EngineValue): unknown => {
@@ -898,6 +905,12 @@ export function defineBrowserClasses(
898
905
  writable: true,
899
906
  value(this: object, ...args: unknown[]) {
900
907
  if (glueCounting) methodCalls += 1;
908
+ // An instance's matrix or colour is an array write, as in three, sent before the next engine call.
909
+ if (instanceWrite !== undefined && writeItemAt(this, instanceWrite, args[0], args[1])) {
910
+ labels.delete(this);
911
+ animated.delete(this);
912
+ return this;
913
+ }
901
914
  // three's toArray(array, offset) writes the lanes into the array it is given and answers that array; the
902
915
  // engine answers a new one, since a plain array crosses by value.
903
916
  if (method === "toArray" && args[0] !== undefined) {
@@ -919,7 +932,7 @@ export function defineBrowserClasses(
919
932
  } else if (schedule === "all") scheduling = new WeakMap();
920
933
  // A per-vertex setter writes its own range and reads no kept array, so a whole-shadow flush
921
934
  // would cost O(N) a call; it syncs just its range back below. Anything else flushes edits.
922
- if (pending.size > 0 && !rangeMethod && !bookkeeping) writeBack();
935
+ if ((pending.size > 0 || dirty.size > 0) && !rangeMethod && !bookkeeping) writeBack();
923
936
  // A full-array attribute transform reads its own array: send the game's shadow first.
924
937
  if (transformMethod) {
925
938
  const entry = arrays.get(this);
@@ -1056,8 +1069,9 @@ export function defineBrowserClasses(
1056
1069
  Object.getPrototypeOf(other) !== prototype
1057
1070
  )
1058
1071
  return engineCopy.call(this, other);
1059
- const from = (addressOf(other) + offset) / 8;
1060
- heapF64().copyWithin((addressOf(this) + offset) / 8, from, from + count);
1072
+ const to = addressOf(this) + offset;
1073
+ const from = addressOf(other) + offset;
1074
+ heapF64(Math.max(to, from) + count * 8).copyWithin(to / 8, from / 8, from / 8 + count);
1061
1075
  return this;
1062
1076
  },
1063
1077
  },
@@ -1071,9 +1085,9 @@ export function defineBrowserClasses(
1071
1085
  Object.getPrototypeOf(other) !== prototype
1072
1086
  )
1073
1087
  return engineEquals.call(this, other);
1074
- const heap = heapF64();
1075
1088
  const a = (addressOf(this) + offset) / 8;
1076
1089
  const b = (addressOf(other) + offset) / 8;
1090
+ const heap = heapF64((Math.max(a, b) + count) * 8);
1077
1091
  for (let i = 0; i < count; i++) if (heap[a + i] !== heap[b + i]) return false;
1078
1092
  return true;
1079
1093
  },
@@ -1715,15 +1729,13 @@ export function defineBrowserClasses(
1715
1729
  );
1716
1730
  }
1717
1731
  pending.delete(this);
1732
+ dirty.delete(this);
1718
1733
  }
1719
1734
  needsUpdate.set?.call(this, value);
1720
1735
  },
1721
1736
  });
1722
1737
  }
1723
1738
  }
1724
- const isFlag = (field: { name: string; type: string; mutable?: boolean }) =>
1725
- /^is[A-Z]/u.test(field.name) &&
1726
- (field.type === "true" || (field.type === "boolean" && field.mutable === false));
1727
1739
  for (const [name, cls] of Object.entries(classes)) {
1728
1740
  const entry = entries.get(name);
1729
1741
  const parent = entry?.extends ? classes[entry.extends] : undefined;
@@ -1735,13 +1747,68 @@ export function defineBrowserClasses(
1735
1747
  link = link.extends ? entries.get(link.extends) : undefined
1736
1748
  )
1737
1749
  // Writable: three's own value classes assign `this.isColor = true` in their constructors.
1738
- for (const field of (link.fields ?? []).filter(isFlag))
1750
+ for (const field of (link.fields ?? []).filter(isTypeFlagField))
1739
1751
  Object.defineProperty(cls.prototype, field.name, {
1740
1752
  configurable: true,
1741
1753
  writable: true,
1742
1754
  value: true,
1743
1755
  });
1744
1756
  }
1757
+ // PRD-828: the engine advances a whole frame's animation rigs in one crossing. Core finds it by this
1758
+ // name and keeps its own per-rig loop when a backend installs nothing, so this cannot change a game
1759
+ // that runs on a backend without it.
1760
+ if (source.animTick !== undefined) {
1761
+ (globalThis as { __tnAnimationTick?: unknown }).__tnAnimationTick = (
1762
+ rigs: readonly {
1763
+ readonly mixer: object;
1764
+ readonly action: object | null;
1765
+ readonly strideRoot: object | null;
1766
+ readonly dt: number;
1767
+ readonly elapsed: number;
1768
+ readonly step: boolean;
1769
+ readonly reset: boolean;
1770
+ readonly lastRate: number;
1771
+ readonly clipGroundSpeed: number;
1772
+ readonly strideSync: boolean;
1773
+ }[],
1774
+ status: Float64Array,
1775
+ ): void => {
1776
+ const count = rigs.length;
1777
+ if (count === 0) return;
1778
+ const mixers: ReturnType<typeof refOf>[] = [];
1779
+ const actions: (ReturnType<typeof refOf> | null)[] = [];
1780
+ const roots: (ReturnType<typeof refOf> | null)[] = [];
1781
+ const values = new Float64Array(count * 5);
1782
+ for (let i = 0; i < count; i += 1) {
1783
+ const rig = rigs[i];
1784
+ if (rig === undefined) continue;
1785
+ mixers.push(refOf(rig.mixer));
1786
+ actions.push(rig.action === null ? null : refOf(rig.action));
1787
+ roots.push(rig.strideRoot === null ? null : refOf(rig.strideRoot));
1788
+ values[i * 5] = rig.dt;
1789
+ values[i * 5 + 1] = rig.elapsed;
1790
+ values[i * 5 + 2] = rig.clipGroundSpeed;
1791
+ values[i * 5 + 3] = rig.lastRate;
1792
+ // bit 0: the stride convention applies; bit 1: the action is real; bit 2: the body is real;
1793
+ // bit 3: this tick poses the rig; bit 4: the player spent ticks this batch did not.
1794
+ values[i * 5 + 4] =
1795
+ (rig.strideSync ? 1 : 0) |
1796
+ (rig.action === null ? 0 : 2) |
1797
+ (rig.strideRoot === null ? 0 : 4) |
1798
+ (rig.step ? 8 : 0) |
1799
+ (rig.reset ? 16 : 0);
1800
+ }
1801
+ crossings += 1;
1802
+ const first = mixers[0];
1803
+ if (meter.counting && first !== undefined) meter.record("call", first, "tn_anim_tick");
1804
+ source.animTick?.({ mixers, actions, roots, values, status });
1805
+ // Nothing to invalidate: every field this call writes — the mixer's `time`, the action's `time`,
1806
+ // `timeScale` and `weight` — is an engine-memory field on this back end (`fastGetter` over
1807
+ // `readDoubles` in the registry's `fields`), not a JS mirror, so a read after it is the engine's
1808
+ // answer. `bridge-mirror.spec.ts` pins exactly that.
1809
+ };
1810
+ }
1811
+
1745
1812
  return {
1746
1813
  classes,
1747
1814
  wrap,
@@ -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,8 +32,12 @@ 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
42
  import {
36
43
  Material,
@@ -42,6 +49,7 @@ import { type PassDraw, definePass } from "./pass-node.js";
42
49
  import { definePropertyBinding } from "./property-binding.js";
43
50
  import { defineQuadMesh } from "./quad-mesh.js";
44
51
  import { defineReflector } from "./reflector.js";
52
+ import { defineLayeredTargets } from "./render-target.js";
45
53
  import { defineRendererUtils } from "./renderer-utils.js";
46
54
  import { ShadowBaseNode } from "./shadow-node.js";
47
55
  import { ReadbackBuffer } from "./storage.js";
@@ -170,7 +178,7 @@ export async function bindWebEngine(
170
178
  ? () => {
171
179
  const totals = { ...counters() };
172
180
  // Off, the engine reads no clock and the totals stand at their last value: listing them would report a stale cost.
173
- if (module._tnw_web_frame(84) !== 0)
181
+ if (module._tnw_web_frame(WEB_FRAME_FIELD.cpuMetersActive) !== 0)
174
182
  for (const [name, field] of Object.entries(CPU_STAGE_FIELDS))
175
183
  totals[name] = module._tnw_web_frame(field);
176
184
  return totals;
@@ -227,6 +235,22 @@ export async function bindWebEngine(
227
235
  Object.assign(bound, { AudioContext, AudioListener, Audio, PositionalAudio, AudioLoader });
228
236
  // three's QuadMesh over the engine Mesh (quad-mesh.ts), shared with the V8 player.
229
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;
230
254
  // three/webgpu's BlendMode, the record mrt().setBlendMode takes (data only, as on the engine's scene pass).
231
255
  bound.BlendMode = BlendMode;
232
256
  // The engine's four MathUtils functions, with the rest of three's number-only ones beside them.
@@ -246,14 +270,16 @@ export async function bindWebEngine(
246
270
  bound.WebGPURenderer = defineWebRenderer(
247
271
  module,
248
272
  classes.Color as never,
249
- (frame) => {
273
+ (frame, kernels) => {
250
274
  // Each renderer render runs the live frame passes' updateBefore, as three's node update does;
251
275
  // a render that advances no frame (a standing frame the runner asks for) still hears them.
252
276
  updatePasses(frame);
253
277
  // A compute dispatch passes no frame: it belongs to the frame already collected.
254
278
  const frameId = frame?.frameId ?? collectedFrame;
255
279
  if (updating || (frameId !== undefined && frameId === collectedFrame)) {
256
- 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 }));
257
283
  return;
258
284
  }
259
285
  collectedFrame = frameId;
@@ -271,11 +297,18 @@ export async function bindWebEngine(
271
297
  bound.DataTexture as never,
272
298
  );
273
299
  // A GLB through the engine's own glTF loader, for the web GLTFLoader (addons/gltf-loader-web.ts).
274
- 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;
275
302
  if (loadGltf !== undefined)
276
- bound.__tnLoadGltf = (bytes: Uint8Array, files?: ReadonlyMap<string, Uint8Array>) => {
277
- const loaded = loadGltf.call(runtime, bytes, files);
278
- 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
+ };
279
312
  };
280
313
  if (tsl !== undefined && runtime.tsl !== undefined) {
281
314
  const native = tsl.exports.reflector as (...args: unknown[]) => object;
@@ -304,10 +337,10 @@ export async function bindWebEngine(
304
337
  // The frame pass draws at the engine's input size, at the frame's sample count (tnw_web_frame's
305
338
  // 35, 36 and 18), so a game reads the size and MSAA the engine actually drew.
306
339
  surface: () => ({
307
- width: hostFrame?.call(module, 35) ?? 0,
308
- height: hostFrame?.call(module, 36) ?? 0,
340
+ width: hostFrame?.call(module, WEB_FRAME_FIELD.inputWidth) ?? 0,
341
+ height: hostFrame?.call(module, WEB_FRAME_FIELD.inputHeight) ?? 0,
309
342
  }),
310
- samples: () => hostFrame?.call(module, 18) ?? 0,
343
+ samples: () => hostFrame?.call(module, WEB_FRAME_FIELD.sampleCount) ?? 0,
311
344
  },
312
345
  );
313
346
  drawSecondaryPasses = passes.updateSecondaryPasses;
@@ -319,13 +352,19 @@ export async function bindWebEngine(
319
352
 
320
353
  /**
321
354
  * The engine classes plus what plain JS adds over them: three's texture sources (typed array,
322
- * canvas, image, ImageBitmapLoader), `DataUtils`, and the `ColorManagement` singleton.
355
+ * canvas, image, ImageBitmapLoader), three's loader base classes, `DataUtils`, and the `ColorManagement` singleton.
323
356
  */
324
357
  export function withTextureSources(
325
358
  classes: Readonly<Record<string, unknown>>,
326
359
  runtime: IBrowserRuntime,
327
360
  ): Record<string, unknown> {
328
- return { ...classes, ...defineTextureSources(classes, runtime), DataUtils, ColorManagement };
361
+ return {
362
+ ...classes,
363
+ ...defineTextureSources(classes, runtime),
364
+ ...LOADERS,
365
+ DataUtils,
366
+ ColorManagement,
367
+ };
329
368
  }
330
369
 
331
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 };