@threenative/core 0.3.11 → 0.3.13

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 (236) hide show
  1. package/README.md +1 -1
  2. package/capabilities.json +1988 -204
  3. package/dist/{assets-YUbXa3-Y.d.ts → assets-CfMKnOsK.d.ts} +78 -1
  4. package/dist/camera-shake-CZKOfGn4.d.ts +46 -0
  5. package/dist/{canvas-layer-vCtanIeB.d.ts → canvas-layer-G7ttVy7y.d.ts} +1 -1
  6. package/dist/chunk-4SRAQFTU.js +133 -0
  7. package/dist/chunk-CFGTPFUH.js +231 -0
  8. package/dist/chunk-DIPIJICH.js +8916 -0
  9. package/dist/chunk-EEABDLUC.js +2237 -0
  10. package/dist/chunk-EFWZWLPY.js +1895 -0
  11. package/dist/chunk-GXY7B3JG.js +46 -0
  12. package/dist/chunk-GYUZJQ7U.js +280 -0
  13. package/dist/chunk-H4J6IAJE.js +504 -0
  14. package/dist/chunk-KIRUKTBQ.js +187 -0
  15. package/dist/chunk-QWJEMUUT.js +94 -0
  16. package/dist/chunk-SV4QVUTQ.js +31 -0
  17. package/dist/chunk-U4YHUKKL.js +615 -0
  18. package/dist/chunk-VP43GIWW.js +18 -0
  19. package/dist/chunk-XDTZ4QMO.js +160 -0
  20. package/dist/default-tone-mapping-GgKPTiBP.d.ts +4 -0
  21. package/dist/{game-DzMcitDO.d.ts → game-k8K3hZai.d.ts} +85 -9
  22. package/dist/hot.d.ts +5 -4
  23. package/dist/hot.js +5 -52
  24. package/dist/index.d.ts +633 -1351
  25. package/dist/index.js +12873 -23068
  26. package/dist/{model-lod-CTpZ6imz.d.ts → model-lod-DPTzeCcD.d.ts} +35 -3
  27. package/dist/playtest.d.ts +5 -4
  28. package/dist/playtest.js +25 -75
  29. package/dist/quality-BYqKGAwo.d.ts +868 -0
  30. package/dist/react-css.js +1 -215
  31. package/dist/react.d.ts +3 -2
  32. package/dist/render-environment.d.ts +170 -0
  33. package/dist/render-environment.js +352 -0
  34. package/dist/{renderer-rZm0hVqq.d.ts → renderer-BtOSseYf.d.ts} +42 -35
  35. package/dist/spells/index.d.ts +643 -0
  36. package/dist/spells/index.js +1558 -0
  37. package/dist/spells/ultra/index.d.ts +1600 -0
  38. package/dist/spells/ultra/index.js +6804 -0
  39. package/dist/terrain-jobs-worker.js +1 -123
  40. package/dist/two-sided-foliage-W523J3UM.js +1 -0
  41. package/dist/ui-layer.js +6 -384
  42. package/dist/worker.js +13 -43
  43. package/dist/world.d.ts +988 -268
  44. package/dist/world.js +17464 -18290
  45. package/mcp/animation-server.mjs +1 -1
  46. package/mcp/animation.mjs +2 -3
  47. package/mcp/engine-server.mjs +245 -52
  48. package/mcp/servers.mjs +10 -3
  49. package/mcp/terrain.mjs +8 -0
  50. package/package.json +19 -7
  51. package/patches/three@0.187.0-prd269-upgrade.patch +2102 -0
  52. package/patches/three@0.187.0.patch +2004 -407
  53. package/src/animation-batch.ts +193 -0
  54. package/src/animation-layers.ts +7 -3
  55. package/src/animation.ts +209 -29
  56. package/src/asset-cache.ts +3 -3
  57. package/src/asset-memo.ts +202 -0
  58. package/src/assets.ts +437 -125
  59. package/src/auto-batch.ts +190 -44
  60. package/src/card-lod.ts +152 -0
  61. package/src/compressed-texture-preparation.ts +1008 -0
  62. package/src/compute-driven.ts +1 -1
  63. package/src/config.ts +8 -0
  64. package/src/debug.ts +103 -22
  65. package/src/dev-global.ts +54 -0
  66. package/src/engine-hooks.ts +37 -0
  67. package/src/frame-budget.ts +50 -23
  68. package/src/game-boot-phase.ts +269 -0
  69. package/src/game-dev-tools.ts +86 -0
  70. package/src/game-frame-loop.ts +958 -0
  71. package/src/game-renderer-metrics.ts +77 -0
  72. package/src/game-startup.ts +1076 -0
  73. package/src/game-ui.ts +84 -0
  74. package/src/game-validate.ts +70 -0
  75. package/src/game.ts +198 -2264
  76. package/src/gamepad-mappings.ts +269 -0
  77. package/src/generated/console-markers.ts +13 -0
  78. package/src/geometry-capture.ts +28 -4
  79. package/src/gpu-readings.ts +98 -0
  80. package/src/gpu-scene-bvh.ts +149 -36
  81. package/src/hot.ts +4 -7
  82. package/src/index.ts +141 -9
  83. package/src/input.ts +237 -25
  84. package/src/instanced-batch-lod.ts +3 -8
  85. package/src/interpolation.ts +171 -40
  86. package/src/launch-diagnostics.ts +22 -12
  87. package/src/look/ao-admission.ts +25 -0
  88. package/src/look/auto-exposure.ts +5 -16
  89. package/src/look/default-tone-mapping.ts +41 -5
  90. package/src/look/filmic-tone-mapping.ts +15 -13
  91. package/src/look/local-exposure.ts +2 -7
  92. package/src/look/look-diagnostics.ts +3 -3
  93. package/src/look/quad-pass.ts +21 -0
  94. package/src/look/quality.ts +14 -5
  95. package/src/look/unreal-bloom.ts +4 -13
  96. package/src/look/world-environment.ts +113 -103
  97. package/src/loop.ts +29 -0
  98. package/src/merge-parts.ts +20 -24
  99. package/src/model-lod.ts +139 -17
  100. package/src/particle-kinds.ts +515 -0
  101. package/src/particle-significance.ts +12 -0
  102. package/src/particles.ts +19 -10
  103. package/src/picking.ts +17 -3
  104. package/src/platform.ts +23 -4
  105. package/src/playtest.ts +27 -1
  106. package/src/profiling/FrameStages.ts +5 -6
  107. package/src/profiling/Spans.ts +3 -17
  108. package/src/profiling/debug-telemetry.ts +2 -6
  109. package/src/profiling/render-list-validate.ts +6 -15
  110. package/src/projection-apply.ts +4 -1
  111. package/src/projection-marker.ts +2 -1
  112. package/src/projection-plan.ts +9 -6
  113. package/src/quiet-markers.ts +3 -10
  114. package/src/render/cpu-bvh.ts +100 -0
  115. package/src/render/depth-pyramid.ts +6 -14
  116. package/src/render/environment/environmentContribution.ts +202 -0
  117. package/src/render/environment/environmentRadiance.ts +44 -0
  118. package/src/render/environment/environmentSampleCache.ts +56 -0
  119. package/src/render/environment/environmentSampling.ts +201 -0
  120. package/src/render/environment/environmentSnapshot.ts +71 -0
  121. package/src/render/environment/gate.ts +57 -0
  122. package/src/render/mesh-pool.ts +4 -20
  123. package/src/render/probe-trace.ts +872 -0
  124. package/src/render/probe-volume.ts +780 -34
  125. package/src/render/radiance-cache.ts +17 -0
  126. package/src/render/resolution-subrect.ts +2 -0
  127. package/src/render/rough-diffuse.ts +46 -12
  128. package/src/render/soft-shadow.ts +27 -12
  129. package/src/render/virtual-shadow-adaptive.ts +55 -0
  130. package/src/render/virtual-shadow-casters.ts +175 -0
  131. package/src/render/virtual-shadow-layers.ts +76 -0
  132. package/src/render/virtual-shadow-level.ts +224 -0
  133. package/src/render/virtual-shadow-markers.ts +193 -0
  134. package/src/render/virtual-shadow-options.ts +370 -0
  135. package/src/render/virtual-shadow-pages.ts +5 -0
  136. package/src/render/virtual-shadow-partial.ts +13 -0
  137. package/src/render/virtual-shadow.ts +231 -1008
  138. package/src/render/world-impostor-surface.ts +402 -40
  139. package/src/render/world-impostor.ts +5 -2
  140. package/src/render-camera-cull.ts +98 -3
  141. package/src/render-environment.ts +41 -0
  142. package/src/render-pass-budget.ts +34 -7
  143. package/src/renderProjection.ts +22 -0
  144. package/src/renderer-config.ts +36 -0
  145. package/src/renderer-facts.ts +37 -0
  146. package/src/renderer.ts +144 -65
  147. package/src/resolution-scaler.ts +3 -2
  148. package/src/scene-entry-inspectors.ts +61 -0
  149. package/src/snow-field.ts +2 -1
  150. package/src/spells/cast-pool.ts +361 -0
  151. package/src/spells/index.ts +177 -0
  152. package/src/spells/mechanisms.ts +295 -0
  153. package/src/spells/reaction-field.ts +415 -0
  154. package/src/spells/spell-lights.ts +139 -0
  155. package/src/spells/spell-world.ts +187 -0
  156. package/src/spells/spell.ts +397 -0
  157. package/src/spells/spells.ts +283 -0
  158. package/src/spells/ultra/engine/camera.ts +184 -0
  159. package/src/spells/ultra/engine/quality.ts +96 -0
  160. package/src/spells/ultra/index.ts +52 -0
  161. package/src/spells/ultra/main.ts +305 -0
  162. package/src/spells/ultra/scene/arenaMaterial.ts +325 -0
  163. package/src/spells/ultra/spells/cast.ts +233 -0
  164. package/src/spells/ultra/spells/fire.ts +1267 -0
  165. package/src/spells/ultra/vfx/FluidVolume.ts +816 -0
  166. package/src/spells/ultra/vfx/FluidVolume.tsl.ts +855 -0
  167. package/src/spells/ultra/vfx/FxTarget.ts +61 -0
  168. package/src/spells/ultra/vfx/GroundField.ts +1399 -0
  169. package/src/spells/ultra/vfx/Particles.ts +1475 -0
  170. package/src/spells/ultra/vfx/Ribbons.ts +645 -0
  171. package/src/spells/ultra/vfx/Shockwaves.ts +286 -0
  172. package/src/spells/ultra/vfx/Volumes.ts +489 -0
  173. package/src/spells/ultra/vfx/common.ts +1195 -0
  174. package/src/spells/ultra/vfx/noise.ts +441 -0
  175. package/src/startup-offscreen-bytes.ts +78 -0
  176. package/src/startup-readiness.ts +128 -34
  177. package/src/static-transform.ts +25 -19
  178. package/src/streamed-textures.ts +112 -0
  179. package/src/streaming.ts +68 -4
  180. package/src/texture-streaming.ts +331 -0
  181. package/src/version.ts +1 -1
  182. package/src/warmup.ts +56 -8
  183. package/src/water-surface.ts +9 -3
  184. package/src/worker.ts +12 -2
  185. package/src/world-bundle-safety.ts +446 -0
  186. package/src/world-cell-batches.ts +1178 -0
  187. package/src/world-cell-chunks.ts +1128 -0
  188. package/src/world-cell-data.ts +995 -0
  189. package/src/world-cell-impostors.ts +1461 -0
  190. package/src/world-cell-lod-bias.ts +151 -0
  191. package/src/world-cell-models.ts +1074 -0
  192. package/src/world-cell-options.ts +177 -0
  193. package/src/world-cell-placements.ts +798 -0
  194. package/src/world-cell-prewarm.ts +592 -0
  195. package/src/world-cell-readiness.ts +357 -0
  196. package/src/world-cell-records.ts +401 -0
  197. package/src/world-cell-render-bundles.ts +459 -0
  198. package/src/world-cell-render-gpu-dress.ts +710 -0
  199. package/src/world-cell-render-main-cull.ts +540 -0
  200. package/src/world-cell-render-shadow-claims.ts +198 -0
  201. package/src/world-cell-render-util.ts +259 -0
  202. package/src/world-cell-render.ts +1501 -0
  203. package/src/world-cell-residency.ts +754 -0
  204. package/src/world-cell-stale.ts +238 -0
  205. package/src/world-cells.ts +1335 -10418
  206. package/src/world-chunk-shadow.ts +308 -0
  207. package/src/world-collar.ts +315 -0
  208. package/src/world-gpu-flags.ts +131 -0
  209. package/src/world-gpu-readback.ts +881 -0
  210. package/src/world-gpu-reference.ts +524 -0
  211. package/src/world-gpu-scene.ts +256 -2286
  212. package/src/world-gpu-shadow.ts +203 -0
  213. package/src/world-gpu-types.ts +409 -0
  214. package/src/world-gpu-validation.ts +518 -0
  215. package/src/world-heightfield.ts +802 -0
  216. package/src/world-load-limiter.ts +111 -0
  217. package/src/world-model-sections.ts +80 -0
  218. package/src/world-noise.ts +241 -0
  219. package/src/world-package.ts +42 -0
  220. package/src/world-region.ts +1 -1
  221. package/src/world-river-ribbon.ts +282 -0
  222. package/src/world-root-frame.ts +39 -0
  223. package/src/world-shore-field.ts +91 -0
  224. package/src/world-static-pose.ts +163 -0
  225. package/src/world-surface-sampler.ts +48 -0
  226. package/src/world-terrain-splat.ts +361 -153
  227. package/src/world-tile-budget.ts +249 -0
  228. package/src/world-tile-geometry.ts +469 -0
  229. package/src/world-tile-lod.ts +408 -0
  230. package/src/world-tile-observation.ts +566 -0
  231. package/src/world-tile-stitch.ts +166 -0
  232. package/src/world-tiles.ts +247 -1755
  233. package/src/world-validate.ts +6 -14
  234. package/src/world-warm.ts +51 -0
  235. package/src/world-water-bodies.ts +359 -0
  236. package/src/world.ts +48 -741
