@threenative/core 0.3.3 → 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 (182) hide show
  1. package/capabilities.json +2019 -59
  2. package/dist/{assets-CYKk2WTu.d.ts → assets-CqvE429w.d.ts} +45 -3
  3. package/dist/{audio-7i3Xl0l3.d.ts → audio-DIJE5HTr.d.ts} +43 -3
  4. package/dist/{canvas-layer-C1SnMoJ-.d.ts → canvas-layer-C1-5CviZ.d.ts} +5 -1
  5. package/dist/{game-D_6r-k4Y.d.ts → game-Bj8G1wmD.d.ts} +242 -17
  6. package/dist/hot.d.ts +5 -5
  7. package/dist/index.d.ts +1131 -105
  8. package/dist/index.js +15201 -4782
  9. package/dist/model-lod-BDAUYgsS.d.ts +197 -0
  10. package/dist/playtest.d.ts +6 -4
  11. package/dist/playtest.js +84 -11
  12. package/dist/react-css.d.ts +62 -0
  13. package/dist/react-css.js +591 -0
  14. package/dist/react.d.ts +2 -2
  15. package/dist/{renderer-Cy4qeBOA.d.ts → renderer-9yEo9hPa.d.ts} +676 -21
  16. package/dist/terrain-jobs-worker.d.ts +2 -0
  17. package/dist/terrain-jobs-worker.js +130 -0
  18. package/dist/ui-layer.d.ts +5 -3
  19. package/dist/ui-layer.js +59 -8
  20. package/dist/world.d.ts +1596 -17
  21. package/dist/world.js +17035 -521
  22. package/gpl/fixtures/make_world_fixture.py +184 -0
  23. package/gpl/recipes/_common.py +11 -0
  24. package/gpl/recipes/decimate.py +11 -5
  25. package/gpl/recipes/export_world.py +699 -0
  26. package/mcp/blender-server.mjs +61 -4
  27. package/mcp/blender.mjs +3 -4
  28. package/mcp/engine-server.mjs +55 -21
  29. package/mcp/servers.mjs +4 -4
  30. package/package.json +15 -9
  31. package/patches/three@0.185.1-prd269-upgrade.patch +22418 -0
  32. package/patches/three@0.185.1.patch +8246 -389
  33. package/scripts/apply-three-patch.mjs +123 -41
  34. package/src/animation-blend.ts +264 -0
  35. package/src/animation-composition.ts +362 -0
  36. package/src/animation-layers.ts +260 -0
  37. package/src/animation-root-motion.ts +283 -0
  38. package/src/animation.ts +896 -0
  39. package/src/assets.ts +1303 -0
  40. package/src/atmosphere/index.ts +335 -0
  41. package/src/atmosphere/luts.ts +298 -0
  42. package/src/atmosphere/params.ts +323 -0
  43. package/src/audio.ts +912 -0
  44. package/src/billboard.ts +124 -0
  45. package/src/bone-lengths.ts +157 -0
  46. package/src/camera-shake.ts +116 -0
  47. package/src/canvas-layer.ts +47 -0
  48. package/src/clip-audit.ts +401 -0
  49. package/src/clustered-batch.ts +492 -0
  50. package/src/clustered-mesh.ts +638 -0
  51. package/src/compute-driven.ts +176 -0
  52. package/src/compute-timing.ts +318 -0
  53. package/src/config.ts +593 -0
  54. package/src/debug.ts +82 -0
  55. package/src/engine-render-hook.ts +25 -0
  56. package/src/entities.ts +79 -0
  57. package/src/entity-snapshot.ts +53 -0
  58. package/src/flight.ts +683 -0
  59. package/src/fluid-field.ts +748 -0
  60. package/src/fluid-particles.ts +1253 -0
  61. package/src/frame-budget.ts +1368 -0
  62. package/src/game.ts +2390 -0
  63. package/src/geometry-capture.ts +1098 -0
  64. package/src/gpu-class.ts +160 -0
  65. package/src/gpu-frame-observation.ts +424 -0
  66. package/src/gpu-readback.ts +143 -0
  67. package/src/gpu-scene-bvh.ts +464 -0
  68. package/src/grounding.ts +100 -0
  69. package/src/hot.ts +161 -0
  70. package/src/import-meta.d.ts +13 -0
  71. package/src/index.ts +1536 -0
  72. package/src/input.ts +690 -0
  73. package/src/instanced-batch-lod.ts +283 -0
  74. package/src/instanced-batch.ts +274 -0
  75. package/src/interpolation.ts +129 -0
  76. package/src/launch-diagnostics.ts +161 -0
  77. package/src/loop.ts +564 -0
  78. package/src/matrix-world.ts +245 -0
  79. package/src/merge-parts.ts +812 -0
  80. package/src/model-lod.ts +1315 -0
  81. package/src/net-protocol.ts +333 -0
  82. package/src/net-session.ts +477 -0
  83. package/src/net.ts +80 -0
  84. package/src/ocean/fft.ts +72 -0
  85. package/src/ocean/spectral.ts +728 -0
  86. package/src/particle-significance.ts +102 -0
  87. package/src/particles.ts +648 -0
  88. package/src/path-follow.ts +175 -0
  89. package/src/picking.ts +250 -0
  90. package/src/pipeline-census.ts +1566 -0
  91. package/src/platform.ts +210 -0
  92. package/src/playtest.ts +839 -0
  93. package/src/pointer-events.ts +411 -0
  94. package/src/pose-measure.ts +435 -0
  95. package/src/profiling/FrameCounters.ts +231 -0
  96. package/src/profiling/Spans.ts +548 -0
  97. package/src/profiling/opacity-convention.ts +21 -0
  98. package/src/profiling/render-list-validate.ts +175 -0
  99. package/src/profiling/render-trap-audit.ts +84 -0
  100. package/src/profiling/scene-warning.ts +190 -0
  101. package/src/profiling/span-probes.ts +191 -0
  102. package/src/profiling/unlit-foliage-warning.ts +149 -0
  103. package/src/projection-apply.ts +1529 -0
  104. package/src/projection-marker.ts +142 -0
  105. package/src/projection-plan.ts +1258 -0
  106. package/src/projection-skinned.ts +419 -0
  107. package/src/projection-stability.ts +409 -0
  108. package/src/projection-uniform.ts +328 -0
  109. package/src/random.ts +41 -0
  110. package/src/react-css.ts +604 -0
  111. package/src/react-glyphs.ts +114 -0
  112. package/src/react-host.ts +576 -0
  113. package/src/react-layout.ts +265 -0
  114. package/src/react.ts +60 -0
  115. package/src/render/alpha-antialiasing.ts +159 -0
  116. package/src/render/batched-velocity.ts +126 -0
  117. package/src/render/chain.ts +1021 -0
  118. package/src/render/daylight.ts +189 -0
  119. package/src/render/depth-pyramid.ts +596 -0
  120. package/src/render/foliage-alpha.ts +166 -0
  121. package/src/render/material-key.ts +60 -0
  122. package/src/render/mesh-pool.ts +144 -0
  123. package/src/render/probe-volume.ts +1668 -0
  124. package/src/render/resolution-subrect.ts +253 -0
  125. package/src/render/velocity.ts +442 -0
  126. package/src/render/virtual-shadow-pages.ts +827 -0
  127. package/src/render/virtual-shadow-partial.ts +174 -0
  128. package/src/render/virtual-shadow.ts +3330 -0
  129. package/src/render/world-impostor-surface.ts +722 -0
  130. package/src/render/world-impostor.ts +558 -0
  131. package/src/render-camera-cull.ts +441 -0
  132. package/src/render-pass-budget.ts +501 -0
  133. package/src/renderProjection.ts +758 -0
  134. package/src/renderer-config.ts +127 -0
  135. package/src/renderer.ts +1847 -0
  136. package/src/replay-protocol.ts +85 -0
  137. package/src/replay.ts +205 -0
  138. package/src/resolution-scaler.ts +819 -0
  139. package/src/rig-preparation.ts +271 -0
  140. package/src/ripple-field.ts +432 -0
  141. package/src/scale.ts +109 -0
  142. package/src/scene.ts +239 -0
  143. package/src/schedule.ts +155 -0
  144. package/src/skeletal-mesh.ts +61 -0
  145. package/src/skeleton.ts +100 -0
  146. package/src/snow-field.ts +744 -0
  147. package/src/softbody-topology.ts +269 -0
  148. package/src/softbody.ts +516 -0
  149. package/src/sprite-animator.ts +222 -0
  150. package/src/startup-readiness.ts +386 -0
  151. package/src/state.ts +66 -0
  152. package/src/static-transform.ts +274 -0
  153. package/src/storage-buffer.ts +253 -0
  154. package/src/streaming.ts +308 -0
  155. package/src/target-fps.ts +92 -0
  156. package/src/terrain-jobs-worker.ts +17 -0
  157. package/src/terrain-jobs.ts +353 -0
  158. package/src/textures.ts +39 -0
  159. package/src/tracers.ts +237 -0
  160. package/src/ui-bridge.ts +368 -0
  161. package/src/ui-hit-regions.ts +380 -0
  162. package/src/ui-layer.ts +83 -0
  163. package/src/ui-state.ts +220 -0
  164. package/src/version.ts +2 -0
  165. package/src/viewport.ts +253 -0
  166. package/src/warmup.ts +1357 -0
  167. package/src/water-surface.ts +384 -0
  168. package/src/wave-field.ts +524 -0
  169. package/src/world-capabilities.ts +131 -0
  170. package/src/world-cell-proxy.ts +392 -0
  171. package/src/world-cells.ts +10564 -0
  172. package/src/world-gpu-scene.ts +3354 -0
  173. package/src/world-heightmap.ts +82 -0
  174. package/src/world-package.ts +469 -0
  175. package/src/world-passes.ts +582 -0
  176. package/src/world-region.ts +17 -0
  177. package/src/world-terrain-splat.ts +564 -0
  178. package/src/world-tiles.ts +3826 -0
  179. package/src/world-topology.ts +370 -0
  180. package/src/world-validate.ts +48 -0
  181. package/src/world.ts +805 -0
  182. package/dist/gpu-readback-CMklJs6r.d.ts +0 -112
