@threenative/three-native 0.0.0-stage → 0.3.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +24 -2
  3. package/package.json +42 -3
  4. package/src/addons/buffer-geometry-utils.ts +14 -0
  5. package/src/addons/data-utils.ts +63 -0
  6. package/src/addons/decal-geometry.ts +25 -0
  7. package/src/addons/decal.ts +218 -0
  8. package/src/addons/gltf-loader-web.ts +323 -0
  9. package/src/addons/hdr-loader.ts +71 -0
  10. package/src/addons/hdr.ts +139 -0
  11. package/src/addons/lut-cube-loader-web.ts +17 -0
  12. package/src/addons/lut-cube-loader.ts +149 -0
  13. package/src/addons/merge-geometries.ts +374 -0
  14. package/src/addons/mesh-bvh-webgpu.ts +13 -0
  15. package/src/addons/mesh-bvh.ts +50 -0
  16. package/src/addons/post-effects-web.ts +22 -0
  17. package/src/addons/post-effects.ts +173 -0
  18. package/src/audio.ts +564 -0
  19. package/src/blend-mode.ts +33 -0
  20. package/src/browser-backend.ts +2156 -0
  21. package/src/browser-entry.ts +305 -0
  22. package/src/browser-math.ts +448 -0
  23. package/src/browser-renderer.ts +527 -0
  24. package/src/browser-tsl.ts +650 -0
  25. package/src/catalog.ts +497 -0
  26. package/src/fixture-format.ts +721 -0
  27. package/src/fixture-native.ts +426 -0
  28. package/src/fixture-protocol.ts +315 -0
  29. package/src/math-utils.ts +65 -0
  30. package/src/object-surface.ts +250 -0
  31. package/src/pass-node.ts +286 -0
  32. package/src/property-binding.ts +93 -0
  33. package/src/quad-mesh.ts +54 -0
  34. package/src/reflector.ts +89 -0
  35. package/src/refused.ts +27 -0
  36. package/src/render-target.ts +107 -0
  37. package/src/rtt.ts +158 -0
  38. package/src/shadow-map.ts +21 -0
  39. package/src/storage.ts +206 -0
  40. package/src/texture-sources.ts +252 -0
  41. package/src/tsl-extras.ts +51 -0
  42. package/src/tsl-struct.ts +20 -0
  43. package/src/tsl-uniforms.ts +234 -0
  44. package/src/update-ranges.ts +109 -0
  45. package/src/wgsl-fn.ts +55 -0