@@ -0,0 +1,1461 @@
1
+ import {
2
+ type BufferGeometry,
3
+ InstancedBufferAttribute,
4
+ InstancedMesh,
5
+ type Material,
6
+ Matrix4,
7
+ type Object3D,
8
+ Quaternion,
9
+ Vector3,
10
+ } from "three";
11
+ import { dropPooledFor } from "./render/mesh-pool.js";
12
+ import {
13
+ IMPOSTOR_FAR_CULL_ATTRIBUTE,
14
+ WorldImpostorSurface,
15
+ } from "./render/world-impostor-surface.js";
16
+ import {
17
+ type IImpostorPart,
18
+ type IImpostorRawRenderer,
19
+ IMPOSTOR_FRAME_PIXELS,
20
+ IMPOSTOR_VIEWS,
21
+ WORLD_IMPOSTOR_MARKER,
22
+ type WorldImpostorAtlas,
23
+ WorldImpostorBaker,
24
+ impostorBounds,
25
+ } from "./render/world-impostor.js";
26
+ import type { IRendererLike } from "./renderer.js";
27
+ import { levelTriangles } from "./world-cell-chunks.js";
28
+ import { cellKey } from "./world-cell-data.js";
29
+ import type {
30
+ IAssetPart,
31
+ IResidentCell,
32
+ IWorldCellsBudget,
33
+ IWorldCellsStats,
34
+ } from "./world-cell-data.js";
35
+ import type { IAssetState } from "./world-cell-models.js";
36
+ import { VIRTUAL_SHADOW_WIDE_CASTER_LAYER } from "./world-chunk-shadow.js";
37
+ import {
38
+ type IWorldAsset,
39
+ type IWorldCell,
40
+ type IWorldPackage,
41
+ type IWorldRun,
42
+ cellPlacements,
43
+ } from "./world-package.js";
44
+
45
+ /**
46
+ * GPU bytes of completed impostor atlases one world admits, 128 MiB. A 128 px two-attachment RGBA8
47
+ * atlas with mips is 2,796,160 B, so 48 fit and the 49th is refused before its atlas is allocated,
48
+ * keeping its source LODs. An atlas a live asset still draws from is never evicted, so the active
49
+ * record count is a hard admission cap rather than a target the cache trims toward — eviction only
50
+ * ever drops an inactive record to make room for a new one.
51
+ */
52
+ const DEFAULT_IMPOSTOR_ATLAS_BUDGET_BYTES = 128 * 1024 * 1024;
53
+
54
+ /**
55
+ * The declared byte cost of one atlas at the bake's fixed frame, the same numbers
56
+ * `WorldImpostorAtlas.bytes` reports: both RGBA8 attachments' mip chains, the logical colour atlas
57
+ * cost rather than every physical GPU buffer a render target holds. Computed here so the cache
58
+ * budget is enforced BEFORE `baker.begin` allocates the atlas, never after.
59
+ */
60
+ const IMPOSTOR_ATLAS_BYTES = ((): number => {
61
+ const levels = Math.floor(Math.log2(Math.max(1, IMPOSTOR_FRAME_PIXELS))) + 1;
62
+ let bytes = 0;
63
+ for (let level = 0; level < levels; level += 1) {
64
+ const edge = Math.max(1, IMPOSTOR_FRAME_PIXELS >> level);
65
+ bytes += edge * edge * IMPOSTOR_VIEWS * 4;
66
+ }
67
+ return 2 * bytes;
68
+ })();
69
+
70
+ /**
71
+ * The far-residency diagnostic marker: one bounded line per whole-map aggregate built, naming the one
72
+ * `InstancedMesh` per atlas cache key, its original placements, the live/near-owned split, its
73
+ * physical instance bytes and how many times its instance buffer has been written.
74
+ */
75
+ const WORLD_IMPOSTOR_FAR_MARKER = "TN_WORLD_IMPOSTOR_FAR";
76
+
77
+ /**
78
+ * Bytes one far instance costs: its sixteen-float32 matrix plus the one-float per-instance cull the
79
+ * shared far surface reads. Both are physical allocations the budget bounds; the cull is uploaded
80
+ * once because the placement never moves.
81
+ */
82
+ const FAR_INSTANCE_BYTES = 16 * 4 + 4;
83
+
84
+ /**
85
+ * One completed whole-asset atlas, cached by its content key and its source cutout contract.
86
+ *
87
+ * Bounded, not a generic cache: the atlas is the one GPU resource a later far reference may want to
88
+ * hold without keeping the full source GLB, and the CPU `center`/`radius` are the two scalars the
89
+ * surface needs to project it. `users` counts the live assets drawing it; a record with no user is
90
+ * inactive and evictable once the byte budget is over, and one with a user is never evicted.
91
+ */
92
+ interface IImpostorRecord {
93
+ readonly key: string;
94
+ readonly atlas: WorldImpostorAtlas;
95
+ readonly center: Vector3;
96
+ readonly radius: number;
97
+ readonly halfExtents: Vector3;
98
+ readonly bytes: number;
99
+ users: number;
100
+ }
101
+
102
+ /** The terminal LOD one asset appended once its bake landed; owned and released with the asset. */
103
+ export interface IImpostorState {
104
+ readonly part: IAssetPart;
105
+ readonly surface: WorldImpostorSurface;
106
+ readonly record: IImpostorRecord;
107
+ }
108
+
109
+ /**
110
+ * One `(cell, run)`'s slice of a whole-map far aggregate.
111
+ *
112
+ * The records are the run's ORIGINAL placement roots, composed once when the aggregate is built and
113
+ * never rewritten while the camera moves. `live` is false while the near ring owns the run, which is
114
+ * the atomic handoff: a run is drawn by exactly one of the two, never both and never neither.
115
+ */
116
+ interface IFarSegment {
117
+ readonly cell: IWorldCell;
118
+ readonly run: IWorldRun;
119
+ /** First instance record in the aggregate's buffer, and how many the run holds. */
120
+ readonly start: number;
121
+ readonly count: number;
122
+ /** This run's own view-distance gate, `Infinity` when its asset authored no `maxDistance`. */
123
+ readonly cull: number;
124
+ live: boolean;
125
+ }
126
+
127
+ /**
128
+ * One whole-map far aggregate per exact atlas cache key: a single `InstancedMesh` holding every
129
+ * ORIGINAL placement root of every canonical asset that bakes to that key, independent of the near
130
+ * full-geometry ring and of the near source GLBs.
131
+ *
132
+ * The surface is the aggregate's own, built from the record's atlas and the first source material
133
+ * that baked to it, so disposing a near asset's surface cannot invalidate the far mesh. The atlas is
134
+ * borrowed: `record.users` is incremented once for the aggregate and held until the world disposes,
135
+ * which is what stops `#evictImpostors` dropping an atlas the far mesh still draws.
136
+ */
137
+ interface IFarAggregate {
138
+ readonly key: string;
139
+ readonly surface: WorldImpostorSurface;
140
+ readonly record: IImpostorRecord;
141
+ mesh: InstancedMesh;
142
+ capacity: number;
143
+ /** Every original placement root the aggregate holds, live and near-owned. */
144
+ readonly segments: Map<IWorldRun, IFarSegment>;
145
+ /** How many times the instance buffer has been written, for the settled-frame check. */
146
+ uploads: number;
147
+ }
148
+
149
+ /**
150
+ * The metadata a refused far cohort is kept as, without its source GLB.
151
+ *
152
+ * A hard budget refusal releases the asset's geometry and materials the way any release does; the
153
+ * atlas is pinned by one borrowed `users` and the aggregate's own surface is built once here, so a
154
+ * later capacity release retries from this alone — no full model is held alive for a cohort that may
155
+ * never fit. See `#deferFar`, `#retryFar`.
156
+ */
157
+ interface IFarCohort {
158
+ readonly id: string;
159
+ readonly key: string;
160
+ readonly record: IImpostorRecord;
161
+ /** The alpha-foliage source material to twin; absent once a refused cohort has its surface built. */
162
+ readonly source?: Material;
163
+ readonly alphaTest: number;
164
+ readonly cull: number;
165
+ readonly runs: ReadonlyArray<{ cell: IWorldCell; run: IWorldRun }>;
166
+ }
167
+
168
+ /**
169
+ * A refused far cohort kept without its source GLB: metadata plus the surface already built from the
170
+ * source at refusal. No material, geometry or texture of the model survives here — only the surface,
171
+ * which cleared its UV maps and borrows the pinned atlas.
172
+ */
173
+ interface IFarRetryEntry {
174
+ readonly id: string;
175
+ readonly key: string;
176
+ readonly record: IImpostorRecord;
177
+ readonly alphaTest: number;
178
+ readonly cull: number;
179
+ readonly runs: ReadonlyArray<{ cell: IWorldCell; run: IWorldRun }>;
180
+ readonly surface: WorldImpostorSurface;
181
+ }
182
+
183
+ /**
184
+ * The raw renderer seam the impostor bake needs, or `undefined` when this backend does not expose it.
185
+ *
186
+ * `IRendererLike.raw` is `unknown` on purpose: it is whatever the running renderer is, and a backend
187
+ * without layered render targets has no bake seam at all. The shape is checked rather than cast, so a
188
+ * stub whose raw is not a renderer leaves the bake un-run instead of throwing inside a frame.
189
+ *
190
+ * A WebGL renderer is the reason the three-method shape alone is not enough: it carries `render`,
191
+ * `setRenderTarget` and `initRenderTarget` and would pass, then fail mid-frame on the layered MRT
192
+ * capture it cannot run. So the backend must declare itself WebGPU (`kind` and the renderer's own
193
+ * `isWebGPURenderer`), which a WebGL fallback and an unsupported native backend do not, and the full
194
+ * getter/setter seam the baker calls must be present before the cast — the ones the baker reaches
195
+ * with `?.` still have to exist on a real backend, and a raw object missing them would be half-run,
196
+ * not skipped cleanly.
197
+ */
198
+ const REQUIRED_IMPOSTOR_METHODS = [
199
+ "getActiveCubeFace",
200
+ "getActiveMipmapLevel",
201
+ "getClearAlpha",
202
+ "getClearColor",
203
+ "getMRT",
204
+ "getRenderTarget",
205
+ "initRenderTarget",
206
+ "render",
207
+ "setClearAlpha",
208
+ "setClearColor",
209
+ "setMRT",
210
+ "setRenderTarget",
211
+ ] as const;
212
+
213
+ function impostorRawRenderer(
214
+ renderer: IRendererLike | undefined,
215
+ ): IImpostorRawRenderer | undefined {
216
+ if (renderer === undefined || renderer.kind !== "webgpu") return undefined;
217
+ const raw = renderer.raw as
218
+ | (Partial<IImpostorRawRenderer> & { isWebGPURenderer?: boolean })
219
+ | null;
220
+ if (raw === null || raw === undefined) return undefined;
221
+ if (raw.isWebGPURenderer !== true) return undefined;
222
+ // A `WebGPURenderer` can wrap the WebGL fallback backend and still report `kind: 'webgpu'` and
223
+ // `isWebGPURenderer === true`; that backend cannot run a layered MRT capture, so the method shape
224
+ // alone would accept it and fail mid-frame. The backend it actually wrapped is the honest answer.
225
+ if ((raw as { backend?: { isWebGLBackend?: boolean } }).backend?.isWebGLBackend === true)
226
+ return undefined;
227
+ for (const method of REQUIRED_IMPOSTOR_METHODS)
228
+ if (typeof raw[method] !== "function") return undefined;
229
+ return raw as IImpostorRawRenderer;
230
+ }
231
+
232
+ /** The bake's view of one asset level: each part's geometry, transform and surface, by reference. */
233
+ function impostorParts(parts: readonly IAssetPart[]): IImpostorPart[] {
234
+ const staged: IImpostorPart[] = [];
235
+ for (const part of parts)
236
+ staged.push({ geometry: part.geometry, local: part.local, material: part.material });
237
+ return staged;
238
+ }
239
+
240
+ /**
241
+ * The alpha threshold a cutout gets when the part's own material names none. ponytail: a fixed
242
+ * 0.5, because the cutout point is authored data a GLB carries per texture and nothing reads it
243
+ * here. A tree whose needles visibly dither at 0.5 wants a lower one — give
244
+ * `transparentScatter` a third mode carrying a threshold when that is worth a knob.
245
+ */
246
+ export const DEFAULT_CUTOUT_ALPHA = 0.5;
247
+
248
+ /** The one test that separates an alpha-cutout foliage part from an opaque one: MASK or BLEND. */
249
+ export function isAlphaFoliage(material: Material): boolean {
250
+ return material.transparent || material.alphaTest > 0;
251
+ }
252
+ export interface ICellImpostorsHost {
253
+ released(): boolean;
254
+ covered(): boolean;
255
+ renderer(): IRendererLike | undefined;
256
+ asset(id: string): IAssetState | undefined;
257
+ hasAsset(id: string): boolean;
258
+ assets(): Iterable<IAssetState>;
259
+ nearWorkPending(): boolean;
260
+ newAsset(id: string, definition: IWorldAsset): IAssetState;
261
+ startAssetLoad(asset: IAssetState): void;
262
+ release(id: string): void;
263
+ noteGate(gate: number): void;
264
+ retargetWideCasters(asset: IAssetState): void;
265
+ terminalPrewarm(asset: IAssetState): void;
266
+ terminalLevelReady(asset: IAssetState): void;
267
+ residentCell(key: string): IResidentCell | undefined;
268
+ canonical(id: string): string;
269
+ shadowRecordsMoved(): void;
270
+ residency(): { readonly instances: number; readonly bytes: number; readonly hlodBytes: number };
271
+ add(object: Object3D): void;
272
+ remove(object: Object3D): void;
273
+ addFailure(): void;
274
+ markReleasedPart(part: IAssetPart): void;
275
+ drawnImpostorInstances(): number;
276
+ }
277
+ export interface ICellImpostorsSettings {
278
+ readonly enabled: boolean;
279
+ readonly preserveAuthoredParts: boolean;
280
+ readonly receiveShadow: boolean;
281
+ readonly candidates: readonly string[];
282
+ readonly cells: readonly IWorldCell[];
283
+ readonly manifest: IWorldPackage;
284
+ readonly placements: ArrayBuffer;
285
+ readonly transparentScatter: "cutout" | "blend";
286
+ readonly autoLodPixelsPerUnit: number;
287
+ readonly castShadowLevels: number;
288
+ readonly budgets: IWorldCellsBudget;
289
+ /** Whether a short-range asset keeps a far aggregate anyway; see `#farReaches`. */
290
+ readonly impostorFar: "ring" | "always";
291
+ /** `ring * cellSize`: the distance inside which a near cell is always resident. */
292
+ readonly nearRingRadius: number;
293
+ }
294
+ export class CellImpostors {
295
+ readonly #host: ICellImpostorsHost;
296
+
297
+ readonly #cells: readonly IWorldCell[];
298
+
299
+ readonly #manifest: IWorldPackage;
300
+
301
+ readonly #placements: ArrayBuffer;
302
+
303
+ readonly #transparentScatter: "cutout" | "blend";
304
+
305
+ /**
306
+ * Pixels per world unit at unit depth, the scale a baked chain's level errors are divided by to
307
+ * reach a switch distance. See `IWorldCellsLoadOptions.autoLod` and {@link chainLevels}.
308
+ */
309
+ readonly #autoLodPixelsPerUnit: number;
310
+
311
+ /** How many of an asset's finest levels cast shadows; 0 when the game asked for none. */
312
+ readonly #castShadowLevels: number;
313
+
314
+ readonly #budgets: IWorldCellsBudget;
315
+
316
+ /** The named `impostorFar` override, and the radius the near ring guarantees below it. */
317
+ readonly #impostorFar: "ring" | "always";
318
+ readonly #nearRingRadius: number;
319
+
320
+ /** Asset ids the `impostorFar: "always"` override kept, so its report prints once each. */
321
+ readonly #farOverrideReported = new Set<string>();
322
+
323
+ readonly #position = new Vector3();
324
+
325
+ readonly #rotation = new Quaternion();
326
+
327
+ readonly #scale = new Vector3();
328
+
329
+ readonly #matrix = new Matrix4();
330
+
331
+ /** Whether alpha-foliage assets append a baked whole-asset terminal level; see the option. */
332
+ readonly #impostors: boolean;
333
+ readonly #preserveAuthoredParts: boolean;
334
+ readonly #receiveShadow: boolean;
335
+
336
+ /** The baker one view per render-cadence update; see `#stepImpostor`. */
337
+ readonly #baker = new WorldImpostorBaker();
338
+
339
+ /** Assets whose bake is queued, in adoption order; `#impostorQueued` is the same set by id. */
340
+ readonly #impostorQueue: IAssetState[] = [];
341
+
342
+ readonly #impostorQueued = new Set<string>();
343
+
344
+ /** The asset whose bake holds the baker right now, if any. */
345
+ #impostorBaking: IAssetState | undefined;
346
+
347
+ /**
348
+ * Completed atlases by content key. An atlas a live asset draws from is active and never evicted;
349
+ * one with no user is kept for a later reference until the byte budget needs the room.
350
+ */
351
+ readonly #impostorRecords = new Map<string, IImpostorRecord>();
352
+
353
+ #impostorRecordBytes = 0;
354
+
355
+ /** The declared bytes of the one bake in flight, held against the budget before `begin`. */
356
+ #impostorReservedBytes = 0;
357
+
358
+ readonly #impostorBudgetBytes: number;
359
+
360
+ /** Assets whose `TN_WORLD_IMPOSTOR` line has printed, so the marker is one per asset. */
361
+ readonly #impostorReported = new Set<string>();
362
+
363
+ /**
364
+ * Assets whose pre-bake wide segments are still waiting for a block in the one whole-asset mesh,
365
+ * because the frame that handed the bake over had spent its fresh-mesh allowance. Retried on the
366
+ * next update rather than left with no far shadow.
367
+ */
368
+ readonly #wideRetry = new Set<string>();
369
+
370
+ /**
371
+ * The whole-map far aggregates, one per exact atlas cache key, and the `run -> aggregate` index a
372
+ * near-ready handoff and an eviction read to toggle a run's far segment without asking the asset.
373
+ *
374
+ * `#farInstances` and `#farBytes` are the physical allocations those meshes hold, charged against
375
+ * the world's own instance and byte budgets beside the near ring's records.
376
+ */
377
+ readonly #far = new Map<string, IFarAggregate>();
378
+
379
+ readonly #farSegments = new Map<IWorldRun, IFarAggregate>();
380
+
381
+ #farInstances = 0;
382
+
383
+ #farBytes = 0;
384
+
385
+ /** Atlas keys whose `TN_WORLD_IMPOSTOR_FAR` line has printed, so the marker is one per aggregate. */
386
+ readonly #farReported = new Set<string>();
387
+
388
+ /**
389
+ * Cohorts whose far aggregate a full budget refused, as metadata plus a built surface and never
390
+ * the source GLB. Retried when a near cell releases its allocation — an event, not a per-frame
391
+ * scan — so a walk away from the ring makes room and the refused species appears without holding
392
+ * a full model alive; see {@link IFarRetryEntry}, `#retryFar` and `#deferFar`.
393
+ */
394
+ readonly #farRetry = new Map<string, IFarRetryEntry>();
395
+
396
+ /**
397
+ * Canonical asset ids placed anywhere in the map, adopted on idle frames so a species that never
398
+ * enters the near ring still bakes its atlas and appears on the far mesh. Enumerated once from the
399
+ * static placements; see `#pumpFarAcquisition`.
400
+ */
401
+ readonly #farCandidateIds: readonly string[];
402
+
403
+ /** The rotating cursor over `#farCandidateIds`, so the map is walked a bounded step per idle frame. */
404
+ #farCursor = 0;
405
+
406
+ /** Canonical ids whose far handling has settled: baked and built, or classified with no atlas. */
407
+ readonly #farSeen = new Set<string>();
408
+
409
+ /** Canonical ids acquired for the far half alone, held until their aggregate lands or is refused. */
410
+ readonly #farTemp = new Set<string>();
411
+
412
+ /** Every candidate is settled, so the idle pump can stop scanning the map; see `#pumpFarAcquisition`. */
413
+ #farExhausted = false;
414
+ constructor(settings: ICellImpostorsSettings, host: ICellImpostorsHost) {
415
+ this.#host = host;
416
+ this.#impostors = settings.enabled;
417
+ this.#preserveAuthoredParts = settings.preserveAuthoredParts;
418
+ this.#receiveShadow = settings.receiveShadow;
419
+ this.#farCandidateIds = settings.candidates;
420
+ this.#impostorBudgetBytes = DEFAULT_IMPOSTOR_ATLAS_BUDGET_BYTES;
421
+ this.#cells = settings.cells;
422
+ this.#manifest = settings.manifest;
423
+ this.#placements = settings.placements;
424
+ this.#transparentScatter = settings.transparentScatter;
425
+ this.#autoLodPixelsPerUnit = settings.autoLodPixelsPerUnit;
426
+ this.#castShadowLevels = settings.castShadowLevels;
427
+ this.#budgets = settings.budgets;
428
+ this.#impostorFar = settings.impostorFar;
429
+ this.#nearRingRadius = settings.nearRingRadius;
430
+ }
431
+ get farBytes(): number {
432
+ return this.#farBytes;
433
+ }
434
+ get farInstances(): number {
435
+ return this.#farInstances;
436
+ }
437
+ hasFarTemp(id: string): boolean {
438
+ return this.#farTemp.has(id);
439
+ }
440
+ hasQueued(id: string): boolean {
441
+ return this.#impostorQueued.has(id);
442
+ }
443
+ deferWide(id: string): void {
444
+ this.#wideRetry.add(id);
445
+ }
446
+
447
+ /**
448
+ * Whether this asset needs extra placement-root records for the generated wide impostor. Preserved
449
+ * authored parts keep their own wide casters, so they use each part's regular instance records.
450
+ */
451
+ rootsNeeded(asset: IAssetState): boolean {
452
+ if (this.#impostors === false || this.#preserveAuthoredParts) return false;
453
+ const parts = asset.levels[0];
454
+ return parts !== undefined && this.#impostorSource(parts) !== undefined;
455
+ }
456
+
457
+ /**
458
+ * The first LOD0 part that is alpha foliage, and the cutoff its own material authored — or
459
+ * `undefined` when no part is. A BLEND part carries `alphaTest 0`, and the scatter path draws it
460
+ * through the same cutout a MASK part gets, so the contract records that default rather than a
461
+ * zero that would bake a solid impostor.
462
+ */
463
+ #impostorSource(
464
+ parts: readonly IAssetPart[],
465
+ ): { readonly source: Material; readonly alphaTest: number } | undefined {
466
+ for (const part of parts) {
467
+ const material = part.material;
468
+ if (!isAlphaFoliage(material)) continue;
469
+ return {
470
+ source: material,
471
+ alphaTest: material.alphaTest > 0 ? material.alphaTest : DEFAULT_CUTOUT_ALPHA,
472
+ };
473
+ }
474
+ return undefined;
475
+ }
476
+
477
+ /**
478
+ * The content key one impostor atlas is cached under: the loader's resolved cooked url of LOD0,
479
+ * plus every LOD0 source part's surface/content key and its exact cutout contract. Two package
480
+ * entries that fetch the same cooked model and draw the same parts with the same cutoffs are one
481
+ * bake, which is the canonical-asset idea applied to the atlas rather than to the levels — the
482
+ * package's own `lods`/`maxDistance` metadata may have stopped the two entries aliasing, but the
483
+ * atlas is built from LOD0 alone, so it must be shared anyway.
484
+ *
485
+ * The cutoff is the exact number the bake uses, never a rounded one: `0.42` and `0.420001` are
486
+ * different silhouettes and must not collide in the cache.
487
+ */
488
+ #impostorKey(asset: IAssetState): string {
489
+ const parts = asset.levels[0] ?? [];
490
+ const contract: string[] = [];
491
+ for (const part of parts) {
492
+ const cutoff = isAlphaFoliage(part.material)
493
+ ? part.material.alphaTest > 0
494
+ ? part.material.alphaTest
495
+ : DEFAULT_CUTOUT_ALPHA
496
+ : 0;
497
+ contract.push(`${part.surface}@${String(cutoff)}`);
498
+ }
499
+ return `${asset.resolvedGlb}|${this.#transparentScatter}|${contract.join(",")}`;
500
+ }
501
+
502
+ /** Mark a cached atlas touched, so the least recently used inactive record is the one evicted. */
503
+ #touchImpostor(key: string, record: IImpostorRecord): void {
504
+ this.#impostorRecords.delete(key);
505
+ this.#impostorRecords.set(key, record);
506
+ }
507
+
508
+ /**
509
+ * Queue one adopted asset's whole-asset impostor, or append it at once from a cached atlas.
510
+ *
511
+ * Called after `#widenWithChain` and before the prewarm, so the terminal level is known to the same
512
+ * prewarm and rebuild machinery every adoption uses. An asset with no alpha-cutout LOD0 part is
513
+ * never baked: a solid impostor is not the thing it replaces.
514
+ */
515
+ maybeQueueImpostor(asset: IAssetState): void {
516
+ if (
517
+ this.#impostors === false ||
518
+ asset.impostor !== undefined ||
519
+ (this.#preserveAuthoredParts && asset.definition.impostorDistance === undefined)
520
+ )
521
+ return;
522
+ const parts = asset.levels[0];
523
+ if (parts === undefined) return;
524
+ const source = this.#impostorSource(parts);
525
+ if (source === undefined) return;
526
+ const key = this.#impostorKey(asset);
527
+ const cached = this.#impostorRecords.get(key);
528
+ if (cached !== undefined) {
529
+ this.#touchImpostor(key, cached);
530
+ this.#finishImpostor(asset, cached);
531
+ return;
532
+ }
533
+ if (this.#impostorQueued.has(asset.id)) return;
534
+ this.#impostorQueued.add(asset.id);
535
+ this.#impostorQueue.push(asset);
536
+ }
537
+
538
+ /**
539
+ * One view of the bake per render-cadence update, then the terminal level when it completes.
540
+ *
541
+ * The renderer is asked for its raw seam and the bake waits for one that can run it: a world that
542
+ * has no renderer yet — or a backend whose raw seam is not the layered-target API — simply does
543
+ * not advance, and nothing downstream of the bake is owed until it does. No landmark is already
544
+ * waited on, so a bake that never runs never deadlocks a loading screen.
545
+ */
546
+ stepImpostor(renderer: IRendererLike | undefined): void {
547
+ if (this.#impostors === false || this.#host.released()) return;
548
+ // A renderer that exists but carries no layered bake seam is a real answer, not a delay. Waiting
549
+ // on it would leave every queued asset pending and its atlas bytes reserved for the world's whole
550
+ // life, so the bake is cancelled, the reservation and queue dropped, and each asset reported:
551
+ // the source LODs stay, which is the documented fallback. A world with no renderer yet keeps
552
+ // waiting — that is the loading-screen case the wait exists for.
553
+ const current = renderer ?? this.#host.renderer();
554
+ if (current !== undefined && impostorRawRenderer(current) === undefined) {
555
+ this.#dropUnsupportedImpostors();
556
+ return;
557
+ }
558
+ const covered = this.#host.covered();
559
+ let jobs = covered
560
+ ? this.#impostorQueue.length + (this.#impostorBaking === undefined ? 0 : 1)
561
+ : 1;
562
+ while (jobs > 0) {
563
+ jobs -= 1;
564
+ if (this.#impostorBaking === undefined) {
565
+ while (this.#impostorQueue.length > 0) {
566
+ const asset = this.#impostorQueue.shift() as IAssetState;
567
+ this.#impostorQueued.delete(asset.id);
568
+ if (
569
+ this.#host.asset(asset.id) !== asset ||
570
+ asset.disposed ||
571
+ asset.impostor !== undefined
572
+ )
573
+ continue;
574
+ const parts = asset.levels[0];
575
+ if (parts === undefined || this.#impostorSource(parts) === undefined) continue;
576
+ // Re-check the completed cache when DEQUEUED, not only when queued: two entries whose bake
577
+ // was queued before either finished share one atlas instead of baking it twice.
578
+ const key = this.#impostorKey(asset);
579
+ const cached = this.#impostorRecords.get(key);
580
+ if (cached !== undefined) {
581
+ this.#touchImpostor(key, cached);
582
+ this.#finishImpostor(asset, cached);
583
+ continue;
584
+ }
585
+ // Enforce the declared colour+mip budget BEFORE the atlas is allocated, and never at the
586
+ // cost of an atlas a live asset draws from: inactive LRU records make room first.
587
+ if (
588
+ this.#impostorRecordBytes + this.#impostorReservedBytes + IMPOSTOR_ATLAS_BYTES >
589
+ this.#impostorBudgetBytes
590
+ )
591
+ this.#evictImpostors(IMPOSTOR_ATLAS_BYTES);
592
+ if (this.#impostorRecordBytes + IMPOSTOR_ATLAS_BYTES > this.#impostorBudgetBytes) {
593
+ // Out of room: keep the source LODs and say why, rather than overrun the budget with one
594
+ // more atlas or evict one still in use.
595
+ this.#reportImpostor(asset, "budget");
596
+ // A far-only species fetched for the far half alone has no near run to fall back on, and
597
+ // nothing here retries an atlas-budget refusal, so keeping its source GLB alive buys
598
+ // nothing. Release it; the near path re-acquires it normally if the follow point reaches it.
599
+ if (this.#farTemp.has(asset.id)) this.releaseFarTemp(asset.id);
600
+ continue;
601
+ }
602
+ const staged: IImpostorPart[] = impostorParts(parts);
603
+ try {
604
+ this.#baker.begin(asset.id, staged, { pixels: IMPOSTOR_FRAME_PIXELS });
605
+ } catch (error) {
606
+ this.#host.addFailure();
607
+ this.#reportImpostor(asset, "begin-failed", error);
608
+ continue;
609
+ }
610
+ this.#impostorReservedBytes = IMPOSTOR_ATLAS_BYTES;
611
+ this.#impostorBaking = asset;
612
+ break;
613
+ }
614
+ }
615
+ const baking = this.#impostorBaking;
616
+ if (baking === undefined) return;
617
+ const raw = impostorRawRenderer(renderer);
618
+ if (raw === undefined) return;
619
+ let atlas: WorldImpostorAtlas | undefined;
620
+ try {
621
+ const views = covered ? IMPOSTOR_VIEWS - (this.#baker.pending?.view ?? 0) : 1;
622
+ for (let remaining = views; remaining > 0; remaining -= 1) {
623
+ const view = this.#baker.pending?.view;
624
+ atlas = this.#baker.step(raw);
625
+ if (atlas !== undefined || this.#baker.pending?.view === view) break;
626
+ }
627
+ } catch (error) {
628
+ this.#host.addFailure();
629
+ this.#impostorBaking = undefined;
630
+ this.#impostorReservedBytes = 0;
631
+ this.#reportImpostor(baking, "bake-failed", error);
632
+ return;
633
+ }
634
+ if (atlas === undefined) return;
635
+ this.#impostorBaking = undefined;
636
+ this.#adoptImpostorAtlas(baking, atlas);
637
+ }
638
+ }
639
+
640
+ /**
641
+ * Drop every queued and in-flight bake because the renderer cannot run the layered capture, and
642
+ * report each asset once. The reservation is released with the abort, so a later supported renderer
643
+ * (a device swap, a backend that only comes up after a frame) can still bake: the queue is empty,
644
+ * but a fresh adoption re-queues, and an asset already refused here is left with its source LODs.
645
+ */
646
+ #dropUnsupportedImpostors(): void {
647
+ if (this.#impostorQueue.length === 0 && this.#impostorBaking === undefined) return;
648
+ const dropped: IAssetState[] = [];
649
+ if (this.#impostorBaking !== undefined) {
650
+ dropped.push(this.#impostorBaking);
651
+ this.#reportImpostor(this.#impostorBaking, "unsupported");
652
+ this.#baker.abort();
653
+ this.#impostorBaking = undefined;
654
+ this.#impostorReservedBytes = 0;
655
+ }
656
+ const queued = this.#impostorQueue.splice(0, this.#impostorQueue.length);
657
+ this.#impostorQueued.clear();
658
+ dropped.push(...queued);
659
+ for (const asset of queued) this.#reportImpostor(asset, "unsupported");
660
+ // A far-only species cannot bake on a backend that has none, so it must not keep holding the
661
+ // source it fetched for a bake that will never land. Its atlas cache key stays for a later backend.
662
+ for (const asset of dropped) if (this.#farTemp.has(asset.id)) this.releaseFarTemp(asset.id);
663
+ }
664
+
665
+ /** Store a finished atlas and hand the asset its terminal level. */ #adoptImpostorAtlas(
666
+ asset: IAssetState,
667
+ atlas: WorldImpostorAtlas,
668
+ ): void {
669
+ this.#impostorReservedBytes = 0;
670
+ const parts = asset.levels[0];
671
+ const source = parts === undefined ? undefined : this.#impostorSource(parts);
672
+ if (parts === undefined || source === undefined || asset.impostor !== undefined) {
673
+ atlas.dispose();
674
+ return;
675
+ }
676
+ const key = this.#impostorKey(asset);
677
+ const existing = this.#impostorRecords.get(key);
678
+ if (existing !== undefined) {
679
+ atlas.dispose();
680
+ this.#touchImpostor(key, existing);
681
+ this.#finishImpostor(asset, existing);
682
+ return;
683
+ }
684
+ const staged: IImpostorPart[] = impostorParts(parts);
685
+ const bounds = impostorBounds(staged);
686
+ const record: IImpostorRecord = {
687
+ atlas,
688
+ bytes: atlas.bytes,
689
+ center: bounds.center,
690
+ halfExtents: bounds.halfExtents,
691
+ key,
692
+ radius: bounds.radius,
693
+ users: 0,
694
+ };
695
+ this.#impostorRecords.set(key, record);
696
+ this.#impostorRecordBytes += record.bytes;
697
+ // Acquire the active user BEFORE any eviction, so the fresh record cannot be the eviction
698
+ // victim and `#finishImpostor` never builds a surface that borrows a disposed atlas. Admission
699
+ // already reserved this record's bytes, so the trim below only drops older inactive records.
700
+ this.#finishImpostor(asset, record);
701
+ this.#evictImpostors();
702
+ }
703
+
704
+ /**
705
+ * Append the whole-asset terminal level: one part, identity local, two triangles, and a switch at
706
+ * the projection the 128 px atlas sphere reaches — never a fixed metre, and strictly beyond the
707
+ * last authored or chain gate so `levelAt` cannot pick it before the level that gate named.
708
+ *
709
+ * The surface's own geometry and material are the part's, so the level is a normal level to every
710
+ * consumer downstream: the prewarm mints its keys, the swap rebuilds the resident runs, and the
711
+ * caster halves read it through `#shapeFor` like any other. The atlas is borrowed and released by
712
+ * the record; see `#releaseImpostor`.
713
+ */
714
+ #finishImpostor(asset: IAssetState, record: IImpostorRecord): void {
715
+ if (asset.impostor !== undefined || asset.disposed) return;
716
+ if (this.#host.asset(asset.id) !== asset) return;
717
+ const parts = asset.levels[0];
718
+ if (parts === undefined) return;
719
+ const source = this.#impostorSource(parts);
720
+ if (source === undefined) return;
721
+ let surface: WorldImpostorSurface;
722
+ try {
723
+ surface = new WorldImpostorSurface({
724
+ alphaTest: source.alphaTest,
725
+ atlas: record.atlas,
726
+ center: record.center,
727
+ halfExtents: record.halfExtents,
728
+ radius: record.radius,
729
+ source: source.source,
730
+ });
731
+ } catch (error) {
732
+ this.#host.addFailure();
733
+ this.#reportImpostor(asset, "surface-failed", error);
734
+ return;
735
+ }
736
+ // The terminal gate is stored as the BASE-sphere projected distance — the distance at which the
737
+ // asset's own LOD0 sphere, at scale 1, covers the 128 px atlas — and the placement's own scale is
738
+ // applied per placement at selection (`levelAtGates`). A placement scaled 8-12x therefore reaches
739
+ // the atlas 8-12x as far instead of switching at the unit-scale distance. There is no fixed
740
+ // margin: `levelAtGates` floors the terminal one representable Float32 step past the last source
741
+ // gate, so the source level keeps a window while the ordering survives the f32 store.
742
+ const switchAt =
743
+ asset.definition.impostorDistance ??
744
+ (2 * record.radius * this.#autoLodPixelsPerUnit) / IMPOSTOR_FRAME_PIXELS;
745
+ if (!Number.isFinite(switchAt) || switchAt <= 0) {
746
+ surface.dispose();
747
+ return;
748
+ }
749
+ const part: IAssetPart = {
750
+ geometry: surface.geometry,
751
+ local: new Matrix4(),
752
+ material: surface.material,
753
+ surface: "",
754
+ };
755
+ asset.levels = [...asset.levels, [part]];
756
+ asset.distances = [...asset.distances, switchAt];
757
+ asset.gates = [...asset.gates, switchAt];
758
+ this.#host.noteGate(switchAt);
759
+ asset.threshold = asset.gates.length === 0 ? undefined : Math.min(...asset.gates);
760
+ asset.impostor = { part, record, surface };
761
+ record.users += 1;
762
+ // The terminal key is part of the same load-time prewarm as the authored levels. Do this before
763
+ // building the far aggregate and before a far-only source is released: either path can bypass
764
+ // `terminalLevelReady`, which owns only resident/GPU publication after this semantic prewarm.
765
+ this.#host.terminalPrewarm(asset);
766
+ // The whole-map far aggregate for this atlas key, before the rebuild loop below: its segments
767
+ // exist when the swaps land, and any run already near-ready is handed over immediately. A budget
768
+ // refusal keeps only the far cohort's metadata and surface in `#farRetry`; see `#buildFar`.
769
+ if (!this.#preserveAuthoredParts || asset.definition.impostorDistance !== undefined)
770
+ this.#buildFar(asset, record);
771
+ this.#reportImpostor(asset, "ready");
772
+ // A far-only asset has no near batches or casters to hand over; once its aggregate is up its
773
+ // temporary source has done its job and goes, while the atlas the aggregate borrows stays. A
774
+ // refusal releases the source too — the deferred cohort in `#farRetry` holds only metadata and a
775
+ // surface, never the GLB — so a far species that cannot fit is not kept alive wholesale.
776
+ if (this.#farTemp.has(asset.id)) {
777
+ this.releaseFarTemp(asset.id);
778
+ return;
779
+ }
780
+ // The far casters of the levels that were already built: part 0's key is re-pointed at the one
781
+ // whole-asset shape, and the per-part keys the terminal level has no counterpart for are dropped,
782
+ // so the far shadow draws one quad per placement rather than a duplicate per bark/needle part.
783
+ if (!this.#preserveAuthoredParts) this.#host.retargetWideCasters(asset);
784
+ // The terminal level's keys and every resident run of this asset, through the same prewarm and
785
+ // swap the first build took: no active job array is mutated halfway.
786
+ this.#host.terminalLevelReady(asset);
787
+ }
788
+
789
+ /**
790
+ * The whole-map far aggregate for one exact atlas cache key: every ORIGINAL placement root of every
791
+ * canonical asset that bakes to that key, in one `InstancedMesh`, independent of the near ring and
792
+ * of the near source GLBs.
793
+ *
794
+ * One aggregate per EXACT atlas key, never one per `maxDistance`: a shared atlas can back assets
795
+ * with different authored cutoffs, and each placement's own value rides the instance buffer (see
796
+ * {@link IFarSegment.cull}) rather than splitting the key into a second aggregate — the exact key
797
+ * is what the atlas cache already bounds, and a split would build a second surface for one atlas.
798
+ * The first asset to bake a key builds the aggregate's own surface and instance buffer; a later
799
+ * canonical asset that shares the key appends its own runs to the same mesh, growing the buffer at
800
+ * most once per asset. A key already carrying every one of this asset's runs is left untouched, so
801
+ * re-adopting an asset from the cached atlas after its near source was released rebuilds nothing.
802
+ * Never `part.local`: the atlas bakes each part's own transform, so the far quad is the placement
803
+ * root alone.
804
+ */
805
+ #buildFar(asset: IAssetState, record: IImpostorRecord): boolean {
806
+ const parts = asset.levels[0];
807
+ const source = parts === undefined ? undefined : this.#impostorSource(parts);
808
+ if (parts === undefined || source === undefined) return false;
809
+ // Every run this asset owns anywhere in the map: the far half covers the whole map, not the ring.
810
+ const runs = this.#farRuns(asset.id);
811
+ if (runs.length === 0) return true;
812
+ const cull = cullDistance(asset.definition.maxDistance) ?? Number.POSITIVE_INFINITY;
813
+ if (!this.#farReaches(cull, asset.id)) {
814
+ this.#dropFarRetry(asset.id);
815
+ return true;
816
+ }
817
+ return this.#buildFarCohort({
818
+ alphaTest: source.alphaTest,
819
+ cull,
820
+ id: asset.id,
821
+ key: record.key,
822
+ record,
823
+ runs,
824
+ source: source.source,
825
+ });
826
+ }
827
+
828
+ /**
829
+ * Whether an asset needs a whole-map far aggregate at all, which only one whose authored draw
830
+ * distance reaches past the near ring's guaranteed radius does.
831
+ *
832
+ * The ring keeps every cell within `ring * cellSize` of the follow point resident, so a run the
833
+ * far half owns is that far from the camera at the closest — and the far surface's own
834
+ * per-instance cull (`cullDistance(maxDistance)`) drops it there. An aggregate for a shorter
835
+ * asset could never draw a pixel while still costing its instance buffer, its atlas and a draw.
836
+ * UE ends grass at `EndCullDistance` with no far representation for the same reason
837
+ * (UE 5.8.3: Engine/Source/Runtime/Landscape/Classes/LandscapeGrassType.h:43-45).
838
+ *
839
+ * `impostorFar: "always"` is the named override; it reports every asset it keeps.
840
+ */
841
+ #farReaches(cull: number, id: string): boolean {
842
+ if (cull >= this.#nearRingRadius) return true;
843
+ if (this.#impostorFar !== "always") return false;
844
+ if (this.#farOverrideReported.has(id)) return true;
845
+ this.#farOverrideReported.add(id);
846
+ console.info(
847
+ `${WORLD_IMPOSTOR_FAR_MARKER} asset=${id} reason=override override=impostorFar ` +
848
+ `cull=${cull.toFixed(2)} nearRingRadius=${String(this.#nearRingRadius)}`,
849
+ );
850
+ return true;
851
+ }
852
+
853
+ /** Every run of one canonical asset anywhere in the map, the whole set a far aggregate holds. */
854
+ #farRuns(id: string): Array<{ cell: IWorldCell; run: IWorldRun }> {
855
+ const runs: Array<{ cell: IWorldCell; run: IWorldRun }> = [];
856
+ for (const held of this.#cells)
857
+ for (const run of held.runs) {
858
+ if (this.#host.canonical(run.asset) !== id || run.count <= 0) continue;
859
+ runs.push({ cell: held, run });
860
+ }
861
+ return runs;
862
+ }
863
+
864
+ /**
865
+ * Build or grow one far cohort's aggregate, or defer it against the hard budget.
866
+ *
867
+ * The budget check counts the growth transient, not the net new count: a grow allocates the new
868
+ * larger buffer while the old one is still alive, so the peak is the new buffer's size — the old
869
+ * buffer is already charged in `#farBytes`. See {@link #farBudgetRefuses}. A refusal is remembered
870
+ * as metadata plus a built surface, never the source GLB; see {@link #deferFar}.
871
+ */
872
+ #buildFarCohort(cohort: IFarCohort): boolean {
873
+ const key = cohort.key;
874
+ const aggregate = this.#far.get(key);
875
+ const missing =
876
+ aggregate === undefined
877
+ ? cohort.runs
878
+ : cohort.runs.filter((entry) => !(aggregate as IFarAggregate).segments.has(entry.run));
879
+ if (missing.length === 0) {
880
+ this.#dropFarRetry(cohort.id);
881
+ return true;
882
+ }
883
+ const extra = missing.reduce((total, entry) => total + entry.run.count, 0);
884
+ const peak = aggregate === undefined ? extra : (aggregate as IFarAggregate).capacity + extra;
885
+ if (this.#farBudgetRefuses(peak)) {
886
+ // Hard finite budget: say why rather than overrun it, and keep only the metadata the retry
887
+ // needs. Never the full source GLB; see `#deferFar`.
888
+ this.#reportFarBudget(key, cohort.id, extra);
889
+ this.#deferFar(cohort);
890
+ return false;
891
+ }
892
+ let built = aggregate as IFarAggregate | undefined;
893
+ const deferred = this.#farRetry.get(cohort.id);
894
+ // The surface actually drawn by the aggregate after this call. A new aggregate adopts the
895
+ // deferred surface; a grow reuses the aggregate's own and leaves the deferred one unused.
896
+ let usedSurface: WorldImpostorSurface | undefined;
897
+ if (built === undefined) {
898
+ usedSurface = deferred?.surface ?? this.#makeFarSurface(cohort);
899
+ if (usedSurface === undefined) return false;
900
+ built = {
901
+ capacity: extra,
902
+ key,
903
+ mesh: this.#newFarMesh(usedSurface, extra, cohort.id),
904
+ record: cohort.record,
905
+ segments: new Map<IWorldRun, IFarSegment>(),
906
+ surface: usedSurface,
907
+ uploads: 0,
908
+ };
909
+ cohort.record.users += 1;
910
+ this.#far.set(key, built);
911
+ this.#farInstances += extra;
912
+ this.#farBytes += extra * FAR_INSTANCE_BYTES;
913
+ } else {
914
+ this.#growFar(built, extra);
915
+ }
916
+ this.#dropFarRetry(cohort.id, usedSurface);
917
+ let at = this.#farAllocated(built);
918
+ for (const { cell: held, run } of missing) {
919
+ const segment: IFarSegment = {
920
+ cell: held,
921
+ count: run.count,
922
+ cull: cohort.cull,
923
+ live: true,
924
+ run,
925
+ start: at,
926
+ };
927
+ at += run.count;
928
+ built.segments.set(run, segment);
929
+ this.#farSegments.set(run, built);
930
+ this.#writeFarSegment(built, segment);
931
+ }
932
+ this.#syncFarSegments(built);
933
+ // The far half just gained records, so the shadow levels drawing the ground they stand on are
934
+ // stale; the same blanket tell a near swap makes. See `#shadowRecordsMoved`.
935
+ this.#host.shadowRecordsMoved();
936
+ if (!this.#farReported.has(key)) {
937
+ this.#farReported.add(key);
938
+ const split = this.#farSplit(built);
939
+ console.info(
940
+ `${WORLD_IMPOSTOR_FAR_MARKER} key=${key} asset=${cohort.id} ` +
941
+ `instances=${String(built.capacity)} live=${String(split.live)} ` +
942
+ `nearOwned=${String(split.nearOwned)} bytes=${String(built.capacity * FAR_INSTANCE_BYTES)} ` +
943
+ `uploads=${String(built.uploads)}`,
944
+ );
945
+ }
946
+ return true;
947
+ }
948
+
949
+ /** The aggregate's own far surface: the record's atlas, the cohort's material twin, per-instance cull. */
950
+ #makeFarSurface(cohort: IFarCohort): WorldImpostorSurface | undefined {
951
+ if (cohort.source === undefined) return undefined;
952
+ try {
953
+ return new WorldImpostorSurface({
954
+ alphaTest: cohort.alphaTest,
955
+ atlas: cohort.record.atlas,
956
+ center: cohort.record.center,
957
+ cull: true,
958
+ halfExtents: cohort.record.halfExtents,
959
+ radius: cohort.record.radius,
960
+ source: cohort.source,
961
+ });
962
+ } catch {
963
+ this.#host.addFailure();
964
+ return undefined;
965
+ }
966
+ }
967
+
968
+ /**
969
+ * Keep a refused far cohort as metadata alone: the atlas pinned by one borrowed user, the runs, and
970
+ * a built surface. The asset's own geometry and materials are released by the caller, so a refused
971
+ * far species never holds a full GLB alive; `#retryFar` rebuilds from this when a near release frees
972
+ * room. Idempotent: a repeat refusal keeps the surface already built.
973
+ */
974
+ #deferFar(cohort: IFarCohort): void {
975
+ if (this.#farRetry.has(cohort.id)) return;
976
+ const surface = this.#makeFarSurface(cohort);
977
+ if (surface === undefined) return;
978
+ cohort.record.users += 1;
979
+ this.#farRetry.set(cohort.id, {
980
+ alphaTest: cohort.alphaTest,
981
+ cull: cohort.cull,
982
+ id: cohort.id,
983
+ key: cohort.key,
984
+ record: cohort.record,
985
+ runs: cohort.runs,
986
+ surface,
987
+ });
988
+ }
989
+
990
+ /** Drop a deferred cohort, releasing its surface and the atlas user it pinned. */
991
+ #dropFarRetry(id: string, consumedSurface?: WorldImpostorSurface): void {
992
+ const entry = this.#farRetry.get(id);
993
+ if (entry === undefined) return;
994
+ this.#farRetry.delete(id);
995
+ if (consumedSurface !== entry.surface) entry.surface.dispose();
996
+ entry.record.users = Math.max(0, entry.record.users - 1);
997
+ this.#evictImpostors();
998
+ }
999
+
1000
+ /** Retry the far aggregates a full budget refused, when a near cell freed its allocation. */
1001
+ retryFar(): void {
1002
+ if (this.#farRetry.size === 0) return;
1003
+ for (const entry of [...this.#farRetry.values()]) this.#buildFarCohort(entry);
1004
+ }
1005
+
1006
+ /**
1007
+ * Adopt one far-only species per idle frame: a canonical asset the map places but no resident run
1008
+ * has asked for yet. Its LOD0 is loaded through the same limiter, classified by its actual
1009
+ * materials, baked on the same queue, and its source released once the aggregate lands. Gated on an
1010
+ * empty near queue so loading the unseen never delays the near ring or holds its overlay open.
1011
+ */
1012
+ pumpFarAcquisition(): void {
1013
+ if (this.#impostors === false || this.#host.released() || this.#farExhausted) return;
1014
+ if (this.#farCandidateIds.length === 0) return;
1015
+ // Near work first: a queued build, an in-flight near load, a bake in flight or waiting. Only a
1016
+ // settled frame spends itself on the unseen far half.
1017
+ if (
1018
+ this.#host.nearWorkPending() ||
1019
+ this.#impostorQueue.length > 0 ||
1020
+ this.#impostorBaking !== undefined
1021
+ )
1022
+ return;
1023
+ // The bake needs a renderer that can run it; acquiring before one exists would hold source GLBs
1024
+ // for a bake with no way to land. A renderer that is present but unsupported is the same answer.
1025
+ const renderer = this.#host.renderer();
1026
+ if (renderer === undefined || impostorRawRenderer(renderer) === undefined) return;
1027
+ const count = this.#farCandidateIds.length;
1028
+ for (let step = 0; step < count; step += 1) {
1029
+ const at = (this.#farCursor + step) % count;
1030
+ const id = this.#farCandidateIds[at] as string;
1031
+ if (this.#farSeen.has(id) || this.#host.hasAsset(id) || this.#farRetry.has(id)) continue;
1032
+ this.#farCursor = (at + 1) % count;
1033
+ const definition = this.#manifest.assets[id];
1034
+ // A species that can only ever draw inside the ring needs no aggregate, so nothing of it is
1035
+ // loaded or baked either: the save is the atlas and the source GLB, not just the draw.
1036
+ if (
1037
+ definition === undefined ||
1038
+ !this.#farReaches(cullDistance(definition.maxDistance) ?? Number.POSITIVE_INFINITY, id)
1039
+ ) {
1040
+ this.#farSeen.add(id);
1041
+ continue;
1042
+ }
1043
+ const asset = this.#host.newAsset(id, definition);
1044
+ asset.refcount += 1;
1045
+ this.#farTemp.add(id);
1046
+ this.#host.startAssetLoad(asset);
1047
+ return;
1048
+ }
1049
+ // A full pass with nothing startable means every species is either baked, held for a retry, or
1050
+ // classified as having no atlas. Static placements add none later, so the scan stops here.
1051
+ this.#farExhausted = true;
1052
+ }
1053
+
1054
+ /**
1055
+ * Drop a far-only asset's temporary reference once its atlas is held by an aggregate or has been
1056
+ * deferred. The deferred cohort keeps its own pinned atlas user, so it is not dropped here.
1057
+ */
1058
+ releaseFarTemp(id: string): void {
1059
+ this.#farTemp.delete(id);
1060
+ this.#farSeen.add(id);
1061
+ this.#host.release(id);
1062
+ }
1063
+
1064
+ /**
1065
+ * Whether an incoming far allocation would overrun the world's instance or byte budget.
1066
+ *
1067
+ * `count` is the peak, not the net: a grow allocates the new larger buffer while the old one is
1068
+ * still alive, so the caller passes the new buffer's full size — the old buffer is already inside
1069
+ * `#farInstances`/`#farBytes`. A net-new count would understate the transient a resize holds.
1070
+ */
1071
+ #farBudgetRefuses(count: number): boolean {
1072
+ return (
1073
+ this.#host.residency().instances + this.#farInstances + count > this.#budgets.instances ||
1074
+ this.#host.residency().bytes +
1075
+ this.#farBytes +
1076
+ this.#host.residency().hlodBytes +
1077
+ count * FAR_INSTANCE_BYTES >
1078
+ this.#budgets.bytes
1079
+ );
1080
+ }
1081
+
1082
+ /** One bounded line for a far aggregate the world's own budgets refused, once per atlas key. */
1083
+ #reportFarBudget(key: string, assetId: string, count: number): void {
1084
+ if (this.#farReported.has(key)) return;
1085
+ this.#farReported.add(key);
1086
+ console.info(
1087
+ `${WORLD_IMPOSTOR_FAR_MARKER} key=${key} asset=${assetId} ` +
1088
+ `instances=${String(count)} reason=budget`,
1089
+ );
1090
+ }
1091
+
1092
+ /**
1093
+ * One far mesh: the whole-asset quad, every original root, drawn regardless of how far the camera
1094
+ * resolves it. `frustumCulled = false` is what keeps the draw: the projected-size gate exempts it
1095
+ * before it ever reads bounds, so no `alwaysRender` marker is needed when a game configured no
1096
+ * shadows to exempt it under `renderer.minimumProjectedPixels`. The per-placement cull rides the
1097
+ * geometry's instance attribute, one static value per placement; see
1098
+ * {@link IMPOSTOR_FAR_CULL_ATTRIBUTE}.
1099
+ */
1100
+ #newFarMesh(surface: WorldImpostorSurface, capacity: number, assetId: string): InstancedMesh {
1101
+ const mesh = new InstancedMesh(surface.geometry, surface.material, capacity);
1102
+ mesh.count = capacity;
1103
+ mesh.frustumCulled = false;
1104
+ // Every nearer draw occludes the far tier, so it draws after them and depth rejects its hidden
1105
+ // quads. three sorts opaques front to back anyway; the owned engine orders a pass's rows by state
1106
+ // with no depth prepass, where drawn first the far quads shaded every pixel the trees then covered
1107
+ // (UE 5.8.3: Engine/Source/Runtime/Renderer/Private/BasePassRendering.cpp:333-341 orders by
1108
+ // occlusion class for the same reason when there is no early-Z pass).
1109
+ mesh.renderOrder = 1;
1110
+ // Three's default usage uploads by version; grow/write/zero announce every matrix change through
1111
+ // needsUpdate. DynamicDrawUsage would upload the same whole-map buffer on every settled draw.
1112
+ mesh.name = `tn-far:${assetId}`;
1113
+ // Drawn on layer 0, so this is a main-pass draw the frame budget counts under the impostor
1114
+ // aggregate's own source rather than under `other` (`RenderPassBudget`).
1115
+ mesh.userData.tnDrawSource = "proxies";
1116
+ if (surface.cull) this.#attachFarCull(surface.geometry, capacity);
1117
+ // Far trees cast like near ones, into the coarse wide caster layer. The same mesh draws the main
1118
+ // pass (layer 0) and the virtual-shadow levels (wide layer), so one representation covers both
1119
+ // and a run hands its far segment over to the near ring exactly once; see `#disableFar`. The
1120
+ // per-asset maxDistance gate is a main-pass shader gate, so the shadow half still reaches the map.
1121
+ if (this.#castShadowLevels > 0) {
1122
+ mesh.layers.enable(VIRTUAL_SHADOW_WIDE_CASTER_LAYER);
1123
+ mesh.castShadow = true;
1124
+ }
1125
+ mesh.receiveShadow = this.#receiveShadow;
1126
+ this.#host.add(mesh);
1127
+ return mesh;
1128
+ }
1129
+
1130
+ /** Install a fresh per-instance cull buffer on the aggregate's shared geometry, all gates open. */
1131
+ #attachFarCull(geometry: BufferGeometry, capacity: number): void {
1132
+ geometry.setAttribute(
1133
+ IMPOSTOR_FAR_CULL_ATTRIBUTE,
1134
+ new InstancedBufferAttribute(new Float32Array(capacity).fill(Number.POSITIVE_INFINITY), 1),
1135
+ );
1136
+ }
1137
+
1138
+ /** Append `extra` instance slots to an aggregate, one mesh swap, charged to the budgets. */
1139
+ #growFar(aggregate: IFarAggregate, extra: number): void {
1140
+ const old = aggregate.mesh;
1141
+ const capacity = aggregate.capacity + extra;
1142
+ // Capture the cull values before the replacement mesh attaches a fresh buffer to the SHARED
1143
+ // geometry; the old attribute object is replaced in place there.
1144
+ const oldCull = aggregate.surface.cull
1145
+ ? (
1146
+ aggregate.surface.geometry.getAttribute(IMPOSTOR_FAR_CULL_ATTRIBUTE)?.array as
1147
+ | Float32Array
1148
+ | undefined
1149
+ )?.slice(0, aggregate.capacity)
1150
+ : undefined;
1151
+ const next = this.#newFarMesh(aggregate.surface, capacity, old.name.replace(/^tn-far:/u, ""));
1152
+ (next.instanceMatrix.array as Float32Array).set(
1153
+ (old.instanceMatrix.array as Float32Array).subarray(0, aggregate.capacity * 16),
1154
+ );
1155
+ next.instanceMatrix.needsUpdate = true;
1156
+ if (oldCull !== undefined) {
1157
+ const attribute = next.geometry.getAttribute(IMPOSTOR_FAR_CULL_ATTRIBUTE) as
1158
+ | InstancedBufferAttribute
1159
+ | undefined;
1160
+ if (attribute !== undefined) (attribute.array as Float32Array).set(oldCull, 0);
1161
+ }
1162
+ this.#host.remove(old);
1163
+ old.dispose();
1164
+ aggregate.mesh = next;
1165
+ aggregate.capacity = capacity;
1166
+ aggregate.uploads += 1;
1167
+ this.#farInstances += extra;
1168
+ this.#farBytes += extra * FAR_INSTANCE_BYTES;
1169
+ }
1170
+
1171
+ /** Slots allocated in an aggregate: the sum of its segment counts, the offset the next one takes. */
1172
+ #farAllocated(aggregate: IFarAggregate): number {
1173
+ let at = 0;
1174
+ for (const segment of aggregate.segments.values()) at += segment.count;
1175
+ return at;
1176
+ }
1177
+
1178
+ /** Compose one run's ORIGINAL placement roots into its segment, exactly as `#addPlacements` does. */
1179
+ #writeFarSegment(aggregate: IFarAggregate, segment: IFarSegment): void {
1180
+ const records = cellPlacements(this.#placements, segment.run);
1181
+ const array = aggregate.mesh.instanceMatrix.array as Float32Array;
1182
+ const base = segment.start * 16;
1183
+ for (let index = 0; index < segment.count; index += 1) {
1184
+ const at = index * PLACEMENT_RECORD_FLOATS;
1185
+ this.#position.set(
1186
+ records[at] as number,
1187
+ records[at + 1] as number,
1188
+ records[at + 2] as number,
1189
+ );
1190
+ this.#rotation.set(
1191
+ records[at + 3] as number,
1192
+ records[at + 4] as number,
1193
+ records[at + 5] as number,
1194
+ records[at + 6] as number,
1195
+ );
1196
+ this.#scale.setScalar(records[at + 7] as number);
1197
+ this.#matrix.compose(this.#position, this.#rotation, this.#scale);
1198
+ this.#matrix.toArray(array, base + index * 16);
1199
+ }
1200
+ aggregate.mesh.instanceMatrix.needsUpdate = true;
1201
+ // The per-placement gate is static, so it is written with the matrices and re-uploaded only when
1202
+ // a handoff rewrites this segment. A whole-map surface reads it so every canonical asset keeps
1203
+ // its own authored cutoff over the shared atlas. See {@link IFarSegment.cull}.
1204
+ const cull = aggregate.mesh.geometry.getAttribute(IMPOSTOR_FAR_CULL_ATTRIBUTE) as
1205
+ | InstancedBufferAttribute
1206
+ | undefined;
1207
+ if (cull !== undefined) {
1208
+ (cull.array as Float32Array).fill(segment.cull, segment.start, segment.start + segment.count);
1209
+ cull.needsUpdate = true;
1210
+ }
1211
+ aggregate.uploads += 1;
1212
+ this.#farBoundsStale(aggregate);
1213
+ }
1214
+
1215
+ /**
1216
+ * Zero one segment's records: the run is drawn by the near ring now, not the far mesh. Each record
1217
+ * keeps a homogeneous `w` of 1 while its xyz/scale terms collapse to 0, so the instance projects
1218
+ * to the origin and draws nothing. An all-zero record would leave `w = 0`, and Three's
1219
+ * `Box3.applyMatrix4` divides by it, so `computeBoundingBox` over the shared buffer would return
1220
+ * NaN and every caster in the aggregate would be dropped by the shadow levels.
1221
+ */
1222
+ #zeroFarSegment(aggregate: IFarAggregate, segment: IFarSegment): void {
1223
+ const array = aggregate.mesh.instanceMatrix.array as Float32Array;
1224
+ const from = segment.start * 16;
1225
+ const to = (segment.start + segment.count) * 16;
1226
+ array.fill(0, from, to);
1227
+ for (let at = from; at < to; at += 16) array[at + 15] = 1;
1228
+ aggregate.mesh.instanceMatrix.needsUpdate = true;
1229
+ aggregate.uploads += 1;
1230
+ this.#farBoundsStale(aggregate);
1231
+ }
1232
+
1233
+ /**
1234
+ * A far matrix write changes the mesh's instance extent, so drop the cached pair and let Three
1235
+ * rebuild it on the next read; this is the native `null` convention `computeBoundingBox` honors.
1236
+ */
1237
+ #farBoundsStale(aggregate: IFarAggregate): void {
1238
+ aggregate.mesh.boundingBox = null;
1239
+ aggregate.mesh.boundingSphere = null;
1240
+ }
1241
+
1242
+ /** The near ring has attached this run's full representation; the far mesh stops drawing it. */
1243
+ disableFar(run: IWorldRun): void {
1244
+ const aggregate = this.#farSegments.get(run);
1245
+ if (aggregate === undefined) return;
1246
+ const segment = aggregate.segments.get(run);
1247
+ if (segment === undefined || segment.live === false) return;
1248
+ this.#zeroFarSegment(aggregate, segment);
1249
+ segment.live = false;
1250
+ }
1251
+
1252
+ /** This run is leaving the ring; the far mesh draws it again before the near batches are cleared. */
1253
+ restoreFar(run: IWorldRun): void {
1254
+ const aggregate = this.#farSegments.get(run);
1255
+ if (aggregate === undefined) return;
1256
+ const segment = aggregate.segments.get(run);
1257
+ if (segment === undefined || segment.live === true) return;
1258
+ this.#writeFarSegment(aggregate, segment);
1259
+ segment.live = true;
1260
+ }
1261
+
1262
+ /**
1263
+ * Hand over every run of an aggregate a resident cell already draws. A run is near-ready exactly
1264
+ * when the cell holds one of its batches; the whole job is attached in one swap, so presence is the
1265
+ * answer. This is the build-time half of the atomic handoff; `#swap` is the per-frame half.
1266
+ */
1267
+ #syncFarSegments(aggregate: IFarAggregate): void {
1268
+ for (const segment of aggregate.segments.values()) {
1269
+ if (segment.live === false) continue;
1270
+ const resident = this.#host.residentCell(cellKey(segment.cell.x, segment.cell.z));
1271
+ if (resident === undefined) continue;
1272
+ if (!resident.batches.some((entry) => entry.run === segment.run)) continue;
1273
+ this.#zeroFarSegment(aggregate, segment);
1274
+ segment.live = false;
1275
+ }
1276
+ }
1277
+
1278
+ /** An aggregate's live and near-owned instance counts. */
1279
+ #farSplit(aggregate: IFarAggregate): { live: number; nearOwned: number } {
1280
+ let live = 0;
1281
+ let nearOwned = 0;
1282
+ for (const segment of aggregate.segments.values()) {
1283
+ if (segment.live) live += segment.count;
1284
+ else nearOwned += segment.count;
1285
+ }
1286
+ return { live, nearOwned };
1287
+ }
1288
+
1289
+ /** The far block {@link stats} reports: aggregates, physical instances/bytes and their split. */
1290
+ #farStats(): IWorldCellsStats["impostor"]["far"] {
1291
+ let instances = 0;
1292
+ let live = 0;
1293
+ let nearOwned = 0;
1294
+ let uploads = 0;
1295
+ for (const aggregate of this.#far.values()) {
1296
+ instances += aggregate.capacity;
1297
+ uploads += aggregate.uploads;
1298
+ const split = this.#farSplit(aggregate);
1299
+ live += split.live;
1300
+ nearOwned += split.nearOwned;
1301
+ }
1302
+ return {
1303
+ aggregates: this.#far.size,
1304
+ bytes: this.#farBytes,
1305
+ instances,
1306
+ live,
1307
+ nearOwned,
1308
+ uploads,
1309
+ };
1310
+ }
1311
+
1312
+ /** Dispose every far aggregate: its own mesh and surface, and its borrowed atlas user. */
1313
+ #drainFar(): void {
1314
+ for (const aggregate of this.#far.values()) {
1315
+ aggregate.mesh.removeFromParent();
1316
+ aggregate.mesh.dispose();
1317
+ aggregate.surface.dispose();
1318
+ aggregate.record.users = Math.max(0, aggregate.record.users - 1);
1319
+ }
1320
+ this.#far.clear();
1321
+ this.#farSegments.clear();
1322
+ this.#farInstances = 0;
1323
+ this.#farBytes = 0;
1324
+ }
1325
+
1326
+ /** Retry the handoffs a frame's fresh-mesh allowance deferred; one bounded pass per update. */
1327
+ retryWide(): void {
1328
+ if (this.#wideRetry.size === 0) return;
1329
+ const ids = [...this.#wideRetry];
1330
+ this.#wideRetry.clear();
1331
+ for (const id of ids) {
1332
+ const asset = this.#host.asset(id);
1333
+ if (asset === undefined || asset.impostor === undefined) continue;
1334
+ this.#host.retargetWideCasters(asset);
1335
+ }
1336
+ }
1337
+
1338
+ /** The impostor block {@link stats} reports: assets landed, bakes pending, atlas bytes, terminal tris. */
1339
+ impostorStats(): IWorldCellsStats["impostor"] {
1340
+ let assets = 0;
1341
+ let terminalTriangles = 0;
1342
+ for (const asset of this.#host.assets()) {
1343
+ if (asset.impostor === undefined) continue;
1344
+ assets += 1;
1345
+ terminalTriangles += levelTriangles(asset.impostor.part.geometry);
1346
+ }
1347
+ return {
1348
+ assets,
1349
+ atlasBytes: this.#impostorRecordBytes,
1350
+ budgetBytes: this.#impostorBudgetBytes,
1351
+ drawn: this.#host.drawnImpostorInstances() + this.#farStats().live,
1352
+ far: this.#farStats(),
1353
+ pending: this.#impostorQueue.length + (this.#impostorBaking === undefined ? 0 : 1),
1354
+ terminalTriangles,
1355
+ };
1356
+ }
1357
+
1358
+ /** Drop queued/baking work for an asset whose source geometry is about to be released. */
1359
+ cancelImpostor(asset: IAssetState): void {
1360
+ this.#impostorQueued.delete(asset.id);
1361
+ const at = this.#impostorQueue.indexOf(asset);
1362
+ if (at >= 0) this.#impostorQueue.splice(at, 1);
1363
+ if (this.#impostorBaking === asset) {
1364
+ // Before the borrowed source geometry is released: the baker stages it, and a view drawn after
1365
+ // the teardown reads a disposed buffer.
1366
+ this.#baker.abort();
1367
+ this.#impostorBaking = undefined;
1368
+ this.#impostorReservedBytes = 0;
1369
+ }
1370
+ }
1371
+
1372
+ /** Release an asset's terminal level and give its atlas back to the cache; see `#release`. */
1373
+ releaseImpostor(asset: IAssetState): void {
1374
+ const impostor = asset.impostor;
1375
+ if (impostor === undefined) return;
1376
+ asset.impostor = undefined;
1377
+ // Marked first, so `#releaseParts` skips the part whose geometry and material the surface owns.
1378
+ this.#host.markReleasedPart(impostor.part);
1379
+ dropPooledFor(impostor.part.geometry, impostor.part.material);
1380
+ impostor.surface.dispose();
1381
+ impostor.record.users = Math.max(0, impostor.record.users - 1);
1382
+ this.#evictImpostors();
1383
+ }
1384
+
1385
+ /**
1386
+ * Drop the oldest inactive atlases until the cache is back under budget; active ones are kept.
1387
+ *
1388
+ * `reserve` is the declared bytes of a bake about to start: the caller asks whether evicting
1389
+ * inactive records can make room for it. A record with a live user is never dropped, so a full
1390
+ * cache of active atlases simply leaves the reservation unmet and the caller refuses the bake.
1391
+ */
1392
+ #evictImpostors(reserve = 0): void {
1393
+ if (this.#impostorRecordBytes + reserve <= this.#impostorBudgetBytes) return;
1394
+ for (const [key, record] of [...this.#impostorRecords]) {
1395
+ if (this.#impostorRecordBytes + reserve <= this.#impostorBudgetBytes) break;
1396
+ if (record.users > 0) continue;
1397
+ this.#impostorRecords.delete(key);
1398
+ this.#impostorRecordBytes -= record.bytes;
1399
+ record.atlas.dispose();
1400
+ }
1401
+ }
1402
+
1403
+ /** Dispose every cached atlas and any in-flight bake; the world's teardown path calls it once. */
1404
+ drainImpostors(): void {
1405
+ // Far-only sources no cell run owns would otherwise never reach `#evict`; release them here so
1406
+ // their geometry goes the way every near asset's does.
1407
+ for (const id of [...this.#farTemp]) this.#host.release(id);
1408
+ this.#farTemp.clear();
1409
+ // Deferred far cohorts own a surface and pin an atlas user; release both before the records are
1410
+ // disposed below, so no surface is left pointing at a disposed atlas.
1411
+ for (const entry of this.#farRetry.values()) {
1412
+ entry.surface.dispose();
1413
+ entry.record.users = Math.max(0, entry.record.users - 1);
1414
+ }
1415
+ this.#farRetry.clear();
1416
+ this.#farSeen.clear();
1417
+ // The far aggregates own surfaces over these atlases and hold a user on their records; they go
1418
+ // first, so no far surface is left pointing at an atlas disposed below it.
1419
+ this.#drainFar();
1420
+ this.#impostorQueue.length = 0;
1421
+ this.#impostorQueued.clear();
1422
+ this.#impostorBaking = undefined;
1423
+ this.#impostorReservedBytes = 0;
1424
+ this.#baker.dispose();
1425
+ for (const record of this.#impostorRecords.values()) record.atlas.dispose();
1426
+ this.#impostorRecords.clear();
1427
+ this.#impostorRecordBytes = 0;
1428
+ }
1429
+
1430
+ /**
1431
+ * `TN_WORLD_IMPOSTOR`, one bounded line per asset: its terminal level, the metres it takes over at,
1432
+ * the views the atlas holds, its GPU bytes, and — when the world can name it — why it did not land.
1433
+ */
1434
+ /** One line per asset; a failure carries its error, so the cause is on the line and not swallowed. */
1435
+ #reportImpostor(asset: IAssetState, reason: string, error?: unknown): void {
1436
+ if (this.#impostorReported.has(asset.id)) return;
1437
+ this.#impostorReported.add(asset.id);
1438
+ const impostor = asset.impostor;
1439
+ const atlas = impostor?.record.atlas ?? this.#baker.pending?.atlas;
1440
+ console.info(
1441
+ `${WORLD_IMPOSTOR_MARKER} asset=${asset.id} level=${String(asset.levels.length - 1)} ` +
1442
+ `switch=${(asset.distances.at(-1) ?? 0).toFixed(1)} ` +
1443
+ `views=${String(atlas === undefined ? 0 : IMPOSTOR_VIEWS)} ` +
1444
+ `bytes=${String(atlas?.bytes ?? 0)} reason=${reason}` +
1445
+ `${error === undefined ? "" : ` error=${error instanceof Error ? error.message : String(error)}`}`,
1446
+ );
1447
+ }
1448
+ }
1449
+
1450
+ export const PLACEMENT_RECORD_BYTES = 32;
1451
+
1452
+ export const PLACEMENT_RECORD_FLOATS = 8;
1453
+
1454
+ /**
1455
+ * The distance a `maxDistance` prop actually culls at, one eighth short of itself: the slack
1456
+ * `#addPlacements` leaves, so a follow point that has not moved a whole eighth of the cull distance
1457
+ * cannot have culled a placement it had not already culled.
1458
+ */
1459
+ export function cullDistance(maxDistance: number | undefined): number | undefined {
1460
+ return maxDistance === undefined ? undefined : maxDistance - maxDistance / 8;
1461
+ }