@threenative/three-native 0.3.6 → 0.3.9

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.
package/src/pass-node.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  /**
2
2
  * three's `pass(scene, camera)`, `mrt()` and the MRT slots over the engine's own scene pass, for both
3
3
  * back ends (the V8 player and the Wasm engine). The engine draws one scene pass whose targets are
4
- * the renderer's colour ("output"), depth and, with an MRT that asks for it, view normals; a pass's
5
- * texture nodes name those targets. `normalView` is the engine's TSL node, as in three, so a graph
4
+ * the renderer's colour ("output"), depth and, with an MRT that asks for it, view normals, material
5
+ * values and the diffuse colour; a pass's texture nodes name those targets. `normalView` is the engine's TSL node, as in three, so a graph
6
6
  * reads it and `mrt({ normal: normalView })` names the normal target by that node's identity.
7
7
  *
8
8
  * Which pass is the frame's is fixed by how it is made, never by when: `pass(scene, camera)` (the
@@ -48,6 +48,19 @@ interface IPassTsl {
48
48
  texture(source: unknown, uv: unknown): unknown;
49
49
  uv(): unknown;
50
50
  readonly normalView: unknown;
51
+ /** The TSL constructors the surface decode composes; a table that lacks them refuses by name. */
52
+ readonly floor?: (value: unknown) => unknown;
53
+ readonly vec4?: (...values: unknown[]) => unknown;
54
+ readonly cameraNear?: IPassMath;
55
+ readonly cameraFar?: IPassMath;
56
+ }
57
+
58
+ /** The node arithmetic getViewZNode composes. */
59
+ interface IPassMath {
60
+ readonly x: IPassMath;
61
+ sub(value: unknown): IPassMath;
62
+ mul(value: unknown): IPassMath;
63
+ div(value: unknown): IPassMath;
51
64
  }
52
65
 