@@ -0,0 +1,558 @@
1
+ import {
2
+ Box3,
3
+ type BufferGeometry,
4
+ type Camera,
5
+ Color,
6
+ type CoordinateSystem,
7
+ type Material,
8
+ type Matrix4,
9
+ Mesh,
10
+ NoBlending,
11
+ NoColorSpace,
12
+ OrthographicCamera,
13
+ SRGBColorSpace,
14
+ Scene,
15
+ Sphere,
16
+ type Texture,
17
+ Vector3,
18
+ } from "three";
19
+ import { diffuseColor, float, mrt, normalWorld, positionView, vec4 } from "three/tsl";
20
+ import {
21
+ LinearFilter,
22
+ LinearMipmapLinearFilter,
23
+ type MRTNode,
24
+ MeshBasicNodeMaterial,
25
+ MeshPhysicalNodeMaterial,
26
+ MeshStandardNodeMaterial,
27
+ type NodeMaterial,
28
+ RGBAFormat,
29
+ RenderTarget,
30
+ UnsignedByteType,
31
+ } from "three/webgpu";
32
+ import { mipAlphaTestNode } from "./foliage-alpha.js";
33
+
34
+ /**
35
+ * The marker the integration and its playtests key on. Kept here rather than repeated as a literal
36
+ * so the next slice's report line uses one spelling.
37
+ */
38
+ export const WORLD_IMPOSTOR_MARKER = "TN_WORLD_IMPOSTOR";
39
+
40
+ /** Views per atlas row and column: a full-sphere octahedral grid, so `N*N` layers. */
41
+ export const IMPOSTOR_VIEW_GRID = 4;
42
+ /** Layers the atlas holds: one per view. */
43
+ export const IMPOSTOR_VIEWS = IMPOSTOR_VIEW_GRID * IMPOSTOR_VIEW_GRID;
44
+ /**
45
+ * Frame edge in texels. Fixed, not derived: the texel rule the prior draft claimed cancelled its
46
+ * own `pixelsPerUnit` and only ever returned a power of two. An honest fixed frame plus the
47
+ * caller's finite atlas budget beats a false adaptive claim.
48
+ */
49
+ export const IMPOSTOR_FRAME_PIXELS = 128;
50
+
51
+ /** One drawable part of one asset level, as the world builds it. Structural, so a stub is the same. */
52
+ export interface IImpostorPart {
53
+ readonly geometry: BufferGeometry;
54
+ /** The mesh transform relative to the model root, composed into every instance matrix. */
55
+ readonly local: Matrix4;
56
+ readonly material: Material;
57
+ }
58
+
59
+ /** A signed one for a component, with zero read as positive so the fold is deterministic. */
60
+ function signNotZero(value: number): number {
61
+ return value >= 0 ? 1 : -1;
62
+ }
63
+
64
+ /**
65
+ * Centre direction of one grid point of a `grid`x`grid` full-sphere octahedral map.
66
+ *
67
+ * Endpoints, not cell centres: point `ix` runs `u = 2*ix/(N-1) - 1` so the grid's corners are the
68
+ * octahedron's corners and the grid's shared edges are continuous. The last octant folds behind the
69
+ * sphere with `(1-|v|, 1-|u|)`, which is what makes the same grid cover both hemispheres.
70
+ */
71
+ export function octahedralViewOf(ix: number, iy: number, grid = IMPOSTOR_VIEW_GRID): Vector3 {
72
+ const u = (2 * ix) / (grid - 1) - 1;
73
+ const v = (2 * iy) / (grid - 1) - 1;
74
+ const z = 1 - Math.abs(u) - Math.abs(v);
75
+ if (z < 0) {
76
+ const x = (1 - Math.abs(v)) * signNotZero(u);
77
+ const y = (1 - Math.abs(u)) * signNotZero(v);
78
+ return new Vector3(x, y, z).normalize();
79
+ }
80
+ return new Vector3(u, v, z).normalize();
81
+ }
82
+
83
+ /** The whole view table, in layer order: index `iy * grid + ix`. */
84
+ export const VIEW_DIRECTIONS: readonly Vector3[] = buildViewDirections();
85
+
86
+ function buildViewDirections(): readonly Vector3[] {
87
+ const out: Vector3[] = [];
88
+ for (let iy = 0; iy < IMPOSTOR_VIEW_GRID; iy += 1)
89
+ for (let ix = 0; ix < IMPOSTOR_VIEW_GRID; ix += 1) out.push(octahedralViewOf(ix, iy));
90
+ return out;
91
+ }
92
+
93
+ /**
94
+ * Project a unit direction onto the octahedral square in `[-1, 1]^2`, folding the back hemisphere.
95
+ * This is the exact inverse of {@link octahedralViewOf}'s decode, so the bake's view table and the
96
+ * next slice's sampler share one frame basis by construction.
97
+ */
98
+ function encodeOctahedral(direction: Vector3): { readonly x: number; readonly y: number } {
99
+ const d = direction.clone().normalize();
100
+ const sum = Math.abs(d.x) + Math.abs(d.y) + Math.abs(d.z);
101
+ if (!(sum > 0)) return { x: 0, y: 0 };
102
+ const px = d.x / sum;
103
+ const py = d.y / sum;
104
+ if (d.z >= 0) return { x: px, y: py };
105
+ return {
106
+ x: (1 - Math.abs(py)) * signNotZero(px),
107
+ y: (1 - Math.abs(px)) * signNotZero(py),
108
+ };
109
+ }
110
+
111
+ /** A blend over three view layers, as integer layer indices and normalized weights. */
112
+ export interface IViewBlend {
113
+ readonly nearest: readonly [number, number, number];
114
+ readonly weights: readonly [number, number, number];
115
+ }
116
+
117
+ /**
118
+ * The three octahedral grid corners around `direction`, and their non-negative weights summing to
119
+ * one.
120
+ *
121
+ * Pure arithmetic over the shared encode, so the next surface's TSL sampler and this test read the
122
+ * same grid. The shared-edge tie always lands the lower cell's `fx+fy<=1` branch, which keeps the
123
+ * blend continuous across every cell boundary and never produces the degenerate all-zero set the
124
+ * prior dot-product draft returned when three directions were tied.
125
+ */
126
+ export function impostorViewWeights(direction: Vector3): IViewBlend {
127
+ const grid = IMPOSTOR_VIEW_GRID;
128
+ const p = encodeOctahedral(direction);
129
+ const gx = (p.x * 0.5 + 0.5) * (grid - 1);
130
+ const gy = (p.y * 0.5 + 0.5) * (grid - 1);
131
+ const cx = Math.min(grid - 2, Math.max(0, Math.floor(gx)));
132
+ const cy = Math.min(grid - 2, Math.max(0, Math.floor(gy)));
133
+ const fx = gx - cx;
134
+ const fy = gy - cy;
135
+ const layer = (ix: number, iy: number) => iy * grid + ix;
136
+ if (fx + fy <= 1) {
137
+ return {
138
+ nearest: [layer(cx, cy), layer(cx + 1, cy), layer(cx, cy + 1)] as const,
139
+ weights: [1 - fx - fy, fx, fy] as const,
140
+ };
141
+ }
142
+ // Same corners in the same `11, 01, 10` order the mailbox fix names; the weight beside each
143
+ // corner is the barycentric one, so `01 = (cx, cy+1)` takes `1-fx` and `10 = (cx+1, cy)` takes
144
+ // `1-fy`. Reconstructing the grid coordinate from these weights is what the test checks.
145
+ return {
146
+ nearest: [layer(cx + 1, cy + 1), layer(cx, cy + 1), layer(cx + 1, cy)] as const,
147
+ weights: [fx + fy - 1, 1 - fx, 1 - fy] as const,
148
+ };
149
+ }
150
+
151
+ /** The source bounds of every transformed part, as a centre and a radius. */
152
+ export function impostorBounds(parts: readonly IImpostorPart[]): {
153
+ readonly center: Vector3;
154
+ readonly radius: number;
155
+ } {
156
+ const whole = new Box3();
157
+ whole.makeEmpty();
158
+ const localBox = new Box3();
159
+ let any = false;
160
+ for (const part of parts) {
161
+ const geometry = part.geometry;
162
+ if (geometry.boundingBox === null) geometry.computeBoundingBox();
163
+ const box = geometry.boundingBox;
164
+ if (box === null) continue;
165
+ // `Box3.applyMatrix4` transforms all eight corners, so a rotated part's world AABB is its true
166
+ // extrema — reading only `min`/`max` through the matrix, as the prior draft did, is not.
167
+ localBox.copy(box).applyMatrix4(part.local);
168
+ whole.union(localBox);
169
+ any = true;
170
+ }
171
+ if (!any) return { center: new Vector3(), radius: 0.5 };
172
+ const center = whole.getCenter(new Vector3());
173
+ const radius = whole.getBoundingSphere(new Sphere()).radius;
174
+ return { center, radius: radius > 0 ? radius : 0.5 };
175
+ }
176
+
177
+ /** The exact byte cost of a mip chain of `levels` RGBA8 levels at `pixels` square and `depth` deep. */
178
+ function mipChainBytes(pixels: number, depth: number, levels: number): number {
179
+ let bytes = 0;
180
+ for (let level = 0; level < levels; level += 1) {
181
+ const edge = Math.max(1, pixels >> level);
182
+ bytes += edge * edge * depth * 4;
183
+ }
184
+ return bytes;
185
+ }
186
+
187
+ /**
188
+ * The octahedral atlas: every view of one asset, albedo and coverage in one array, the baked
189
+ * object-space normal and stored ortho depth in another.
190
+ *
191
+ * One atlas is one asset's whole far representation. Nothing here decides appearance: the colour is
192
+ * whatever the asset's own surface drew and the normal is the geometry's own. Both attachments carry
193
+ * a full mip chain so the next surface can compensate the cutout cutoff by mip level.
194
+ */
195
+ export class WorldImpostorAtlas {
196
+ readonly target: RenderTarget;
197
+ readonly pixels: number;
198
+ readonly bytes: number;
199
+ readonly #color: Texture;
200
+ readonly #normal: Texture;
201
+
202
+ constructor(pixels: number) {
203
+ if (!Number.isInteger(pixels) || pixels <= 0) {
204
+ throw new Error(`WorldImpostorAtlas pixels must be a positive integer, received ${pixels}.`);
205
+ }
206
+ this.pixels = pixels;
207
+ this.target = new RenderTarget(pixels, pixels, {
208
+ count: 2,
209
+ depth: IMPOSTOR_VIEWS,
210
+ format: RGBAFormat,
211
+ type: UnsignedByteType,
212
+ generateMipmaps: true,
213
+ magFilter: LinearFilter,
214
+ minFilter: LinearMipmapLinearFilter,
215
+ depthBuffer: true,
216
+ stencilBuffer: false,
217
+ });
218
+ this.#color = this.target.textures[0] as Texture;
219
+ this.#normal = this.target.textures[1] as Texture;
220
+ // MRT keys are looked up by name on the target's textures, so the names have to be the ones the
221
+ // bake's `mrt()` node uses; see `getTextureIndex` in three's MRTNode.
222
+ this.#color.name = "output";
223
+ this.#normal.name = "normal";
224
+ this.#color.colorSpace = SRGBColorSpace;
225
+ this.#normal.colorSpace = NoColorSpace;
226
+ const levels = Math.floor(Math.log2(Math.max(1, pixels))) + 1;
227
+ this.bytes = 2 * mipChainBytes(pixels, IMPOSTOR_VIEWS, levels);
228
+ }
229
+
230
+ get color(): Texture {
231
+ return this.#color;
232
+ }
233
+
234
+ get normal(): Texture {
235
+ return this.#normal;
236
+ }
237
+
238
+ dispose(): void {
239
+ this.target.dispose();
240
+ }
241
+ }
242
+
243
+ /**
244
+ * The raw three renderer seam the bake needs: layered targets, MRT, clear state and render-target
245
+ * initialisation. Structural, so a stub in a test is the same input. `render` is three's own and
246
+ * `initRenderTarget` is three's public `Renderer.initRenderTarget`, which allocates the target's
247
+ * textures — and their mip levels when `generateMipmaps` is set — without drawing.
248
+ */
249
+ export interface IImpostorRawRenderer {
250
+ readonly coordinateSystem?: CoordinateSystem;
251
+ render(scene: Scene, camera: Camera): void;
252
+ setRenderTarget(target: unknown, activeCubeFace?: number, activeMipmapLevel?: number): void;
253
+ getRenderTarget?(): unknown;
254
+ getActiveCubeFace?(): number;
255
+ getActiveMipmapLevel?(): number;
256
+ getMRT?(): unknown;
257
+ setMRT?(mrt: unknown): unknown;
258
+ xr?: { enabled: boolean };
259
+ autoClear?: boolean;
260
+ getClearAlpha?(): number;
261
+ setClearAlpha?(alpha: number): void;
262
+ /**
263
+ * Three's public `Renderer.getClearColor(target)` requires a `Color` target; the baker passes a
264
+ * fresh one and clones the result, so the renderer's own object is never mutated.
265
+ */
266
+ getClearColor?(target: Color): unknown;
267
+ setClearColor?(color: unknown, alpha?: number): void;
268
+ /** Three's public `Renderer.initRenderTarget`: allocate a target's textures, allocate mip levels. */
269
+ initRenderTarget(target: RenderTarget): void;
270
+ }
271
+
272
+ const NODE_CLASSES: ReadonlyMap<string, new () => NodeMaterial> = new Map<
273
+ string,
274
+ new () => NodeMaterial
275
+ >([
276
+ ["MeshBasicMaterial", MeshBasicNodeMaterial],
277
+ ["MeshPhysicalMaterial", MeshPhysicalNodeMaterial],
278
+ ["MeshStandardMaterial", MeshStandardNodeMaterial],
279
+ ]);
280
+
281
+ /** Properties that must not carry from the source onto its node twin, exactly as foliage-alpha.ts. */
282
+ const UNSYNCED = new Set(["_listeners", "id", "uuid", "version"]);
283
+
284
+ /**
285
+ * How much of the mip chain's alpha loss one mip level is compensated by when the bake captures a
286
+ * cutout. The scatter path draws the same cards with 0.75 (`SCATTER_MIP_ALPHA_SCALE`), and the bake
287
+ * has to keep at least what that path keeps, or a tree's impostor holds less than the tree it
288
+ * replaces. Measured on Machinefall: the pine atlas alpha coverage went from 3.7% to 13.5%.
289
+ */
290
+ export const IMPOSTOR_BAKE_MIP_ALPHA_SCALE = 0.75;
291
+
292
+ /** A node twin of a source material: its class, every value it authored, by reference. */
293
+ function cloneNodeMaterial(source: Material): NodeMaterial {
294
+ if (Reflect.get(source, "isNodeMaterial") === true) return (source as NodeMaterial).clone();
295
+ const nodeClass = NODE_CLASSES.get(source.type);
296
+ if (nodeClass === undefined) {
297
+ throw new Error(`WorldImpostorBaker cannot convert material type '${source.type}' to nodes.`);
298
+ }
299
+ const twin = new nodeClass();
300
+ for (const key in source)
301
+ if (!UNSYNCED.has(key)) Reflect.set(twin, key, Reflect.get(source, key));
302
+ return twin;
303
+ }
304
+
305
+ /**
306
+ * The capture material for one source part: the source's own albedo and normal, written to the two
307
+ * attachments unlit.
308
+ *
309
+ * `NoBlending` is deliberate. The alpha test's `discard` already carves the silhouette, so the
310
+ * coverage is not at risk of disappearing. What `builder.isOpaque()` costs is the fractional
311
+ * coverage on soft cutout edges: it forces `diffuseColor.a = 1` on every surviving fragment.
312
+ * NoBlending keeps `isOpaque()` false so the surviving alpha is written, and replaces instead of
313
+ * compositing, which is the honest answer for one nearest surface per view.
314
+ *
315
+ * `normalWorld` is the current name of the node the mailbox calls `transformedNormalWorld`; in the
316
+ * installed three the deprecated symbol returns it verbatim. It derives from the material's own
317
+ * `setupNormal`, so the authored normal map travels into the second attachment.
318
+ */
319
+ function captureMaterial(source: Material, alphaTest: number, depthScale: number): NodeMaterial {
320
+ const material = cloneNodeMaterial(source);
321
+ const coverage = diffuseColor.a;
322
+ const encodedNormal = normalWorld.mul(0.5).add(0.5).mul(coverage);
323
+ // Secondary MRT attachments clear to alpha one; clear contributes zero depth numerator.
324
+ const depth = float(1).sub(positionView.z.mul(-depthScale).mul(coverage));
325
+ material.mrtNode = mrt({
326
+ output: vec4(diffuseColor.rgb.mul(coverage), coverage),
327
+ normal: vec4(encodedNormal, depth),
328
+ }) as MRTNode;
329
+ material.transparent = false;
330
+ material.blending = NoBlending;
331
+ material.alphaTest = alphaTest;
332
+ // The same mip-aware cutoff the scatter cutout draws with. The 128 px frame minifies a needle card
333
+ // by many mips, and a plain discard at `alphaTest` deletes every needle: the atlas kept the trunk
334
+ // and nothing else. `alphaTest` stays the authored number for readers that only take a number.
335
+ const node = mipAlphaTestNode(source, alphaTest, IMPOSTOR_BAKE_MIP_ALPHA_SCALE);
336
+ if (node !== undefined) material.alphaTestNode = node;
337
+ material.depthWrite = true;
338
+ material.depthTest = true;
339
+ material.toneMapped = false;
340
+ material.needsUpdate = true;
341
+ return material;
342
+ }
343
+
344
+ /**
345
+ * An orthographic camera taking in a sphere of `radius` at `center`, facing `-Z` in object space.
346
+ *
347
+ * `up` is the shared frame's vertical: world-up except at the poles, where it flips to `+Z` so the
348
+ * cross product never degenerates. The next slice's sampler must derive the same basis from the
349
+ * same direction.
350
+ */
351
+ export function impostorViewCamera(
352
+ center: Vector3,
353
+ radius: number,
354
+ direction: Vector3,
355
+ into = new OrthographicCamera(),
356
+ ): OrthographicCamera {
357
+ into.left = -radius;
358
+ into.right = radius;
359
+ into.top = radius;
360
+ into.bottom = -radius;
361
+ into.near = 0;
362
+ into.far = 2 * radius;
363
+ into.position.copy(center).addScaledVector(direction, radius);
364
+ const up = Math.abs(direction.y) > 0.999 ? new Vector3(0, 0, 1) : new Vector3(0, 1, 0);
365
+ into.up.copy(up);
366
+ into.lookAt(center);
367
+ into.updateProjectionMatrix();
368
+ into.updateMatrixWorld(true);
369
+ return into;
370
+ }
371
+
372
+ /** Clone a renderer's clear colour so the baker's restore does not depend on the renderer's copy. */
373
+ function cloneClearColor(value: unknown): unknown {
374
+ if (value === undefined || value === null) return value;
375
+ const clone = (value as { clone?: () => unknown }).clone;
376
+ return typeof clone === "function" ? clone.call(value) : value;
377
+ }
378
+
379
+ /** One in-flight atlas bake: one asset's parts staged at the model root, captured one view per step. */
380
+ export interface IPendingImpostorBake {
381
+ readonly asset: string;
382
+ readonly atlas: WorldImpostorAtlas;
383
+ readonly scene: Scene;
384
+ readonly camera: OrthographicCamera;
385
+ readonly center: Vector3;
386
+ readonly radius: number;
387
+ /** Owned material twins, disposed with the bake; the source materials are never touched. */
388
+ readonly materials: readonly Material[];
389
+ view: number;
390
+ }
391
+
392
+ /** The options one bake is started with. Colour and normal come from the source, never from here. */
393
+ export interface IImpostorBakeOptions {
394
+ readonly pixels?: number;
395
+ /** The alpha cutoff that carve's the silhouette; the source's own when it authored one. */
396
+ readonly alphaTest?: number;
397
+ }
398
+
399
+ /**
400
+ * One render-phase slice of an atlas bake, saving and restoring every piece of renderer state the
401
+ * capture touches.
402
+ *
403
+ * The state save/restore follows `probe-volume.ts`'s capture seam: target, face, mip, MRT, clear
404
+ * alpha, clear colour, autoClear and XR are read before the capture and written back in `finally`,
405
+ * so a bake that throws leaves the next real frame exactly as it found the renderer. The mip chain
406
+ * is allocated on the first view and regenerated once after the last, never per view.
407
+ */
408
+ export class WorldImpostorBaker {
409
+ #pending: IPendingImpostorBake | undefined;
410
+ #disposed = false;
411
+
412
+ get pending(): IPendingImpostorBake | undefined {
413
+ return this.#pending;
414
+ }
415
+
416
+ get baking(): boolean {
417
+ return this.#pending !== undefined;
418
+ }
419
+
420
+ /** Stage one asset's parts into a private scene and allocate its atlas. */
421
+ begin(
422
+ asset: string,
423
+ parts: readonly IImpostorPart[],
424
+ options: IImpostorBakeOptions = {},
425
+ ): IPendingImpostorBake {
426
+ if (this.#disposed) throw new Error("WorldImpostorBaker.begin called after dispose().");
427
+ if (this.#pending !== undefined)
428
+ throw new Error(
429
+ `WorldImpostorBaker.begin: an atlas bake for '${this.#pending.asset}' is already in flight.`,
430
+ );
431
+ if (parts.length === 0) throw new Error("WorldImpostorBaker.begin requires at least one part.");
432
+ const bounds = impostorBounds(parts);
433
+ const radius = Math.max(bounds.radius, 1e-4);
434
+ const atlas = new WorldImpostorAtlas(options.pixels ?? IMPOSTOR_FRAME_PIXELS);
435
+ const materials: Material[] = [];
436
+ try {
437
+ const scene = new Scene();
438
+ scene.matrixWorldAutoUpdate = false;
439
+ const depthScale = 1 / (2 * radius);
440
+ for (const part of parts) {
441
+ const alphaTest =
442
+ part.material.alphaTest > 0 ? part.material.alphaTest : (options.alphaTest ?? 0.5);
443
+ const material = captureMaterial(part.material, alphaTest, depthScale);
444
+ materials.push(material);
445
+ const mesh = new Mesh(part.geometry, material);
446
+ mesh.matrixAutoUpdate = false;
447
+ mesh.matrix.copy(part.local);
448
+ mesh.matrixWorld.copy(part.local);
449
+ scene.add(mesh);
450
+ }
451
+ const pending: IPendingImpostorBake = {
452
+ asset,
453
+ atlas,
454
+ camera: new OrthographicCamera(),
455
+ center: bounds.center,
456
+ materials,
457
+ radius,
458
+ scene,
459
+ view: 0,
460
+ };
461
+ this.#pending = pending;
462
+ return pending;
463
+ } catch (error) {
464
+ atlas.dispose();
465
+ for (const material of materials) material.dispose();
466
+ throw error;
467
+ }
468
+ }
469
+
470
+ /**
471
+ * Capture one view, or finish the bake when the last view is written.
472
+ *
473
+ * Returns the completed atlas on the final call, or `undefined` while views remain. A throw
474
+ * releases the partial atlas and the owned material twins, then rethrows: the caller's source
475
+ * geometry and materials are never disposed here.
476
+ */
477
+ step(renderer: IImpostorRawRenderer): WorldImpostorAtlas | undefined {
478
+ if (this.#disposed) throw new Error("WorldImpostorBaker.step called after dispose().");
479
+ const pending = this.#pending;
480
+ if (pending === undefined) return undefined;
481
+ try {
482
+ this.#captureView(renderer, pending, pending.view);
483
+ } catch (error) {
484
+ this.abort();
485
+ throw error;
486
+ }
487
+ pending.view += 1;
488
+ if (pending.view < IMPOSTOR_VIEWS) return undefined;
489
+ const atlas = pending.atlas;
490
+ this.#pending = undefined;
491
+ for (const material of pending.materials) material.dispose();
492
+ return atlas;
493
+ }
494
+
495
+ #captureView(renderer: IImpostorRawRenderer, pending: IPendingImpostorBake, view: number): void {
496
+ const atlas = pending.atlas;
497
+ const color = atlas.color;
498
+ const normal = atlas.normal;
499
+ const previousTarget = renderer.getRenderTarget?.() ?? null;
500
+ const previousFace = renderer.getActiveCubeFace?.() ?? 0;
501
+ const previousMip = renderer.getActiveMipmapLevel?.() ?? 0;
502
+ const previousMrt = renderer.getMRT?.() ?? null;
503
+ const previousXr = renderer.xr?.enabled;
504
+ const previousAutoClear = renderer.autoClear;
505
+ const previousClearAlpha = renderer.getClearAlpha?.();
506
+ const previousClearColor = cloneClearColor(renderer.getClearColor?.(new Color()));
507
+ const last = view === IMPOSTOR_VIEWS - 1;
508
+ // The camera's projection convention follows the renderer's before the projection is built.
509
+ if (renderer.coordinateSystem !== undefined)
510
+ pending.camera.coordinateSystem = renderer.coordinateSystem;
511
+ const direction = VIEW_DIRECTIONS[view] as Vector3;
512
+ impostorViewCamera(pending.center, pending.radius, direction, pending.camera);
513
+ // Allocate the mip chain once through the public seam, then leave generation off for the first
514
+ // fifteen passes and on for the final one, where three's own finishRender generates every layer.
515
+ if (view === 0) {
516
+ color.generateMipmaps = true;
517
+ normal.generateMipmaps = true;
518
+ renderer.initRenderTarget(atlas.target);
519
+ }
520
+ color.generateMipmaps = last;
521
+ normal.generateMipmaps = last;
522
+ try {
523
+ if (renderer.xr !== undefined) renderer.xr.enabled = false;
524
+ renderer.autoClear = true;
525
+ renderer.setMRT?.(null);
526
+ renderer.setClearAlpha?.(0);
527
+ renderer.setClearColor?.(0x000000, 0);
528
+ renderer.setRenderTarget(atlas.target, view, 0);
529
+ renderer.render(pending.scene, pending.camera);
530
+ } finally {
531
+ renderer.setRenderTarget(previousTarget, previousFace, previousMip);
532
+ renderer.setMRT?.(previousMrt);
533
+ if (renderer.xr !== undefined && previousXr !== undefined) renderer.xr.enabled = previousXr;
534
+ renderer.autoClear = previousAutoClear;
535
+ if (previousClearAlpha !== undefined) renderer.setClearAlpha?.(previousClearAlpha);
536
+ if (previousClearColor !== undefined)
537
+ renderer.setClearColor?.(previousClearColor, previousClearAlpha);
538
+ color.generateMipmaps = true;
539
+ normal.generateMipmaps = true;
540
+ }
541
+ }
542
+
543
+ /** Dispose a partial bake's atlas and material twins; idempotent. */
544
+ abort(): void {
545
+ const pending = this.#pending;
546
+ this.#pending = undefined;
547
+ if (pending === undefined) return;
548
+ pending.atlas.dispose();
549
+ for (const material of pending.materials) material.dispose();
550
+ }
551
+
552
+ /** Abort and close the baker; idempotent. */
553
+ dispose(): void {
554
+ if (this.#disposed) return;
555
+ this.#disposed = true;
556
+ this.abort();
557
+ }
558
+ }