@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.
@@ -13,11 +13,36 @@
13
13
  */
14
14
 
15
15
  import { ENGINE_COST_KNOB, createBridgeMeter } from "./bridge-meter.js";
16
+ import {
17
+ type EngineValue,
18
+ type IBrowserRuntime,
19
+ type IEngineRef,
20
+ isRef,
21
+ } from "./browser-abi-types.js";
22
+ import { ATTRIBUTE_CLASSES, defineAttributeSync, denormalize } from "./browser-attribute-sync.js";
23
+ import { REF, type TypedArray, isPlainObject, setValues } from "./browser-marshal.js";
16
24
  import { UpstreamVector3, defineMath } from "./browser-math.js";
17
- import type { ITslRuntime, TslArgValue } from "./browser-tsl.js";
18
- import { type DebugTelemetry, debugTelemetry } from "./debug-telemetry.js";
25
+ import {
26
+ type IValueClass,
27
+ defaultPlan,
28
+ defineValueViews,
29
+ valuePlans,
30
+ } from "./browser-value-views.js";
31
+ import { debugTelemetry } from "./debug-telemetry.js";
32
+ import { isCustomMrtOutput } from "./pass-node.js";
19
33
  import { detachVirtualShadow, shadowFilterOptions, virtualShadowOptions } from "./shadow-node.js";
20
- import { withUpdateRanges } from "./update-ranges.js";
34
+ import { uploadRanges, withUpdateRanges } from "./update-ranges.js";
35
+
36
+ // The surface this module has always exported, kept on its path (PRD-803): `browser-entry.ts`,
37
+ // `browser-renderer.ts`, `browser-tsl.ts`, `texture-sources.ts` and the specs import them here.
38
+ export type {
39
+ EngineValue,
40
+ IBrowserRuntime,
41
+ IEngineRef,
42
+ TnAbiModule,
43
+ } from "./browser-abi-types.js";
44
+ export { createWasmRuntime } from "./browser-wasm-runtime.js";
45
+ export { eulerFromQuaternion } from "./browser-value-views.js";
21
46
 