53
66
  interface IMRTSlot {
@@ -65,6 +78,8 @@ interface IMRTNode {
65
78
  readonly blendModes: Record<string, unknown>;
66
79
  setBlendMode(name: string, blend: unknown): IMRTNode;
67
80
  getBlendMode(name: string): unknown;
81
+ /** three's MRTNode.has: the render chain asks before it provisions an output. */
82
+ has(name: string): boolean;
68
83
  }
69
84
 
70
85
  /**
@@ -102,6 +117,8 @@ export function definePass(
102
117
  const normalView = tsl.normalView;
103
118
  const metalness = slot("metalness");
104
119
  const roughness = slot("roughness");
120
+ const diffuseColor = slot("diffuseColor");
121
+ const emissive = slot("emissive");
105
122
 
106
123
  function mrt(outputs: Record<string, unknown>): IMRTNode {
107
124
  const named: Record<string, unknown> = {};
@@ -115,7 +132,7 @@ export function definePass(
115
132
  ((value as IMRTSlot | null)?.isMRTSlot !== true || name !== (value as IMRTSlot).name)
116
133
  )
117
134
  throw new Error(
118
- `TN_NATIVE_MRT_UNSUPPORTED: ${name} must be one of output, normal: normalView or vec4(normalView, 0), metalness, roughness`,
135
+ `TN_NATIVE_MRT_UNSUPPORTED: ${name} must be one of output, normal: normalView or vec4(normalView, 0), metalness, roughness, diffuseColor, emissive`,
119
136
  );
120
137
  named[name] = normal ? normalView : value;
121
138
  }
@@ -128,10 +145,36 @@ export function definePass(
128
145
  return node;
129
146
  },
130
147
  getBlendMode: (name: string): unknown => node.blendModes[name],
148
+ has: (name: string): boolean => name in named,
131
149
  });
132
150
  return node;
133
151
  }
134
152
 
153
+ const slots: Record<string, IMRTSlot> = { metalness, roughness, diffuseColor };
154
+
155
+ /**
156
+ * The engine's normal target carries the surface in its alpha (Renderer::planNormals):
157
+ * `2 * round(7 * metalness) + 0.25 + 0.5 * roughness`, 0 where no material wrote. Each name reads as a
158
+ * splat of its own value, as three splats a float MRT output to RGBA (and as the separate material
159
+ * target does). A pixel with no material reads as metalness 0 and roughness 1: it reflects nothing.
160
+ */
161
+ function surfaceNode(name: string): unknown {
162
+ const { floor, vec4 } = tsl;
163
+ if (floor === undefined || vec4 === undefined)
164
+ throw new Error(
165
+ "TN_NATIVE_PASS_TEXTURE_UNSUPPORTED: this TSL table has no floor and vec4 to unpack the surface",
166
+ );
167
+ // quality-allow: the engine's untyped TSL node surface (chained operator calls).
168
+ // biome-ignore lint/suspicious/noExplicitAny: the engine's TSL node surface is open-ended chained calls.
169
+ const alpha = (tsl.texture({ name: "normal" }, tsl.uv()) as any).a;
170
+ const level = floor(alpha.mul(0.5)) as typeof alpha;
171
+ const written = alpha.greaterThan(0.125);
172
+ const roughness = alpha.sub(level.mul(2)).sub(0.25).mul(2).clamp(0, 1);
173
+ const value =
174
+ name === "metalness" ? written.select(level.div(7), 0) : written.select(roughness, 1);
175
+ return vec4(value, value, value, value);
176
+ }
177
+
135
178
  const framePass = Symbol("tn.framePass");
136
179
  const drawPass = Symbol("tn.drawPass");
137
180
  interface IOffscreen {
@@ -151,6 +194,7 @@ export function definePass(
151
194
  #target: IPassTarget | null = null;
152
195
  #offscreen: boolean;
153
196
  #disposed = false;
197
+ #viewZ = new Map<string, unknown>();
154
198
 
155
199
  constructor(scope: unknown, scene: unknown, camera: unknown) {
156
200
  this.#scene = scene;
@@ -246,13 +290,48 @@ export function definePass(
246
290
  }
247
291
  if (name === "output") return tsl.texture({ name: "scene" }, tsl.uv());
248
292
  if (name === "depth") return tsl.texture({ name: "depth" }, tsl.uv());
293
+ // The temporal pass's velocity target (the NDC difference between two frames, the camera's own motion where no
294
+ // rigid draw wrote one). The engine draws it while a traa() effect is in the graph, no MRT asks for it.
295
+ if (name === "velocity") return tsl.texture({ name: "velocity" }, tsl.uv());
249
296
  if (name === "normal" && this.#mrt?.outputs.normal === normalView)
250
297
  return tsl.texture({ name: "normal" }, tsl.uv());
298
+ // The renderer's albedo pass: each opaque lit draw's diffuse colour in rgb, alpha 1 where it wrote one.
299
+ if (name === "diffuseColor" && this.#mrt?.outputs.diffuseColor === diffuseColor)
300
+ return tsl.texture({ name: "albedo" }, tsl.uv());
301
+ if (name === "emissive" && this.#mrt?.outputs.emissive === emissive)
302
+ return tsl.texture({ name: "emissive" }, tsl.uv());
303
+ if (
304
+ (name === "metalness" || name === "roughness") &&
305
+ this.#mrt?.outputs.normal === normalView &&
306
+ this.#mrt?.outputs[name] === slots[name]
307
+ )
308
+ return surfaceNode(name);
309
+ if (
310
+ (name === "metalness" && this.#mrt?.outputs.metalness === metalness) ||
311
+ (name === "roughness" && this.#mrt?.outputs.roughness === roughness)
312
+ )
313
+ return tsl.texture({ name }, tsl.uv());
251
314
  throw new Error(
252
315
  `TN_NATIVE_PASS_TEXTURE_UNSUPPORTED: the native scene pass has no '${name}' target`,
253
316
  );
254
317
  }
255
318
 
319
+ /** three's `perspectiveDepthToViewZ(depth, cameraNear, cameraFar)` of a depth target, once per name. */
320
+ getViewZNode(name = "depth"): unknown {
321
+ let viewZ = this.#viewZ.get(name);
322
+ if (viewZ === undefined) {
323
+ const depth = (this.getTextureNode(name) as IPassMath).x;
324
+ const { cameraNear: near, cameraFar: far } = tsl;
325
+ if (near === undefined || far === undefined)
326
+ throw new Error(
327
+ "TN_NATIVE_PASS_TEXTURE_UNSUPPORTED: this TSL table has no cameraNear and cameraFar",
328
+ );
329
+ viewZ = near.mul(far).div(far.sub(near).mul(depth).sub(far));
330
+ this.#viewZ.set(name, viewZ);
331
+ }
332
+ return viewZ;
333
+ }
334
+
256
335
  /** Releases an offscreen pass's target and stops drawing it. The frame pass owns nothing to release. */
257
336
  dispose(): void {
258
337
  if (this.#disposed) return;
@@ -282,5 +361,16 @@ export function definePass(
282
361
  for (const entry of [...offscreen]) entry[drawPass](lastSurface, draw);
283
362
  }
284
363
 
285
- return { pass, PassNode, updateSecondaryPasses, mrt, output, normalView, metalness, roughness };
364
+ return {
365
+ pass,
366
+ PassNode,
367
+ updateSecondaryPasses,
368
+ mrt,
369
+ output,
370
+ normalView,
371
+ metalness,
372
+ roughness,
373
+ diffuseColor,
374
+ emissive,
375
+ };
286
376
  }
package/src/refused.ts CHANGED
@@ -1,7 +1,9 @@
1
1
  /**
2
2
  * A three export the native engine does not provide, for both back ends: any call, construction or
3
3
  * property access throws `diagnostic` naming the export. A game that only imports it (core's WebGL2
4
- * fallback, a renderer it never builds) runs; one that uses it fails at that use, by name.
4
+ * fallback, a renderer it never builds) runs; one that uses it fails at that use, by name. Its
5
+ * `prototype` alone reads, as on the Wasm engine (browser-entry.ts), so a module may hook or extend
6
+ * a refused class (core's `installRoughDiffuse`) and fail only when it constructs one.
5
7
  */
6
8
  export function refused(name: string, diagnostic: string): unknown {
7
9
  const fail = (): never => {
@@ -10,7 +12,7 @@ export function refused(name: string, diagnostic: string): unknown {
10
12
  return new Proxy(function refusedExport() {}, {
11
13
  apply: fail,
12
14
  construct: fail,
13
- get: fail,
15
+ get: (target, key) => (key === "prototype" ? target.prototype : fail()),
14
16
  set: fail,
15
17
  has: fail,
16
18
  ownKeys: fail,
@@ -27,20 +27,24 @@ function halfToFloat(bits: number): number {
27
27
  return bits & 0x8000 ? -magnitude : magnitude;
28
28
  }
29
29
 
30
+ /** Bytes a pixel in the rows `read` returns: a FloatType target is RGBA32Float, any other RGBA16Float. */
31
+ export function targetTexelBytes(type: number): number {
32
+ return type === FLOAT_TYPE ? 16 : 8;
33
+ }
34
+
30
35
  /**
31
- * RGBA16Float rows as three's readRenderTargetPixelsAsync types them for the target's texture type:
32
- * the half bits as a Uint16Array (HalfFloatType), floats (FloatType), or bytes (UnsignedByteType,
33
- * each channel clamped to [0, 1] and rounded, as an RGBA8 target stores it).
36
+ * The engine's rows as three's readRenderTargetPixelsAsync types them for the target's texture type:
37
+ * the half bits as a Uint16Array (HalfFloatType), the float32 values as stored (FloatType), or bytes
38
+ * (UnsignedByteType, each channel clamped to [0, 1] and rounded, as an RGBA8 target stores it).
34
39
  */
35
40
  export function pixelsOfType(
36
41
  bytes: Uint8Array,
37
42
  type: number,
38
43
  ): Uint8Array | Uint16Array | Float32Array {
39
- const halves = new Uint16Array(
40
- bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength),
41
- );
44
+ const copy = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
45
+ if (type === FLOAT_TYPE) return new Float32Array(copy);
46
+ const halves = new Uint16Array(copy);
42
47
  if (type === HALF_FLOAT_TYPE) return halves;
43
- if (type === FLOAT_TYPE) return Float32Array.from(halves, halfToFloat);
44
48
  return Uint8Array.from(halves, (bits) =>
45
49
  Math.round(Math.min(1, Math.max(0, halfToFloat(bits))) * 255),
46
50
  );
@@ -50,7 +54,7 @@ export function pixelsOfType(
50
54
  export interface IRenderTargetEngine {
51
55
  /** Draws `root` through `camera` into `target`; throws the engine's refusal. */
52
56
  draw(target: unknown, root: unknown, camera: unknown): void;
53
- /** The region's RGBA16Float rows, top row first. */
57
+ /** The region's rows in the target's format (see targetTexelBytes), top row first. */
54
58
  read(target: unknown, x: number, y: number, width: number, height: number): Promise<Uint8Array>;
55
59
  }
56
60
 
@@ -0,0 +1,65 @@
1
+ // three r185: src/renderers/common/RendererUtils.js, for state the Wasm facade exposes.
2
+ interface IRendererStateSurface {
3
+ toneMapping: unknown;
4
+ toneMappingExposure: unknown;
5
+ outputColorSpace: unknown;
6
+ autoClear: boolean;
7
+ getRenderTarget(): unknown;
8
+ setRenderTarget(target: unknown, face?: number, mip?: number): void;
9
+ getActiveCubeFace(): number;
10
+ getActiveMipmapLevel(): number;
11
+ getPixelRatio(): number;
12
+ setPixelRatio(value: number): void;
13
+ getClearColor(target: object): object;
14
+ getClearAlpha(): number;
15
+ setClearColor(color: unknown, alpha: number): void;
16
+ }
17
+ interface IRendererState {
18
+ toneMapping?: unknown;
19
+ toneMappingExposure?: unknown;
20
+ outputColorSpace?: unknown;
21
+ autoClear?: boolean;
22
+ renderTarget?: unknown;
23
+ activeCubeFace?: number;
24
+ activeMipmapLevel?: number;
25
+ pixelRatio?: number;
26
+ clearColor?: object;
27
+ clearAlpha?: number;
28
+ }
29
+ export function defineRendererUtils(Color: new () => object) {
30
+ const saveRendererState = (renderer: IRendererStateSurface, state: IRendererState = {}) => {
31
+ for (const key of [
32
+ "toneMapping",
33
+ "toneMappingExposure",
34
+ "outputColorSpace",
35
+ "autoClear",
36
+ ] as const)
37
+ Object.assign(state, { [key]: renderer[key] });
38
+ state.renderTarget = renderer.getRenderTarget();
39
+ state.activeCubeFace = renderer.getActiveCubeFace();
40
+ state.activeMipmapLevel = renderer.getActiveMipmapLevel();
41
+ state.pixelRatio = renderer.getPixelRatio();
42
+ state.clearColor = renderer.getClearColor(state.clearColor ?? new Color());
43
+ state.clearAlpha = renderer.getClearAlpha();
44
+ return state;
45
+ };
46
+ return {
47
+ saveRendererState,
48
+ resetRendererState(renderer: IRendererStateSurface, state?: IRendererState) {
49
+ const saved = saveRendererState(renderer, state);
50
+ renderer.setClearColor(0, 1);
51
+ renderer.autoClear = true;
52
+ return saved;
53
+ },
54
+ restoreRendererState(renderer: IRendererStateSurface, state: IRendererState) {
55
+ renderer.toneMapping = state.toneMapping;
56
+ renderer.toneMappingExposure = state.toneMappingExposure;
57
+ renderer.outputColorSpace = state.outputColorSpace;
58
+ renderer.autoClear = state.autoClear as boolean;
59
+ renderer.setRenderTarget(state.renderTarget, state.activeCubeFace, state.activeMipmapLevel);
60
+ if (renderer.getPixelRatio() !== state.pixelRatio)
61
+ renderer.setPixelRatio(state.pixelRatio as number);
62
+ renderer.setClearColor(state.clearColor, state.clearAlpha as number);
63
+ },
64
+ };
65
+ }
package/src/rtt.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import { gpuStageId } from "./gpu-stages.js";
2
+
1
3
  /** RTTNode's mutable target and quad over the engine's scheduled fullscreen pass. */
2
4
  interface IRttNode {
3
5
  __effect(name: string, value?: number): number;
@@ -35,6 +37,11 @@ function validateOptions(options: Record<string, unknown>): void {
35
37
  for (const [key, value] of Object.entries(options)) {
36
38
  if (key === "type" && value === 1016) continue;
37
39
  if (key === "depthBuffer" && value === false) continue;
40
+ // Not a RenderTarget option: the GPU stage the pass reports its time under (gpu-stages.ts).
41
+ if (key === "gpuStage") {
42
+ if (value !== undefined) gpuStageId(value);
43
+ continue;
44
+ }
38
45
  if ((key === "minFilter" || key === "magFilter") && (value === 1003 || value === 1006))
39
46
  continue;
40
47
  throw new TypeError(`TN_TSL_RTT_OPTION: unsupported ${key}=${value}`);
@@ -60,7 +67,8 @@ export function defineRtt(make: (...args: unknown[]) => IRttNode, classes?: IRtt
60
67
  const material = new classes.NodeMaterial();
61
68
  material.fragmentNode = source;
62
69
  const quad = new classes.QuadMesh(material as never) as IRttQuad;
63
- const { minFilter = 1006, magFilter = 1006, ...targetOptions } = options;
70
+ if (options.gpuStage !== undefined) node.__effect("stage", gpuStageId(options.gpuStage));
71
+ const { minFilter = 1006, magFilter = 1006, gpuStage: _stage, ...targetOptions } = options;
64
72
  const target = new classes.RenderTarget(width ?? 1, height ?? 1, targetOptions);
65
73
  Object.assign(target.texture as object, { minFilter, magFilter });
66
74
  node.__rtt(target, quad);
@@ -0,0 +1,192 @@
1
+ /** Native VSM owns the clip cameras and sampling; core keeps its public option validation. */
2
+ let nextId = 0;
3
+ const installed = new Set<ShadowBaseNode>();
4
+ const dispatchKey = Symbol.for("threenative.virtualShadowCommand");
5
+ const bridgeKey = Symbol.for("threenative.virtualShadow");
6
+ /** Core's registration counter for the discrete LOD chains (see `bumpChains` in core's model-lod). */
7
+ const chainsVersionKey = Symbol.for("threenative.discreteLodChainsVersion");
8
+ /** The facade's count of `mesh.geometry` assignments (browser-backend's setter): a swap moves no hierarchy. */
9
+ const geometryAssignmentsKey = Symbol.for("threenative.geometryAssignments");
10
+ /** The symbol-keyed slots the native bridge keeps on a core shadow node. */
11
+ interface IBridgeSlots {
12
+ [dispatchKey]?: unknown;
13
+ [bridgeKey]?: unknown;
14
+ }
15
+ interface IShadowObject {
16
+ id: number;
17
+ parent?: IShadowObject | null;
18
+ geometry?: object;
19
+ traverse(callback: (child: IShadowObject) => void): void;
20
+ }
21
+ /** Transfer registered chain data: the derived rungs and their errors. Native chooses its rung separately for every shadow level. */
22
+ export function detachVirtualShadow(value: unknown): void {
23
+ if (!(value instanceof ShadowBaseNode)) return;
24
+ installed.delete(value);
25
+ value.dispatch = undefined;
26
+ value.lods.clear();
27
+ delete (value as IBridgeSlots)[dispatchKey];
28
+ }
29
+ /**
30
+ * Records what the light-root walk depends on and answers whether the last one still holds. Its answer
31
+ * can change in exactly three ways: core registered a chain (the version), a mesh's geometry was assigned
32
+ * (the facade's counter), or the hierarchy moved (the
33
+ * engine's counter, stamped on the root and every one of its ancestors). A backend without that counter
34
+ * (JSDOM, another engine) never skips.
35
+ */
36
+ function walkStillCurrent(node: ShadowBaseNode, root: IShadowObject): boolean {
37
+ const revision = (root as { __hierarchyRevision?: number }).__hierarchyRevision;
38
+ if (revision === undefined) return false;
39
+ const host = globalThis as Record<symbol, unknown>;
40
+ const version = host[chainsVersionKey] as number | undefined;
41
+ const assignments = host[geometryAssignmentsKey] as number | undefined;
42
+ const current =
43
+ revision === node.walkedAt &&
44
+ version === node.walkedVersion &&
45
+ assignments === node.walkedAssignments;
46
+ node.walkedAt = revision;
47
+ node.walkedVersion = version;
48
+ node.walkedAssignments = assignments;
49
+ return current;
50
+ }
51
+ export function syncVirtualShadowLods(): void {
52
+ const chains = (globalThis as Record<symbol, unknown>)[
53
+ Symbol.for("threenative.discreteLodChains")
54
+ ] as WeakMap<object, { chain: { levels: object[]; errors: number[] } }> | undefined;
55
+ if (!chains) return;
56
+ for (const node of installed) {
57
+ if (node.disposed) {
58
+ installed.delete(node);
59
+ continue;
60
+ }
61
+ let root = node.light as IShadowObject;
62
+ while (root.parent) root = root.parent;
63
+ if (typeof root.traverse !== "function") continue;
64
+ if (walkStillCurrent(node, root)) continue;
65
+ const present = new Set<number>();
66
+ root.traverse((child) => {
67
+ if (!child.geometry) return;
68
+ const chain = chains.get(child.geometry)?.chain;
69
+ if (!chain || chain.levels.length < 2) return;
70
+ present.add(child.id);
71
+ if (node.lods.get(child.id) === chain) return;
72
+ // Rung 0 is the caster's own geometry; native already holds it.
73
+ node.dispatch?.({
74
+ command: "lod",
75
+ id: child.id,
76
+ geometries: chain.levels.slice(1),
77
+ errors: chain.errors.slice(1),
78
+ });
79
+ node.lods.set(child.id, chain);
80
+ });
81
+ for (const id of node.lods.keys()) {
82
+ if (present.has(id)) continue;
83
+ node.dispatch?.({ command: "unlod", id });
84
+ node.lods.delete(id);
85
+ }
86
+ }
87
+ }
88
+ export class ShadowBaseNode {
89
+ static get type(): string {
90
+ return "ShadowBaseNode";
91
+ }
92
+ readonly id = nextId++;
93
+ readonly isNode = true;
94
+ readonly isShadowBaseNode = true;
95
+ updateBeforeType = "render";
96
+ disposed = false;
97
+ dispatch?: (value: object) => void;
98
+ readonly lods = new Map<number, object>();
99
+ /** What the last light-root walk saw; neither number moving means its result cannot have changed. */
100
+ walkedAt?: number;
101
+ walkedVersion?: number;
102
+ walkedAssignments?: number;
103
+ constructor(readonly light: object) {}
104
+ dispose(): void {
105
+ const shadow = (this.light as { shadow?: { shadowNode?: unknown } }).shadow;
106
+ if (shadow?.shadowNode === this) shadow.shadowNode = null;
107
+ this.disposed = true;
108
+ detachVirtualShadow(this);
109
+ }
110
+ }
111
+
112
+ /** Core stores selection guards after subtracting refreshStep; native's factory subtracts it. */
113
+ export function virtualShadowOptions(
114
+ value: unknown,
115
+ dispatch?: (value: object) => void,
116
+ ): Record<string, unknown> | null {
117
+ if (value === null) return null;
118
+ if (
119
+ !(value instanceof ShadowBaseNode) ||
120
+ (value.constructor as typeof ShadowBaseNode).type !== "VirtualShadowNode" ||
121
+ !("options" in value)
122
+ )
123
+ throw new TypeError("TN_NATIVE_SHADOW_NODE_UNSUPPORTED: expected core VirtualShadowNode");
124
+ if (value.disposed) throw new Error("TN_NATIVE_SHADOW_NODE_DISPOSED");
125
+ if (dispatch) {
126
+ value.dispatch = dispatch;
127
+ (value as IBridgeSlots)[dispatchKey] = dispatch;
128
+ installed.add(value);
129
+ }
130
+ const bridge = (value as IBridgeSlots)[bridgeKey];
131
+ const options = (bridge ?? value.options) as Record<string, unknown>;
132
+ const guards = options.selectionGuard as number[];
133
+ const steps = options.refreshStep as number[];
134
+ return {
135
+ ...options,
136
+ selectionGuard: guards.map((guard, i) => guard + (steps[Math.min(i, steps.length - 1)] ?? 0)),
137
+ };
138
+ }
139
+
140
+ /**
141
+ * Only the source-angle filter (a sun) and the source-radius filter (a lamp) have engine
142
+ * implementations; never silently drop a callback.
143
+ */
144
+ export function shadowFilterOptions(value: unknown): Record<string, number> | null {
145
+ if (value === null) return null;
146
+ const tagged = (name: string) =>
147
+ typeof value === "function" ? Reflect.get(value, Symbol.for(`threenative.${name}`)) : undefined;
148
+ const angle = tagged("sourceAngleShadowFilter");
149
+ const options = angle ?? tagged("sourceRadiusShadowFilter");
150
+ if (typeof options !== "object" || options === null)
151
+ throw new Error(
152
+ "TN_VIRTUAL_SHADOW_UNSUPPORTED: filterNode (sourceAngleShadowFilter or sourceRadiusShadowFilter required)",
153
+ );
154
+ const config = options as Record<string, unknown>;
155
+ const size = angle ? "sourceAngleRad" : "sourceRadius";
156
+ const { [size]: extent, blockerSamples, filterSamples, penumbraScale } = config;
157
+ // A sun's optional keys, each with its range; a lamp has none.
158
+ const sunKeys: Record<string, (n: number) => boolean> = {
159
+ minPenumbraPixels: (n) => Number.isFinite(n) && n >= 0 && n <= 16,
160
+ samplesPerRay: (n) => Number.isInteger(n) && n >= 0 && n <= 64,
161
+ rayLengthScale: (n) => Number.isFinite(n) && n > 0,
162
+ };
163
+ const optional =
164
+ angle === undefined
165
+ ? []
166
+ : Object.keys(sunKeys)
167
+ .filter((key) => config[key] !== undefined)
168
+ .map((key) => [key, config[key]] as const);
169
+ if (
170
+ typeof extent !== "number" ||
171
+ !Number.isFinite(extent) ||
172
+ extent < 0 ||
173
+ (angle !== undefined && extent >= Math.PI / 2) ||
174
+ [blockerSamples, filterSamples].some(
175
+ (count) => typeof count !== "number" || !Number.isInteger(count) || count < 1 || count > 64,
176
+ ) ||
177
+ (angle === undefined &&
178
+ (typeof penumbraScale !== "number" || !(penumbraScale > 0 && penumbraScale <= 4))) ||
179
+ optional.some(([key, v]) => typeof v !== "number" || sunKeys[key]?.(v) !== true)
180
+ )
181
+ throw new Error(
182
+ `TN_VIRTUAL_SHADOW_INVALID: ${angle ? "source-angle" : "source-radius"} filter`,
183
+ );
184
+ return {
185
+ [size]: extent,
186
+ blockerSamples: blockerSamples as number,
187
+ filterSamples: filterSamples as number,
188
+ // A lamp keeps a share of its geometric penumbra (sourceRadiusShadowFilter's penumbraScale).
189
+ ...(angle === undefined ? { penumbraScale: penumbraScale as number } : {}),
190
+ ...(Object.fromEntries(optional) as Record<string, number>),
191
+ };
192
+ }
@@ -0,0 +1,123 @@
1
+ /** HDR faces in probes::captureFace order (+X,-X,+Y,-Y,+Z,-Z), repacked for the existing PMREM path. */
2
+ export function cubemapToEquirectangular(faces: readonly Float32Array[], size: number) {
3
+ if (
4
+ !Number.isInteger(size) ||
5
+ size < 1 ||
6
+ size > 1024 ||
7
+ faces.length !== 6 ||
8
+ faces.some((face) => face.length !== size * size * 3 || !face.every(Number.isFinite))
9
+ )
10
+ throw new Error("TN_REFLECTION_CAPTURE_FACES: six finite RGB faces required");
11
+ const width = size * 4;
12
+ const height = size * 2;
13
+ const data = new Float32Array(width * height * 4);
14
+ for (let y = 0; y < height; y++) {
15
+ const theta = ((y + 0.5) * Math.PI) / height;
16
+ for (let x = 0; x < width; x++) {
17
+ // Inverse of three's equirectUV: atan2(z,x)/(2*pi)+0.5, asin(y)/pi+0.5.
18
+ const phi = ((x + 0.5) / width - 0.5) * 2 * Math.PI;
19
+ const dx = Math.sin(theta) * Math.cos(phi);
20
+ const dy = Math.cos(theta);
21
+ const dz = Math.sin(theta) * Math.sin(phi);
22
+ const ax = Math.abs(dx);
23
+ const ay = Math.abs(dy);
24
+ const az = Math.abs(dz);
25
+ let face: number;
26
+ let col: number;
27
+ let row: number;
28
+ if (ax >= ay && ax >= az) {
29
+ face = dx > 0 ? 0 : 1;
30
+ col = (dx > 0 ? -dz : dz) / ax;
31
+ row = dy / ax;
32
+ } else if (ay >= az) {
33
+ face = dy > 0 ? 2 : 3;
34
+ col = dx / ay;
35
+ row = (dy > 0 ? -dz : dz) / ay;
36
+ } else {
37
+ face = dz > 0 ? 4 : 5;
38
+ col = (dz > 0 ? dx : -dx) / az;
39
+ row = dy / az;
40
+ }
41
+ const px = Math.min(size - 1, Math.max(0, Math.floor(((col + 1) * size) / 2)));
42
+ const py = Math.min(size - 1, Math.max(0, Math.floor(((1 - row) * size) / 2)));
43
+ const source = faces[face] as Float32Array;
44
+ const offset = (py * size + px) * 3;
45
+ const out = (y * width + x) * 4;
46
+ data[out] = source[offset] as number;
47
+ data[out + 1] = source[offset + 1] as number;
48
+ data[out + 2] = source[offset + 2] as number;
49
+ data[out + 3] = 1;
50
+ }
51
+ }
52
+ return { data, width, height };
53
+ }
54
+
55
+ export type CaptureFace = (
56
+ scene: unknown,
57
+ x: number,
58
+ y: number,
59
+ z: number,
60
+ size: number,
61
+ face: number,
62
+ /** The renderer the capture was called on: a face is a render of `scene` by it, as three's CubeCamera.update is. */
63
+ renderer: unknown,
64
+ ) => Promise<Float32Array | null>;
65
+ interface IEnvironmentTexture {
66
+ mapping: number;
67
+ colorSpace: string;
68
+ flipY: boolean;
69
+ needsUpdate: boolean;
70
+ }
71
+
72
+ /**
73
+ * A static scene capture from a point. The engine PMREM-filters this HDR texture when used as envMap.
74
+ * @alias reflection probe, cube capture
75
+ */
76
+ export function defineSphereReflectionCapture(
77
+ capture: CaptureFace,
78
+ Texture: new (
79
+ data: Float32Array,
80
+ width: number,
81
+ height: number,
82
+ format: number,
83
+ type: number,
84
+ ) => IEnvironmentTexture,
85
+ ) {
86
+ return async function SphereReflectionCapture(
87
+ this: unknown,
88
+ scene: unknown,
89
+ position: { x: number; y: number; z: number },
90
+ faceSize = 256,
91
+ ) {
92
+ const { x, y, z } = position;
93
+ if (
94
+ ![x, y, z].every(Number.isFinite) ||
95
+ !Number.isInteger(faceSize) ||
96
+ faceSize < 16 ||
97
+ faceSize > 1024
98
+ )
99
+ throw new Error(
100
+ "TN_REFLECTION_CAPTURE_INPUT: finite position and face size 16..1024 required",
101
+ );
102
+ const faces: Float32Array[] = [];
103
+ const deadline = performance.now() + 120_000;
104
+ for (let face = 0; face < 6; face++) {
105
+ for (;;) {
106
+ if (performance.now() > deadline) throw new Error("TN_REFLECTION_CAPTURE_TIMEOUT");
107
+ const pixels = await capture(scene, x, y, z, faceSize, face, this);
108
+ if (pixels !== null) {
109
+ faces.push(pixels);
110
+ break;
111
+ }
112
+ await new Promise((resolve) => setTimeout(resolve, 0));
113
+ }
114
+ }
115
+ const { data, width, height } = cubemapToEquirectangular(faces, faceSize);
116
+ const texture = new Texture(data, width, height, 1023, 1015); // RGBAFormat, FloatType
117
+ texture.mapping = 303; // EquirectangularReflectionMapping; existing engine PMREM preparation.
118
+ texture.colorSpace = "srgb-linear";
119
+ texture.flipY = true; // rows above start at the north pole, as HDRLoader's decoded image does.
120
+ texture.needsUpdate = true;
121
+ return texture;
122
+ };
123
+ }
package/src/storage.ts CHANGED
@@ -204,3 +204,40 @@ export async function readStorageBytes(
204
204
  new Uint8Array(target as ArrayBuffer).set(new Uint8Array(bytes));
205
205
  return target;
206
206
  }
207
+
208
+ /** r185's StorageTextureNode: retain the resource and append a store only when asked. */
209
+ export function defineStorageTextures(tsl: {
210
+ storageTexture(...args: unknown[]): object;
211
+ textureStore(...args: unknown[]): object;
212
+ }) {
213
+ const { storageTexture, textureStore } = tsl;
214
+ const decorate = (node: object, value: unknown, uv?: unknown, stored?: unknown) =>
215
+ Object.assign(node, {
216
+ isStorageTextureNode: true,
217
+ value,
218
+ store: (coordinate: unknown, data: unknown) =>
219
+ decorate(textureStore(node, coordinate, data), value, coordinate, data),
220
+ toStack() {
221
+ textureStore(node, uv, stored);
222
+ return node;
223
+ },
224
+ });
225
+ return {
226
+ storageTexture: (value: unknown, uv?: unknown, stored?: unknown) =>
227
+ decorate(
228
+ storageTexture(value, ...[uv, stored].filter((arg) => arg !== undefined)),
229
+ value,
230
+ uv,
231
+ stored,
232
+ ),
233
+ textureStore: (value: unknown, uv: unknown, stored: unknown) =>
234
+ decorate(
235
+ textureStore(value, uv, stored),
236
+ (value as { isStorageTextureNode?: boolean; value?: unknown })?.isStorageTextureNode
237
+ ? (value as { value: unknown }).value
238
+ : value,
239
+ uv,
240
+ stored,
241
+ ),
242
+ };
243
+ }