@@ -0,0 +1,374 @@
1
+ // Ported from three.js r185 (three@0.185.1). The MIT License, Copyright © 2010-2026 three.js authors.
2
+ /**
3
+ * three's `BufferGeometryUtils.mergeGeometries`, `mergeAttributes` and `mergeVertices` (three@0.185.1
4
+ * examples/jsm/utils/BufferGeometryUtils.js) over an engine's own BufferGeometry and
5
+ * BufferAttribute, for both back ends.
6
+ *
7
+ * One order differs from three's, never a result: three builds the merged BufferAttribute around an
8
+ * empty typed array and fills the array afterwards, which works because three keeps the array it is
9
+ * handed. An engine attribute copies its array when it is built, so the array is filled first.
10
+ * Every refusal is three's: `console.error` with three's message, then `null`.
11
+ */
12
+
13
+ type TypedArray =
14
+ | Float32Array
15
+ | Uint8Array
16
+ | Uint16Array
17
+ | Uint32Array
18
+ | Int8Array
19
+ | Int16Array
20
+ | Int32Array;
21
+
22
+ interface IAttributeLike {
23
+ readonly array: TypedArray;
24
+ readonly itemSize: number;
25
+ readonly normalized: boolean;
26
+ readonly count: number;
27
+ gpuType?: number;
28
+ readonly isInterleavedBufferAttribute?: boolean;
29
+ getComponent(index: number, component: number): number;
30
+ }
31
+
32
+ interface IGeometryLike {
33
+ readonly index: (IAttributeLike & { getX(index: number): number }) | null;
34
+ readonly attributes: Readonly<Record<string, IAttributeLike>>;
35
+ readonly morphAttributes: Readonly<Record<string, readonly IAttributeLike[]>>;
36
+ readonly morphTargetsRelative: boolean;
37
+ }
38
+
39
+ interface IVertexGeometry extends IGeometryLike {
40
+ getIndex(): IGeometryLike["index"];
41
+ clone(): IMergedGeometry;
42
+ }
43
+
44
+ /** three's MathUtils.denormalize and normalize: a normalized integer attribute's stored value and its number. */
45
+ function denormalize(value: number, array: TypedArray): number {
46
+ if (array instanceof Uint32Array) return value / 4294967295;
47
+ if (array instanceof Uint16Array) return value / 65535;
48
+ if (array instanceof Uint8Array) return value / 255;
49
+ if (array instanceof Int32Array) return Math.max(value / 2147483647, -1);
50
+ if (array instanceof Int16Array) return Math.max(value / 32767, -1);
51
+ if (array instanceof Int8Array) return Math.max(value / 127, -1);
52
+ return value;
53
+ }
54
+ function normalize(value: number, array: TypedArray): number {
55
+ if (array instanceof Uint32Array) return Math.round(value * 4294967295);
56
+ if (array instanceof Uint16Array) return Math.round(value * 65535);
57
+ if (array instanceof Uint8Array) return Math.round(value * 255);
58
+ if (array instanceof Int32Array) return Math.round(value * 2147483647);
59
+ if (array instanceof Int16Array) return Math.round(value * 32767);
60
+ if (array instanceof Int8Array) return Math.round(value * 127);
61
+ return value;
62
+ }
63
+
64
+ /** three's `attribute.getX(index)` and its siblings for one component. */
65
+ function component(attribute: IAttributeLike, index: number, k: number): number {
66
+ if (attribute.isInterleavedBufferAttribute) return attribute.getComponent(index, k);
67
+ const value = attribute.array[index * attribute.itemSize + k] as number;
68
+ return attribute.normalized ? denormalize(value, attribute.array) : value;
69
+ }
70
+
71
+ /** three's `attribute.setX(index, value)` into the array a new attribute is built from. */
72
+ function store(array: TypedArray, source: IAttributeLike, at: number, value: number): void {
73
+ array[at] = source.normalized ? normalize(value, array) : value;
74
+ }
75
+
76
+ interface IMergedGeometry {
77
+ addGroup(start: number, count: number, materialIndex: number): void;
78
+ setIndex(index: IAttributeLike | number[]): void;
79
+ setAttribute(name: string, attribute: IAttributeLike): void;
80
+ morphAttributes: Record<string, IAttributeLike[]>;
81
+ __mergeFrom?(parts: readonly IGeometryLike[], indexed: boolean, names: string[]): string;
82
+ }
83
+
84
+ /**
85
+ * The merged index three builds with `getX` per element, from each index's array read once: an
86
+ * engine attribute's getX is a crossing per call. Typed as three's setIndex(number[]) types it:
87
+ * Uint32 when any value reaches 65535, each value converted as that array converts it.
88
+ */
89
+ function mergedIndex(geometries: readonly IGeometryLike[]): Uint16Array | Uint32Array {
90
+ let length = 0;
91
+ for (const geometry of geometries) length += (geometry.index as IAttributeLike).count;
92
+ const values = new Float64Array(length);
93
+ let at = 0;
94
+ let offset = 0;
95
+ let wide = false;
96
+ for (const geometry of geometries) {
97
+ const index = geometry.index as IAttributeLike;
98
+ const count = index.count;
99
+ const array = index.isInterleavedBufferAttribute || index.normalized ? undefined : index.array;
100
+ const step = index.itemSize;
101
+ for (let j = 0; j < count; ++j) {
102
+ const value = (array ? (array[j * step] as number) : component(index, j, 0)) + offset;
103
+ wide ||= value >= 65535;
104
+ values[at++] = value;
105
+ }
106
+ offset += (geometry.attributes.position as IAttributeLike).count;
107
+ }
108
+ return wide ? new Uint32Array(values) : new Uint16Array(values);
109
+ }
110
+
111
+ /** What one engine supplies: the two classes a merge builds. */
112
+ export interface IGeometryUtilsEngine {
113
+ // quality-allow: three's PascalCase class name passed in engine constructor map.
114
+ // biome-ignore lint/style/useNamingConvention: three's class name, so a back end passes its class map.
115
+ readonly BufferGeometry: new () => object;
116
+ // quality-allow: three's PascalCase class name passed in engine constructor map.
117
+ // biome-ignore lint/style/useNamingConvention: see BufferGeometry.
118
+ readonly BufferAttribute: new (
119
+ array: TypedArray,
120
+ itemSize: number,
121
+ normalized?: boolean,
122
+ ) => object;
123
+ }
124
+
125
+ const PREFIX = "THREE.BufferGeometryUtils:";
126
+
127
+ export function defineBufferGeometryUtils(engine: IGeometryUtilsEngine) {
128
+ function mergeAttributes(attributes: readonly IAttributeLike[]): IAttributeLike | null {
129
+ let Typed: (new (length: number) => TypedArray) | undefined;
130
+ let itemSize: number | undefined;
131
+ let normalized: boolean | undefined;
132
+ let gpuType: number | undefined = -1;
133
+ let arrayLength = 0;
134
+ for (const attribute of attributes) {
135
+ const made = attribute.array.constructor as new (length: number) => TypedArray;
136
+ Typed ??= made;
137
+ if (Typed !== made) {
138
+ console.error(
139
+ `${PREFIX} .mergeAttributes() failed. BufferAttribute.array must be of consistent array types across matching attributes.`,
140
+ );
141
+ return null;
142
+ }
143
+ itemSize ??= attribute.itemSize;
144
+ if (itemSize !== attribute.itemSize) {
145
+ console.error(
146
+ `${PREFIX} .mergeAttributes() failed. BufferAttribute.itemSize must be consistent across matching attributes.`,
147
+ );
148
+ return null;
149
+ }
150
+ normalized ??= attribute.normalized;
151
+ if (normalized !== attribute.normalized) {
152
+ console.error(
153
+ `${PREFIX} .mergeAttributes() failed. BufferAttribute.normalized must be consistent across matching attributes.`,
154
+ );
155
+ return null;
156
+ }
157
+ if (gpuType === -1) gpuType = attribute.gpuType;
158
+ if (gpuType !== attribute.gpuType) {
159
+ console.error(
160
+ `${PREFIX} .mergeAttributes() failed. BufferAttribute.gpuType must be consistent across matching attributes.`,
161
+ );
162
+ return null;
163
+ }
164
+ arrayLength += attribute.count * itemSize;
165
+ }
166
+ if (Typed === undefined || itemSize === undefined) return null;
167
+ const array = new Typed(arrayLength);
168
+ let offset = 0;
169
+ for (const attribute of attributes) {
170
+ if (attribute.isInterleavedBufferAttribute) {
171
+ for (let j = 0; j < attribute.count; j++)
172
+ for (let c = 0; c < itemSize; c++)
173
+ array[offset + j * itemSize + c] = attribute.getComponent(j, c);
174
+ } else array.set(attribute.array, offset);
175
+ offset += attribute.count * itemSize;
176
+ }
177
+ const result = new engine.BufferAttribute(array, itemSize, normalized) as IAttributeLike;
178
+ // The engine attribute already holds three's default; its gpuType is written only to change it.
179
+ if (gpuType !== undefined && result.gpuType !== gpuType) result.gpuType = gpuType;
180
+ return result;
181
+ }
182
+
183
+ // Each geometry's attributes and morph attributes, grouped by name; a string is three's refusal.
184
+ function collect(
185
+ geometries: readonly IGeometryLike[],
186
+ merged: IMergedGeometry,
187
+ useGroups: boolean,
188
+ ) {
189
+ const first = geometries[0] as IGeometryLike;
190
+ const isIndexed = first.index !== null;
191
+ const attributesUsed = new Set(Object.keys(first.attributes));
192
+ const morphAttributesUsed = new Set(Object.keys(first.morphAttributes));
193
+ const attributes: Record<string, IAttributeLike[]> = {};
194
+ const morphAttributes: Record<string, (readonly IAttributeLike[])[]> = {};
195
+ let offset = 0;
196
+ for (const [i, geometry] of geometries.entries()) {
197
+ const at = `${PREFIX} .mergeGeometries() failed with geometry at index ${i}.`;
198
+ if (isIndexed !== (geometry.index !== null))
199
+ return `${at} All geometries must have compatible attributes; make sure index attribute exists among all geometries, or in none of them.`;
200
+ let attributesCount = 0;
201
+ for (const name of Object.keys(geometry.attributes)) {
202
+ if (!attributesUsed.has(name))
203
+ return `${at} All geometries must have compatible attributes; make sure "${name}" attribute exists among all geometries, or in none of them.`;
204
+ attributes[name] ??= [];
205
+ attributes[name].push(geometry.attributes[name] as IAttributeLike);
206
+ attributesCount++;
207
+ }
208
+ if (attributesCount !== attributesUsed.size)
209
+ return `${at} Make sure all geometries have the same number of attributes.`;
210
+ if (first.morphTargetsRelative !== geometry.morphTargetsRelative)
211
+ return `${at} .morphTargetsRelative must be consistent throughout all geometries.`;
212
+ for (const name of Object.keys(geometry.morphAttributes)) {
213
+ if (!morphAttributesUsed.has(name))
214
+ return `${at} .morphAttributes must be consistent throughout all geometries.`;
215
+ morphAttributes[name] ??= [];
216
+ morphAttributes[name].push(geometry.morphAttributes[name] as readonly IAttributeLike[]);
217
+ }
218
+ if (useGroups) {
219
+ const count = isIndexed ? geometry.index?.count : geometry.attributes.position?.count;
220
+ if (count === undefined)
221
+ return `${at} The geometry must have either an index or a position attribute`;
222
+ merged.addGroup(offset, count, i);
223
+ offset += count;
224
+ }
225
+ }
226
+ return { attributes, morphAttributes, isIndexed };
227
+ }
228
+
229
+ type Found = Exclude<ReturnType<typeof collect>, string>;
230
+
231
+ /**
232
+ * An engine geometry merges the index and attributes in one call, reading each array where it
233
+ * lives. Answers "" when merged, the refused attribute's name after mergeAttributes' message, and
234
+ * undefined when the engine leaves the merge to the port ("?").
235
+ */
236
+ function mergeInEngine(merged: IMergedGeometry, parts: readonly IGeometryLike[], found: Found) {
237
+ if (typeof merged.__mergeFrom !== "function") return undefined;
238
+ const answer = merged.__mergeFrom(parts, found.isIndexed, Object.keys(found.attributes));
239
+ if (answer === "?") return undefined;
240
+ if (answer === "") return "";
241
+ const [field, name] = answer.split("\n");
242
+ const rule = field === "array" ? "of consistent array types" : "consistent";
243
+ console.error(
244
+ `${PREFIX} .mergeAttributes() failed. BufferAttribute.${field} must be ${rule} across matching attributes.`,
245
+ );
246
+ return name as string;
247
+ }
248
+
249
+ /** The port's merge of the index and attributes: "" when merged, else the refused attribute's name. */
250
+ function mergeInPort(merged: IMergedGeometry, parts: readonly IGeometryLike[], found: Found) {
251
+ if (found.isIndexed)
252
+ merged.setIndex(new engine.BufferAttribute(mergedIndex(parts), 1) as IAttributeLike);
253
+ for (const [name, list] of Object.entries(found.attributes)) {
254
+ const attribute = mergeAttributes(list);
255
+ if (!attribute) return name;
256
+ merged.setAttribute(name, attribute);
257
+ }
258
+ return "";
259
+ }
260
+
261
+ function mergeGeometries(geometries: readonly IGeometryLike[], useGroups = false): object | null {
262
+ const merged = new engine.BufferGeometry() as IMergedGeometry;
263
+ const found = collect(geometries, merged, useGroups);
264
+ if (typeof found === "string") {
265
+ console.error(found);
266
+ return null;
267
+ }
268
+ const refused =
269
+ mergeInEngine(merged, geometries, found) ?? mergeInPort(merged, geometries, found);
270
+ if (refused !== "") {
271
+ console.error(
272
+ `${PREFIX} .mergeGeometries() failed while trying to merge the ${refused} attribute.`,
273
+ );
274
+ return null;
275
+ }
276
+ for (const [name, perGeometry] of Object.entries(found.morphAttributes)) {
277
+ const numMorphTargets = (perGeometry[0] as readonly IAttributeLike[]).length;
278
+ if (numMorphTargets === 0) continue;
279
+ const targets: IAttributeLike[] = [];
280
+ for (let i = 0; i < numMorphTargets; ++i) {
281
+ const attribute = mergeAttributes(perGeometry.map((list) => list[i] as IAttributeLike));
282
+ if (!attribute) {
283
+ console.error(
284
+ `${PREFIX} .mergeGeometries() failed while trying to merge the ${name} morphAttribute.`,
285
+ );
286
+ return null;
287
+ }
288
+ targets.push(attribute);
289
+ }
290
+ merged.morphAttributes[name] = targets;
291
+ }
292
+ return merged;
293
+ }
294
+
295
+ /**
296
+ * three's mergeVertices: vertices whose attributes hash alike (to `tolerance`) become one vertex,
297
+ * and the clone is re-indexed. The merged attributes are engine BufferAttributes over the source
298
+ * arrays' types, as three keeps each attribute's constructor.
299
+ */
300
+ function mergeVertices(geometry: IVertexGeometry, tolerance = 1e-4): object {
301
+ const used = Math.max(tolerance, Number.EPSILON);
302
+ const hashToIndex = new Map<string, number>();
303
+ const indices = geometry.getIndex();
304
+ const positions = geometry.attributes.position as IAttributeLike;
305
+ const vertexCount = indices ? indices.count : positions.count;
306
+ const names = Object.keys(geometry.attributes);
307
+ const arrays: Record<string, TypedArray> = {};
308
+ const morphArrays: Record<string, TypedArray[]> = {};
309
+ const made = (attribute: IAttributeLike) =>
310
+ new (attribute.array.constructor as new (length: number) => TypedArray)(
311
+ attribute.count * attribute.itemSize,
312
+ );
313
+ for (const name of names) {
314
+ arrays[name] = made(geometry.attributes[name] as IAttributeLike);
315
+ const morphs = geometry.morphAttributes[name];
316
+ if (morphs) morphArrays[name] = morphs.map(made);
317
+ }
318
+ const hashMultiplier = 10 ** Math.log10(1 / used);
319
+ const hashAdditive = used * 0.5 * hashMultiplier;
320
+ const newIndices: number[] = [];
321
+ let nextIndex = 0;
322
+ for (let i = 0; i < vertexCount; i++) {
323
+ const index = indices ? indices.getX(i) : i;
324
+ let hash = "";
325
+ for (const name of names) {
326
+ const attribute = geometry.attributes[name] as IAttributeLike;
327
+ for (let k = 0; k < attribute.itemSize; k++)
328
+ hash += `${~~(component(attribute, index, k) * hashMultiplier + hashAdditive)},`;
329
+ }
330
+ const known = hashToIndex.get(hash);
331
+ if (known !== undefined) {
332
+ newIndices.push(known);
333
+ continue;
334
+ }
335
+ for (const name of names) {
336
+ const attribute = geometry.attributes[name] as IAttributeLike;
337
+ const morphs = geometry.morphAttributes[name];
338
+ for (let k = 0; k < attribute.itemSize; k++) {
339
+ const at = nextIndex * attribute.itemSize + k;
340
+ store(arrays[name] as TypedArray, attribute, at, component(attribute, index, k));
341
+ morphs?.forEach((morph, m) => {
342
+ const target = (morphArrays[name] as TypedArray[])[m] as TypedArray;
343
+ store(target, morph, nextIndex * morph.itemSize + k, component(morph, index, k));
344
+ });
345
+ }
346
+ }
347
+ hashToIndex.set(hash, nextIndex);
348
+ newIndices.push(nextIndex);
349
+ nextIndex++;
350
+ }
351
+ const result = geometry.clone();
352
+ const rebuilt = (array: TypedArray, source: IAttributeLike) =>
353
+ new engine.BufferAttribute(
354
+ array.slice(0, nextIndex * source.itemSize),
355
+ source.itemSize,
356
+ source.normalized,
357
+ ) as IAttributeLike;
358
+ for (const name of names) {
359
+ result.setAttribute(
360
+ name,
361
+ rebuilt(arrays[name] as TypedArray, geometry.attributes[name] as IAttributeLike),
362
+ );
363
+ const morphs = geometry.morphAttributes[name];
364
+ if (morphs)
365
+ result.morphAttributes[name] = morphs.map((morph, m) =>
366
+ rebuilt((morphArrays[name] as TypedArray[])[m] as TypedArray, morph),
367
+ );
368
+ }
369
+ result.setIndex(newIndices);
370
+ return result;
371
+ }
372
+
373
+ return { mergeGeometries, mergeAttributes, mergeVertices };
374
+ }
@@ -0,0 +1,13 @@
1
+ /**
2
+ * `three-mesh-bvh/webgpu` as the engine back ends provide it. The upstream module pulls in
3
+ * three-mesh-bvh's whole CPU tree, which builds a `Line3` and extends `Triangle` at module scope,
4
+ * and it extends three's node classes, so it cannot load over the engine. Core imports it for
5
+ * `GPUSceneBVH`; each export refuses at use, by name, so a game that builds no GPU scene BVH boots.
6
+ *
7
+ * ponytail: refused at use; bind the TSL ray query when a native-engine game needs GPUSceneBVH.
8
+ */
9
+ import { unsupportedExport } from "../refused.js";
10
+
11
+ export const bvhIntersectFirstHit = unsupportedExport("bvhIntersectFirstHit");
12
+ export const rayStruct = unsupportedExport("rayStruct");
13
+ export const bvhNodeStruct = unsupportedExport("bvhNodeStruct");
@@ -0,0 +1,50 @@
1
+ /**
2
+ * `three-mesh-bvh`'s `MeshBVH` as the engine back ends provide it: the ray queries core's picking
3
+ * makes (`raycastObject3D`, honouring `raycaster.firstHitOnly`), answered by the engine's own
4
+ * triangle raycast. The upstream package runs its tree walk through `Triangle`, `Line3` and a
5
+ * `Vector3` per step, every one an ABI crossing here, so it is not run as JS against engine objects.
6
+ *
7
+ * ponytail: the engine raycast tests every triangle of the mesh in C++; build a native tree when a
8
+ * profile shows picking cost, with these results as its oracle.
9
+ */
10
+
11
+ interface IRaycasterLike {
12
+ firstHitOnly?: boolean;
13
+ intersectObject(object: object, recursive: boolean): readonly object[];
14
+ }
15
+
16
+ /** three-mesh-bvh's split strategies, with its values (src/core/Constants.js). */
17
+ export const CENTER = 0;
18
+ export const AVERAGE = 1;
19
+ export const SAH = 2;
20
+
21
+ export class MeshBVH {
22
+ readonly geometry: object;
23
+
24
+ constructor(geometry: object, options?: Readonly<Record<string, unknown>>) {
25
+ const { strategy, ...rest } = options ?? {};
26
+ // A split strategy changes how three-mesh-bvh builds its tree, never which triangles a ray
27
+ // hits; the engine raycast answers the same either way, so any of the three is accepted.
28
+ if (strategy !== undefined && strategy !== CENTER && strategy !== AVERAGE && strategy !== SAH)
29
+ throw new Error(
30
+ `TN_NATIVE_MESH_BVH_STRATEGY: ${String(strategy)} is not CENTER, AVERAGE or SAH`,
31
+ );
32
+ const unsupported = Object.keys(rest);
33
+ if (unsupported.length > 0)
34
+ throw new Error(
35
+ `TN_NATIVE_MESH_BVH_OPTIONS_UNSUPPORTED: ${unsupported.join(", ")}: the engine MeshBVH builds no tree, so it takes no other build option`,
36
+ );
37
+ this.geometry = geometry;
38
+ }
39
+
40
+ /** three-mesh-bvh's `raycastObject3D`: the object's hits (only the nearest with `firstHitOnly`). */
41
+ raycastObject3D(object: object, raycaster: IRaycasterLike, intersects: object[] = []): object[] {
42
+ const hits = raycaster.intersectObject(object, false);
43
+ if (raycaster.firstHitOnly === true) {
44
+ if (hits[0] !== undefined) intersects.push(hits[0]);
45
+ } else {
46
+ for (const hit of hits) intersects.push(hit);
47
+ }
48
+ return intersects;
49
+ }
50
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * The browser entry for three/addons/tsl/display's GTAO, Denoise, SMAA and Bloom (and the refused rest) under
3
+ * `engine: "threenative"` (PRD-540): the shared post effects over the Wasm engine's TSL functions, which
4
+ * the web engine module hands over as `__tnTsl` beside three's own exports.
5
+ */
6
+ // quality-allow: the symbol exists only in the web engine module the bundler resolves "three/tsl" to, so no declaration can type it.
7
+ // @ts-expect-error -- `__tnTsl` exists only in the web engine module "three/tsl" resolves to.
8
+ import { __tnTsl } from "three/tsl";
9
+ import { unsupportedExport } from "../refused.js";
10
+ import { type IEffectTsl, definePostEffects } from "./post-effects.js";
11
+
12
+ export const { ao, denoise, smaa, bloom, traa, film, lut3D } = definePostEffects(
13
+ __tnTsl as IEffectTsl,
14
+ );
15
+
16
+ // The other display nodes need live addon-node construction the engine lacks: importable, and they
17
+ // refuse at use by name (as core-addons.mjs on the V8 player).
18
+ export const fxaa = unsupportedExport("fxaa");
19
+ export const godrays = unsupportedExport("godrays");
20
+ export const ssgi = unsupportedExport("ssgi");
21
+ export const ssr = unsupportedExport("ssr");
22
+ export const sharpen = unsupportedExport("sharpen");
@@ -0,0 +1,173 @@
1
+ /**
2
+ * three/addons/tsl/display's GTAO, Denoise, SMAA and Bloom as the engine's live effects, for both
3
+ * back ends (PRD-540; moved from the V8 player's core-addons.mjs). Each returns the effect's node; its
4
+ * scalar uniforms read and write the native effect (`ao(...).radius.value`) through the node's
5
+ * `__effect(name[, value])`, which the back end routes to tslEffectParameter.
6
+ */
7
+
8
+ interface IEffectNode {
9
+ __effect(name: string, value?: number): number;
10
+ getTextureNode?: () => IEffectNode;
11
+ }
12
+
13
+ type Effect = (...args: unknown[]) => IEffectNode;
14
+
15
+ /** The back end's TSL functions the effects are built by (the shared table's "ao", "bloom", ...). */
16
+ export interface IEffectTsl {
17
+ readonly ao: Effect;
18
+ readonly denoise: Effect;
19
+ readonly smaa: Effect;
20
+ readonly bloom: Effect;
21
+ readonly traa: Effect;
22
+ readonly film: Effect;
23
+ readonly lut3D: Effect;
24
+ }
25
+
26
+ function uniforms(node: IEffectNode, names: readonly string[]): IEffectNode {
27
+ for (const name of names)
28
+ Object.defineProperty(node, name, {
29
+ configurable: true,
30
+ value: Object.freeze({
31
+ get value() {
32
+ return node.__effect(name);
33
+ },
34
+ set value(value: number) {
35
+ node.__effect(name, value);
36
+ },
37
+ }),
38
+ });
39
+ return node;
40
+ }
41
+
42
+ export function definePostEffects(tsl: IEffectTsl) {
43
+ return {
44
+ film: (input: unknown, intensity?: unknown, uv?: unknown): IEffectNode =>
45
+ tsl.film(input, intensity, uv),
46
+ lut3D: (input: unknown, lut: unknown, size: number, intensity: unknown): IEffectNode =>
47
+ uniforms(tsl.lut3D(input, lut, size, intensity), ["size"]),
48
+ traa(input: unknown, depth: unknown, velocity: unknown, camera: unknown): IEffectNode {
49
+ const node = tsl.traa(input, depth, velocity, camera);
50
+ const viewCamera = camera as {
51
+ updateProjectionMatrix(): void;
52
+ projectionMatrix: { elements: readonly number[] };
53
+ setViewOffset(w: number, h: number, x: number, y: number, vw: number, vh: number): void;
54
+ clearViewOffset(): void;
55
+ };
56
+ let jitterIndex = 0;
57
+ const halton = (start: number, base: number): number => {
58
+ let index = start;
59
+ let fraction = 1;
60
+ let result = 0;
61
+ while (index > 0) {
62
+ fraction /= base;
63
+ result += fraction * (index % base);
64
+ index = Math.floor(index / base);
65
+ }
66
+ return result;
67
+ };
68
+ const setViewOffset = (width: number, height: number) => {
69
+ if (![width, height].every((v) => Number.isFinite(v) && v > 0))
70
+ throw new TypeError("TN_NATIVE_TRAA_SIZE: expected positive finite dimensions");
71
+ viewCamera.updateProjectionMatrix();
72
+ viewCamera.projectionMatrix.elements.forEach((value, i) =>
73
+ node.__effect(`projection${i}`, value),
74
+ );
75
+ viewCamera.setViewOffset(
76
+ width,
77
+ height,
78
+ halton(jitterIndex + 1, 2) - 0.5,
79
+ halton(jitterIndex + 1, 3) - 0.5,
80
+ width,
81
+ height,
82
+ );
83
+ node.__effect("viewOffset", 1);
84
+ };
85
+ const clearViewOffset = () => {
86
+ viewCamera.clearViewOffset();
87
+ node.__effect("viewOffset", 0);
88
+ jitterIndex = (jitterIndex + 1) % 31;
89
+ };
90
+ Object.defineProperties(node, {
91
+ setViewOffset: { value: setViewOffset, configurable: true },
92
+ clearViewOffset: { value: clearViewOffset, configurable: true },
93
+ setup: {
94
+ configurable: true,
95
+ value: (builder: {
96
+ context: { renderPipeline?: { context: Record<string, unknown> } };
97
+ renderer: { getDrawingBufferSize(target: unknown): { width: number; height: number } };
98
+ }) => {
99
+ const pipeline = builder.context.renderPipeline;
100
+ if (pipeline) {
101
+ pipeline.context.onBeforeRenderPipeline = () => {
102
+ const size = builder.renderer.getDrawingBufferSize({
103
+ set(width: number, height: number) {
104
+ return { width, height };
105
+ },
106
+ });
107
+ setViewOffset(size.width, size.height);
108
+ };
109
+ pipeline.context.onAfterRenderPipeline = clearViewOffset;
110
+ }
111
+ // The engine already lowers the resolve graph and exposes its output as this node.
112
+ return node;
113
+ },
114
+ },
115
+ });
116
+ for (const name of [
117
+ "depthThreshold",
118
+ "edgeDepthDiff",
119
+ "maxVelocityLength",
120
+ "useSubpixelCorrection",
121
+ ])
122
+ Object.defineProperty(node, name, {
123
+ configurable: true,
124
+ get: () =>
125
+ name === "useSubpixelCorrection" ? node.__effect(name) !== 0 : node.__effect(name),
126
+ set: (value: number | boolean) => node.__effect(name, Number(value)),
127
+ });
128
+ return node;
129
+ },
130
+ ao(depthNode: unknown, normalNode: unknown, camera: unknown): IEffectNode {
131
+ const node = uniforms(tsl.ao(depthNode, normalNode ?? null, camera), [
132
+ "radius",
133
+ "thickness",
134
+ "distanceExponent",
135
+ "distanceFallOff",
136
+ "scale",
137
+ "samples",
138
+ ]);
139
+ Object.defineProperty(node, "resolutionScale", {
140
+ configurable: true,
141
+ get() {
142
+ return node.__effect("resolutionScale");
143
+ },
144
+ set(value: number) {
145
+ node.__effect("resolutionScale", value);
146
+ },
147
+ });
148
+ node.getTextureNode = () => node;
149
+ return node;
150
+ },
151
+ denoise: (
152
+ node: unknown,
153
+ depthNode: unknown,
154
+ normalNode: unknown,
155
+ camera: unknown,
156
+ ): IEffectNode =>
157
+ uniforms(tsl.denoise(node, depthNode, normalNode ?? null, camera), [
158
+ "lumaPhi",
159
+ "depthPhi",
160
+ "normalPhi",
161
+ "radius",
162
+ "index",
163
+ ]),
164
+ smaa: (node: unknown): IEffectNode => tsl.smaa(node),
165
+ bloom: (node: unknown, strength?: number, radius?: number, threshold?: number): IEffectNode =>
166
+ uniforms(tsl.bloom(node, strength, radius, threshold), [
167
+ "strength",
168
+ "radius",
169
+ "threshold",
170
+ "smoothWidth",
171
+ ]),
172
+ };
173
+ }