22
47
  export interface IRegistryClass {
23
48
  readonly constructor: boolean;
@@ -39,83 +64,6 @@ export interface IRegistryDump {
39
64
  readonly classes: Readonly<Record<string, IRegistryClass>>;
40
65
  }
41
66
 
42
- /** A ref with its handle words kept (see `createWasmRuntime`): type | context << 16, index, generation. */
43
- interface IPackedRef extends IEngineRef {
44
- w0: number;
45
- w1: number;
46
- w2: number;
47
- }
48
-
49
- /** An engine object as the back end sees it: an opaque key and its catalog type id. */
50
- export interface IEngineRef {
51
- readonly key: string;
52
- readonly type: number;
53
- }
54
-
55
- export type EngineValue =
56
- | null
57
- | undefined
58
- | number
59
- | boolean
60
- | string
61
- | TypedArray
62
- | readonly EngineValue[]
63
- | IEngineRef
64
- | { readonly [key: string]: EngineValue };
65
-
66
- /** What the classes call; the Wasm ABI implements it, and a surface-only runtime refuses every call. */
67
- export interface IBrowserRuntime {
68
- readonly debugTelemetry?: DebugTelemetry;
69
- typeId(className: string): number;
70
- construct(className: string, args: readonly EngineValue[]): IEngineRef;
71
- invoke(self: IEngineRef, method: string, args: readonly EngineValue[]): EngineValue;
72
- get(self: IEngineRef, path: string): EngineValue;
73
- set(self: IEngineRef, path: string, value: EngineValue): void;
74
- release(self: IEngineRef): void;
75
- /** For each ref, how many references other engine objects hold to its object; one call a batch. */
76
- engineReferences?(refs: readonly IEngineRef[]): ArrayLike<number>;
77
- /** A numeric typed array argument crosses as is, no boxed copy; Wasm only. */
78
- readonly typedArrays?: boolean;
79
- /** Doubles at `address` in the engine's memory (one as a number, more as an array); Wasm only. */
80
- readDoubles?(address: number, count: number): number | number[];
81
- /**
82
- * The engine's memory as doubles, current: Emscripten replaces the view when the memory grows, so a caller
83
- * reads it per operation and never keeps it. Wasm only.
84
- */
85
- heapF64?(): Float64Array;
86
- /** The byte at `address` in the engine's memory; Wasm only. A registry field `[offset, 0]` is a byte flag. */
87
- readByte?(address: number): number;
88
- /** The 32-bit word at `address` in the engine's memory (the hierarchy counter's low word); Wasm only. */
89
- readWord?(address: number): number;
90
- /** Writes one double at `address` in the engine's memory; Wasm only. */
91
- writeDouble?(address: number, value: number): void;
92
- /** Writes the byte at `address` in the engine's memory (a flag field); Wasm only. */
93
- writeByte?(address: number, value: number): void;
94
- /**
95
- * A copy of the attribute's data, of its scalar type; three's `attribute.array` is built on it.
96
- * With `offset`/`count`, a copy of that scalar subrange only (a per-vertex setter syncs one item).
97
- */
98
- attributeArray?(self: IEngineRef, offset?: number, count?: number): TypedArray;
99
- /**
100
- * Writes `array` into the attribute's data; present with attributeArray. With `offset`, writes that
101
- * subrange; without it, `array` must be the attribute's whole data.
102
- */
103
- attributeWrite?(self: IEngineRef, array: TypedArray, offset?: number): void;
104
- /** Sets (or, with null, clears) a callback the engine runs; `handler` gets the engine's arguments. */
105
- setCallback(
106
- self: IEngineRef,
107
- name: string,
108
- handler: ((args: readonly EngineValue[]) => void) | null,
109
- ): void;
110
- /** TSL by name (PRD-540), when the module carries `tn_tsl_call`. */
111
- readonly tsl?: ITslRuntime;
112
- /** A GLB through the engine's own glTF loader (PRD-540), when the module carries the web host. */
113
- loadGltf?(
114
- bytes: Uint8Array,
115
- files?: ReadonlyMap<string, Uint8Array>,
116
- ): { readonly scene: IEngineRef; readonly animations: IEngineRef[] };
117
- }
118
-
119
67
  /** The engine node id a TSL wrapper (`browser-tsl.ts`) carries. */
120
68
  export const TSL_NODE = Symbol("tn.tslNode");
121
69
 
@@ -140,41 +88,10 @@ export interface IBrowserEngine {
140
88
  /** Safe points a pass over the settled wrappers spans. */
141
89
  const SETTLED_PASS = 64;
142
90
 
143
- const REF = Symbol("tn.engineRef");
144
91
  /** An engine object's address, kept on it after the first ask: every lane read and write needs it. */
145
92
  const ADDRESS = Symbol("tn.engineAddress");
146
93
 
147
- type TypedArray =
148
- | Float32Array
149
- | Float64Array
150
- | Int8Array
151
- | Uint8Array
152
- | Int16Array
153
- | Uint16Array
154
- | Int32Array
155
- | Uint32Array;
156
- /** A number list that came from a typed array names it, so the engine keeps three's storage type. */
157
- const TYPED = Symbol("tn.typedArray");
158
- // The engine's Scalar order: F32, F64, I8, U8, I16, U16, I32, U32.
159
- const SCALARS = [
160
- Float32Array,
161
- Float64Array,
162
- Int8Array,
163
- Uint8Array,
164
- Int16Array,
165
- Uint16Array,
166
- Int32Array,
167
- Uint32Array,
168
- ];
169
- const ATTRIBUTE_CLASSES = new Set([
170
- "BufferAttribute",
171
- "Float32BufferAttribute",
172
- "Uint16BufferAttribute",
173
- "Uint32BufferAttribute",
174
- "InstancedBufferAttribute",
175
- ]);
176
-
177
- interface IWrapped {
94
+ export interface IWrapped {
178
95
  [REF]: IEngineRef;
179
96
  }
180
97
 
@@ -197,54 +114,6 @@ export function engineRef(object: object): IEngineRef | undefined {
197
114
  return (object as Partial<IWrapped>)[REF];
198
115
  }
199
116
 
200
- function isRef(value: unknown): value is IEngineRef {
201
- return typeof value === "object" && value !== null && "key" in value && "type" in value;
202
- }
203
-
204
- function isPlainObject(value: unknown): boolean {
205
- return (
206
- typeof value === "object" && value !== null && Object.getPrototypeOf(value) === Object.prototype
207
- );
208
- }
209
-
210
- function isWrapperOf(
211
- value: unknown,
212
- className: string,
213
- ): value is Record<string, (...args: unknown[]) => unknown> {
214
- return (
215
- typeof value === "object" &&
216
- value !== null &&
217
- REF in value &&
218
- value.constructor.name === className
219
- );
220
- }
221
-
222
- /** three's `Color.set`: a hex number, a CSS string, or another Color. */
223
- function setColor(color: Record<string, (...args: unknown[]) => unknown>, value: unknown): void {
224
- if (typeof value === "number") color.setHex?.(value);
225
- else if (typeof value === "string") color.setStyle?.(value);
226
- else color.copy?.(value);
227
- }
228
-
229
- /**
230
- * three's `Material.setValues`: an undefined value is skipped, a Color member is set from a hex,
231
- * a CSS string or another Color, a Vector3 member copies a Vector3, everything else is assigned.
232
- * three warns and drops a key the object does not have; here that key fails.
233
- */
234
- function setValues(target: object, className: string, values: object): void {
235
- const self = target as Record<string, unknown>;
236
- for (const [key, value] of Object.entries(values)) {
237
- if (value === undefined) continue;
238
- const current = self[key];
239
- if (current === undefined)
240
- throw new TypeError(`TN_BROWSER_PARAMETER_UNSUPPORTED: ${className} has no '${key}'`);
241
- if (isWrapperOf(current, "Color")) setColor(current, value);
242
- else if (isWrapperOf(current, "Vector3") && (value as { isVector3?: boolean }).isVector3)
243
- current.copy?.(value);
244
- else self[key] = value;
245
- }
246
- }
247
-
248
117
  /** What the back end reads from the catalog: each class's parent and three's `is*` flags. */
249
118
  export interface ICatalogShape {
250
119
  readonly entries: readonly {
@@ -270,8 +139,18 @@ export const LANGUAGE_MEMBERS = [
270
139
  "getObjectByName",
271
140
  "getObjectById",
272
141
  "raycast",
142
+ "dispose",
273
143
  ] as const;
274
144
 
145
+ /**
146
+ * three r187's `Object3D.dispose()`: it fires `dispose`, the event a renderer frees the object's
147
+ * render objects on, so a game's `Group` subclass can end its own `dispose()` with
148
+ * `super.dispose()`. An engine binding with a `dispose` of its own keeps that one.
149
+ */
150
+ function disposeObject(this: { dispatchEvent?(event: { type: string }): void }): void {
151
+ this.dispatchEvent?.({ type: "dispose" });
152
+ }
153
+
275
154
  type TraverseCallback = (object: object) => void;
276
155
 
277
156
  /** The engine classes with their own raycast (`Mesh::raycast`, `Line::raycast`, `LOD::raycast`). */
@@ -727,457 +606,8 @@ export function defineBrowserClasses(
727
606
  Object.defineProperty(self, ADDRESS, { value: address });
728
607
  return address;
729
608
  };
730
- // three's math values are JS (browser-math.ts): `new Vector3()` holds its own lanes. The engine's
731
- // vectors (`mesh.position`) share that prototype through `engine`, whose lanes are its memory.
732
- // An engine call takes a JS value by value: a method borrows a pooled engine object and copies
733
- // the lanes back after the call (an output argument); a constructor or setter, which may keep the
734
- // object, gets the value itself turned into an engine object in place, so identity survives.
735
- //
736
- // A class may store its lanes under three's private names (`Quaternion._x`, `Matrix4.elements`) or
737
- // hold them in member vectors (`Box3.min`): its plan reads and writes those, and says which own
738
- // properties a promoted value must drop so the engine accessors take over.
739
- /** A value class's JS storage: its public lanes, three's private names, and member vectors. */
740
- interface IValueLanes {
741
- [key: string]: unknown;
742
- _x?: number;
743
- _y?: number;
744
- _z?: number;
745
- _w?: number;
746
- _order?: string;
747
- elements?: number[];
748
- radius?: number;
749
- min?: { x: number; y: number; z: number; set(x: number, y: number, z: number): unknown };
750
- max?: { x: number; y: number; z: number; set(x: number, y: number, z: number): unknown };
751
- center?: { x: number; y: number; z: number; set(x: number, y: number, z: number): unknown };
752
- }
753
- interface IValuePlan {
754
- /** The engine's lane names, in the order its constructor takes them. */
755
- lanes: readonly string[];
756
- /** Own JS properties the class keeps its storage in; a promoted value drops them. */
757
- drop: readonly string[];
758
- /** The lanes of a JS value, in `lanes` order (Euler appends its order). */
759
- read(value: IValueLanes): number[];
760
- /** Writes engine lanes back into a JS value, as `lend` copies them back. */
761
- write(value: IValueLanes, values: readonly number[]): void;
762
- /** Engine constructor arguments; the lanes themselves by default. */
763
- args?(values: number[], make: (name: string, values: number[]) => IEngineRef): EngineValue[];
764
- /** A method argument becomes an engine object in place: whole-object lanes and output targets. */
765
- promote?: boolean;
766
- /** Copies the lanes from one value to another with no list between: a loan's two copies. */
767
- copy?(target: IValueLanes, source: IValueLanes): void;
768
- }
769
- interface IValueClass {
770
- name: string;
771
- engine: object;
772
- pool: object[];
773
- top: number;
774
- plan: IValuePlan;
775
- }
776
- const eulerOrders = ["XYZ", "YXZ", "ZXY", "ZYX", "YZX", "XZY"] as const;
777
- const defaultPlan = (lanes: readonly string[]): IValuePlan => ({
778
- lanes,
779
- drop: lanes,
780
- copy: (target, source) => {
781
- for (const lane of lanes) target[lane] = source[lane];
782
- },
783
- read: (value) => lanes.map((lane) => value[lane] as number),
784
- write: (value, values) => {
785
- lanes.forEach((lane, index) => {
786
- value[lane] = values[index] as number;
787
- });
788
- },
789
- });
790
- /** A value's member vector (`Box3.min`, `Sphere.center`): present on every real instance. */
791
- const memberVector = (vector: IValueLanes["min"]): NonNullable<IValueLanes["min"]> => {
792
- if (vector === undefined)
793
- throw new TypeError("TN_BROWSER_VALUE_MEMBER: the value has no vector");
794
- return vector;
795
- };
796
- // three's private storage names, and the classes whose lanes are not plain fields.
797
- const valuePlans: Record<string, IValuePlan> = {
798
- // quality-allow: the plan table is keyed by three's PascalCase class names, so the name rule cannot apply.
799
- // biome-ignore lint/style/useNamingConvention: keyed by three's class name.
800
- Color: defaultPlan(["r", "g", "b"]),
801
- // quality-allow: the plan table is keyed by three's PascalCase class names, so the name rule cannot apply.
802
- // biome-ignore lint/style/useNamingConvention: keyed by three's class name.
803
- Vector4: defaultPlan(["x", "y", "z", "w"]),
804
- // quality-allow: the plan table is keyed by three's PascalCase class names, so the name rule cannot apply.
805
- // biome-ignore lint/style/useNamingConvention: keyed by three's class name.
806
- Quaternion: {
807
- lanes: ["x", "y", "z", "w"],
808
- drop: ["_x", "_y", "_z", "_w"],
809
- read: (value) => [value._x, value._y, value._z, value._w] as number[],
810
- write: (value, values) => {
811
- value._x = values[0];
812
- value._y = values[1];
813
- value._z = values[2];
814
- value._w = values[3];
815
- },
816
- },
817
- // quality-allow: the plan table is keyed by three's PascalCase class names, so the name rule cannot apply.
818
- // biome-ignore lint/style/useNamingConvention: keyed by three's class name.
819
- Euler: {
820
- lanes: ["x", "y", "z"],
821
- drop: ["_x", "_y", "_z", "_order"],
822
- read: (value) =>
823
- [
824
- value._x,
825
- value._y,
826
- value._z,
827
- eulerOrders.indexOf(value._order as (typeof eulerOrders)[number]),
828
- ] as number[],
829
- write: (value, values) => {
830
- value._x = values[0];
831
- value._y = values[1];
832
- value._z = values[2];
833
- value._order = eulerOrders[values[3] as number] ?? "XYZ";
834
- },
835
- args: (values) => [
836
- values[0],
837
- values[1],
838
- values[2],
839
- eulerOrders[values[3] as number] ?? "XYZ",
840
- ],
841
- },
842
- // quality-allow: the plan table is keyed by three's PascalCase class names, so the name rule cannot apply.
843
- // biome-ignore lint/style/useNamingConvention: keyed by three's class name.
844
- Matrix3: {
845
- promote: true,
846
- lanes: ["elements"],
847
- drop: ["elements"],
848
- read: (value) => Array.from(value.elements as number[]),
849
- write: (value, values) => {
850
- value.elements = Array.from(values);
851
- },
852
- // `elements` is column-major; the engine constructor takes three's row-major set order.
853
- args: (values) => [0, 3, 6, 1, 4, 7, 2, 5, 8].map((index) => values[index] as number),
854
- },
855
- // quality-allow: the plan table is keyed by three's PascalCase class names, so the name rule cannot apply.
856
- // biome-ignore lint/style/useNamingConvention: keyed by three's class name.
857
- Matrix4: {
858
- promote: true,
859
- lanes: ["elements"],
860
- drop: ["elements"],
861
- read: (value) => Array.from(value.elements as number[]),
862
- write: (value, values) => {
863
- value.elements = Array.from(values);
864
- },
865
- // `elements` is column-major; the engine constructor takes three's row-major set order.
866
- args: (values) =>
867
- [0, 4, 8, 12, 1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15].map(
868
- (index) => values[index] as number,
869
- ),
870
- },
871
- // quality-allow: the plan table is keyed by three's PascalCase class names, so the name rule cannot apply.
872
- // biome-ignore lint/style/useNamingConvention: keyed by three's class name.
873
- Box3: {
874
- promote: true,
875
- lanes: [],
876
- drop: ["min", "max"],
877
- read: (value) => {
878
- const min = memberVector(value.min);
879
- const max = memberVector(value.max);
880
- return [min.x, min.y, min.z, max.x, max.y, max.z];
881
- },
882
- write: (value, values) => {
883
- memberVector(value.min).set(values[0] as number, values[1] as number, values[2] as number);
884
- memberVector(value.max).set(values[3] as number, values[4] as number, values[5] as number);
885
- },
886
- args: (values, make) => [
887
- make("Vector3", values.slice(0, 3).map(Number)),
888
- make("Vector3", values.slice(3, 6).map(Number)),
889
- ],
890
- },
891
- // quality-allow: the plan table is keyed by three's PascalCase class names, so the name rule cannot apply.
892
- // biome-ignore lint/style/useNamingConvention: keyed by three's class name.
893
- Sphere: {
894
- promote: true,
895
- lanes: ["radius"],
896
- drop: ["center", "radius"],
897
- read: (value) => {
898
- const center = memberVector(value.center);
899
- return [center.x, center.y, center.z, value.radius as number];
900
- },
901
- write: (value, values) => {
902
- memberVector(value.center).set(
903
- values[0] as number,
904
- values[1] as number,
905
- values[2] as number,
906
- );
907
- value.radius = values[3] as number;
908
- },
909
- args: (values, make) => [make("Vector3", values.slice(0, 3).map(Number)), values[3]],
910
- },
911
- };
609
+
912
610
  const math = defineMath() as Record<string, new (...args: unknown[]) => object>;
913
- const valueClasses = new Map<object, IValueClass>(); // JS prototype -> its engine side
914
- const loans: [IValueLanes, IValueLanes, IValueClass][] = [];
915
- let borrowing = false;
916
- const toEngineArgs = (args: readonly unknown[]): EngineValue[] => {
917
- borrowing = true;
918
- try {
919
- return args.map(toEngine);
920
- } finally {
921
- borrowing = false;
922
- }
923
- };
924
- // A plan's member-vector arguments (Box3's two, Sphere's one) are native temporaries: the engine
925
- // copies them, so they are released as soon as the value that owns the lanes is constructed.
926
- const engineArgs = (
927
- info: IValueClass,
928
- values: number[],
929
- ): { args: EngineValue[]; temporaries: IEngineRef[] } => {
930
- if (info.plan.args === undefined) return { args: values, temporaries: [] };
931
- const temporaries: IEngineRef[] = [];
932
- const args = info.plan.args(values, (name, lanes) => {
933
- const ref = runtime.construct(name, lanes);
934
- temporaries.push(ref);
935
- return ref;
936
- });
937
- return { args, temporaries };
938
- };
939
- const lend = (value: IValueLanes, info: IValueClass): IEngineRef => {
940
- let scratch = info.pool[info.top];
941
- if (scratch === undefined) {
942
- const built = engineArgs(info, info.plan.read(value));
943
- try {
944
- scratch = wrap(runtime.construct(info.name, built.args));
945
- } finally {
946
- for (const temporary of built.temporaries) runtime.release(temporary);
947
- }
948
- info.pool.push(scratch);
949
- }
950
- info.top++;
951
- const lanes = scratch as IValueLanes;
952
- if (info.plan.copy !== undefined) info.plan.copy(lanes, value);
953
- else info.plan.write(lanes, info.plan.read(value));
954
- loans.push([value, lanes, info]);
955
- return refOf(scratch);
956
- };
957
- // Copies each borrowed object's lanes back to its JS value; the result answers the value itself.
958
- const repay = (mark: number, returned: unknown): unknown => {
959
- let result = returned;
960
- for (let i = loans.length - 1; i >= mark; i--) {
961
- const [value, scratch, info] = loans[i] as (typeof loans)[number];
962
- if (info.plan.copy !== undefined) info.plan.copy(value, scratch);
963
- else info.plan.write(value, info.plan.read(scratch));
964
- info.top--;
965
- if (result === scratch) result = value;
966
- }
967
- loans.length = mark;
968
- return result;
969
- };
970
- const promote = (value: IValueLanes, info: IValueClass): void => {
971
- const values = info.plan.read(value);
972
- for (const key of info.plan.drop) delete value[key];
973
- Object.setPrototypeOf(value, info.engine);
974
- const built = engineArgs(info, values);
975
- try {
976
- adopt(value, runtime.construct(info.name, built.args));
977
- } finally {
978
- for (const temporary of built.temporaries) runtime.release(temporary);
979
- }
980
- };
981
- // An engine-owned value reads and writes its lanes in the engine's memory through accessors named
982
- // for the storage its class actually uses. Quaternion and Euler store `_x`, Matrix stores
983
- // `elements`, and an Euler's order is a string over the engine's byte enum; Box3 and Sphere reach
984
- // their vectors through the registry's fixed members, so they need nothing here.
985
- const defineValueView = (
986
- name: string,
987
- accessors: Record<string, unknown>,
988
- binding: IRegistryClass,
989
- skip: Set<string>,
990
- ): void => {
991
- const read = runtime.readDoubles;
992
- const write = runtime.writeDouble;
993
- const peek = runtime.readByte;
994
- if (read === undefined || write === undefined) return;
995
- const heap = runtime.heapF64;
996
- const lane = heap
997
- ? (address: number): number => heap()[address / 8] as number
998
- : (address: number): number => read(address, 1) as number;
999
- if (name === "Quaternion" && binding.fields !== undefined) {
1000
- const offsets = ["x", "y", "z", "w"].map((key) => binding.fields?.[key]?.[0] ?? 0);
1001
- ["_x", "_y", "_z", "_w"].forEach((key, index) => {
1002
- const offset = offsets[index] as number;
1003
- Object.defineProperty(accessors, key, {
1004
- configurable: true,
1005
- get(this: object): number {
1006
- return lane(addressOf(this) + offset);
1007
- },
1008
- set(this: object, value: number): void {
1009
- const address = addressOf(this) + offset;
1010
- const next = Number(value);
1011
- sharedTransformWrite?.(this, address, next);
1012
- write(address, next);
1013
- },
1014
- });
1015
- });
1016
- skip.add("x").add("y").add("z").add("w");
1017
- // three syncs an Object3D's rotation from its quaternion. Physics interpolation sets every body's
1018
- // quaternion every frame, so a call per sync cost 1,732 crossings a frame on the stress lab. This is
1019
- // Euler::setFromQuaternion with update off (Euler.cpp), written into the rotation's lanes: the same
1020
- // formulas, and Math is V8's fdlibm, which the engine's ieee754 functions are, so the bits match.
1021
- const eulerFields = registry.classes.Euler?.fields;
1022
- const angles = ["x", "y", "z"].map((key) => eulerFields?.[key]?.[0]);
1023
- const orderAt = eulerFields?.__order?.[0];
1024
- const local =
1025
- peek !== undefined && orderAt !== undefined && angles.every((at) => at !== undefined);
1026
- const [ax, ay, az] = angles as [number, number, number];
1027
- Object.defineProperty(accessors, "_onChangeCallback", {
1028
- configurable: true,
1029
- writable: true,
1030
- value(this: object): void {
1031
- const owner = quaternions.get(this) as
1032
- | { rotation?: object & { _order?: string } }
1033
- | undefined;
1034
- if (owner?.rotation === undefined) return;
1035
- if (!local) {
1036
- // The rotation's own order; the engine refuses a missing one on this call.
1037
- runtime.invoke(refOf(owner.rotation), "setFromQuaternion", [
1038
- refOf(this),
1039
- owner.rotation._order ?? "XYZ",
1040
- ]);
1041
- return;
1042
- }
1043
- const q = addressOf(this);
1044
- const e = addressOf(owner.rotation);
1045
- const [ex, ey, ez] = eulerFromQuaternion(
1046
- lane(q + (offsets[0] as number)),
1047
- lane(q + (offsets[1] as number)),
1048
- lane(q + (offsets[2] as number)),
1049
- lane(q + (offsets[3] as number)),
1050
- eulerOrders[(peek as (address: number) => number)(e + (orderAt as number))] ?? "XYZ",
1051
- );
1052
- write(e + ax, ex);
1053
- write(e + ay, ey);
1054
- write(e + az, ez);
1055
- },
1056
- });
1057
- return;
1058
- }
1059
- if (name === "Euler" && binding.fields !== undefined && peek !== undefined) {
1060
- const offsets = ["x", "y", "z"].map((key) => binding.fields?.[key]?.[0] ?? 0) as number[];
1061
- const orderAt = binding.fields.__order?.[0] ?? 0;
1062
- const quaternionFields = registry.classes.Quaternion?.fields;
1063
- const targets = ["x", "y", "z", "w"].map((key) => quaternionFields?.[key]?.[0] ?? 0);
1064
- // three's setFromEuler: each order only signs the second terms, in the engine enum's order.
1065
- const signs = [
1066
- [1, -1, 1, -1],
1067
- [1, -1, -1, 1],
1068
- [-1, 1, 1, -1],
1069
- [-1, 1, -1, 1],
1070
- [1, 1, -1, -1],
1071
- [-1, -1, 1, 1],
1072
- ];
1073
- const sync = (euler: object): void => {
1074
- const owner = rotations.get(euler) as { quaternion?: object } | undefined;
1075
- if (owner?.quaternion === undefined) return;
1076
- const at = addressOf(euler);
1077
- const q = addressOf(owner.quaternion);
1078
- const x = lane(at + (offsets[0] as number)) / 2;
1079
- const y = lane(at + (offsets[1] as number)) / 2;
1080
- const z = lane(at + (offsets[2] as number)) / 2;
1081
- const sign = signs[peek(at + orderAt)] ?? (signs[0] as number[]);
1082
- const c1 = Math.cos(x);
1083
- const c2 = Math.cos(y);
1084
- const c3 = Math.cos(z);
1085
- const s1 = Math.sin(x);
1086
- const s2 = Math.sin(y);
1087
- const s3 = Math.sin(z);
1088
- write(q + (targets[0] as number), s1 * c2 * c3 + (sign[0] as number) * c1 * s2 * s3);
1089
- write(q + (targets[1] as number), c1 * s2 * c3 + (sign[1] as number) * s1 * c2 * s3);
1090
- write(q + (targets[2] as number), c1 * c2 * s3 + (sign[2] as number) * s1 * s2 * c3);
1091
- write(q + (targets[3] as number), c1 * c2 * c3 + (sign[3] as number) * s1 * s2 * s3);
1092
- };
1093
- ["_x", "_y", "_z"].forEach((key, index) => {
1094
- const offset = offsets[index] as number;
1095
- Object.defineProperty(accessors, key, {
1096
- configurable: true,
1097
- get(this: object): number {
1098
- return lane(addressOf(this) + offset);
1099
- },
1100
- set(this: object, value: number): void {
1101
- const address = addressOf(this) + offset;
1102
- const next = Number(value);
1103
- sharedTransformWrite?.(this, address, next);
1104
- write(address, next);
1105
- },
1106
- });
1107
- });
1108
- Object.defineProperty(accessors, "_order", {
1109
- configurable: true,
1110
- get(this: object): string {
1111
- return eulerOrders[peek(addressOf(this) + orderAt)] ?? "XYZ";
1112
- },
1113
- set(this: object, value: unknown): void {
1114
- const index = eulerOrders.indexOf(value as (typeof eulerOrders)[number]);
1115
- if (index < 0)
1116
- throw new TypeError(
1117
- `Euler order is not one of ${eulerOrders.join(", ")}: ${String(value)}`,
1118
- );
1119
- // The order is the engine's byte enum: its setter reorders and syncs, so only a change
1120
- // crosses (four numbers are not worth a call on every `rotation.set`).
1121
- if (index !== peek(addressOf(this) + orderAt))
1122
- runtime.set(refOf(this), "order", value as string);
1123
- },
1124
- });
1125
- Object.defineProperty(accessors, "_onChangeCallback", {
1126
- configurable: true,
1127
- writable: true,
1128
- value(this: object): void {
1129
- sync(this);
1130
- },
1131
- });
1132
- skip.add("x").add("y").add("z").add("order");
1133
- return;
1134
- }
1135
- if ((name === "Matrix3" || name === "Matrix4") && binding.fields?.elements !== undefined) {
1136
- const [offset = 0, count = 0] = binding.fields.elements;
1137
- // three keeps one `elements` array; this keeps one proxy per matrix over a mirrored array and
1138
- // writes every element it sets straight to engine memory, so the array never detaches.
1139
- const mirrors = new WeakMap<object, { values: number[]; view: number[] }>();
1140
- // Off the heap view when there is one: a game reads `matrixWorld.elements` hundreds of times
1141
- // a frame, and a copy call allocates two arrays a read.
1142
- const refresh = heap
1143
- ? (address: number, values: number[]): void => {
1144
- const memory = heap();
1145
- for (let i = 0, at = address / 8; i < count; i++) values[i] = memory[at + i] as number;
1146
- }
1147
- : (address: number, values: number[]): void => {
1148
- const memory = read(address, count) as number[];
1149
- for (let i = 0; i < count; i++) values[i] = memory[i] as number;
1150
- };
1151
- Object.defineProperty(accessors, "elements", {
1152
- configurable: true,
1153
- get(this: object): number[] {
1154
- const address = addressOf(this) + offset;
1155
- let mirror = mirrors.get(this);
1156
- if (mirror === undefined) {
1157
- const values = new Array<number>(count);
1158
- const view = new Proxy(values, {
1159
- set: (target, key, value): boolean => {
1160
- const index = typeof key === "string" ? Number(key) : Number.NaN;
1161
- if (Number.isInteger(index) && index >= 0 && index < count)
1162
- write(address + index * 8, Number(value));
1163
- target[key as never] = value as never;
1164
- return true;
1165
- },
1166
- });
1167
- mirror = { values, view };
1168
- mirrors.set(this, mirror);
1169
- }
1170
- refresh(address, mirror.values);
1171
- return mirror.view;
1172
- },
1173
- set(this: object, value: ArrayLike<number>): void {
1174
- const address = addressOf(this) + offset;
1175
- for (let i = 0; i < count; i++) write(address + i * 8, Number(value[i]));
1176
- },
1177
- });
1178
- skip.add("elements");
1179
- }
1180
- };
1181
611
  const wrappers = new Map<string, WeakRef<object>>();
1182
612
  // Callbacks: the function lives on its wrapper (a WeakMap entry), so wrapper -> closure is an edge
1183
613
  // the collector sees; `held` roots a wrapper while the engine may still call it.
@@ -1193,112 +623,7 @@ export function defineBrowserClasses(
1193
623
  // userData is the game's: it lives with the wrapper, which `held` keeps while the engine references it.
1194
624
  const userData = new WeakMap<object, unknown>();
1195
625
  const shaderNodes = new Map<string, Map<string, unknown>>(); // material key -> slot -> TSL node
1196
- // three's `attribute.array` is the attribute's own JS typed array (PRD-540): the array the
1197
- // constructor was handed, or a copy of the engine's data on first read. A view of Wasm memory
1198
- // would detach when the memory grows, so the shadow is a JS array. The shadow and the engine's
1199
- // store are kept in step (PRD-617): an engine mutator copies back ONLY the range it wrote, so a
1200
- // later game edit to the array wins, and `needsUpdate` sends the array to the engine. A read hands
1201
- // the game the array, so the attribute is `pending` until its array is written back before the next
1202
- // engine call (a per-vertex setter reads no kept array and flushes nothing).
1203
- const { attributeArray, attributeWrite } = runtime;
1204
- const arrays = new WeakMap<object, { array: TypedArray }>();
1205
- const itemSizes = new WeakMap<object, number>();
1206
- // Shape survives data uploads and transform calls; only copy/replacement changes it.
1207
- const shapes = new WeakMap<object, Map<string, unknown>>();
1208
- const pending = new Set<object>();
1209
- const writeBack = (): void => {
1210
- for (const attribute of pending) {
1211
- const entry = arrays.get(attribute);
1212
- if (entry !== undefined) attributeWrite?.call(runtime, refOf(attribute), entry.array);
1213
- }
1214
- pending.clear();
1215
- };
1216
- const itemSizeOf = (attribute: object): number => {
1217
- let size = itemSizes.get(attribute);
1218
- if (size === undefined) {
1219
- size = Number(runtime.get(refOf(attribute), "itemSize"));
1220
- itemSizes.set(attribute, size);
1221
- }
1222
- return size;
1223
- };
1224
- // The scalar range an attribute mutator wrote: derived from the method and its arguments, so the
1225
- // engine syncs back only those elements. A component setter writes one, setXY/XYZ/XYZW an item's
1226
- // lanes, copyAt a whole destination item.
1227
- const lanes: Record<string, number> = { setX: 0, setY: 1, setZ: 2, setW: 3 };
1228
- const rangeOf = (
1229
- method: string,
1230
- args: readonly unknown[],
1231
- itemSize: number,
1232
- ): readonly [number, number] => {
1233
- const at = Number(args[0]) * itemSize;
1234
- if (method === "copyAt") return [at, itemSize];
1235
- const component = lanes[method];
1236
- if (component !== undefined) return [at + component, 1];
1237
- if (method === "setComponent") return [at + Number(args[1]), 1];
1238
- return [at, method === "setXY" ? 2 : method === "setXYZ" ? 3 : 4];
1239
- };
1240
- const syncRange = (
1241
- attribute: object,
1242
- entry: { array: TypedArray },
1243
- offset: number,
1244
- count: number,
1245
- ): void => {
1246
- // A malformed range (a fraction, NaN, Infinity, a negative offset or a non-positive count) names
1247
- // no element: it must fail, not slip to element 0 through subarray's own coercion. A range that
1248
- // only runs past the end is the engine's documented bounds no-op (`setComponent`/`setRaw`
1249
- // ignore it, as JS does), so there is nothing to read back. A required range read that comes
1250
- // back missing or short is a provider fault, never a silently stale shadow.
1251
- if (!Number.isSafeInteger(offset) || !Number.isSafeInteger(count) || offset < 0 || count <= 0)
1252
- throw new RangeError(
1253
- `TN_NATIVE_ATTRIBUTE_RANGE: [${String(offset)}, ${String(count)}) is not a valid element range`,
1254
- );
1255
- if (offset + count > entry.array.length) return;
1256
- const fresh = attributeArray?.call(runtime, refOf(attribute), offset, count);
1257
- if (fresh === undefined || fresh.length !== count)
1258
- throw new TypeError(
1259
- `TN_NATIVE_ATTRIBUTE_SYNC: attributeArray gave ${fresh === undefined ? "no array" : `${String(fresh.length)} elements`} for [${String(offset)}, ${String(count)})`,
1260
- );
1261
- entry.array.set(fresh, offset);
1262
- };
1263
- const syncFull = (attribute: object, entry: { array: TypedArray }): void => {
1264
- const fresh = attributeArray?.call(runtime, refOf(attribute));
1265
- if (fresh === undefined) return;
1266
- if (fresh.length === entry.array.length) entry.array.set(fresh);
1267
- else entry.array = fresh;
1268
- };
1269
- // three's `InstancedMesh.setMatrixAt`/`setColorAt` write the mesh's own `instanceMatrix`/
1270
- // `instanceColor` array item (`index * 16`, `index * 3`); the engine's mesh-level call writes only
1271
- // its own store, so the shadow a game already holds (core's velocity capture reads one per mesh a
1272
- // frame) would send its frozen snapshot back at `needsUpdate` and leave the mesh where it stood.
1273
- // Take the item the call writes into that same array, as three does. No shadow, no work: this is
1274
- // a pair of map lookups and an array copy, never an engine call.
1275
- const instanceItem = (
1276
- mesh: object,
1277
- attribute: string,
1278
- index: unknown,
1279
- argument: unknown,
1280
- ): { array: TypedArray; at: number; values: ArrayLike<number> } | undefined => {
1281
- const held = shapes.get(mesh)?.get(attribute);
1282
- if (held === null || held === undefined) return undefined;
1283
- const entry = arrays.get(held as object);
1284
- if (entry === undefined) return undefined;
1285
- const source = argument as {
1286
- elements?: ArrayLike<number>;
1287
- r?: number;
1288
- g?: number;
1289
- b?: number;
1290
- } | null;
1291
- const values =
1292
- attribute === "instanceMatrix"
1293
- ? source?.elements
1294
- : [Number(source?.r), Number(source?.g), Number(source?.b)];
1295
- if (values === undefined) return undefined;
1296
- const at = Number(index) * values.length;
1297
- // three's `toArray` writes one lane at a time, so a lane outside the array is ignored, not an error.
1298
- if (!Number.isSafeInteger(at) || at < 0 || at + values.length > entry.array.length)
1299
- return undefined;
1300
- return { array: entry.array, at, values };
1301
- };
626
+
1302
627
  const released = new FinalizationRegistry<IEngineRef>((ref) => {
1303
628
  if (wrappers.get(ref.key)?.deref() === undefined) {
1304
629
  debug?.add("bridgeWrappersReleased");
@@ -1338,56 +663,34 @@ export function defineBrowserClasses(
1338
663
  );
1339
664
  return ref;
1340
665
  };
1341
- const toEngine = (value: unknown): EngineValue => {
1342
- if (value === null || value === undefined) return null;
1343
- if (typeof value === "number" || typeof value === "boolean" || typeof value === "string")
1344
- return value;
1345
- if (ArrayBuffer.isView(value) && !(value instanceof DataView)) {
1346
- // An image's `getImageData` pixels are a Uint8ClampedArray: boxed into a list, a 4096x2048 sky took 1.4 s.
1347
- if (
1348
- runtime.typedArrays === true &&
1349
- (value instanceof Uint8ClampedArray || SCALARS.some((scalar) => value instanceof scalar))
1350
- )
1351
- return value as TypedArray;
1352
- // quality-allow: a typed-array view read as its numeric index signature, which ArrayBufferView does not declare.
1353
- const list = Array.from(value as unknown as ArrayLike<number>);
1354
- Object.defineProperty(list, TYPED, { value: value.constructor.name });
1355
- return list;
1356
- }
1357
- if (Array.isArray(value)) return Array.from(value as ArrayLike<unknown>, toEngine);
1358
- const info = valueClasses.get(Object.getPrototypeOf(value) as object);
1359
- if (info !== undefined) {
1360
- if (borrowing && info.plan.promote !== true) return lend(value as IValueLanes, info);
1361
- promote(value as IValueLanes, info);
1362
- }
1363
- if (typeof value === "object" && REF in value) {
1364
- // A wrapper passed into the engine is held until the next safe point decides (collect()).
1365
- hold(value);
1366
- return (value as IWrapped)[REF];
1367
- }
1368
- // An options object (`new ExtrudeGeometry(shape, { depth })`) crosses as a record of scalars and
1369
- // engine objects, as the V8 adapter passes it; an undefined value is left out, as three reads it.
1370
- if (isPlainObject(value)) {
1371
- const fields: Record<string, EngineValue> = {};
1372
- for (const [key, item] of Object.entries(value as object)) {
1373
- if (item === undefined) continue;
1374
- if (
1375
- item !== null &&
1376
- typeof item === "object" &&
1377
- !(REF in item) &&
1378
- !valueClasses.has(Object.getPrototypeOf(item) as object)
1379
- )
1380
- throw new TypeError(
1381
- `TN_BROWSER_ARGUMENT_UNSUPPORTED: option ${key} cannot cross to the engine`,
1382
- );
1383
- fields[key] = toEngine(item);
1384
- }
1385
- return fields;
1386
- }
1387
- throw new TypeError(
1388
- `TN_BROWSER_ARGUMENT_UNSUPPORTED: ${typeof value} cannot cross to the engine`,
1389
- );
1390
- };
666
+
667
+ const { toEngine, valueClasses, loans, repay, toEngineArgs, defineValueView } = defineValueViews({
668
+ runtime,
669
+ registry,
670
+ refOf,
671
+ adopt,
672
+ wrap,
673
+ hold,
674
+ addressOf,
675
+ rotations,
676
+ quaternions,
677
+ sharedTransformWrite,
678
+ });
679
+ const {
680
+ attributeArray,
681
+ attributeWrite,
682
+ arrays,
683
+ itemSizes,
684
+ shapes,
685
+ pending,
686
+ writeBack,
687
+ itemSizeOf,
688
+ rangeOf,
689
+ syncRange,
690
+ syncFull,
691
+ instanceItem,
692
+ } = defineAttributeSync({ runtime, refOf });
693
+
1391
694
  const fromEngine = (value: EngineValue): unknown => {
1392
695
  if (isRef(value)) return wrap(value);
1393
696
  if (Array.isArray(value)) return value.map(fromEngine);
@@ -1562,6 +865,10 @@ export function defineBrowserClasses(
1562
865
  // kinds are exclusive, so an attribute setter never enumerates a geometry and vice versa.
1563
866
  const rangeMethod = attributeClass && rangeMethods.has(method);
1564
867
  const transformMethod = attributeClass && transformMethods.has(method);
868
+ // Update-range bookkeeping reads no attribute bytes, so it flushes no shadow: a streamed batch
869
+ // that clears and re-adds its range each write sent every pending array, whole, twice.
870
+ const bookkeeping =
871
+ attributeClass && (method === "clearUpdateRanges" || method === "addUpdateRange");
1565
872
  const geometryWrite = geometryClass && geometryWrites.has(method);
1566
873
  // A mesh-level write into an attribute a game can hold a shadow of (see `instanceItem`).
1567
874
  const instanceWrite =
@@ -1612,7 +919,7 @@ export function defineBrowserClasses(
1612
919
  } else if (schedule === "all") scheduling = new WeakMap();
1613
920
  // A per-vertex setter writes its own range and reads no kept array, so a whole-shadow flush
1614
921
  // would cost O(N) a call; it syncs just its range back below. Anything else flushes edits.
1615
- if (pending.size > 0 && !rangeMethod) writeBack();
922
+ if (pending.size > 0 && !rangeMethod && !bookkeeping) writeBack();
1616
923
  // A full-array attribute transform reads its own array: send the game's shadow first.
1617
924
  if (transformMethod) {
1618
925
  const entry = arrays.get(this);
@@ -1662,6 +969,14 @@ export function defineBrowserClasses(
1662
969
  if (loans.length > mark) result = repay(mark, result);
1663
970
  if (drives) animated = new WeakMap();
1664
971
  }
972
+ // The engine's clone and copy carry the material's graphs; the TSL nodes a slot reads back
973
+ // follow them, or `clone().maskNode` answers null and a composed mask drops the source's.
974
+ if (materialClass && (method === "clone" || method === "copy")) {
975
+ const [from, to] = method === "clone" ? [this, result] : [args[0], this];
976
+ const slots = shaderNodes.get(refOf(from as object).key);
977
+ if (slots === undefined) shaderNodes.delete(refOf(to as object).key);
978
+ else shaderNodes.set(refOf(to as object).key, new Map(slots));
979
+ }
1665
980
  if (method === "copy") {
1666
981
  shapes.delete(this);
1667
982
  itemSizes.delete(this);
@@ -1768,7 +1083,7 @@ export function defineBrowserClasses(
1768
1083
  const setters = new Set(binding.setters);
1769
1084
  // A node material's TSL slots (`colorNode`) take an engine graph node, which no ABI value
1770
1085
  // carries: the graph goes in through the TSL runtime, and reading the slot answers the node set.
1771
- for (const property of binding.setters.filter((key) => /^[a-z]+Node$/u.test(key))) {
1086
+ for (const property of binding.setters.filter((key) => /^[a-z][A-Za-z]*Node$/u.test(key))) {
1772
1087
  Object.defineProperty(prototype, property, {
1773
1088
  configurable: true,
1774
1089
  get(this: object) {
@@ -1807,6 +1122,47 @@ export function defineBrowserClasses(
1807
1122
  shaderNodes.set(ref.key, slots.set(property, value));
1808
1123
  return;
1809
1124
  }
1125
+ // three's MRTNode: one engine graph node per output name, each at its own slot path, so a
1126
+ // material writes every colour target its mrt() names (pass-node.ts accepts any name).
1127
+ if (property === "mrtNode") {
1128
+ const slots = shaderNodes.get(ref.key) ?? new Map<string, unknown>();
1129
+ const previous =
1130
+ (slots.get(property) as { outputs?: Record<string, unknown> } | undefined)?.outputs ??
1131
+ {};
1132
+ if (value === null) {
1133
+ for (const [slot, node] of Object.entries(previous))
1134
+ if (isCustomMrtOutput(slot, node)) runtime.tsl?.set(ref, `mrtNode.${slot}`, 0);
1135
+ slots.delete(property);
1136
+ shaderNodes.set(ref.key, slots);
1137
+ return;
1138
+ }
1139
+ const outputs = (value as { isMRTNode?: boolean; outputs?: unknown }).outputs;
1140
+ if (
1141
+ (value as { isMRTNode?: boolean }).isMRTNode !== true ||
1142
+ outputs === null ||
1143
+ typeof outputs !== "object"
1144
+ )
1145
+ throw new TypeError(`TN_BROWSER_SHADER_NODE: ${name}.mrtNode takes mrt()`);
1146
+ for (const [slot, node] of Object.entries(outputs as Record<string, unknown>)) {
1147
+ // The scene pass draws the reserved targets itself; a material writes the custom ones.
1148
+ if (!isCustomMrtOutput(slot, node)) continue;
1149
+ if (node === null || typeof node !== "object" || !(TSL_NODE in node))
1150
+ throw new TypeError(
1151
+ `TN_BROWSER_SHADER_NODE: ${name}.mrtNode '${slot}' is not a TSL node`,
1152
+ );
1153
+ runtime.tsl?.set(
1154
+ ref,
1155
+ `mrtNode.${slot}`,
1156
+ (node as Record<symbol, number>)[TSL_NODE] as number,
1157
+ );
1158
+ }
1159
+ for (const [slot, node] of Object.entries(previous))
1160
+ if (isCustomMrtOutput(slot, node) && !Object.hasOwn(outputs as object, slot))
1161
+ runtime.tsl?.set(ref, `mrtNode.${slot}`, 0);
1162
+ slots.set(property, value);
1163
+ shaderNodes.set(ref.key, slots);
1164
+ return;
1165
+ }
1810
1166
  if (value === null) {
1811
1167
  runtime.set(ref, property, null);
1812
1168
  shaderNodes.get(ref.key)?.delete(property);
@@ -2246,6 +1602,12 @@ export function defineBrowserClasses(
2246
1602
  walked,
2247
1603
  raycasts(name),
2248
1604
  );
1605
+ if (!binding.methods.includes("dispose"))
1606
+ Object.defineProperty(prototype, "dispose", {
1607
+ configurable: true,
1608
+ writable: true,
1609
+ value: disposeObject,
1610
+ });
2249
1611
  }
2250
1612
  classes[name] = cls;
2251
1613
  byType.set(runtime.typeId(name), { prototype: accessors, ...(materialClass ? { own } : {}) });
@@ -2278,7 +1640,61 @@ export function defineBrowserClasses(
2278
1640
  return entry.array;
2279
1641
  },
2280
1642
  });
1643
+ // three's per-element getters read the attribute's own array; one engine call each made a vertex
1644
+ // walk (core's pose measurement over a licensed forest) cost 15 s of load. They read the shadow,
1645
+ // which the engine's own mutators keep in step, fetched once without marking it pending: the game
1646
+ // never holds this array, so there is no edit to write back.
1647
+ const shadow = (attribute: object): TypedArray => {
1648
+ let entry = arrays.get(attribute);
1649
+ if (entry === undefined) {
1650
+ entry = { array: attributeArray.call(runtime, refOf(attribute)) };
1651
+ arrays.set(attribute, entry);
1652
+ }
1653
+ return entry.array;
1654
+ };
1655
+ const component = (attribute: object, index: number, lane: number): number => {
1656
+ const array = shadow(attribute);
1657
+ const value = Number(array[index * itemSizeOf(attribute) + lane]);
1658
+ return (attribute as { normalized?: boolean }).normalized === true
1659
+ ? denormalize(value, array)
1660
+ : value;
1661
+ };
1662
+ Object.defineProperties(cls.prototype, {
1663
+ getX: {
1664
+ configurable: true,
1665
+ value(this: object, i: number) {
1666
+ return component(this, i, 0);
1667
+ },
1668
+ },
1669
+ getY: {
1670
+ configurable: true,
1671
+ value(this: object, i: number) {
1672
+ return component(this, i, 1);
1673
+ },
1674
+ },
1675
+ getZ: {
1676
+ configurable: true,
1677
+ value(this: object, i: number) {
1678
+ return component(this, i, 2);
1679
+ },
1680
+ },
1681
+ getW: {
1682
+ configurable: true,
1683
+ value(this: object, i: number) {
1684
+ return component(this, i, 3);
1685
+ },
1686
+ },
1687
+ getComponent: {
1688
+ configurable: true,
1689
+ value(this: object, i: number, lane: number) {
1690
+ return component(this, i, lane);
1691
+ },
1692
+ },
1693
+ });
2281
1694
  // needsUpdate is a property write, not a call: it hands the shadow to the engine as it stands.
1695
+ // Declared update ranges send only themselves, as three's own upload does
1696
+ // (WebGPUAttributeUtils.updateAttribute): a 10,000-instance batch that rewrote 40 records sent
1697
+ // all 10,000 each time. An edit outside the declared ranges stays unsent, as on three's GPU.
2282
1698
  const needsUpdate = Object.getOwnPropertyDescriptor(cls.prototype, "needsUpdate");
2283
1699
  if (needsUpdate?.set !== undefined)
2284
1700
  Object.defineProperty(cls.prototype, "needsUpdate", {
@@ -2286,7 +1702,18 @@ export function defineBrowserClasses(
2286
1702
  set(this: object, value: unknown) {
2287
1703
  const entry = arrays.get(this);
2288
1704
  if (value === true && entry !== undefined) {
2289
- attributeWrite.call(runtime, refOf(this), entry.array);
1705
+ const ranges = uploadRanges(this);
1706
+ if (ranges.length === 0) attributeWrite.call(runtime, refOf(this), entry.array);
1707
+ for (const { start, count } of ranges) {
1708
+ const end = Math.min(start + count, entry.array.length);
1709
+ if (end > start)
1710
+ attributeWrite.call(
1711
+ runtime,
1712
+ refOf(this),
1713
+ entry.array.subarray(start, end),
1714
+ start,
1715
+ );
1716
+ }
2290
1717
  pending.delete(this);
2291
1718
  }
2292
1719
  needsUpdate.set?.call(this, value);
@@ -2423,880 +1850,3 @@ export function defineBrowserClasses(
2423
1850
  },
2424
1851
  };
2425
1852
  }
2426
-
2427
- /**
2428
- * The engine's C ABI as built by `tn-native-engine-abi-module` (Emscripten, wasm32). The names are
2429
- * Emscripten's (`HEAPU8`, `_malloc`, `_tn_*`), so they are declared as record keys.
2430
- */
2431
- type AbiCall =
2432
- | "_malloc"
2433
- | "_free"
2434
- | "_tn_engine_version"
2435
- | "_tn_context_create"
2436
- | "_tn_type_id"
2437
- | "_tn_object_release"
2438
- | "_tn_object_engine_references"
2439
- | "_tn_construct"
2440
- | "_tn_invoke"
2441
- | "_tn_get"
2442
- | "_tn_set"
2443
- | "_tn_set_callback"
2444
- | "_tn_diagnostic_release";
2445
- export type TnAbiModule = Record<AbiCall, (...args: number[]) => number> &
2446
- Partial<
2447
- Record<"_tnw_attribute_view" | "_tnw_attribute_view_release", (...args: number[]) => number>
2448
- > &
2449
- Record<"HEAPU8", Uint8Array> &
2450
- Record<"HEAPF64", Float64Array> &
2451
- Record<"UTF8ToString", (pointer: number, maxBytes?: number) => string> &
2452
- Record<
2453
- "addFunction",
2454
- (fn: (...args: number[]) => number | undefined, signature: string) => number
2455
- > & {
2456
- stringToUTF8(text: string, pointer: number, maxBytes: number): void;
2457
- lengthBytesUTF8(text: string): number;
2458
- };
2459
-
2460
- // wasm32 layouts of tn_abi.h, measured with offsetof under emcc: tn_handle_t 12 bytes; tn_value_t
2461
- // 56 bytes (kind 0, boolean 4, number 8, handle 16, text 32, count 40, numbers 48); tn_diagnostic_t
2462
- // 8 bytes (message 0, code 4); tn_version_info_t 32 bytes. A struct passed by value goes by pointer.
2463
- const HANDLE = 12;
2464
- const VALUE = 56;
2465
- const KIND = {
2466
- null: 0,
2467
- number: 1,
2468
- bool: 2,
2469
- string: 3,
2470
- handle: 4,
2471
- numbers: 5,
2472
- array: 6,
2473
- record: 7,
2474
- undefined: 8,
2475
- bytes: 9,
2476
- } as const;
2477
-
2478
- // wasm32 layout of tn_tsl_arg_t (tn_tsl.h): kind 0, lanes 4, node 8 (u64), number 16, text 24,
2479
- // numbers 32 (four f64); 64 bytes. A handle argument's 12 bytes start at lanes (4) and run through node.
2480
- const TSL_ARG = 64;
2481
- const TSL_KIND = {
2482
- node: 0,
2483
- number: 1,
2484
- string: 2,
2485
- named: 3,
2486
- rgb: 4,
2487
- vector: 5,
2488
- other: 6,
2489
- handle: 7,
2490
- } as const;
2491
- type TslCall =
2492
- | "_tn_tsl_call"
2493
- | "_tn_tsl_release"
2494
- | "_tn_tsl_set"
2495
- | "_tn_tsl_set_uniform"
2496
- | "_tn_tsl_effect_parameter"
2497
- | "_tnw_web_set_post"
2498
- | "_tnw_web_compute"
2499
- | "_tnw_web_compute_flush"
2500
- | "_tnw_web_read_storage"
2501
- | "_tnw_web_read_storage_size"
2502
- | "_tnw_web_read_storage_take"
2503
- | "_tnw_web_delete_storage"
2504
- | "_tnw_web_poll"
2505
- | "_tnw_web_error";
2506
-
2507
- interface IAbiHelpers {
2508
- scoped<T>(work: () => T): T;
2509
- alloc(size: number): number;
2510
- string(text: string): { pointer: number; bytes: number };
2511
- diagnostic(): number;
2512
- check(status: number, diag: number, what: string): void;
2513
- handleOf(ref: IEngineRef): number;
2514
- writeHandle(pointer: number, ref: IEngineRef): void;
2515
- view(): DataView;
2516
- }
2517
-
2518
- /** The engine glTF loader over the product web host's `tnw_web_load_gltf`, when the module has it. */
2519
- function gltfOf(
2520
- abi: TnAbiModule,
2521
- context: number,
2522
- h: Pick<IAbiHelpers, "scoped" | "alloc"> & { keyOf(pointer: number): IEngineRef },
2523
- ): Pick<IBrowserRuntime, "loadGltf"> {
2524
- // quality-allow: the Emscripten module is read through the exports this call site names, not its full surface.
2525
- const host = abi as unknown as Partial<
2526
- Record<
2527
- | "_tnw_web_load_gltf"
2528
- | "_tnw_web_load_error"
2529
- | "_tnw_web_gltf_file"
2530
- | "_tnw_web_gltf_files_clear",
2531
- (...args: number[]) => number
2532
- >
2533
- >;
2534
- const {
2535
- _tnw_web_load_gltf: load,
2536
- _tnw_web_load_error: error,
2537
- _tnw_web_gltf_file: file,
2538
- _tnw_web_gltf_files_clear: clearFiles,
2539
- } = host;
2540
- if (load === undefined || error === undefined) return {};
2541
- return {
2542
- loadGltf: (bytes, files) =>
2543
- h.scoped(() => {
2544
- // Files the model names by relative uri (shared images), read by the engine loader.
2545
- if (files !== undefined && files.size > 0) {
2546
- if (file === undefined || clearFiles === undefined)
2547
- throw new Error(
2548
- "TN_WASM_GLTF_FILES_UNAVAILABLE: this web engine cannot read a model's image files",
2549
- );
2550
- for (const [uri, content] of files) {
2551
- const name = h.alloc(abi.lengthBytesUTF8(uri) + 1);
2552
- abi.stringToUTF8(uri, name, abi.lengthBytesUTF8(uri) + 1);
2553
- const copy = h.alloc(Math.max(1, content.byteLength));
2554
- abi.HEAPU8.set(content, copy);
2555
- file(name, copy, content.byteLength);
2556
- }
2557
- }
2558
- try {
2559
- const data = h.alloc(Math.max(1, bytes.byteLength));
2560
- abi.HEAPU8.set(bytes, data);
2561
- const count = h.alloc(4);
2562
- // Retried once with the exact size when the model has more clips than the first guess.
2563
- for (let capacity = 64; ; ) {
2564
- const out = h.alloc(HANDLE * capacity);
2565
- const status = load(context, data, bytes.byteLength, out, capacity, count);
2566
- const needed = new DataView(abi.HEAPU8.buffer).getUint32(count, true);
2567
- if (status === 0) {
2568
- const refs = Array.from({ length: needed }, (_, i) => h.keyOf(out + i * HANDLE));
2569
- return { scene: refs[0] as IEngineRef, animations: refs.slice(1) };
2570
- }
2571
- const reason = abi.UTF8ToString(error());
2572
- if (reason !== "TN_WASM_GLTF_CAPACITY" || needed <= capacity) throw new Error(reason);
2573
- capacity = needed;
2574
- }
2575
- } finally {
2576
- clearFiles?.();
2577
- }
2578
- }),
2579
- };
2580
- }
2581
-
2582
- /** TSL by name over `tn_tsl_call`, when the module exports it (the product web host does). */
2583
- function tslOf(
2584
- abi: TnAbiModule,
2585
- context: number,
2586
- h: IAbiHelpers,
2587
- ): { tsl: ITslRuntime } | undefined {
2588
- // Node ids are u64 in the C ABI; Emscripten passes a 64-bit parameter as a BigInt.
2589
- // quality-allow: the Emscripten module is read through the TSL call exports this call site names, not its full surface.
2590
- const calls = abi as unknown as Partial<
2591
- Record<TslCall, (...args: (number | bigint)[]) => number>
2592
- >;
2593
- const {
2594
- _tn_tsl_call: call,
2595
- _tn_tsl_release: release,
2596
- _tn_tsl_set: set,
2597
- _tn_tsl_set_uniform: setUniform,
2598
- _tn_tsl_effect_parameter: effectParameter,
2599
- _tnw_web_set_post: setPost,
2600
- _tnw_web_compute: computeNode,
2601
- _tnw_web_compute_flush: computeFlush,
2602
- _tnw_web_read_storage: readStorage,
2603
- _tnw_web_read_storage_size: readStorageSize,
2604
- _tnw_web_read_storage_take: readStorageTake,
2605
- _tnw_web_delete_storage: deleteStorage,
2606
- _tnw_web_poll: poll,
2607
- _tnw_web_error: webError,
2608
- } = calls;
2609
- if (
2610
- call === undefined ||
2611
- release === undefined ||
2612
- set === undefined ||
2613
- setUniform === undefined ||
2614
- effectParameter === undefined
2615
- )
2616
- return undefined;
2617
- // Writes tn_tsl_arg_t values; text is allocated first, since an allocation can grow the memory.
2618
- const writeArgs = (args: readonly TslArgValue[]): number => {
2619
- const pointer = h.alloc(Math.max(TSL_ARG, args.length * TSL_ARG));
2620
- args.forEach((arg, i) => {
2621
- const at = pointer + i * TSL_ARG;
2622
- const text = arg.kind === "string" || arg.kind === "named" ? h.string(arg.text).pointer : 0;
2623
- const v = h.view();
2624
- v.setUint32(at, TSL_KIND[arg.kind], true);
2625
- if (arg.kind === "node") v.setBigUint64(at + 8, BigInt(arg.node), true);
2626
- else if (arg.kind === "number") v.setFloat64(at + 16, arg.number, true);
2627
- else if (arg.kind === "rgb" || arg.kind === "vector") {
2628
- v.setUint32(at + 4, arg.numbers.length, true);
2629
- arg.numbers.forEach((c, j) => v.setFloat64(at + 32 + j * 8, c, true));
2630
- } else if (arg.kind === "handle") h.writeHandle(at + 4, arg.ref);
2631
- else v.setUint32(at + 24, text, true);
2632
- });
2633
- return pointer;
2634
- };
2635
- const nodeOf = (node: number | null): number => {
2636
- if (node === null) return 0;
2637
- const pointer = h.alloc(8);
2638
- h.view().setBigUint64(pointer, BigInt(node), true);
2639
- return pointer;
2640
- };
2641
- return {
2642
- tsl: {
2643
- call: (name, receiver, args) =>
2644
- h.scoped(() => {
2645
- const pointer = writeArgs(args);
2646
- const self = nodeOf(receiver);
2647
- const out = h.alloc(8);
2648
- const diag = h.diagnostic();
2649
- h.check(
2650
- call(context, h.string(name).pointer, self, pointer, args.length, out, diag),
2651
- diag,
2652
- `TSL ${name}`,
2653
- );
2654
- return Number(h.view().getBigUint64(out, true));
2655
- }),
2656
- release: (node) =>
2657
- h.scoped(() => {
2658
- const diag = h.diagnostic();
2659
- release(context, BigInt(node), diag);
2660
- abi._tn_diagnostic_release(diag);
2661
- }),
2662
- set: (material, path, node) =>
2663
- h.scoped(() => {
2664
- const diag = h.diagnostic();
2665
- h.check(
2666
- set(context, h.handleOf(material), h.string(path).pointer, BigInt(node), diag),
2667
- diag,
2668
- `set ${path}`,
2669
- );
2670
- }),
2671
- effectParameter: (node, name, value) =>
2672
- h.scoped(() => {
2673
- const self = nodeOf(node);
2674
- const input = value === undefined ? 0 : h.alloc(8);
2675
- if (value !== undefined) h.view().setFloat64(input, value, true);
2676
- const out = h.alloc(8);
2677
- const diag = h.diagnostic();
2678
- h.check(
2679
- effectParameter(context, self, h.string(name).pointer, input, out, diag),
2680
- diag,
2681
- `effect ${name}`,
2682
- );
2683
- return h.view().getFloat64(out, true);
2684
- }),
2685
- // three's RenderPipeline on the product web host: the graph between scene and output.
2686
- setPost: (node) =>
2687
- h.scoped(() => {
2688
- if (setPost === undefined) throw new Error("TN_WASM_POST: this module has no web host");
2689
- if (setPost(context, nodeOf(node), 0) !== 0) throw new Error("TN_WASM_POST: refused");
2690
- }),
2691
- setToneMapping: (node) =>
2692
- h.scoped(() => {
2693
- if (setPost === undefined)
2694
- throw new Error("TN_NATIVE_CUSTOM_TONEMAPPING_MISSING: no web output binding");
2695
- if (setPost(context, nodeOf(node), 1) !== 0)
2696
- throw new Error("TN_NATIVE_CUSTOM_TONEMAPPING_INVALID: refused output node");
2697
- }),
2698
- // PRD-620: renderer.compute and storage reads over the product web host.
2699
- compute: (node) =>
2700
- h.scoped(() => {
2701
- if (computeNode === undefined || webError === undefined)
2702
- throw new Error("TN_WASM_COMPUTE: this module has no web host");
2703
- if (computeNode(context, nodeOf(node)) !== 0)
2704
- throw new Error(abi.UTF8ToString(webError()));
2705
- }),
2706
- readStorage: async (attribute) => {
2707
- if (
2708
- readStorage === undefined ||
2709
- readStorageSize === undefined ||
2710
- readStorageTake === undefined ||
2711
- computeFlush === undefined ||
2712
- poll === undefined ||
2713
- webError === undefined
2714
- )
2715
- throw new Error("TN_WASM_COMPUTE: this module has no web host");
2716
- const id = h.scoped(() => {
2717
- const pointer = h.alloc(HANDLE);
2718
- h.writeHandle(pointer, attribute);
2719
- return readStorage(pointer);
2720
- });
2721
- if (id === 0) throw new Error(abi.UTF8ToString(webError()));
2722
- computeFlush();
2723
- for (;;) {
2724
- poll();
2725
- const size = readStorageSize(id);
2726
- if (size > 0 || readStorageTake(id, 0, 0) < 0) {
2727
- const out = abi._malloc(size) >>> 0;
2728
- try {
2729
- if (readStorageTake(id, out, size) === 1)
2730
- return abi.HEAPU8.slice(out, out + size).buffer;
2731
- } finally {
2732
- abi._free(out);
2733
- }
2734
- throw new Error("TN_NATIVE_READ_STORAGE: the read failed");
2735
- }
2736
- await new Promise((resolve) => setTimeout(resolve, 0));
2737
- }
2738
- },
2739
- deleteStorage: (attribute) =>
2740
- h.scoped(() => {
2741
- if (deleteStorage === undefined || webError === undefined)
2742
- throw new Error("TN_WASM_COMPUTE: this module has no web host");
2743
- const pointer = h.alloc(HANDLE);
2744
- h.writeHandle(pointer, attribute);
2745
- if (deleteStorage(pointer) !== 0) throw new Error(abi.UTF8ToString(webError()));
2746
- }),
2747
- setUniform: (node, lanes) =>
2748
- h.scoped(() => {
2749
- const pointer = h.alloc(8);
2750
- const values = h.alloc(Math.max(8, lanes.length * 8));
2751
- const v = h.view();
2752
- v.setBigUint64(pointer, BigInt(node), true);
2753
- lanes.forEach((lane, i) => v.setFloat64(values + i * 8, lane, true));
2754
- const diag = h.diagnostic();
2755
- h.check(setUniform(context, pointer, values, lanes.length, diag), diag, "uniform.value");
2756
- }),
2757
- },
2758
- };
2759
- }
2760
-
2761
- /** The runtime over a loaded ABI module: one engine context, every call checked. */
2762
- /**
2763
- * Opt-in boundary census for `pnpm profile:wasm-page --calls`: while the page sets
2764
- * `globalThis.__tnCallCounts` to a Map, every engine get, set and invoke counts under
2765
- * "<kind> <type id>.<name>" (`__tnEngineTypes` names the type ids). Off, it costs one global read.
2766
- */
2767
- function countCall(kind: string, self: IEngineRef, name: string): void {
2768
- const counts = (globalThis as { __tnCallCounts?: Map<string, number> }).__tnCallCounts;
2769
- if (counts === undefined) return;
2770
- const key = `${kind} ${self.type}.${name}`;
2771
- counts.set(key, (counts.get(key) ?? 0) + 1);
2772
- }
2773
-
2774
- export function createWasmRuntime(abi: TnAbiModule): IBrowserRuntime {
2775
- const debug = debugTelemetry(abi);
2776
- let encoding = "arguments";
2777
- // The heap's views, made again only when the memory grows: Emscripten replaces HEAPU8 then, so one
2778
- // identity test per use stands in for reading two `.buffer`s, which every crossing paid (PRD-748).
2779
- let heap = abi.HEAPU8;
2780
- let heapBytes = heap.byteLength;
2781
- let dataView = new DataView(heap.buffer);
2782
- let words = new Uint32Array(heap.buffer);
2783
- const grown = () => {
2784
- debug?.add("wasmGrowthEvents");
2785
- debug?.add("wasmGrowthBytes", Math.max(0, abi.HEAPU8.byteLength - heapBytes), "memory");
2786
- heap = abi.HEAPU8;
2787
- heapBytes = heap.byteLength;
2788
- dataView = new DataView(heap.buffer);
2789
- words = new Uint32Array(heap.buffer);
2790
- };
2791
- const view = () => {
2792
- if (abi.HEAPU8 !== heap) grown();
2793
- return dataView;
2794
- };
2795
- const wordView = () => {
2796
- if (abi.HEAPU8 !== heap) grown();
2797
- return words;
2798
- };
2799
- // Each call frees what it allocated, and only that: a callback can run a nested call.
2800
- // A call's scratch (its handle, arguments, result and diagnostic) comes from one arena that each
2801
- // scope rewinds, a stack as nested calls (a callback inside an invoke) need; a scope that outgrows
2802
- // it falls back to malloc and frees on exit. Every engine call crosses here, many per frame.
2803
- const arenaSize = 64 * 1024;
2804
- const arenaBase = abi._malloc(arenaSize) >>> 0;
2805
- let arenaTop = arenaBase;
2806
- const allocations: number[] = [];
2807
- const alloc = (size: number): number => {
2808
- const aligned = (size + 7) & ~7;
2809
- debug?.add("bridgeScratchBytes", aligned);
2810
- let pointer: number;
2811
- if (arenaTop + aligned <= arenaBase + arenaSize) {
2812
- pointer = arenaTop;
2813
- arenaTop += aligned;
2814
- } else {
2815
- // `>>> 0`: the module addresses up to 4 GB, and an export returns a pointer as a signed i32.
2816
- pointer = abi._malloc(aligned) >>> 0;
2817
- allocations.push(pointer);
2818
- debug?.add("bridgeOverflowAllocations");
2819
- debug?.add("bridgeOverflowBytes", aligned);
2820
- }
2821
- // A call's scratch is a few words (a handle, a value, a diagnostic): word stores beat a fill call.
2822
- // `wordView` first: a `_malloc` above may have grown the memory.
2823
- const w = wordView();
2824
- if (aligned > 64) heap.fill(0, pointer, pointer + aligned);
2825
- else for (let at = pointer >>> 2, end = (pointer + aligned) >>> 2; at < end; at++) w[at] = 0;
2826
- return pointer;
2827
- };
2828
- const scoped = <T>(work: () => T): T => {
2829
- const mark = allocations.length;
2830
- const top = arenaTop;
2831
- try {
2832
- return work();
2833
- } finally {
2834
- while (allocations.length > mark) abi._free(allocations.pop() as number);
2835
- arenaTop = top;
2836
- }
2837
- };
2838
- const string = (text: string): { pointer: number; bytes: number } => {
2839
- const bytes = abi.lengthBytesUTF8(text);
2840
- const pointer = alloc(bytes + 1);
2841
- abi.stringToUTF8(text, pointer, bytes + 1);
2842
- return { pointer, bytes };
2843
- };
2844
- // Member, method and class names: a bounded set, encoded once and kept for the module's life.
2845
- const names = new Map<string, number>();
2846
- const name = (text: string): number => {
2847
- let pointer = names.get(text);
2848
- if (pointer === undefined) {
2849
- const bytes = abi.lengthBytesUTF8(text);
2850
- pointer = abi._malloc(bytes + 1) >>> 0;
2851
- abi.stringToUTF8(text, pointer, bytes + 1);
2852
- names.set(text, pointer);
2853
- }
2854
- return pointer;
2855
- };
2856
- const diagnostic = () => alloc(8);
2857
- const check = (status: number, diag: number, what: string) => {
2858
- if (status === 0) return;
2859
- const message = view().getUint32(diag, true);
2860
- const text = message === 0 ? "" : abi.UTF8ToString(message);
2861
- abi._tn_diagnostic_release(diag);
2862
- throw new Error(`TN_ABI_${status}: ${what}${text ? `: ${text}` : ""}`);
2863
- };
2864
- // A handle is three words in memory: type and context as two halves of the first, then index and
2865
- // generation. A ref made here keeps those words, so writing one back is three stores, no parse.
2866
- const keyOf = (pointer: number): IEngineRef => {
2867
- const v = view();
2868
- const type = v.getUint16(pointer, true);
2869
- const context = v.getUint16(pointer + 2, true);
2870
- const index = v.getUint32(pointer + 4, true);
2871
- const generation = v.getUint32(pointer + 8, true);
2872
- const ref: IPackedRef = {
2873
- key: `${type}:${context}:${index}:${generation}`,
2874
- type,
2875
- w0: (type | (context << 16)) >>> 0,
2876
- w1: index,
2877
- w2: generation,
2878
- };
2879
- return ref;
2880
- };
2881
- const writeHandle = (pointer: number, ref: IEngineRef) => {
2882
- let packed = ref as Partial<IPackedRef>;
2883
- if (packed.w0 === undefined) {
2884
- // A ref some other source made: parse its key once and keep the words on it.
2885
- const [type = 0, context = 0, index = 0, generation = 0] = ref.key.split(":").map(Number);
2886
- packed = Object.isExtensible(ref) ? (ref as IPackedRef) : { ...ref };
2887
- Object.assign(packed, { w0: (type | (context << 16)) >>> 0, w1: index, w2: generation });
2888
- }
2889
- if ((pointer & 3) === 0) {
2890
- const at = pointer >>> 2;
2891
- const w = wordView();
2892
- w[at] = packed.w0 as number;
2893
- w[at + 1] = packed.w1 as number;
2894
- w[at + 2] = packed.w2 as number;
2895
- return;
2896
- }
2897
- const v = view();
2898
- v.setUint32(pointer, packed.w0 as number, true);
2899
- v.setUint32(pointer + 4, packed.w1 as number, true);
2900
- v.setUint32(pointer + 8, packed.w2 as number, true);
2901
- };
2902
- const handleOf = (ref: IEngineRef): number => {
2903
- const pointer = alloc(HANDLE);
2904
- writeHandle(pointer, ref);
2905
- return pointer;
2906
- };
2907
- const writeValue = (pointer: number, value: EngineValue) => {
2908
- const v = view();
2909
- if (value === null) return v.setUint32(pointer, KIND.null, true);
2910
- if (value === undefined) return v.setUint32(pointer, KIND.undefined, true);
2911
- if (typeof value === "number") {
2912
- v.setUint32(pointer, KIND.number, true);
2913
- return v.setFloat64(pointer + 8, value, true);
2914
- }
2915
- if (typeof value === "boolean") {
2916
- v.setUint32(pointer, KIND.bool, true);
2917
- return v.setUint32(pointer + 4, value ? 1 : 0, true);
2918
- }
2919
- if (typeof value === "string") {
2920
- const text = string(value);
2921
- const w = view();
2922
- w.setUint32(pointer, KIND.string, true);
2923
- w.setUint32(pointer + 32, text.pointer, true);
2924
- return w.setBigUint64(pointer + 40, BigInt(text.bytes), true);
2925
- }
2926
- if (isRef(value)) {
2927
- v.setUint32(pointer, KIND.handle, true);
2928
- return writeHandle(pointer + 16, value);
2929
- }
2930
- if (ArrayBuffer.isView(value) && !(value instanceof DataView)) {
2931
- // A forwarded typed array (see `toEngine`): one heap copy, its view bounds kept, no boxed list.
2932
- const typed = value as TypedArray;
2933
- debug?.widen(typed, encoding, typed.byteLength);
2934
- const numbers = alloc(Math.max(8, typed.byteLength));
2935
- abi.HEAPU8.set(new Uint8Array(typed.buffer, typed.byteOffset, typed.byteLength), numbers);
2936
- const name = string(typed.constructor.name).pointer;
2937
- const w = view();
2938
- w.setUint32(pointer, KIND.bytes, true);
2939
- w.setUint32(pointer + 32, name, true);
2940
- w.setUint32(pointer + 48, numbers, true);
2941
- return w.setBigUint64(pointer + 40, BigInt(typed.length), true);
2942
- }
2943
- if (!Array.isArray(value)) {
2944
- // A record: count key/value pairs, each key a string value, as the engine returns one.
2945
- const entries = Object.entries(value as Record<string, EngineValue>);
2946
- const children = values(entries.flat());
2947
- const w = view();
2948
- w.setUint32(pointer, KIND.record, true);
2949
- w.setUint32(pointer + 48, children, true);
2950
- return w.setBigUint64(pointer + 40, BigInt(entries.length), true);
2951
- }
2952
- if (value.every((item) => typeof item === "number")) {
2953
- const numbers = alloc(Math.max(8, value.length * 8));
2954
- abi.HEAPF64.set(value as number[], numbers / 8);
2955
- const typed = (value as { [TYPED]?: string })[TYPED];
2956
- const name = typed === undefined ? 0 : string(typed).pointer;
2957
- const w = view();
2958
- w.setUint32(pointer, KIND.numbers, true);
2959
- w.setUint32(pointer + 32, name, true);
2960
- w.setUint32(pointer + 48, numbers, true);
2961
- w.setBigUint64(pointer + 40, BigInt(value.length), true);
2962
- } else {
2963
- const children = values(value);
2964
- const w = view();
2965
- w.setUint32(pointer, KIND.array, true);
2966
- w.setUint32(pointer + 48, children, true);
2967
- w.setBigUint64(pointer + 40, BigInt(value.length), true);
2968
- }
2969
- };
2970
- const values = (args: readonly EngineValue[]): number => {
2971
- const pointer = alloc(Math.max(VALUE, args.length * VALUE));
2972
- args.forEach((arg, i) => writeValue(pointer + i * VALUE, arg));
2973
- return pointer;
2974
- };
2975
- const readValue = (pointer: number): EngineValue => {
2976
- const v = view();
2977
- switch (v.getUint32(pointer, true)) {
2978
- case KIND.undefined:
2979
- return undefined;
2980
- case KIND.number:
2981
- return v.getFloat64(pointer + 8, true);
2982
- case KIND.bool:
2983
- return v.getUint32(pointer + 4, true) !== 0;
2984
- case KIND.string:
2985
- return abi.UTF8ToString(
2986
- v.getUint32(pointer + 32, true),
2987
- Number(v.getBigUint64(pointer + 40, true)),
2988
- );
2989
- case KIND.handle:
2990
- return keyOf(pointer + 16);
2991
- case KIND.array: {
2992
- const at = v.getUint32(pointer + 48, true);
2993
- return Array.from({ length: Number(v.getBigUint64(pointer + 40, true)) }, (_, i) =>
2994
- readValue(at + i * VALUE),
2995
- );
2996
- }
2997
- case KIND.record: {
2998
- const at = v.getUint32(pointer + 48, true);
2999
- return Object.fromEntries(
3000
- Array.from({ length: Number(v.getBigUint64(pointer + 40, true)) }, (_, i) => {
3001
- const key = readValue(at + i * 2 * VALUE);
3002
- if (typeof key !== "string") throw new TypeError("TN_ABI_RECORD_KEY: expected string");
3003
- return [key, readValue(at + (i * 2 + 1) * VALUE)];
3004
- }),
3005
- );
3006
- }
3007
- case KIND.numbers: {
3008
- const at = v.getUint32(pointer + 48, true) / 8;
3009
- return Array.from(
3010
- abi.HEAPF64.subarray(at, at + Number(v.getBigUint64(pointer + 40, true))),
3011
- );
3012
- }
3013
- default:
3014
- return null;
3015
- }
3016
- };
3017
-
3018
- // Callbacks: one invoke and one release trampoline in the function table; the context is a
3019
- // handler id, and the engine's release (once per pair) forgets it.
3020
- const handlers = new Map<number, (args: readonly EngineValue[]) => void>();
3021
- let nextHandler = 1;
3022
- let invokeTrampoline = 0;
3023
- let releaseTrampoline = 0;
3024
- const trampolines = () => {
3025
- if (invokeTrampoline !== 0) return;
3026
- invokeTrampoline = abi.addFunction((id, rawArgs, count, rawError, capacity) => {
3027
- // Pointers arrive as signed i32; the module addresses up to 4 GB.
3028
- const args = (rawArgs ?? 0) >>> 0;
3029
- const error = (rawError ?? 0) >>> 0;
3030
- const handler = handlers.get(id ?? 0);
3031
- if (handler === undefined) return 0;
3032
- const decoded: EngineValue[] = [];
3033
- for (let i = 0; i < (count ?? 0); i++) decoded.push(readValue(args + i * VALUE));
3034
- try {
3035
- handler(decoded);
3036
- return 0;
3037
- } catch (thrown) {
3038
- abi.stringToUTF8(
3039
- thrown instanceof Error ? thrown.message : String(thrown),
3040
- error,
3041
- capacity ?? 0,
3042
- );
3043
- return 8; // TN_ERROR_INVALID_STATE: the engine records it and goes on
3044
- }
3045
- }, "iiiiii");
3046
- releaseTrampoline = abi.addFunction((id) => {
3047
- handlers.delete(id ?? 0);
3048
- return undefined;
3049
- }, "vi");
3050
- };
3051
-
3052
- // A view over the attribute's storage, used only inside one call: the lease pins the storage and
3053
- // nothing in between can grow the memory and detach the view. A kept view would detach on growth,
3054
- // so the back end keeps JS arrays and copies through this (see defineBrowserClasses).
3055
- const withAttributeView = <T>(self: IEngineRef, use: (view: TypedArray) => T): T =>
3056
- scoped(() => {
3057
- const call = abi._tnw_attribute_view;
3058
- if (call === undefined)
3059
- throw new TypeError("TN_WASM_MODULE: this module exports no attribute views");
3060
- const out = alloc(24);
3061
- const lease = call(handleOf(self), out);
3062
- if (lease === 0) throw new TypeError("TN_NATIVE_UNSUPPORTED array: not an attribute");
3063
- try {
3064
- const v = view();
3065
- const [address, count, scalar] = [0, 8, 16].map((at) =>
3066
- Number(v.getBigUint64(out + at, true)),
3067
- );
3068
- const Typed = SCALARS[scalar ?? -1];
3069
- if (Typed === undefined)
3070
- throw new TypeError(`TN_NATIVE_UNSUPPORTED array: scalar ${String(scalar)}`);
3071
- return use(new Typed(abi.HEAPU8.buffer as ArrayBuffer, address ?? 0, count ?? 0));
3072
- } finally {
3073
- abi._tnw_attribute_view_release?.(lease);
3074
- }
3075
- });
3076
-
3077
- const context = scoped(() => {
3078
- const version = alloc(32);
3079
- abi._tn_engine_version(version);
3080
- const contextOut = alloc(4);
3081
- const diag = diagnostic();
3082
- check(abi._tn_context_create(contextOut, version, diag), diag, "tn_context_create");
3083
- return view().getUint32(contextOut, true);
3084
- });
3085
-
3086
- return {
3087
- ...(tslOf(abi, context, {
3088
- scoped,
3089
- alloc,
3090
- string,
3091
- diagnostic,
3092
- check,
3093
- handleOf,
3094
- writeHandle,
3095
- view,
3096
- }) ?? {}),
3097
- ...gltfOf(abi, context, { scoped, alloc, keyOf }),
3098
- ...(debug === undefined ? {} : { debugTelemetry: debug }),
3099
- typedArrays: true,
3100
- typeId: (className) => abi._tn_type_id(name(className)),
3101
- construct: (className, args) =>
3102
- scoped(() => {
3103
- const out = alloc(HANDLE);
3104
- const diag = diagnostic();
3105
- check(
3106
- abi._tn_construct(
3107
- context,
3108
- string(className).pointer,
3109
- values(args),
3110
- args.length,
3111
- out,
3112
- diag,
3113
- ),
3114
- diag,
3115
- `new ${className}`,
3116
- );
3117
- return keyOf(out);
3118
- }),
3119
- invoke: (self, method, args) =>
3120
- scoped(() => {
3121
- countCall("call", self, method);
3122
- if (debug !== undefined) encoding = method;
3123
- const out = alloc(VALUE);
3124
- const diag = diagnostic();
3125
- check(
3126
- abi._tn_invoke(handleOf(self), name(method), values(args), args.length, out, diag),
3127
- diag,
3128
- `${method}()`,
3129
- );
3130
- return readValue(out);
3131
- }),
3132
- engineReferences: (refs) =>
3133
- scoped(() => {
3134
- const handles = alloc(Math.max(1, refs.length) * HANDLE);
3135
- refs.forEach((ref, i) => writeHandle(handles + i * HANDLE, ref));
3136
- const out = alloc(Math.max(1, refs.length) * 4);
3137
- abi._tn_object_engine_references(handles, refs.length, out);
3138
- const v = view();
3139
- return refs.map((_, i) => v.getUint32(out + i * 4, true));
3140
- }),
3141
- readByte: (address) => abi.HEAPU8[address] as number,
3142
- readWord: (address) => view().getUint32(address, true),
3143
- writeDouble: (address, value) => {
3144
- abi.HEAPF64[address / 8] = value;
3145
- },
3146
- writeByte: (address, value) => {
3147
- abi.HEAPU8[address] = value;
3148
- },
3149
- heapF64: () => abi.HEAPF64,
3150
- readDoubles: (address, count) => {
3151
- const at = address / 8;
3152
- return count === 1
3153
- ? (abi.HEAPF64[at] as number)
3154
- : Array.from(abi.HEAPF64.subarray(at, at + count));
3155
- },
3156
- get: (self, path) =>
3157
- scoped(() => {
3158
- countCall("get", self, path);
3159
- const out = alloc(VALUE);
3160
- const diag = diagnostic();
3161
- check(abi._tn_get(handleOf(self), name(path), out, diag), diag, `get ${path}`);
3162
- return readValue(out);
3163
- }),
3164
- set: (self, path, value) =>
3165
- scoped(() => {
3166
- countCall("set", self, path);
3167
- if (debug !== undefined) encoding = path;
3168
- // One value written in place: no one-item list per write.
3169
- const pointer = alloc(VALUE);
3170
- writeValue(pointer, value);
3171
- const diag = diagnostic();
3172
- check(abi._tn_set(handleOf(self), name(path), pointer, diag), diag, `set ${path}`);
3173
- }),
3174
- release: (self) =>
3175
- scoped(() => {
3176
- const diag = diagnostic();
3177
- abi._tn_object_release(handleOf(self), diag);
3178
- abi._tn_diagnostic_release(diag);
3179
- }),
3180
- attributeArray: (self, offset, count) =>
3181
- withAttributeView(self, (target) => {
3182
- const from = offset === undefined ? 0 : offset;
3183
- const length = count === undefined ? target.length - from : count;
3184
- if (
3185
- !Number.isSafeInteger(from) ||
3186
- !Number.isSafeInteger(length) ||
3187
- from < 0 ||
3188
- length < 0 ||
3189
- from + length > target.length
3190
- )
3191
- throw new RangeError(
3192
- `TN_NATIVE_ATTRIBUTE_RANGE: [${String(from)}, ${String(length)}) is outside ${String(target.length)} elements`,
3193
- );
3194
- return target.subarray(from, from + length).slice();
3195
- }),
3196
- attributeWrite: (self, array, offset) =>
3197
- withAttributeView(self, (target) => {
3198
- // An omitted offset writes the whole attribute, so the array must be its exact data; an
3199
- // explicit offset (including 0) writes that subrange.
3200
- if (offset === undefined) {
3201
- if (target.length !== array.length)
3202
- throw new RangeError(
3203
- `TN_NATIVE_ATTRIBUTE_LENGTH: attribute.array has ${String(array.length)} elements, the attribute ${String(target.length)}`,
3204
- );
3205
- target.set(array);
3206
- return;
3207
- }
3208
- if (!Number.isSafeInteger(offset) || offset < 0 || offset + array.length > target.length)
3209
- throw new RangeError(
3210
- `TN_NATIVE_ATTRIBUTE_LENGTH: attribute.array has ${String(array.length)} elements at ${String(offset)}, the attribute ${String(target.length)}`,
3211
- );
3212
- target.set(array, offset);
3213
- }),
3214
- setCallback: (self, name, handler) =>
3215
- scoped(() => {
3216
- const diag = diagnostic();
3217
- if (handler === null) {
3218
- check(
3219
- abi._tn_set_callback(handleOf(self), string(name).pointer, 0, 0, 0, diag),
3220
- diag,
3221
- `clear ${name}`,
3222
- );
3223
- return;
3224
- }
3225
- trampolines();
3226
- const id = nextHandler++;
3227
- handlers.set(id, handler);
3228
- const status = abi._tn_set_callback(
3229
- handleOf(self),
3230
- string(name).pointer,
3231
- invokeTrampoline,
3232
- id,
3233
- releaseTrampoline,
3234
- diag,
3235
- );
3236
- if (status !== 0) handlers.delete(id); // a refused pair was never taken
3237
- check(status, diag, `set ${name}`);
3238
- }),
3239
- };
3240
- }
3241
-
3242
- /**
3243
- * three's `Euler.setFromQuaternion` (and the engine's Euler.cpp, whose ieee754 functions are V8's fdlibm, so the
3244
- * bits match): the rotation matrix of a unit quaternion, then the angles of the given order.
3245
- */
3246
- export function eulerFromQuaternion(
3247
- x: number,
3248
- y: number,
3249
- z: number,
3250
- w: number,
3251
- order: string,
3252
- ): [number, number, number] {
3253
- const x2 = x + x;
3254
- const y2 = y + y;
3255
- const z2 = z + z;
3256
- const xx = x * x2;
3257
- const xy = x * y2;
3258
- const xz = x * z2;
3259
- const yy = y * y2;
3260
- const yz = y * z2;
3261
- const zz = z * z2;
3262
- const wx = w * x2;
3263
- const wy = w * y2;
3264
- const wz = w * z2;
3265
- const m11 = 1 - (yy + zz);
3266
- const m12 = xy - wz;
3267
- const m13 = xz + wy;
3268
- const m21 = xy + wz;
3269
- const m22 = 1 - (xx + zz);
3270
- const m23 = yz - wx;
3271
- const m31 = xz - wy;
3272
- const m32 = yz + wx;
3273
- const m33 = 1 - (xx + yy);
3274
- const asin = (value: number): number => Math.asin(Math.max(-1, Math.min(1, value)));
3275
- const free = (value: number): boolean => Math.abs(value) < 0.9999999;
3276
- switch (order) {
3277
- case "YXZ":
3278
- return free(m23)
3279
- ? [-asin(m23), Math.atan2(m13, m33), Math.atan2(m21, m22)]
3280
- : [-asin(m23), Math.atan2(-m31, m11), 0];
3281
- case "ZXY":
3282
- return free(m32)
3283
- ? [asin(m32), Math.atan2(-m31, m33), Math.atan2(-m12, m22)]
3284
- : [asin(m32), 0, Math.atan2(m21, m11)];
3285
- case "ZYX":
3286
- return free(m31)
3287
- ? [Math.atan2(m32, m33), -asin(m31), Math.atan2(m21, m11)]
3288
- : [0, -asin(m31), Math.atan2(-m12, m22)];
3289
- case "YZX":
3290
- return free(m21)
3291
- ? [Math.atan2(-m23, m22), Math.atan2(-m31, m11), asin(m21)]
3292
- : [0, Math.atan2(m13, m33), asin(m21)];
3293
- case "XZY":
3294
- return free(m12)
3295
- ? [Math.atan2(m32, m22), Math.atan2(m13, m11), -asin(m12)]
3296
- : [Math.atan2(-m23, m33), 0, -asin(m12)];
3297
- default:
3298
- return free(m13)
3299
- ? [Math.atan2(-m23, m33), asin(m13), Math.atan2(-m12, m11)]
3300
- : [Math.atan2(m32, m22), asin(m13), 0];
3301
- }
3302
- }