@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
package/dist/world.d.ts CHANGED
@@ -1,8 +1,8 @@
1
- import { Object3D, Mesh, LOD, Vector3, Group, BufferGeometry } from 'three';
2
- import { I as IComputeDriven, a as IGPUReadbackSample } from './gpu-readback-CMklJs6r.js';
3
- import { I as IRendererLike } from './renderer-Cy4qeBOA.js';
4
- import { I as IAssetLoader } from './assets-CYKk2WTu.js';
5
- import 'three/webgpu';
1
+ import { Object3D, Mesh, LOD, Vector3, Camera, Material, Group, BufferGeometry } from 'three';
2
+ import { I as IComputeDriven, a as ILodView, b as IModelLodPolicy, c as IGPUReadbackSample } from './model-lod-BDAUYgsS.js';
3
+ import { I as IRendererLike } from './renderer-9yEo9hPa.js';
4
+ import { I as IAssetLoader } from './assets-CqvE429w.js';
5
+ import { Node } from 'three/webgpu';
6
6
 
7
7
  interface IWorldErosionOptions {
8
8
  readonly depositionRate: number;
@@ -25,9 +25,27 @@ interface IWorldTileColliderInput {
25
25
  readonly tileX: number;
26
26
  readonly tileZ: number;
27
27
  }
28
+ /**
29
+ * One frame's allowance for admission work — the millisecond budget every path that puts streamed
30
+ * content on screen draws on, spent in bounded units rather than in one lump.
31
+ *
32
+ * `admit` is the whole contract: run one unit and charge the frame for it, or report that there was
33
+ * no room and run nothing. A caller that is refused leaves the work for a later frame instead of
34
+ * dropping it, so the budget decides *when* content is admitted, never *whether*.
35
+ *
36
+ * Nothing here decides what anything looks like; it decides only how much of it a frame may pay for.
37
+ */
38
+ interface IAdmissionBudget {
39
+ /**
40
+ * Run one unit of admission work, charging the frame's budget for it. `false` means the budget
41
+ * was spent and `work` was never called, so the caller must stop and resume on a later frame.
42
+ */
43
+ admit(work: () => void): boolean;
44
+ }
28
45
  interface IWorldTile {
29
46
  readonly bytes: number;
30
- readonly collider: IWorldTileCollider;
47
+ /** `undefined` for a resident tile outside `colliderRadius`, or when no factory was given. */
48
+ readonly collider: IWorldTileCollider | undefined;
31
49
  readonly field: Heightfield;
32
50
  readonly key: string;
33
51
  readonly lod: LOD;
@@ -41,6 +59,9 @@ interface IWorldTilesFollowPosition {
41
59
  readonly x: number;
42
60
  readonly z: number;
43
61
  }
62
+ /** Actual render view and the resolved model LOD policy; distance floors still apply. */
63
+ interface IWorldTilesLodView extends Pick<ILodView, "camera" | "viewportHeight">, IModelLodPolicy {
64
+ }
44
65
  interface IWorldTilesTopologyObservation {
45
66
  readonly columns: number;
46
67
  readonly depth: number;
@@ -53,6 +74,14 @@ interface IWorldTilesOptions {
53
74
  readonly assets?: Pick<IAssetLoader, "release">;
54
75
  /** A game-owned, already-loaded logical model key, or a key resolver per tile. */
55
76
  readonly assetKey?: string | ((tileX: number, tileZ: number) => string);
77
+ /**
78
+ * Chebyshev radius, in tiles from the followed one, that gets a `createCollider` body. Defaults
79
+ * to `streamRadius`, so every resident tile collides. A smaller radius keeps a wide render ring
80
+ * cheap to simulate: a tile crossing the radius has its collider created or disposed as it goes.
81
+ */
82
+ readonly colliderRadius?: number;
83
+ /** Terrain tiles and seam bridges receive the scene's shadows. Default false. */
84
+ readonly receiveShadow?: boolean;
56
85
  /** Creates the physics body from the field's explicit collider-order copy. */
57
86
  readonly createCollider?: (input: IWorldTileColliderInput) => IWorldTileCollider;
58
87
  /** TSL pass options are game supplied and are forwarded to each resident field. */
@@ -70,8 +99,26 @@ interface IWorldTilesOptions {
70
99
  readonly tileSize: number;
71
100
  /** Vertex decimation factors. Defaults to 1, 2, and 4 over the same field. */
72
101
  readonly lodFactors?: readonly number[];
73
- /** Distances in world units at which the next LOD becomes active. */
102
+ /** Nearest world-unit distances at which the next LOD may become active; screen error may delay it. */
74
103
  readonly lodDistances?: readonly number[];
104
+ /**
105
+ * Re-derive the terrain every frame and assert it: a finiteness scan of every rendered vertex,
106
+ * a seam measurement per resident pair and an LOD pop sample per blending tile. Off by default
107
+ * because it is a measurement and it cost ~270 ms over a six-second walk on a 289-tile ring.
108
+ * `TN_TERRAIN_VALIDATE=1` or `?tnTerrainValidate=1` turns it on for a run; this overrides that.
109
+ */
110
+ readonly validate?: boolean;
111
+ /**
112
+ * Merge settled same-LOD terrain tiles into super-tiles: one mesh per K×K block, one block rebuilt
113
+ * per frame. It changes how many draws the main pass submits, never how the ground looks — a merged
114
+ * vertex lands on the world position its tile's vertex did, on the same game-owned `surface`.
115
+ *
116
+ * On by default, like `validate`'s measurements are off by default only because they cost a
117
+ * measurement a frame. `mergeTiles: false`, `?tnTerrainMerge=0` or `TN_TERRAIN_MERGE=0` turns it
118
+ * off for a run. A block's bytes are reported as `terrainTiles.blockBytes` and are never charged to
119
+ * `residentByteBudget`, so the merge changes draws and no tile the budget would admit without it.
120
+ */
121
+ readonly mergeTiles?: boolean;
75
122
  /** Explicit game-owned measurement region used by the topology evaluator. */
76
123
  readonly topologyObservation?: IWorldTilesTopologyObservation;
77
124
  }
@@ -86,7 +133,8 @@ interface IWorldTilesOptions {
86
133
  * @alias stream terrain across chunks
87
134
  * @constraint sampleHeight and surface are required game choices; no landform or surface preset is installed
88
135
  * @constraint residentTileBudget and residentByteBudget are hard caps; a tile that cannot fit throws
89
- * @override tileSize, tileResolution, lodFactors, lodDistances, skirtDepth, streamRadius, and budgets
136
+ * @constraint seam gap, LOD pop and the rendered-vertex finiteness scan are measurements that are off by default; TN_TERRAIN_VALIDATE=1, ?tnTerrainValidate=1 or validate: true runs them, and maxSeamGap, maxVisualSeamGap and maxLodPop report undefined while they are off
137
+ * @override tileSize, tileResolution, lodFactors, lodDistances, skirtDepth, streamRadius, colliderRadius, mergeTiles, validate, and budgets
90
138
  * @example const tiles = new TerrainTiles({ sampleHeight, surface: gameSurface(), tileSize: 256, tileResolution: 129, residentTileBudget: 25, residentByteBudget: 32_000_000 });
91
139
  */
92
140
  declare class TerrainTiles extends Object3D implements IComputeDriven {
@@ -98,8 +146,23 @@ declare class TerrainTiles extends Object3D implements IComputeDriven {
98
146
  readonly tileSize: number;
99
147
  readonly processCadence: "render";
100
148
  constructor(options: IWorldTilesOptions);
149
+ /** Fresh residency and colliders; retain the visible tree until follow() regenerates it. */
150
+ clone(recursive?: boolean): this;
101
151
  get released(): boolean;
102
152
  get residentTileCount(): number;
153
+ /**
154
+ * Every retained terrain byte, against `residentByteBudget`: the resident tiles with their levels
155
+ * and edge samples, the stitch bridges, and the retained topology.
156
+ *
157
+ * A merged super-tile is deliberately absent. A block duplicates the level vertices of the tiles it
158
+ * covers, and those tiles stay resident because a tile that leaves the block draws its own mesh
159
+ * again — so charging the copy made a derived artefact evict real terrain detail out of the same
160
+ * budget the tiles were admitted against, and a budget sized for unmerged terrain held fewer tiles
161
+ * with the merge on. The copy is reported as `terrainTiles.blockBytes` instead. (PRD-475.)
162
+ *
163
+ * ponytail: terrain geometry costs up to ~2x while merged; free the per-tile GPU buffers behind a
164
+ * block (keep the height field for queries) if that memory ever matters.
165
+ */
103
166
  get residentBytes(): number;
104
167
  get peakResidentTileCount(): number;
105
168
  get peakResidentBytes(): number;
@@ -107,29 +170,115 @@ declare class TerrainTiles extends Object3D implements IComputeDriven {
107
170
  get residentColliderKeys(): readonly string[];
108
171
  get lodLevelCount(): number;
109
172
  get lodTransitions(): number;
110
- /** Maximum per-render-frame displacement of the visible LOD surface during transitions. */
111
- get maxLodPop(): number;
173
+ /**
174
+ * What the main pass submits for terrain levels right now: `tiles` surfaces, held as `blocks`
175
+ * merged super-tiles plus one mesh each for the tiles that are not merged (a lone block member or
176
+ * a tile mid LOD morph). `draws` is `blocks` plus those individual meshes, so with the merge off
177
+ * it is exactly the number of visible level meshes — the census the merge exists to cut. `blending`
178
+ * counts the resident tiles mid LOD morph, which are always among the individual meshes. A block
179
+ * whose tile just left stops being drawn until its rebuild lands, and those tiles are counted as the
180
+ * individual meshes they went back to — see `#releaseStaleBlock`.
181
+ * `rebuilds` counts the block geometries built over this residency owner's life. `blockBytes` is
182
+ * what the held blocks cost, reported and not charged to `residentByteBudget` — see `residentBytes`.
183
+ */
184
+ get terrainTiles(): {
185
+ readonly blockBytes: number;
186
+ readonly blocks: number;
187
+ readonly blending: number;
188
+ readonly draws: number;
189
+ readonly rebuilds: number;
190
+ readonly tiles: number;
191
+ };
192
+ /**
193
+ * Resident tiles mid LOD morph right now, so `process` is still owed. A blend is
194
+ * `LOD_TRANSITION_FRAMES` frames long and only `process` advances it, so a caller that skips
195
+ * `process` while its follow point is standing still would freeze every blend on frame one.
196
+ */
197
+ get blendingTiles(): number;
198
+ /**
199
+ * Maximum per-render-frame displacement of the visible LOD surface during transitions.
200
+ *
201
+ * `undefined` when validation is off: the pop is sampled by measuring the rendered surface twice
202
+ * a frame, and reporting the empty value `0` instead of a measurement would be a lie a caller
203
+ * could assert on.
204
+ */
205
+ get maxLodPop(): number | undefined;
112
206
  /** Maximum number of rendered frames during which an LOD transition remained observable. */
113
207
  get maxLodTransitionFrames(): number;
114
- /** Maximum visible edge gap observed across follow/process calls for this residency owner. */
115
- get maxSeamGap(): number;
116
- /** Maximum remaining visible gap after skirt or bridge coverage observed across follow/process calls. */
117
- get maxVisualSeamGap(): number;
208
+ /**
209
+ * Maximum visible edge gap observed across follow/process calls for this residency owner, or
210
+ * `undefined` when validation is off — see `maxLodPop`.
211
+ */
212
+ get maxSeamGap(): number | undefined;
213
+ /**
214
+ * Maximum remaining visible gap after skirt or bridge coverage observed across follow/process
215
+ * calls, or `undefined` when validation is off — see `maxLodPop`.
216
+ */
217
+ get maxVisualSeamGap(): number | undefined;
118
218
  /** Number of mixed-LOD edge reconciliations observed during this residency lifetime. */
119
219
  get stitchedEdgeCount(): number;
220
+ /**
221
+ * A tile or a collider the last `follow` wanted and its budget refused, so the next one is owed
222
+ * work even for an unmoved follow point. `0` once a pass wanted nothing it did not get.
223
+ */
224
+ get deferredAdmissions(): number;
120
225
  get warmupNodes(): readonly unknown[];
121
226
  getTile(key: string): IWorldTile | undefined;
122
- follow(position: IWorldTilesFollowPosition | Pick<Vector3, "x" | "z">): void;
227
+ /**
228
+ * Move residency to the followed point: admit, evict and re-level every tile.
229
+ *
230
+ * `budget` caps construction chunks as well as completed admissions. An unfinished tile stays
231
+ * outside residency and resumes on a later call while it remains wanted. Moving it outside the
232
+ * selected ring cancels and releases that work. Omitted, a call drains synchronously as before.
233
+ * `view` shares the resolved model pixel policy; omitted, selection remains distance-only.
234
+ */
235
+ follow(position: IWorldTilesFollowPosition | Pick<Vector3, "x" | "z">, budget?: IAdmissionBudget, view?: IWorldTilesLodView): void;
123
236
  heightAt(x: number, z: number): number;
124
237
  normalAt(x: number, z: number, target?: Vector3): Vector3;
125
238
  sample(channel: string, x: number, z: number): number;
126
239
  attachRenderer(renderer: IRendererLike): void;
127
- process(renderer?: IRendererLike | undefined): void;
240
+ process(renderer?: IRendererLike | undefined, _camera?: Camera, _covered?: boolean, view?: IWorldTilesLodView | undefined): void;
241
+ /** Completed render tiles intersecting a square in world metres; pending builds do not count. */
242
+ readinessAt(position: IWorldTilesFollowPosition, radius?: number): {
243
+ required: number;
244
+ loaded: number;
245
+ };
128
246
  debug(): Record<string, unknown>;
129
247
  detach(): void;
130
248
  dispose(): void;
131
249
  }
132
250
 
251
+ /**
252
+ * The oracle for terrain geometry that is otherwise trusted every frame.
253
+ *
254
+ * `TerrainTiles` re-derives what it already knows — every rendered vertex checked for finiteness,
255
+ * every resident seam re-measured, every LOD blend's visible displacement sampled — and that is a
256
+ * measurement, not a mechanism: on a 289-tile ring a six-second walk paid ~270 ms in three loops
257
+ * that only throw when something is already broken. So it is off by default and the shipped frame
258
+ * trusts the cheap change detector instead, which compares buffer versions and the residency and
259
+ * LOD state the class writes itself.
260
+ *
261
+ * `TN_TERRAIN_VALIDATE=1`, `?tnTerrainValidate=1`, or `validate: true` on the constructor puts the
262
+ * loops back and every assertion with them. It is a validation mode, not a proof: it proves the
263
+ * frames it ran on.
264
+ */
265
+ /** Marker printed when terrain validation is on, so a log says which mode produced it. */
266
+ declare const TERRAIN_VALIDATE_MARKER = "TN_TERRAIN_VALIDATE";
267
+ /** The launch flag. */
268
+ declare const TERRAIN_VALIDATE_FLAG = "TN_TERRAIN_VALIDATE";
269
+ /**
270
+ * Whether `TN_TERRAIN_VALIDATE` asks for terrain validation on this launch.
271
+ *
272
+ * @situation turn terrain's per-frame seam, LOD pop and vertex checks on for one run
273
+ * @situation assert the terrain geometry a game streams before it ships
274
+ * @constraint off by default: it is the work it checks, every frame
275
+ * @example // Reads its own the way `renderListValidationRequested` does: a native launch sets the
276
+ * // environment variable, a browser asks with the query string, a test or harness sets the
277
+ * // global. `0` and `false` are off, so a saved URL that enabled it still says "off".
278
+ * const tiles = new TerrainTiles({ ...options, validate: terrainValidationRequested() });
279
+ */
280
+ declare function terrainValidationRequested(): boolean;
281
+
133
282
  type WorldGenerationPath = "gpu" | "cpu-fallback" | "unsupported";
134
283
  interface IWorldComputeLimits {
135
284
  readonly maxComputeInvocationsPerWorkgroup: number;
@@ -171,6 +320,1367 @@ interface IWorldCapabilitiesOptions {
171
320
  */
172
321
  declare function getWorldCapabilities(options?: IWorldCapabilitiesOptions): IWorldCapabilities;
173
322
 
323
+ /**
324
+ * The `world.json` package contract: a versioned manifest that names a raw heightmap, stable
325
+ * asset ids, placement runs and the square cells that stream them.
326
+ *
327
+ * Every value is authored by the world exporter and read by the runtime, so the game never
328
+ * hard-codes a cell layout or an asset path. Validation never throws on malformed JSON-shaped
329
+ * input: it collects named errors so an exporter can report every problem in one pass.
330
+ */
331
+ type WorldPackageErrorCode = "WORLD_VERSION_MISMATCH" | "WORLD_UNKNOWN_ASSET" | "WORLD_RUN_OUT_OF_RANGE" | "WORLD_CELL_OUTSIDE_EXTENT" | "WORLD_MALFORMED";
332
+ interface IWorldPackageError {
333
+ readonly code: WorldPackageErrorCode;
334
+ readonly message: string;
335
+ /** JSON-shaped path to the offending field, e.g. `cells[2].runs[0].offset`. */
336
+ readonly path: string;
337
+ }
338
+ interface IWorldExtent {
339
+ readonly minX: number;
340
+ readonly minZ: number;
341
+ readonly sizeX: number;
342
+ readonly sizeZ: number;
343
+ }
344
+ interface IWorldTerrain {
345
+ /** Package-relative path to the raw little-endian uint16 heightmap. */
346
+ readonly heightmap: string;
347
+ /** Vertex counts; `columns = sizeX / spacing + 1`, likewise `rows`. */
348
+ readonly columns: number;
349
+ readonly rows: number;
350
+ /** Metres between adjacent heightmap vertices on both axes. */
351
+ readonly spacing: number;
352
+ readonly heightMin: number;
353
+ readonly heightMax: number;
354
+ /** Optional opaque layer-mask paths, passed through to the game's surface untouched. */
355
+ readonly layers?: Readonly<Record<string, string>>;
356
+ }
357
+ interface IWorldAssetLod {
358
+ readonly glb: string;
359
+ readonly distance: number;
360
+ }
361
+ interface IWorldAssetBounds {
362
+ readonly min: readonly [number, number, number];
363
+ readonly max: readonly [number, number, number];
364
+ }
365
+ interface IWorldAsset {
366
+ readonly glb: string;
367
+ readonly lods?: readonly IWorldAssetLod[];
368
+ readonly bounds: IWorldAssetBounds;
369
+ readonly maxDistance?: number;
370
+ }
371
+ interface IWorldRun {
372
+ readonly asset: string;
373
+ /** Record offset into `placements`; one record is eight float32 values. */
374
+ readonly offset: number;
375
+ readonly count: number;
376
+ }
377
+ interface IWorldCellProxy {
378
+ readonly glb: string;
379
+ /** Conservative world-space simplification error bound, in metres. */
380
+ readonly error: number;
381
+ readonly triangles: number;
382
+ readonly materialGroups: number;
383
+ /** Older records without scope cover chunks only. */
384
+ readonly scope?: "cell" | "chunks";
385
+ readonly bounds?: IWorldAssetBounds;
386
+ readonly sourceTriangles?: number;
387
+ /** Cook census only: runtime compares the currently active shared batches. */
388
+ readonly sourcePrimitives?: number;
389
+ }
390
+ interface IWorldCell {
391
+ readonly x: number;
392
+ readonly z: number;
393
+ readonly runs: readonly IWorldRun[];
394
+ readonly chunks?: readonly string[];
395
+ readonly proxy?: IWorldCellProxy;
396
+ }
397
+ interface IWorldPackage {
398
+ readonly version: 1;
399
+ readonly extent: IWorldExtent;
400
+ readonly cellSize: number;
401
+ readonly terrain: IWorldTerrain;
402
+ readonly assets: Readonly<Record<string, IWorldAsset>>;
403
+ readonly placements: string;
404
+ readonly cells: readonly IWorldCell[];
405
+ }
406
+ interface IWorldPackageValidationOptions {
407
+ /** Byte length of the placement buffer the runs index into. */
408
+ readonly placementsByteLength: number;
409
+ /** When known, the heightmap length must be `columns * rows * 2`. */
410
+ readonly heightmapByteLength?: number;
411
+ }
412
+ /**
413
+ * Validate a `world.json` manifest against the v1 contract.
414
+ *
415
+ * Never throws on garbage input: a non-object manifest is `WORLD_MALFORMED`. Every problem is
416
+ * collected, so an exporter sees the complete list at once.
417
+ *
418
+ * @situation check a Blender-exported world package before the runtime attaches anything
419
+ * @situation report why a world package cannot be streamed
420
+ * @constraint validation only checks structure and ranges; it never fetches the heightmap or GLBs
421
+ * @example const { ok, errors } = validateWorldPackage(json, { placementsByteLength: buffer.byteLength });
422
+ */
423
+ declare function validateWorldPackage(manifest: unknown, options: IWorldPackageValidationOptions): {
424
+ ok: boolean;
425
+ errors: IWorldPackageError[];
426
+ };
427
+ /**
428
+ * Borrow the run's placement records as a live view over the placement buffer.
429
+ *
430
+ * @situation feed one cell's instance transforms into a batch without copying
431
+ * @constraint the returned view aliases the caller's buffer; writing to it mutates the source
432
+ * @example const records = cellPlacements(buffer, { asset: "tree", offset: 0, count: 120 });
433
+ */
434
+ declare function cellPlacements(placements: ArrayBuffer, run: IWorldRun): Float32Array;
435
+
436
+ /**
437
+ * What one contact footprint wants at a local offset, sampled in the contact's own frame.
438
+ *
439
+ * A footprint describes a shape, never a load: the same sole sinks deeper under a heavier
440
+ * contact. Every field is 0..1 except `relief`, which is metres.
441
+ */
442
+ interface ISnowFootprintSample {
443
+ /** 0..1 fraction of the footprint touching snow here; erases displaced bank and adds compaction. */
444
+ readonly coverage: number;
445
+ /** 0..1 relative depth at this offset, so a toe can press deeper than a heel. */
446
+ readonly shape: number;
447
+ /** Metres of tread relief subtracted from the impression at this offset. */
448
+ readonly relief: number;
449
+ /** 0..1 raised snow pushed out beside the contact at this offset. */
450
+ readonly bank: number;
451
+ /** 0..1 surface disturbance at this offset, for render shading and game queries. */
452
+ readonly disturbance: number;
453
+ }
454
+ /** A game-authored contact shape: a boot sole, a tyre, a hull, a sphere. */
455
+ interface ISnowFootprint {
456
+ /** Half-width of the square sampled around the contact centre, in metres. */
457
+ readonly extent: number;
458
+ /** Local contact-space sample; +z runs forward along the contact's orientation. */
459
+ readonly sample: (x: number, z: number) => ISnowFootprintSample;
460
+ }
461
+ /** One contact between a supported object and the snow surface. */
462
+ interface ISnowContact {
463
+ readonly x: number;
464
+ readonly z: number;
465
+ /** Game-authored imprint shape. */
466
+ readonly footprint: ISnowFootprint;
467
+ /** Supported contact area in square metres. Pressure is load over area, never a fixed constant. */
468
+ readonly area: number;
469
+ /** Normal load in newtons. */
470
+ readonly load: number;
471
+ /** Orientation about +y in radians. Default 0. */
472
+ readonly rotation?: number;
473
+ /** 0..1 snow hardness. Defaults to the field's hardness. */
474
+ readonly hardness?: number;
475
+ /** Seconds the contact is applied. Defaults to the field's response time. */
476
+ readonly duration?: number;
477
+ }
478
+ /** The four snow channels at one world position. */
479
+ interface ISnowFieldSample {
480
+ readonly indent: number;
481
+ readonly bank: number;
482
+ readonly compaction: number;
483
+ readonly disturbance: number;
484
+ }
485
+ interface ISnowFieldOptions {
486
+ /** The canonical terrain. Snow composes onto it; there is no second terrain representation. */
487
+ readonly field: Heightfield;
488
+ /** Snow depth in metres. Zero is bare ground. Default 0.28. */
489
+ readonly depth?: number;
490
+ /** 0..1 snow hardness used by contacts that do not override it. Default 0.3. */
491
+ readonly hardness?: number;
492
+ /** Fraction of its target impression a contact reaches in one response time. Default 0.9. */
493
+ readonly yieldFraction?: number;
494
+ /** Metres of raised bank allowed beside a contact. Default 0.085. */
495
+ readonly maxBank?: number;
496
+ /** Seconds a fully-loaded contact takes to reach its full impression. Default 0.1. */
497
+ readonly responseTime?: number;
498
+ }
499
+ interface ISnowDiscFootprintOptions {
500
+ /** 0..1 width of the falloff at the disc's edge, as a fraction of the radius. Default 0.25. */
501
+ readonly softness?: number;
502
+ }
503
+ /**
504
+ * A circular contact footprint, sized from a radius the caller measures.
505
+ *
506
+ * The shape a sphere, a ball, a wheel or a probe presses into snow, and the default the physics
507
+ * binding derives from a sphere's contact geometry. Flat inside the radius, eased over the
508
+ * softness band, with a raised rim just outside it.
509
+ * @situation press a ball, wheel or probe into snow
510
+ * @situation give a sphere a physically sized snow contact instead of a boot shape
511
+ * @constraint radius is metres; the footprint never grows with load, only deeper
512
+ * @override softness widens the eased edge without changing the contact radius
513
+ * @example const footprint = snowDiscFootprint(0.25);
514
+ */
515
+ declare function snowDiscFootprint(radius: number, options?: ISnowDiscFootprintOptions): ISnowFootprint;
516
+ /**
517
+ * Persistent snow deformation over one canonical heightfield.
518
+ *
519
+ * Snow keeps four channels per cell — indentation, displaced bank, compaction and disturbance —
520
+ * and writes the combined surface (`terrain + depth + bank - indent`) back into the heightfield
521
+ * it was given. Queries, rendered geometry and collider export therefore all read one surface,
522
+ * and no second terrain representation exists.
523
+ *
524
+ * The field is numeric only: it never chooses a boot, a tread, a particle, a material or a
525
+ * camera. Games supply terrain heights, the snow depth, the contact profile and the response
526
+ * coefficients; this class owns the storage, the load-dependent penetration and the bounded
527
+ * recovery. It is a heightfield approximation — not granular snow, displaced-volume
528
+ * conservation, avalanches, melting or a calibrated material law.
529
+ * @situation leave footprints, tracks and tyre ruts in snow that persist and fill in over time
530
+ * @situation let a pushed sphere carve a connected track and a dropped one settle into a crater
531
+ * @situation store snow deformation that rendered geometry and collision both read
532
+ * @situation reset a snowfield between rounds or change its depth at runtime
533
+ * @situation show how packed the snow is where people have walked or objects have rested
534
+ * @constraint the field composes onto a Heightfield; construct the terrain first and let this own the surface
535
+ * @constraint zero depth is bare ground: contacts register no indentation at all
536
+ * @constraint out-of-region heightAt and normalAt follow Heightfield's error contract; sample returns zeros
537
+ * @override depth, hardness, yieldFraction, maxBank and responseTime name the response coefficients
538
+ * @requires @threenative/core/world Heightfield as the canonical terrain and surface
539
+ * @example import { Heightfield } from "@threenative/core/world";
540
+ * const terrain = Heightfield.fromSampler({ rows: 129, columns: 129, width: 64, depth: 64, origin: { x: 0, z: 0 }, sampleHeight: (x, z) => Math.sin(x * 0.1) * 0.5 });
541
+ * const snow = new SnowField({ field: terrain, depth: 0.28, hardness: 0.3 });
542
+ * snow.stamp({ x: 0, z: 0, area: 0.074, load: 784, duration: 0.1, footprint: snowDiscFootprint(0.12) });
543
+ * snow.recover(1 / 60, 0.0012, 0.4);
544
+ */
545
+ declare class SnowField {
546
+ #private;
547
+ /** Canonical terrain and the surface snow composes onto. */
548
+ readonly field: Heightfield;
549
+ readonly columns: number;
550
+ readonly rows: number;
551
+ readonly cellWidth: number;
552
+ readonly cellDepth: number;
553
+ /** World x of column 0. */
554
+ readonly minimumX: number;
555
+ /** World z of row 0. */
556
+ readonly minimumZ: number;
557
+ /** 0..1 snow hardness used by contacts that do not override it. */
558
+ hardness: number;
559
+ /** Fraction of its target impression a contact reaches in one response time. */
560
+ readonly yieldFraction: number;
561
+ /** Metres of raised bank allowed beside a contact. */
562
+ readonly maxBank: number;
563
+ /** Seconds a fully-loaded contact takes to reach its full impression. */
564
+ readonly responseTime: number;
565
+ constructor(options: ISnowFieldOptions);
566
+ /** Snow depth in metres. Zero is bare ground. */
567
+ get depth(): number;
568
+ /** Contacts applied since construction or the last reset. */
569
+ get steps(): number;
570
+ /** Penetration the most recent contact reached, in metres. */
571
+ get lastSink(): number;
572
+ /** Cells still carrying deformation. Recovery drops a cell once it is fully buried. */
573
+ get activeCells(): number;
574
+ /** Monotonic version, incremented once per batch that changed the canonical surface. */
575
+ get version(): number;
576
+ /** Window of the canonical field the last change wrote, or undefined before the first change. */
577
+ get dirtyRegion(): IHeightfieldRegionBounds | undefined;
578
+ /**
579
+ * Union of every window written since the previous call, then forgotten.
580
+ *
581
+ * One fixed step can write several windows — each contact, then recovery — and `dirtyRegion`
582
+ * keeps only the last, so a renderer that refreshes geometry once per drawn frame takes this
583
+ * instead. It has one owner: two consumers taking it would each miss the other's windows.
584
+ */
585
+ takeDirtyRegion(): IHeightfieldRegionBounds | undefined;
586
+ /** Bytes retained by the four snow channels and the base terrain copy. */
587
+ get memoryBytes(): number;
588
+ /**
589
+ * The four snow channels at a world position, bilinearly interpolated.
590
+ *
591
+ * Returns zeros outside the field rather than throwing, so a caller sweeping a broad area does
592
+ * not have to bounds-check first. `heightAt` keeps the strict contract.
593
+ */
594
+ sample(x: number, z: number): ISnowFieldSample;
595
+ /**
596
+ * One channel over a window of cells, row-major, written into `target` (allocated when absent
597
+ * or too small) and returned. The bulk read a renderer uses to encode a refreshed window: a
598
+ * `sample` per vertex costs a bilinear lookup and an object each, and a refill window is
599
+ * thousands of vertices. A window outside the field throws.
600
+ */
601
+ copyChannel(channel: keyof ISnowFieldSample, bounds: IHeightfieldRegionBounds, target?: Float32Array): Float32Array;
602
+ /** Snow surface height at a world position, from the same samples geometry and collision read. */
603
+ heightAt(x: number, z: number): number;
604
+ /** Surface normal at a world position. */
605
+ normalAt(x: number, z: number, target?: Vector3): Vector3;
606
+ /**
607
+ * Press one contact into the snow and return the penetration it reached, in metres.
608
+ *
609
+ * Pressure is `load / area`, so the same profile responds to how much weight it carries and how
610
+ * widely that weight is spread. `duration` scales how far the contact gets towards its target
611
+ * impression, which is what makes a run of shorter contacts agree with one long one. A contact
612
+ * entirely outside the field returns 0 and leaves the version unchanged.
613
+ */
614
+ stamp(contact: ISnowContact): number;
615
+ /**
616
+ * Let snowfall fill depressions and wind soften banks over `seconds`.
617
+ *
618
+ * Deposition and wind are rates, so this is presentation-rate independent: a second of
619
+ * simulation recovers the same amount however many ticks it was split into. It accelerates
620
+ * deposition only — never gravity, movement, falling flakes or the physics timestep.
621
+ */
622
+ recover(seconds: number, deposition: number, wind: number): void;
623
+ /**
624
+ * Change the snow depth in metres and push the new surface through the canonical field.
625
+ *
626
+ * Existing indentation is capped to the new depth rather than scaled, so deepening snow does
627
+ * not erase tracks and shallowing it buries them.
628
+ */
629
+ setDepth(depth: number): void;
630
+ /** Clear every track, bank and compaction record and return the surface to bare snow. */
631
+ reset(): void;
632
+ }
633
+
634
+ /**
635
+ * Build a game-usable `sampleHeight` from a raw v1 heightmap.
636
+ *
637
+ * The returned function interpolates bilinearly in world units and clamps to the map edges, so it
638
+ * plugs straight into `Heightfield.fromSampler` and `TerrainTiles`. Height is
639
+ * `heightMin + v / 65535 * (heightMax - heightMin)` at vertex `(column, row)`.
640
+ *
641
+ * @situation turn an exported raw heightmap into terrain collision and rendering
642
+ * @situation query ground height from a Blender-authored world package
643
+ * @constraint the sampler reads the game's data; the framework never selects a terrain shape
644
+ * @example const sampleHeight = heightSamplerFromHeightmap(terrain, extent, await loadWorldHeightmap(url));
645
+ */
646
+ declare function heightSamplerFromHeightmap(terrain: IWorldTerrain, extent: IWorldExtent, data: Uint16Array): (x: number, z: number) => number;
647
+ /**
648
+ * Fetch a raw little-endian uint16 heightmap and expose it as samples.
649
+ *
650
+ * @situation load a world package's heightmap once before building terrain
651
+ * @constraint a non-OK response throws; bytes are byte-swapped only on a big-endian host
652
+ * @example const data = await loadWorldHeightmap("/world/terrain/heightmap.u16");
653
+ */
654
+ declare function loadWorldHeightmap(url: string): Promise<Uint16Array>;
655
+
656
+ type Channel = "r" | "g" | "b" | "a";
657
+ /** One texture set: albedo (and optionally a normal and ORM map) tiled in metres, tinted in linear. */
658
+ interface ITerrainSplatLayer {
659
+ readonly id: string;
660
+ readonly tile: number;
661
+ readonly tint: readonly [number, number, number];
662
+ readonly normal?: boolean;
663
+ /** `<id>_orm.jpg`: occlusion in r, roughness in g, metalness in b, read as linear data. */
664
+ readonly orm?: boolean;
665
+ /** Without an ORM map, how this layer answers light. Defaults to `DEFAULT_ROUGHNESS` and 0. */
666
+ readonly metalness?: number;
667
+ readonly roughness?: number;
668
+ readonly saturation?: number;
669
+ /** Box-projected, for cliffs a top-down projection smears. */
670
+ readonly triplanar?: boolean;
671
+ /**
672
+ * `<id>_h.jpg`: the layer's own height in r, read as linear data and handed to `layerWeight`.
673
+ * Read only on a masked layer; the base has no weight to bend.
674
+ */
675
+ readonly height?: boolean;
676
+ /**
677
+ * The same map again at a larger `tile`, mixed in by up to `amount` as camera distance goes from
678
+ * `from` to `to` metres, so a repeated pattern stops reading as a grid at grazing angles.
679
+ * Top-down layers only; every value is the game's.
680
+ */
681
+ readonly far?: {
682
+ readonly tile: number;
683
+ readonly from: number;
684
+ readonly to: number;
685
+ readonly amount: number;
686
+ };
687
+ }
688
+ /** A layer blended over what is below it by one mask channel, remapped from `lo..hi`. */
689
+ interface ITerrainSplatMaskedLayer extends ITerrainSplatLayer {
690
+ readonly mask: string;
691
+ /** The component of a `rgb` mask; ignored by a single-component mask. */
692
+ readonly channel: "r" | "g" | "b";
693
+ readonly lo: number;
694
+ readonly hi: number;
695
+ }
696
+ /**
697
+ * The package's terrain table (`terrain.layers.table`). Written by the export recipe
698
+ * `export_terrain_layers.py` from the game's own table; every value is the game's.
699
+ */
700
+ interface ITerrainSplatTable {
701
+ readonly base: ITerrainSplatLayer;
702
+ /** Noise (0..1 at `scale` per metre) that pushes every mask edge by +-`push`. */
703
+ readonly breakup: {
704
+ readonly scale: number;
705
+ readonly push: number;
706
+ };
707
+ /** Large-scale brightness variation against visible tiling, mapped to `min..max`. */
708
+ readonly macro: {
709
+ readonly scale: number;
710
+ readonly min: number;
711
+ readonly max: number;
712
+ };
713
+ readonly layers: readonly ITerrainSplatMaskedLayer[];
714
+ /**
715
+ * `terrain.layers.splat`: `planes` RGBA8 planes of `size`², rows bottom-up, covering the
716
+ * package extent. `masks` names each mask's plane and component (`rgb` = pick by the layer's
717
+ * `channel`).
718
+ */
719
+ readonly splat: {
720
+ readonly size: number;
721
+ readonly planes: number;
722
+ readonly masks: Readonly<Record<string, readonly [number, Channel | "rgb"]>>;
723
+ };
724
+ /** Package-relative folder of `<id>_diff.jpg`, `<id>_nrm.jpg`, `<id>_orm.jpg` and `<id>_h.jpg`. */
725
+ readonly textures: string;
726
+ }
727
+ /** What `ILoadTerrainSplatOptions.layerWeight` is told about the layer whose weight it returns. */
728
+ interface ITerrainSplatWeightContext {
729
+ readonly layer: ITerrainSplatMaskedLayer;
730
+ /** The layer's height sample, projected as its albedo is; `undefined` when it ships no `height`. */
731
+ readonly height: Node<"float"> | undefined;
732
+ /** The layer's index in `table.layers`. */
733
+ readonly index: number;
734
+ }
735
+ interface ILoadTerrainSplatOptions {
736
+ readonly assets: IAssetLoader;
737
+ /**
738
+ * The live renderer. Uncompressed layers stack into one array texture per set through GPU copies,
739
+ * which need one; without it every layer keeps its own sampler and the marker says so.
740
+ */
741
+ readonly renderer?: IRendererLike;
742
+ /**
743
+ * Replaces each layer's blend weight, given the mask's own (remapped, 0..1) and the layer's
744
+ * height sample. The game owns the curve, for example a height blend; the package mixes colour,
745
+ * normal and ORM by whatever this returns. Absent, the mask weight is used unchanged.
746
+ */
747
+ readonly layerWeight?: (weight: Node<"float">, context: ITerrainSplatWeightContext) => Node<"float">;
748
+ /** The world package's `world.json`, as `WorldCells.load` takes it. */
749
+ readonly url: string;
750
+ }
751
+ /**
752
+ * The splat terrain surface a world package describes, for `WorldCells.load({ surface })`.
753
+ *
754
+ * Layers blend over a base by mask channels read as linear data (the masks ship raw, beside the
755
+ * heightmap, so no cook moves a blend threshold), with noise-broken edges and macro brightness
756
+ * variation. Texture sets tile in world metres on the package's ground plane (x, -z: a Z-up
757
+ * authoring tool's x and y), cliffs can be triplanar, and the base plus any layer that asks carries
758
+ * a normal map. Each layer answers light from its own ORM map where the table ships one and from
759
+ * the table's own roughness and metalness where it does not; a layer that states neither is matte
760
+ * and dielectric, and named in a warning. Nothing here is a look choice:
761
+ * textures, tiles, tints, thresholds, surface response and noise scales all come from the package's
762
+ * table, which the game authors once and its DCC shares.
763
+ *
764
+ * @situation terrain textured by splat masks exported from Blender with the world package
765
+ * @situation the game's terrain should match the DCC's terrain material without a second copy
766
+ * @constraint the package's world.json must carry `terrain.layers.table` and `terrain.layers.splat`, written by `export_terrain_layers` in the `export_world.py` recipe
767
+ * @constraint WebGPU allows 16 sampled textures per stage: same-size layers stack into one array texture per set, and `TN_TERRAIN_SPLAT samplers=<n>` reports what is left
768
+ * @override every value comes from the package's table; the returned material is the game's to adjust
769
+ * @example
770
+ * const surface = await loadTerrainSplat({ assets: ctx.assets, renderer: ctx.renderer, url: "world/world.json" });
771
+ * const world = await WorldCells.load({ assets: ctx.assets, url: "world/world.json", surface, follow, ring: 2 });
772
+ */
773
+ declare function loadTerrainSplat(options: ILoadTerrainSplatOptions): Promise<Material>;
774
+
775
+ /** What a launch asked the GPU-scene occlusion cull to do. `measure` counts; `off` runs no test. */
776
+ type OcclusionMode = "off" | "measure";
777
+
778
+ /**
779
+ * One shadow map's own three numbers, which is the whole of what a level render knows that the main
780
+ * camera does not.
781
+ *
782
+ * They are the level's, never the camera's: a map's frustum is the light's window, its gate is the
783
+ * texel size it can resolve, and its base is the chain level the cluster path hands it — `#probe`
784
+ * swaps a coarse level's geometry for the coarsest shape, so a coarse map draws that shape whatever a
785
+ * placement's own distance would have selected. The distance itself is the main pass's, from the
786
+ * eye: a placement's shape and its cast come from the key the main pass draws it in.
787
+ */
788
+ interface IShadowLevel {
789
+ /** The six frustum planes of this map's own shadow camera. */
790
+ readonly planes: Float32Array;
791
+ /** This map's texel gate in world metres: a placement narrower than it casts nothing here. */
792
+ readonly gate: number;
793
+ /**
794
+ * The chain level this map draws at, floored over the placement's own. 0 is the placement's own
795
+ * LOD by distance — what the finest map draws — and the coarsest index is what every level past
796
+ * the first draws. A base whose keys are not minted draws nothing, which is why a caller settling
797
+ * the prewarm first is the contract rather than a fallback.
798
+ *
799
+ * {@link COARSEST_SHADOW_LEVEL} is past every chain, and means the coarsest shape an asset has: a
800
+ * map that coarsens its casters does not know how long each asset's chain is, and the floor is
801
+ * clamped per asset, so one number asks every chain for its own coarsest level.
802
+ */
803
+ readonly base: number;
804
+ }
805
+ /** What one landed readback concluded, in the three words a log line can carry. */
806
+ type GpuSceneVerdict = "ok" | "mismatch" | "error";
807
+ /**
808
+ * The memory numbers a validation line can carry, all of them optional.
809
+ *
810
+ * The first seven are three's `info.memory` fields (`WebGPURenderer`, 0.185); a backend that tracks
811
+ * none of them reports none, which is why every field is optional and only finite numbers are
812
+ * printed — an absent reading is not a zero. `footprintBytes` is the sum of this scene's own storage
813
+ * buffer `footprint()` bytes, the one number here Three did not write.
814
+ */
815
+ type GpuSceneMemoryField = "storageAttributes" | "storageAttributesSize" | "indirectStorageAttributes" | "indirectStorageAttributesSize" | "readbackBuffers" | "readbackBuffersSize" | "total" | "footprintBytes";
816
+ /** One validation's memory reading; a field is absent when the backend did not offer a finite one. */
817
+ type GpuSceneMemory = Partial<Record<GpuSceneMemoryField, number>>;
818
+ /**
819
+ * The one placement nearest the camera (in XZ) a zero/zero comparison was handed, as the dispatch's
820
+ * own snapshot held it. Every number is the snapshot's, never the live scene's: the camera's eye and
821
+ * this placement's sphere, root translation, slot, slot cull, horizontal distance and the margin to
822
+ * the nearest of the six frustum planes are what say whether the snapshot held no live source or
823
+ * held one the camera, sphere, range or frustum rejected. A field is omitted, not printed as a fake
824
+ * zero, when the snapshot has no finite number for it.
825
+ */
826
+ interface IValidationNearest {
827
+ /** The bounding sphere: X, Y, Z and the radius. */
828
+ readonly centre: readonly [number, number, number];
829
+ readonly radius: number;
830
+ /** The placement matrix's translation, which is what a draw places. */
831
+ readonly root: readonly [number, number, number];
832
+ /** The asset slot the placement names. */
833
+ readonly slot: number;
834
+ /** The slot's authored cull distance, or absent when it has none. */
835
+ readonly cull?: number;
836
+ /** `hypot(cx - eye.x, cz - eye.z)`, the distance the level and cull gates read. */
837
+ readonly distance: number;
838
+ /** The least `plane·centre + plane.constant + radius` over the six planes: negative is rejected. */
839
+ readonly margin: number;
840
+ }
841
+ /**
842
+ * Why a comparison that landed both counts at zero was handed nothing: the snapshot's own camera eye,
843
+ * how many placements it held and how many of them were live, and the one live placement nearest the
844
+ * camera in XZ. Taken from the snapshot, so nothing that streams while the bytes are in flight can
845
+ * rewrite the answer. Attached only when `instancesGpu` and `instancesCpu` are both zero.
846
+ */
847
+ interface IValidationProbe {
848
+ readonly eye: readonly [number, number, number];
849
+ /** Placements the snapshot held, live and released. */
850
+ readonly snapshot: number;
851
+ /** Placements whose slot was not `SLOT_NONE`, the only ones the kernel considers. */
852
+ readonly live: number;
853
+ /** Absent when the snapshot held no live placement to name. */
854
+ readonly nearest?: IValidationNearest;
855
+ }
856
+ /** What a landed readback is judged on, gathered from the scene before it is formatted. */
857
+ interface IGpuSceneComparison {
858
+ /** Keys whose GPU instance count was read back and held against the reference. */
859
+ readonly compared: number;
860
+ readonly instancesGpu: number;
861
+ readonly instancesCpu: number;
862
+ /** Up to {@link VALIDATE_REPORTED_KEYS} `name gpu=… cpu=…` lines; the count is the whole total. */
863
+ readonly mismatches: readonly string[];
864
+ readonly mismatched: number;
865
+ /**
866
+ * Keys whose drawn matrices, `firstInstance` or `indexCount` disagreed, and up to
867
+ * {@link MATRIX_REPORTED_KEYS} of them by name. The counts above are what the dispatch promised;
868
+ * these are what the draw reads, which is a different question and the one the picture answers.
869
+ */
870
+ readonly matricesMismatched: number;
871
+ readonly matrixMismatches: readonly string[];
872
+ /**
873
+ * Dressed main meshes whose own record was read back and held against the CPU path's own records
874
+ * for that mesh's key, and up to {@link MESH_REPORTED_MESHES} of them by name. This is the check
875
+ * the reference above cannot make: a key/record/mesh mapping that is wrong is one both sides
876
+ * reproduce, and a mesh drawing another asset's placements out of its own record is the picture
877
+ * that proves it.
878
+ */
879
+ readonly meshMismatched: number;
880
+ readonly meshMismatches: readonly string[];
881
+ /** Resident placements the scene held when the readback was issued. */
882
+ readonly placed: number;
883
+ /** The device's last uncaptured error, or `""` for none since the last check reported one. */
884
+ readonly deviceError: string;
885
+ /** What stopped the check — a rejected readback, say. Non-empty is an `error` on its own. */
886
+ readonly cause?: string;
887
+ /**
888
+ * What the device and this scene held when the check reported. Absent when neither offered a
889
+ * finite number, and a field is omitted rather than printed as zero when its backend has none.
890
+ */
891
+ readonly memory?: GpuSceneMemory;
892
+ /** The snapshot's own camera and nearest live placement, when both instance totals landed zero. */
893
+ readonly probe?: IValidationProbe;
894
+ }
895
+ /** One completed manual frame check, identified by the caller's frame and this scene's dispatch. */
896
+ interface IWorldGpuFrameValidation extends IGpuSceneComparison {
897
+ /** The caller's rendered-frame identity, never inferred from readback timing. */
898
+ readonly frame: number;
899
+ /** The dispatch whose buffers and snapshot this readback completed against. */
900
+ readonly dispatch: number;
901
+ readonly verdict: GpuSceneVerdict;
902
+ }
903
+ /**
904
+ * What `TN_WORLD_GPU_SCENE` reports, and what `stats().gpuScene` carries.
905
+ *
906
+ * `dispatches`/`instances`/`keys` are the scene's own tables — the placements it holds and the keys
907
+ * it is ready to draw. The optional `gpu*` trio is different in kind: it is a sample of what the GPU
908
+ * actually selected in the **main** pass, read back from the same indirect args records the draw
909
+ * uses (sum of `instanceCount`, and sum of `instanceCount x indexCount / 3`). Shadow passes are not
910
+ * tallied, and a count three reports from `renderer.info.render.triangles` is an upper bound over a
911
+ * mesh's CPU capacity, not a GPU-selected count — see {@link IFrameBudgetWindow.mainGpuTriangles}.
912
+ */
913
+ interface IWorldGpuSceneReport {
914
+ readonly dispatches: number;
915
+ readonly instances: number;
916
+ readonly keys: number;
917
+ readonly on: boolean;
918
+ readonly reason: string;
919
+ /** Instances the GPU selected in the main pass, from the last landed tally. */
920
+ readonly gpuInstances?: number;
921
+ /** Triangles the GPU selected in the main pass (`instanceCount x indexCount / 3`), from the tally. */
922
+ readonly gpuTriangles?: number;
923
+ /** Dispatches between the tally's bytes being issued and now; grows until the first lands. */
924
+ readonly gpuTallyAgeFrames?: number;
925
+ /**
926
+ * What the pyramid occlusion test would cull, when a launch asked it to measure. Absent unless
927
+ * `?tnOcclusion=measure` asked, `reason` names why it measured nothing (`no scene depth`), and the
928
+ * counts and `occlusion.gpuTriangles` come from one landed dispatch, even if a later tally
929
+ * was skipped for occlusion.
930
+ */
931
+ readonly occlusion?: {
932
+ readonly mode: OcclusionMode;
933
+ readonly reason: string;
934
+ /** Pyramid levels and the dispatches that rebuild them each frame. */
935
+ readonly levels: number;
936
+ readonly buildDispatches: number;
937
+ /** The last landed sample, and the mean over every sample that landed. */
938
+ readonly instances: number;
939
+ readonly triangles: number;
940
+ readonly meanInstances: number;
941
+ readonly meanTriangles: number;
942
+ readonly samples: number;
943
+ /** `triangles / gpuTriangles` of the same sample, which is what the go/no-go multiplies. */
944
+ readonly share: number;
945
+ readonly gpuTriangles: number;
946
+ readonly ageFrames: number;
947
+ };
948
+ }
949
+
950
+ /** The point a streamed world follows; an `Object3D` satisfies this shape. */
951
+ interface IWorldCellsFollow {
952
+ readonly position: {
953
+ readonly x: number;
954
+ readonly y?: number;
955
+ readonly z: number;
956
+ };
957
+ }
958
+ /** Hard caps on what stays resident. A cap that is reached reports pressure, it never throws. */
959
+ interface IWorldCellsBudget {
960
+ readonly residentCells: number;
961
+ readonly instances: number;
962
+ /** Placement-record bytes (`32` per instance) the resident cells are allowed to weigh. */
963
+ readonly bytes: number;
964
+ }
965
+ /** Terrain options forwarded to the composed `TerrainTiles`; `tileSize` defaults to `cellSize`. */
966
+ interface IWorldCellsTerrainOptions {
967
+ readonly tileSize?: number;
968
+ readonly tileResolution?: number;
969
+ readonly lodFactors?: readonly number[];
970
+ readonly lodDistances?: readonly number[];
971
+ readonly skirtDepth?: number;
972
+ /**
973
+ * Tiles kept resident around the follow tile, independent of the cell `ring`: terrain can reach
974
+ * to the horizon while props stay near. Defaults to `ring`, so raising only this widens the
975
+ * ground without widening the props, and the far tiles take the coarser `lodDistances` levels.
976
+ */
977
+ readonly streamRadius?: number;
978
+ /**
979
+ * Tiles that get a `createCollider` body, by Chebyshev radius from the follow tile. Defaults to
980
+ * `ring`. A tile entering or leaving it creates or disposes its collider, so a wide terrain
981
+ * radius does not have to mean a physics body for every tile in it.
982
+ */
983
+ readonly colliderRadius?: number;
984
+ }
985
+ interface IWorldCellsLoadOptions {
986
+ /**
987
+ * Logical path of `world.json` (`world/world.json`); every other path in the package resolves
988
+ * against it. A leading `/` is accepted and stripped, so an uncompiled `public/world` keeps
989
+ * working.
990
+ */
991
+ readonly url: string;
992
+ /**
993
+ * Loader the package's paths resolve through — its manifest, or the authored names when there is
994
+ * none. Defaults to a fresh `createAssetLoader()`; inside a game, pass `ctx.assets` so the
995
+ * package's compiled output and compressed textures reach the renderer the game booted with.
996
+ *
997
+ * The world releases the source models it asks this loader for only when it created the loader
998
+ * itself: each asset's requested level paths are released through `release("model", path)` once
999
+ * the last asset naming a path is gone, so a streamed package does not pin an internally owned
1000
+ * cache. An explicitly supplied loader is the caller's — the world never releases its cache, so a
1001
+ * second game or world holding the same model keeps it alive; the caller ends that lifetime with
1002
+ * its own `release`. The loader is never cleared, and a path this world never asked for is never
1003
+ * touched either way.
1004
+ */
1005
+ readonly assets?: IAssetLoader;
1006
+ /** Game-owned terrain surface, handed straight to `TerrainTiles`. */
1007
+ readonly surface: IWorldTilesOptions["surface"];
1008
+ /** Passed straight to `TerrainTiles` for per-tile colliders. */
1009
+ readonly createCollider?: IWorldTilesOptions["createCollider"];
1010
+ /** Read once per update; an `Object3D` works. */
1011
+ readonly follow: IWorldCellsFollow;
1012
+ /** Chebyshev radius in cells to keep resident; a cell leaves only beyond `ring + 1`. */
1013
+ readonly ring: number;
1014
+ readonly budgets: IWorldCellsBudget;
1015
+ /** False streams props/chunks only; the caller owns terrain geometry and collision. */
1016
+ readonly terrain?: IWorldCellsTerrainOptions | false;
1017
+ /** Cooked cell proxies are considered by default; false retains source rendering. Static CPU
1018
+ * cells only, with strict measured triangle/draw savings and projected-error hysteresis.
1019
+ * Source collision and shadow representations stay resident; unsupported sources retain detail. */
1020
+ readonly hlod?: boolean;
1021
+ /** Optional immutable per-record 3D draw reach in metres, indexed like placements.
1022
+ * Nonnegative finite values or Infinity (no extra limit); combined with asset maxDistance.
1023
+ * Filtered by the existing admission/refilter budget, never by a separate culler.
1024
+ */
1025
+ readonly placementReach?: Float32Array;
1026
+ /** Inward return margin for authored CPU LODs, in [0, 1). Requires gpuScene:false and impostors:false; omission keeps source levels.
1027
+ * Omitted, selection uses the existing direct gates. State survives cell eviction/revisit. */
1028
+ readonly lodHysteresis?: number;
1029
+ /** Preserve supplied part/material identity and exact authored LOD membership, including shadow batches. Requires impostors:false; omission keeps source levels.
1030
+ * Default content sharing and missing-alpha-part coverage remain enabled when omitted. */
1031
+ readonly preserveAuthoredParts?: boolean;
1032
+ /** Already decoded immutable world-v1 data; URL still supplies the base for model paths. */
1033
+ readonly data?: {
1034
+ readonly manifest: IWorldPackage;
1035
+ readonly placements: ArrayBuffer;
1036
+ /** Omitted values load the manifest heightmap unless terrain is false. */
1037
+ readonly heightmap?: Uint16Array;
1038
+ };
1039
+ /**
1040
+ * How a scattered part whose own material is `transparent` is drawn. `"cutout"` (the default)
1041
+ * gives the part a clone of that material with `transparent: false` and an `alphaTest`, so the
1042
+ * instanced draw needs no per-instance sorting and the depth buffer rejects what is behind it;
1043
+ * `"blend"` draws the material as authored. One clone per asset part, never per cell.
1044
+ */
1045
+ readonly transparentScatter?: "cutout" | "blend";
1046
+ /**
1047
+ * Shadows for the streamed world, all off by default. `cast` makes scattered batches cast into
1048
+ * the scene's shadow map. Their `castLevels` finest distance levels (default 1: the near shape)
1049
+ * each cast their own shape; a placement drawn at a coarser level of a chain casts with the
1050
+ * coarsest of those, so it keeps its shadow without a caster mesh per level — every level casting
1051
+ * its own minted ~3x the casters and the churn showed as garbage collection on a walk (PRD-541).
1052
+ * Authored `lods` past `castLevels` cast nothing. `receive` lets scatter and terrain receive
1053
+ * shadows.
1054
+ */
1055
+ readonly shadows?: {
1056
+ readonly cast?: boolean;
1057
+ readonly castLevels?: number;
1058
+ readonly receive?: boolean;
1059
+ /**
1060
+ * @deprecated Accepted and ignored. Clusters replace it: what a shadow level submits is bounded
1061
+ * by the clusters its own window covers, not by a hand-tuned radius. It still validates, so a
1062
+ * game that set it keeps compiling and keeps loading.
1063
+ */
1064
+ readonly castDistance?: number;
1065
+ /**
1066
+ * Called in a batch at most once a second after streamed records changed, so the shadow levels
1067
+ * that read them redraw. A call with no region asks `VirtualShadowNode.invalidateAll`;
1068
+ * nothing changed means no call.
1069
+ *
1070
+ * Admissions and evictions are separate calls, each with the union of the bounds of the records
1071
+ * that changed — the placement position widened by the asset's own bounds, unioned over the
1072
+ * records of this update and nothing else, so a hook that forwards it to
1073
+ * `VirtualShadowNode.invalidateRegion` redraws the levels whose window covers them and leaves
1074
+ * the rest of the cascade holding its maps. A call with no region is still a blanket one: the
1075
+ * prewarm passes it while a caster's first draw is owed, and there is no region for that.
1076
+ */
1077
+ readonly invalidate?: (region?: IShadowRegion) => void;
1078
+ /**
1079
+ * An asset whose authored bounds are shorter than this casts into the finest shadow level only,
1080
+ * default 1.5 m. Ground cover below it — ferns, grass, bushes — casts a shadow that is sub-texel
1081
+ * noise at every range a wide level covers, and costs one draw per key per level there. Raise it
1082
+ * to draw everything at every range, lower it to cull more. Measured on the authored bounds, so
1083
+ * a package that scales a fern up four times is judged on the un-scaled fern.
1084
+ */
1085
+ readonly smallCasterMetres?: number;
1086
+ };
1087
+ /**
1088
+ * Triangles a hand-placed chunk's merged material group may reach before one of its
1089
+ * `InstancedMesh` is left instanced. Defaults to 43,690, the same 4 MiB
1090
+ * budget the merged buffers are split on counted in the worst case, a de-indexed triangle: a merged
1091
+ * group is a single draw, so expanding into it wins until the merged geometry is too big for the
1092
+ * frame, and above it the instanced draw is the cheaper of the two. A group that crosses the budget
1093
+ * is split into several meshes in traversal order rather than grown, and an instanced shape over
1094
+ * 2,048 triangles is never expanded. Everything else in a chunk merges regardless — one mesh per
1095
+ * material, in the main pass and in every shadow pass that redraws it.
1096
+ */
1097
+ readonly chunkMergeMaxTriangles?: number;
1098
+ /**
1099
+ * `(url) => Promise<Object3D>`, overriding `assets.model`; a raw `GLTFLoader` or a game's own
1100
+ * loader works. The url is the authored one, so a compiled package wants `assets` instead.
1101
+ */
1102
+ readonly loadModel?: (url: string) => Promise<Object3D>;
1103
+ /**
1104
+ * Model loads in flight at once, assets and chunks together. Defaults to `loadAll`'s
1105
+ * `concurrency`, six.
1106
+ */
1107
+ readonly concurrency?: number;
1108
+ /**
1109
+ * Cell-asset batches refiltered per `update`, nearest cell first. Defaults to 16. A cell that did
1110
+ * not get its turn keeps drawing the batches it has until a later update replaces them.
1111
+ */
1112
+ readonly rebuildsPerUpdate?: number;
1113
+ /**
1114
+ * Seconds of motion to stream ahead of, default 1.5: the ring centres on where the follow point
1115
+ * will be (`position + velocity * prefetchSeconds`), so a fast camera finds cells already loaded
1116
+ * instead of outrunning them. The lead is capped at three quarters of the ring, so the cell the
1117
+ * follow point is in always stays resident. `0` streams around the follow point itself.
1118
+ */
1119
+ readonly prefetchSeconds?: number;
1120
+ /**
1121
+ * New batch meshes created per update, default 2. On WebGPU each new InstancedMesh builds its
1122
+ * own shader the first frame it draws (~10-20 ms of main thread), so a burst of first-seen assets
1123
+ * is spread over frames instead of stacked into one; recycled meshes are not counted.
1124
+ */
1125
+ readonly freshMeshesPerUpdate?: number;
1126
+ /**
1127
+ * New batch meshes per update while the startup cover hides the world, default 8x
1128
+ * `freshMeshesPerUpdate`. The first-draw shader cost the default spreads is invisible behind an
1129
+ * opaque loading screen, and a canopy that needs fresh meshes otherwise trickles in two a frame.
1130
+ */
1131
+ readonly coveredFreshMeshesPerUpdate?: number;
1132
+ /**
1133
+ * Side of the world-grid square one shared batch's records are clustered into, in world units.
1134
+ * Defaults to the package's own `cellSize`, which is the square the placements are already cut
1135
+ * on. Each `(key, cluster)` is its own caster InstancedMesh with its own bounds on the shadow
1136
+ * caster layer, so a virtual-shadow level submits only the clusters its window covers. The main
1137
+ * pass keeps one mesh per `asset:level:part` whatever this is, so it costs main-pass draws
1138
+ * nothing. A larger square means fewer caster meshes and more of the world in every level render.
1139
+ */
1140
+ readonly clusterSize?: number;
1141
+ /**
1142
+ * Milliseconds one `update` may spend admitting streamed content — cell batches, terrain tiles,
1143
+ * colliders and `maxDistance`/`lods` refilters together. Defaults to 2, and `Infinity` opts out
1144
+ * of the ceiling entirely.
1145
+ *
1146
+ * The ceiling is a budget, not a promise: one unit of work always finishes, so a frame spends at
1147
+ * most this plus its last unit. Work that does not fit waits for the next `update` rather than
1148
+ * being dropped, and `stats().admission` reports what is waiting. A frame that admits nothing
1149
+ * costs nothing here.
1150
+ */
1151
+ readonly admissionBudgetMs?: number;
1152
+ /**
1153
+ * The admission budget while the startup cover hides the world and readiness is pending. Defaults
1154
+ * to 8x `admissionBudgetMs` (16 ms for the 2 ms default), so the spawn a loading screen waits on
1155
+ * is admitted in fewer frames. Set it equal to `admissionBudgetMs` to keep one budget throughout.
1156
+ */
1157
+ readonly coveredAdmissionBudgetMs?: number;
1158
+ /**
1159
+ * Milliseconds source for the admission budget, `performance.now` by default. Injectable so a
1160
+ * test can prove the ceiling instead of hoping a machine is slow enough to show it.
1161
+ */
1162
+ readonly admissionNow?: () => number;
1163
+ /**
1164
+ * The screen-space projection the extra levels of a baked AutoLOD chain are switched at, for an
1165
+ * asset whose `world.json` entry names no nonempty authored `lods` of its own. An explicit empty
1166
+ * list also uses the chain when prepared geometry and material still match its static contract.
1167
+ *
1168
+ * A chain measures its levels' geometric error in world units and the model runtime turns that
1169
+ * into pixels per frame; a batched draw cannot, so the same test is solved for distance once,
1170
+ * here, and every placement beyond it draws the next level. `fovY` is the vertical field of view
1171
+ * in degrees and `viewportHeight` the drawing-buffer height in raster pixels — a CSS height is the
1172
+ * wrong number, exactly as it is for the model runtime.
1173
+ *
1174
+ * Defaults are 60° over 1080 raster rows: a desktop view, and what the switch distance is a
1175
+ * function of. A world whose camera this class cannot see should pass its own, or a world with a
1176
+ * narrow field of view (a telephoto gun sight) or a tall window will switch earlier than its
1177
+ * pixels ask for. An asset with nonempty authored `lods` ignores all three numbers entirely: the package is
1178
+ * the authority on its own shape.
1179
+ *
1180
+ * `maxPixelError` is the error budget, in pixels, every synthesized level is selected against, and
1181
+ * it defaults to 4 rather than to the budget the asset's chain was registered with. The
1182
+ * registered budget is calibrated for a `ModelLod`, which picks a level for *one* mesh from where
1183
+ * that mesh is on screen; an instanced draw cannot, because every placement in the draw is at its
1184
+ * own distance and the draw is one call with one geometry. The batched answer has to be solved
1185
+ * once, for the whole key, which moves every switch distance outward by the ratio of the budgets —
1186
+ * and a 1 px budget is calibrated for a hero object filling the screen. At 1 px a tree's switches
1187
+ * land at 400–600 m on a 1080-row view, which on a 2 km map with a 640 m ring is past most of the
1188
+ * resident world: the levels are all there and none of them is ever selected, which is the same
1189
+ * full triangle bill the chain was added to remove. Four pixels puts the first switch inside the
1190
+ * ring, where it can actually do something.
1191
+ */
1192
+ readonly autoLod?: {
1193
+ readonly fovY?: number;
1194
+ readonly viewportHeight?: number;
1195
+ readonly maxPixelError?: number;
1196
+ };
1197
+ /**
1198
+ * The GPU-driven main pass: one compute dispatch culls and LOD-selects every resident placement
1199
+ * into a shared matrix buffer, and each main key draws its own region of it through an indirect
1200
+ * record. The CPU keeps only coarse per-cell visibility and admits the complete resident
1201
+ * `maxDistance` source set; a walking camera therefore costs no instance repack or cull/LOD
1202
+ * replacement. An explicit `placementReach` remains an admission boundary because it has no GPU
1203
+ * slot equivalent.
1204
+ *
1205
+ * `true` by default where the backend can run it: it needs compute, storage buffers and
1206
+ * `drawIndexedIndirect`, and a backend without them falls back to exactly this class's CPU path —
1207
+ * a lost saving, never a wrong picture. `gpuScene: false`, `TN_GPU_SCENE=0` or `?tnGpuScene=0`
1208
+ * turns it off, and `stats().gpuScene` and the `TN_WORLD_GPU_SCENE` line say which path a run
1209
+ * took.
1210
+ */
1211
+ readonly gpuScene?: boolean;
1212
+ /**
1213
+ * Hold every dispatch's indirect args against the pure `cullAndSelect` reference and print the keys
1214
+ * that disagree. `false` by default, and `TN_GPU_SCENE_VALIDATE=1` or `?tnGpuSceneValidate=1` turns
1215
+ * it on.
1216
+ *
1217
+ * A readback is a queue submission and a mapped buffer, so this is a mode for answering "which key
1218
+ * draws fewer instances than the CPU path" and never a walk to be measured with.
1219
+ * For a fixed-step diagnostic walk, call {@link validateGpuFrame} after the render and await its
1220
+ * promise before advancing the next frame; that opt-in fence checks every dispatch and replaces
1221
+ * the periodic samples for that world.
1222
+ */
1223
+ readonly gpuSceneValidate?: boolean;
1224
+ /**
1225
+ * Sample what the GPU actually selects in the main pass — a readback of the indirect args every
1226
+ * 30 dispatches — and report it as `stats().gpuScene` and on the `TN_WORLD_GPU_SCENE`
1227
+ * line. Off unless asked: the engine asks when the frame budget is on, and a validation turns it on
1228
+ * by itself, so `TN_FRAME_BUDGET`'s `mainGpuTriangles` is the GPU-selected count and not the mesh
1229
+ * capacity `tri=` reports. Set it explicitly when driving the world without a frame budget.
1230
+ */
1231
+ readonly gpuSceneTally?: boolean;
1232
+ /**
1233
+ * Run the hierarchical-depth occlusion test in the cull kernel and report what it would cull.
1234
+ *
1235
+ * `"measure"` (the default unless `?tnOcclusion=off`, `TN_OCCLUSION=off` or a caller's own value
1236
+ * says otherwise) builds a max-distance pyramid from the previous frame's scene-pass depth and
1237
+ * counts the placements the test hides **while drawing all of them**: a measured frame is the frame
1238
+ * an unmeasured run draws, so the only difference between the two runs is the count and the cost of
1239
+ * building the pyramid. `"off"` runs no test and allocates nothing. `stats().gpuScene.occlusion`
1240
+ * reports the counts, the pyramid's own cost, and `refused: no scene depth` when no render chain
1241
+ * installed a pass to take a depth from.
1242
+ *
1243
+ * See {@link occlusionMode} and `render/depth-pyramid.ts`.
1244
+ */
1245
+ readonly occlusion?: OcclusionMode;
1246
+ /**
1247
+ * Record every GPU-dressed main batch mesh and every resident cell's hand-placed chunks into
1248
+ * `BundleGroup`s, and replay the records instead of re-walking three's per-object path for each
1249
+ * draw. On by default: PRD-494 AC-2 measured the walking `draw` span at a 5.0 ms lower p95 than
1250
+ * develop over 3 interleaved runs with bundles on and a picture a blind world gate called equal,
1251
+ * which is the measurement the old opt-in default was decided without — so `bundles: false`,
1252
+ * `?tnBundles=0` or `TN_BUNDLES=0` is the way back to the per-object path, and `stats().bundle`
1253
+ * and the `TN_WORLD_BUNDLE` line say which way a run took and what asked for it.
1254
+ *
1255
+ * A record is an encoder, not a render pass, so only a draw that needs no live pass is recorded:
1256
+ * a framebuffer reader, a transmissive impostor, a skinned or morphed mesh and a per-object hook
1257
+ * all stay on the path they were already on. See `bundleSafe`.
1258
+ *
1259
+ * The render list inside a bundle is fixed when it is recorded, so a bundled mesh is never hidden:
1260
+ * the dispatch draws zero instances for a key the camera cannot see, and an indirect draw of zero
1261
+ * instances costs the GPU nothing. Toggling `visible` would force a re-record instead, and the
1262
+ * shadow node's texel gate skips a bundled mesh for the same reason.
1263
+ *
1264
+ * A chunk has no dispatch behind it, so the two answers it needs are its own: its meshes are never
1265
+ * culled by the record, because a mesh a record dropped is missing geometry the moment the camera
1266
+ * turns towards it, and each cell records into its own group whose `visible` is the main cull's
1267
+ * answer for that cell — the same coarse answer the scatter batches take, one cell wide. What that
1268
+ * costs is the price of the option: a cell the cull cannot see is not drawn at all, which takes its
1269
+ * chunk casters out of the shadow levels with it, and a cell it can only partly see draws the part
1270
+ * facing away. Both rasterize nothing or nearly so; the missing shadow is the real difference.
1271
+ */
1272
+ readonly bundles?: boolean;
1273
+ /**
1274
+ * Raise the LOD distance bias when the main pass is over its share of the frame's GPU budget, and
1275
+ * decay it back toward 1 when it is comfortably under, default true.
1276
+ *
1277
+ * The main pass is triangle-bound: a flyover's near and mid tree levels are millions of triangles
1278
+ * and the GPU time tracks that count. When `renderer.gpuMainMs()` — the smoothed main-pass GPU
1279
+ * time — exceeds `mainGpuShare` of a 60 fps frame, every LOD switch is crossed earlier by
1280
+ * multiplying the camera distance both selection paths compare by one shared multiplier, coarsening
1281
+ * the same placements the GPU is already struggling to draw. It rises in bounded steps, never in a
1282
+ * jump, so no level pops. `false` pins the bias at 1 for the whole run, which is byte-identical to
1283
+ * the selection before this feature existed: `?tnAdaptiveLod=0`, `TN_ADAPTIVE_LOD=0` or
1284
+ * `__tnAdaptiveLod = 0` also turns it off.
1285
+ */
1286
+ readonly adaptiveLod?: boolean;
1287
+ /**
1288
+ * The fraction of a frame's GPU time the main pass may take before the adaptive LOD bias rises,
1289
+ * `(0, 1]`, default 0.5.
1290
+ *
1291
+ * The budget is `mainGpuShare x min(deltaTime, 1/60 s)`: the frame cap keeps the budget honest the
1292
+ * same way the shadow refresh gate does, because the frame that draws an expensive main pass is
1293
+ * itself long and reading its own inflated delta would let the cost it judges pass its own test.
1294
+ * `?tnMainGpuShare=0.1`, `TN_MAIN_GPU_SHARE=0.1` or `__tnMainGpuShare = 0.1` forces adaptation on a
1295
+ * GPU that would otherwise never exceed the share.
1296
+ */
1297
+ readonly mainGpuShare?: number;
1298
+ /**
1299
+ * Bake a whole-asset octahedral impostor for every alpha-cutout foliage asset and append it as the
1300
+ * asset's terminal, two-triangle LOD. Default false: omission keeps the authored/generated source
1301
+ * levels, and `?tnImpostors=1` or `TN_IMPOSTORS=1` opts a launch in. It is opt-in until the judged
1302
+ * Machinefall capture passes (PRD-473 AC-3); `preserveAuthoredParts` and `lodHysteresis` still
1303
+ * require it to be off.
1304
+ *
1305
+ * Set true to bake them, or leave it off to keep the source levels for a visual comparison.
1306
+ *
1307
+ * The bake runs inside the render cadence — one of its sixteen views per `process` — so it costs a
1308
+ * slice of a frame rather than a hitch, and it starts only after the asset's own model has been
1309
+ * adopted. A seamless switch needs the impostor's atlas to cover the same cutout the source draws,
1310
+ * so an asset whose levels carry no alpha-cutout part is never baked. `false` drops only the atlas
1311
+ * terminal: every level the authored package and its baked chain give is kept, and the authored
1312
+ * middle-level cutout coverage a level would otherwise be missing its foliage at is still applied.
1313
+ */
1314
+ readonly impostors?: boolean;
1315
+ }
1316
+ /**
1317
+ * What the GPU actually selected in the main pass, from the scene's last landed tally.
1318
+ *
1319
+ * `triangles` is the GPU-selected count (`instanceCount x indexCount / 3` summed over the indirect
1320
+ * records), never the mesh-capacity upper bound `renderer.info.render.triangles` reports, and it
1321
+ * covers the main pass only: shadow passes are not tallied. `ageFrames` is how many dispatches have
1322
+ * passed since those bytes were issued, so a caller never mistakes a stale sample for this frame's.
1323
+ */
1324
+ interface IWorldCellsGpuTally {
1325
+ readonly instances: number;
1326
+ readonly triangles: number;
1327
+ readonly ageFrames: number;
1328
+ }
1329
+ interface IWorldCellsStats {
1330
+ readonly residentCells: number;
1331
+ /** Resident cells whose initial placement runs and chunks have completed admission. */
1332
+ readonly loadedCells: number;
1333
+ readonly residentKeys: readonly string[];
1334
+ /** Terrain tiles drawn, out to `terrain.streamRadius`; independent of the props' `ring`. */
1335
+ readonly residentTiles: number;
1336
+ /** Tiles holding a `createCollider` body, inside `terrain.colliderRadius`; 0 with no factory. */
1337
+ readonly residentColliders: number;
1338
+ /** Placement instances the resident cells hold, before any `maxDistance` filter. */
1339
+ readonly instances: number;
1340
+ readonly loadsInFlight: number;
1341
+ /** Model loads waiting for a free lane; served nearest-cell first, in admission order. */
1342
+ readonly loadsQueued: number;
1343
+ /**
1344
+ * Shared batches still to be minted, plus the ones minted and not yet drawn; `0` once
1345
+ * `prewarmed` has resolved.
1346
+ */
1347
+ readonly pendingPrewarm: number;
1348
+ /** Shared batches minted by the prewarm so far, cumulative. */
1349
+ readonly prewarmMinted: number;
1350
+ readonly evictions: number;
1351
+ /** Cumulative `maxDistance`/`lods` refilters performed, across every update. */
1352
+ readonly rebuilds: number;
1353
+ /**
1354
+ * Cumulative refilter *passes* run, whether or not they queued a rebuild. The pass walks every
1355
+ * resident cell, derives both distance brackets and sorts what it found, so this is what says
1356
+ * whether a follow point standing inside the 2 m step paid for it; `rebuilds` only says whether it
1357
+ * was worth anything. See `LEVEL_REFILTER_STEP_METRES`.
1358
+ */
1359
+ readonly refilters: number;
1360
+ /**
1361
+ * Cumulative replacement builds that entered CPU placement-level selection. Initial admission is
1362
+ * excluded; GPU `maxDistance`/LOD movement is not a replacement because its complete resident
1363
+ * source set stays available to dispatch selection. Explicit `placementReach` replacements are
1364
+ * included because reach remains a CPU admission boundary.
1365
+ */
1366
+ readonly levelRefilters: number;
1367
+ /**
1368
+ * Cumulative stale cell-assets the refilter passes found, across every update. The pass walks every
1369
+ * resident cell and gates it as a whole before it looks at one batch, so a follow point that has
1370
+ * crossed nothing leaves this still — which is what says the walk cost brackets and comparisons and
1371
+ * not allocations.
1372
+ */
1373
+ readonly refilterEntries: number;
1374
+ /**
1375
+ * Cumulative refilters whose rebuild held the same records and were settled without a write,
1376
+ * clear or compaction. A rising share of `rebuilds` is a follow point crossing a cell's distance
1377
+ * bracket rather than any placement crossing a gate.
1378
+ */
1379
+ readonly unchanged: number;
1380
+ readonly failures: number;
1381
+ /**
1382
+ * What the main-pass cull cost, cumulative, and the evidence that a settled camera costs nothing.
1383
+ *
1384
+ * `frustums` is one a frame that had a perspective camera — it used to be one per main mesh, ~230
1385
+ * of them on a 2 km walk. `windows` is how many of those meshes had to re-derive their window at
1386
+ * all, and `repacks` how many copied records: both are 0 on a frame where the visible squares did
1387
+ * not change and no record joined or left, which is what the two integer comparisons in
1388
+ * `SharedBatch.cullFrom` buy.
1389
+ */
1390
+ readonly mainCull: {
1391
+ readonly frustums: number;
1392
+ readonly windows: number;
1393
+ readonly repacks: number;
1394
+ readonly visibleEpoch: number;
1395
+ };
1396
+ /**
1397
+ * What the GPU-driven main pass is doing, and why it is not: `on` is the answer, `reason` is the
1398
+ * one line `TN_WORLD_GPU_SCENE` printed, and `dispatches` is what the walk actually paid for its
1399
+ * per-instance work. `mainCull.repacks` stays at `0` while it is on, and `levelRefilters` reports
1400
+ * replacement builds that still execute CPU placement-level selection. GPU `maxDistance`/LOD
1401
+ * movement is not a replacement because the source set stays resident for dispatch selection.
1402
+ * The aggregate `refilters` counter can still rise for its retained scan, and explicit
1403
+ * `placementReach` replacements remain visible. `dressed` over `meshes` is the marker line's own
1404
+ * pair, and it is the one that says the scene has meshes to draw with: an `on` with `0` dressed is
1405
+ * a ring the CPU path is still drawing.
1406
+ */
1407
+ readonly gpuScene: {
1408
+ readonly on: boolean;
1409
+ readonly reason: string;
1410
+ readonly dispatches: number;
1411
+ /** Resident source records: one per placement, shared by every part of the level it reached. */
1412
+ readonly instances: number;
1413
+ readonly keys: number;
1414
+ readonly dressed: number;
1415
+ readonly meshes: number;
1416
+ /**
1417
+ * Instances and triangles the GPU actually selected in the main pass, and the age of that
1418
+ * sample in dispatches. Absent until the first tally lands, never zero: the scene's own
1419
+ * `instances` above is what it holds, and `gpuInstances` is what the GPU drew.
1420
+ */
1421
+ readonly gpuInstances?: number;
1422
+ readonly gpuTriangles?: number;
1423
+ readonly gpuTallyAgeFrames?: number;
1424
+ /**
1425
+ * What the pyramid occlusion test would cull, when a launch asked it to measure. `share` is the
1426
+ * would-cull share of the main pass's GPU-selected triangles from the same landed readback, which
1427
+ * is the number the go/no-go multiplies by `gpuMain`; `reason` names why nothing was measured.
1428
+ */
1429
+ readonly occlusion?: NonNullable<IWorldGpuSceneReport["occlusion"]>;
1430
+ };
1431
+ /**
1432
+ * Main-pass bundle membership: `children` counts grouped roots — every recorded main mesh under one
1433
+ * of the main record's shards, plus every chunk of every resident cell under that cell's own group —
1434
+ * `cpuMeshes` and `gpuMeshes` count shared batch members, and `on` reports actual main/chunk
1435
+ * membership. These are membership counts, not observed backend draws. `records` counts
1436
+ * invalidations since load: membership, material or geometry changes and CPU window repacks
1437
+ * invalidate; GPU indirect count updates do not.
1438
+ *
1439
+ * `eligibility` counts CPU material checks, snapshot validations, fresh structural walks and
1440
+ * oversized or unsupported child output. Snapshots check own links and Three's child readers on
1441
+ * every check, detecting deep edits without requiring `needsUpdate`; child discovery still allocates.
1442
+ *
1443
+ * `reason` is who asked: `default` is a run that set nothing, `option` is a load that named
1444
+ * `bundles`, and `launch` is `?tnBundles` / `TN_BUNDLES` / `__tnBundles`. It is on the marker line
1445
+ * too, because a run that turns the default off is exactly the run a reader cannot tell from a
1446
+ * failing one without it.
1447
+ */
1448
+ readonly bundle: {
1449
+ readonly on: boolean;
1450
+ readonly children: number;
1451
+ readonly cpuMeshes: number;
1452
+ readonly gpuMeshes: number;
1453
+ readonly eligibility: {
1454
+ readonly checks: number;
1455
+ readonly refreshes: number;
1456
+ readonly validations: number;
1457
+ readonly uncached: number;
1458
+ };
1459
+ readonly reason: string;
1460
+ readonly records: number;
1461
+ };
1462
+ /**
1463
+ * The runtime impostor path: how many assets appended a terminal level, how many bakes are still
1464
+ * queued or in flight, the triangles all terminal levels submit together — the number the whole
1465
+ * feature exists to reduce — and the cache size: the logical colour atlas bytes held (each atlas's
1466
+ * RGBA8 colour and normal mip chains), not every physical GPU buffer a render target may own, and
1467
+ * the budget those bytes are enforced against.
1468
+ */
1469
+ readonly impostor: {
1470
+ readonly assets: number;
1471
+ readonly pending: number;
1472
+ readonly atlasBytes: number;
1473
+ readonly budgetBytes: number;
1474
+ readonly terminalTriangles: number;
1475
+ /**
1476
+ * The whole-map far aggregates: one `InstancedMesh` per atlas cache key, the ORIGINAL placements
1477
+ * they hold (`instances`), how many of those the near ring has taken back (`nearOwned`), the
1478
+ * physical instance bytes, and how many times an aggregate's buffer has been written. Missing
1479
+ * measurements stay absent; a settled camera holds `uploads` still.
1480
+ */
1481
+ readonly far: {
1482
+ readonly aggregates: number;
1483
+ readonly instances: number;
1484
+ readonly live: number;
1485
+ readonly nearOwned: number;
1486
+ readonly bytes: number;
1487
+ readonly uploads: number;
1488
+ };
1489
+ };
1490
+ /** Cumulative rejected requests: cells skipped, instances or bytes refused, terrain retries. */
1491
+ /** Compilation and zero-count main backend submission are separate observations. These counts
1492
+ * do not prove GPU execution, image quality, or reduced frame time. bytes includes pending
1493
+ * reservation and decoded copies/textures, never a claim about physical driver allocation. */
1494
+ readonly hlod: {
1495
+ readonly on: boolean;
1496
+ readonly loaded: number;
1497
+ readonly compiled: number;
1498
+ readonly observed: number;
1499
+ readonly active: number;
1500
+ readonly pending: number;
1501
+ readonly bytes: number;
1502
+ readonly refused: number;
1503
+ /** Why the latest proxy was refused, or empty when none was; a count alone names no cause. */
1504
+ readonly reason: string;
1505
+ readonly failures: number;
1506
+ };
1507
+ readonly pressure: {
1508
+ readonly cells: number;
1509
+ readonly instances: number;
1510
+ readonly bytes: number;
1511
+ };
1512
+ /**
1513
+ * What the last `update` spent on admitting streamed content, and what it left behind.
1514
+ *
1515
+ * A rising `backlog` is the honest signal that admission is not keeping up with the follow point;
1516
+ * it is the one number that says a player is outrunning the world.
1517
+ */
1518
+ readonly admission: {
1519
+ /** Milliseconds the last `update` spent admitting; at most the budget plus its last unit. */
1520
+ readonly spentMs: number;
1521
+ /** Cell-asset builds the last `update` had no budget for, still queued for a later one. */
1522
+ readonly deferred: number;
1523
+ /** Placement slices and meshes left to publish, plus one unit while terrain admission is owed. */
1524
+ readonly backlog: number;
1525
+ };
1526
+ }
1527
+ /** Local render coverage, independent of shader prewarm and distant admission. */
1528
+ interface IWorldRegionReadiness {
1529
+ readonly requiredCells: number;
1530
+ readonly loadedCells: number;
1531
+ readonly requiredTerrainTiles: number;
1532
+ readonly loadedTerrainTiles: number;
1533
+ readonly failures: number;
1534
+ readonly cancelled: boolean;
1535
+ readonly ready: boolean;
1536
+ }
1537
+ /**
1538
+ * A plain `{ min, max }` region, the shape a shadow level's invalidation reads and the shape a game
1539
+ * can be handed without importing three. Plain numbers, so the object a caller records its bounds
1540
+ * in is the object that crosses the boundary.
1541
+ */
1542
+ interface IShadowRegion {
1543
+ /** Only added casters; their redraw can retain the existing depth. */
1544
+ admission?: boolean;
1545
+ min: {
1546
+ x: number;
1547
+ y: number;
1548
+ z: number;
1549
+ };
1550
+ max: {
1551
+ x: number;
1552
+ y: number;
1553
+ z: number;
1554
+ };
1555
+ }
1556
+ /**
1557
+ * Stream a Blender-authored world package by cell and keep it resident around a followed point.
1558
+ *
1559
+ * The class composes `TerrainTiles` for the package's heightmap, builds one `InstancedBatch` per
1560
+ * resident cell asset run, distance level and mesh part, and loads hand-placed chunk GLBs through
1561
+ * `loadAll` + `addInSlices`. Ring residency, CPU per-asset `maxDistance` filtering, GPU dispatch
1562
+ * culling, the per-asset `lods` levels, hard budgets and generation-tokened cancellation all live
1563
+ * here; every geometry, material and surface still comes from the package's GLBs and the game.
1564
+ *
1565
+ * An asset is drawn per part, not per model: a GLB with several primitives is one `InstancedBatch`
1566
+ * each, and a scattered part whose own material is transparent draws as an alpha cutout unless the
1567
+ * game asks for blending, because an `InstancedMesh` cannot sort its instances.
1568
+ *
1569
+ * An asset with no nonempty authored `lods` can draw its own model's baked AutoLOD chain at distances
1570
+ * measured over the `autoLod` viewport. An explicit empty list enrolls only unchanged static parts;
1571
+ * section ranges, custom attributes, alpha foliage and vertex deformation retain source geometry.
1572
+ *
1573
+ * @situation stream a large Blender-authored world by cell instead of one huge GLB
1574
+ * @situation keep scattered props and hand-placed chunks resident around a moving player
1575
+ * @situation honour per-asset draw distances and hard streaming budgets without a mid-frame throw
1576
+ * @constraint surface is the game's; this class creates no material, colour or geometry
1577
+ * @constraint budgets are hard caps that report pressure instead of over-committing
1578
+ * @constraint model loads are bounded by `concurrency` (default 12) across every resident cell, not per cell
1579
+ * @constraint refilters are bounded by `rebuildsPerUpdate` (default 16) per update, nearest cell first
1580
+ * @constraint admission is bounded by `admissionBudgetMs` (default 2) per update across every path, plus at most one unit each for terrain and props; while props are queued terrain takes at most half, so neither starves the other, and a deferred cell keeps drawing what it has
1581
+ * @constraint SkinnedMesh parts are skipped; an instanced copy would draw one rest pose
1582
+ * @constraint a baked chain's switch distances are measured against `autoLod` (default 4 px of error over 60° and 1080 raster rows), because an instanced draw cannot select a level per instance; an asset with nonempty authored `lods` never consults it; explicit empty lists enroll only unchanged static geometry/material parts
1583
+ * @constraint eligible static sources can use cooked HLOD (chunk-only alongside GPU scatter, whole-cell on CPU) after compilation and an observed main-context backend submission; projected-error hysteresis requires actual source triangle reduction and no extra material draws, unsupported or shared source stays resident, and collision/shadow paths retain source representations; stats().hlod counts lifecycle and charged resources, not GPU timing or physical allocation
1584
+ * @override `hlod: false` keeps source rendering; ring, budgets, terrain tile size/resolution, terrain stream and collider radius, `transparentScatter`, `clusterSize` and `shadows.invalidate`, load `concurrency`, `rebuildsPerUpdate`, `admissionBudgetMs` and the package's per-asset maxDistance
1585
+ * @constraint `prewarmed` resolves once every prewarmed shared batch has been drawn; a game with a loading screen waits on it, and `stats().pendingPrewarm` is the same gate as a number
1586
+ * @constraint every `asset:level:part` is one InstancedMesh for the main pass, plus one caster InstancedMesh per world-grid square of `clusterSize` on the shadow caster layer, so the main pass draws one mesh per key and a shadow level submits only the squares it covers
1587
+ * @constraint two definitions the asset loader resolves to one model — the same cooked `glb`, the same `lods` at the same distances, the same `maxDistance` and bounds — are one asset under the lexicographically smallest id: one model load, one set of `asset:level:part` keys, one prewarm and one refcount, released when the last cell holding any member of the group leaves the ring; `TN_WORLD_ASSET_ALIAS` reports how many of the package's assets are really distinct
1588
+ * @constraint the main pass mesh draws only the squares the render camera's frustum covers — on by default, narrowed once per frame for every main batch by the engine's render-cadence dispatch, never for an orthographic camera — a batch with nothing to draw is hidden rather than submitted at `count 0`, and `TN_WORLD_MAIN_CULL` reports both every five seconds
1589
+ * @constraint a loaded chunk is merged by material before it is added, so it submits one draw per material rather than one per node; a skinned, multi-material or morph-target mesh, one carrying a baked AutoLOD chain, and an instanced mesh past `chunkMergeMaxTriangles` (default 43,690 triangles) or with a shape over 2,048 triangles, all keep their own geometry; a material group crossing 131,072 vertices (4 MiB of position + normal + uv) is split into several meshes in traversal order instead of one giant upload, indexed parts keep their index, and `TN_WORLD_CHUNK_MERGE` reports what the merge did and the bytes it left
1590
+ * @constraint `shadows.castDistance` is accepted and ignored (clusters replaced it); `shadows.invalidate` is called at most once a second after streamed records changed
1591
+ * @example
1592
+ * const world = await WorldCells.load({ url: "/world/world.json", surface, follow, ring: 1, budgets: { residentCells: 25, instances: 20000, bytes: 8000000 } });
1593
+ * scene.add(world);
1594
+ * world.update();
1595
+ */
1596
+ declare class WorldCells extends Group implements IComputeDriven {
1597
+ #private;
1598
+ readonly processCadence: "render";
1599
+ readonly processDuringStartup = true;
1600
+ /**
1601
+ * How the shadow cascade reaches this world's GPU keys: a level render hands its own four numbers
1602
+ * here and gets its set selected into the shadow twins, which the shadow key meshes on
1603
+ * `VIRTUAL_SHADOW_KEY_LAYER` then draw. Published on this object — the world's own root, which is
1604
+ * what `VirtualShadowNode` walks — and duck-typed there, because the world chunk and the shadow
1605
+ * node are separate and neither names the other's package types.
1606
+ *
1607
+ * Published only when `?tnShadowGpuKeys=1` asked for it, which is what makes the node's own
1608
+ * keyed path and this world's twin meshes one switch: with nothing published a level reads no
1609
+ * keys, mints no twin and submits nothing, and every picture is the one it drew before.
1610
+ */
1611
+ readonly tnShadowGpuKeys: ((renderer: IRendererLike, level: IShadowLevel) => void) | undefined;
1612
+ private constructor();
1613
+ static load(options: IWorldCellsLoadOptions): Promise<WorldCells>;
1614
+ /** Fresh streaming state; the visible snapshot is replaced on the first update. Owned caches are independent. */
1615
+ clone(recursive?: boolean): this;
1616
+ get released(): boolean;
1617
+ get warmupNodes(): readonly unknown[];
1618
+ /**
1619
+ * Resolves once every minted batch has been drawn at least once, main and shadow context.
1620
+ *
1621
+ * The loading gate a game with a loading screen waits on, so the shader builds the prewarm exists
1622
+ * to move happen behind it instead of in the first seconds of play. It counts updates the world
1623
+ * was in a scene for, because a batch added while the world is not in a scene is projected by
1624
+ * nothing and builds nothing. `dispose` settles it too: a world torn down mid-load must not leave
1625
+ * a game awaiting it forever.
1626
+ */
1627
+ get prewarmed(): Promise<void>;
1628
+ /**
1629
+ * Fence one just-rendered GPU dispatch for a diagnostic walk, resolving after both readbacks land.
1630
+ * Call after {@link update} and the render, then await it before advancing the measured frame.
1631
+ */
1632
+ validateGpuFrame(frame: number): Promise<IWorldGpuFrameValidation>;
1633
+ /**
1634
+ * Per-frame residency step; call it wherever `TerrainTiles.process` is called.
1635
+ *
1636
+ * Reads the follow target, keeps the in-ring cells, evicts cells beyond the hysteresis ring, and
1637
+ * spends one admission budget on everything the ring newly wants: cell-asset batches, terrain
1638
+ * tiles, colliders and the `maxDistance`/`lods` refilters the follow point has moved far enough to
1639
+ * have changed. Whatever does not fit waits for the next call — nothing is dropped, and
1640
+ * `stats().admission` is the honest report of what is waiting. A terrain budget throw is caught
1641
+ * and counted, and so is a teardown that throws while releasing what left; `failures` carries
1642
+ * both. Every other error, the game's included, escapes.
1643
+ *
1644
+ * The residency pass itself is skipped while the follow point has moved less than half a metre
1645
+ * since the last one and nothing is pending (a load, a cell build, a deferred terrain admission, a
1646
+ * prewarm mint or a shadow level not yet told), because the pass would re-derive the set the
1647
+ * world already holds. The drain, the prewarm, the invalidation and the main cull below it run
1648
+ * every time.
1649
+ *
1650
+ * `camera` is the frame's render camera, which the engine's render-cadence dispatch hands over
1651
+ * because it is the one this world draws with. A game that drives this world itself can pass it,
1652
+ * and a game that does not keeps every resident record drawn.
1653
+ */
1654
+ update(renderer?: IRendererLike, camera?: Camera): void;
1655
+ process(renderer?: IRendererLike, camera?: Camera, covered?: boolean): void;
1656
+ attachRenderer(renderer: IRendererLike): void;
1657
+ /** Current per-asset reference count; an asset absent from the map is `0`. */
1658
+ assetRefCounts(): Readonly<Record<string, number>>;
1659
+ /**
1660
+ * Turn on the GPU-selected tally for the rest of the world's life.
1661
+ *
1662
+ * The engine calls this when the frame budget is on, and a `gpuSceneValidate` turns it on without
1663
+ * it. Set `gpuSceneTally: true` at load instead when a world is driven outside a frame budget.
1664
+ */
1665
+ enableGpuSceneTally(): void;
1666
+ /**
1667
+ * The GPU's own main-pass selection from the last landed tally, or `undefined` before one lands.
1668
+ *
1669
+ * `triangles` is the GPU-selected count, which `renderer.info.render.triangles` cannot give for an
1670
+ * indirect draw: three counts the mesh capacity there, an upper bound over what the kernel could
1671
+ * select. This is what the kernel selected. Main pass only, and `ageFrames` is its staleness.
1672
+ */
1673
+ gpuSceneTally(): IWorldCellsGpuTally | undefined;
1674
+ stats(): IWorldCellsStats;
1675
+ detach(): void;
1676
+ /** Completed content intersecting a square around a fixed spawn, in world metres. */
1677
+ readinessAt(position: {
1678
+ readonly x: number;
1679
+ readonly z: number;
1680
+ }, radius?: number): IWorldRegionReadiness;
1681
+ dispose(): void;
1682
+ }
1683
+
174
1684
  interface IHeightfieldOrigin {
175
1685
  readonly x: number;
176
1686
  readonly z: number;
@@ -184,6 +1694,29 @@ interface IHeightfieldOptions {
184
1694
  readonly width: number;
185
1695
  readonly worldPasses?: IHeightfieldWorldPassOptions;
186
1696
  }
1697
+ /** A rectangular window of a heightfield's canonical samples, in grid indices. */
1698
+ /** Hands out the union of every window `updateHeights` wrote since the last `take`. */
1699
+ interface IHeightfieldChangeTracker {
1700
+ /** The changed window since the previous take, or undefined when nothing changed. */
1701
+ take(): IHeightfieldRegionBounds | undefined;
1702
+ /** Stop tracking. Idempotent. */
1703
+ dispose(): void;
1704
+ }
1705
+ interface IHeightfieldRegionBounds {
1706
+ /** First column (x index), inclusive. */
1707
+ readonly column: number;
1708
+ /** Number of columns covered. */
1709
+ readonly columns: number;
1710
+ /** First row (z index), inclusive. */
1711
+ readonly row: number;
1712
+ /** Number of rows covered. */
1713
+ readonly rows: number;
1714
+ }
1715
+ /** A rectangular window plus the replacement samples written over it. */
1716
+ interface IHeightfieldRegion extends IHeightfieldRegionBounds {
1717
+ /** Row-major samples, `columns * rows` long and read with the region's own stride. */
1718
+ readonly heights: Float32Array;
1719
+ }
187
1720
  interface IHeightfieldWorldPassOptions {
188
1721
  /** Maximum TSL compute dispatches submitted by one rendered frame. */
189
1722
  readonly dispatchBudget: number;
@@ -213,6 +1746,7 @@ interface IStoredHeightfieldChannels {
213
1746
  * @situation query the same ground height or normal that a player sees and collides with
214
1747
  * @situation ask how high the ground is here
215
1748
  * @situation build islands and coastlines from terrain
1749
+ * @situation keep a collider or other copy of a deforming terrain in step without rescanning the whole field (`trackChanges`)
216
1750
  * @constraint sampleHeight owns the terrain shape and stays in game source; the framework stores and interpolates its output
217
1751
  * @constraint rows and columns are vertex counts; geometry is row-major z-then-x and collider export transposes once into Rapier's column-major matrix order
218
1752
  * @override rows, columns, width, depth, origin, and sampleHeight are explicit on every field
@@ -245,10 +1779,55 @@ declare class Heightfield extends Group implements IComputeDriven {
245
1779
  get memoryBytes(): number;
246
1780
  heightAt(x: number, z: number): number;
247
1781
  normalAt(x: number, z: number, target?: Vector3): Vector3;
1782
+ /**
1783
+ * Monotonic sample version, incremented by every `updateHeights` call.
1784
+ *
1785
+ * A renderer or collider that caches derived data compares this against its own last-seen value
1786
+ * instead of diffing the whole grid each frame.
1787
+ */
1788
+ get version(): number;
1789
+ /**
1790
+ * Overwrite one rectangular window of the canonical samples.
1791
+ *
1792
+ * Height is the one buffer queries, rendered geometry and collider export share, so a second
1793
+ * terrain representation is never needed: a simulation writes its surface here and every
1794
+ * consumer already reads it. The whole window is validated before any sample changes, so a
1795
+ * malformed call leaves the field untouched rather than half-written.
1796
+ * @situation deform terrain, snow or water in place and have queries and collision follow
1797
+ * @constraint the region must lie inside the field; an out-of-bounds window throws and writes nothing
1798
+ * @constraint heights is `columns * rows` long, row-major, and every sample must be finite
1799
+ */
1800
+ updateHeights(region: IHeightfieldRegion): void;
1801
+ /**
1802
+ * Follow which samples change, independently of every other follower.
1803
+ *
1804
+ * A consumer that mirrors the surface — a collider, a GPU copy, a cache — needs the window that
1805
+ * changed since *it* last looked; comparing the whole field instead costs every sample on every
1806
+ * change. Each tracker keeps its own union of the windows `updateHeights` wrote, so two
1807
+ * consumers never take each other's changes.
1808
+ *
1809
+ * ```ts
1810
+ * const changes = field.trackChanges();
1811
+ * const changed = changes.take(); // undefined when nothing was written
1812
+ * ```
1813
+ */
1814
+ trackChanges(): IHeightfieldChangeTracker;
1815
+ /** The collider sample at `row`, `column`: what `toColliderHeights()` holds there, without a copy. */
1816
+ colliderHeight(row: number, column: number): number;
1817
+ /**
1818
+ * Rewrite an existing `toGeometry()` result from the current canonical samples.
1819
+ *
1820
+ * Positions carry over unchanged because only the surface moves; y and normals are refreshed
1821
+ * from the same sampler queries use, which is what keeps a rendered vertex and a height query
1822
+ * from disagreeing. Pass a region to touch only the window a simulation just changed.
1823
+ * @situation redraw a terrain, snow or water mesh after its samples changed
1824
+ * @constraint geometry must come from `toGeometry()` with the same rows and columns
1825
+ */
1826
+ refreshGeometry(geometry: BufferGeometry, bounds?: IHeightfieldRegionBounds): void;
248
1827
  /** The same values transposed once into Rapier's column-major height-matrix order. */
249
1828
  toColliderHeights(): Float32Array;
250
1829
  /** Builds an ordinary Three.js geometry without choosing its surface. */
251
1830
  toGeometry(): BufferGeometry;
252
1831
  }
253
1832
 
254
- export { Heightfield, type IHeightfieldOptions, type IHeightfieldOrigin, type IHeightfieldSamplerOptions, type IHeightfieldWorldPassOptions, type IWorldCapabilities, type IWorldTileColliderInput, type IWorldTilesTopologyObservation, TerrainTiles, getWorldCapabilities };
1833
+ export { Heightfield, type IAdmissionBudget, type IHeightfieldChangeTracker, type IHeightfieldOptions, type IHeightfieldOrigin, type IHeightfieldRegion, type IHeightfieldRegionBounds, type IHeightfieldSamplerOptions, type IHeightfieldWorldPassOptions, type ILoadTerrainSplatOptions, type IShadowRegion, type ISnowContact, type ISnowFieldOptions, type ISnowFieldSample, type ISnowFootprint, type ISnowFootprintSample, type ITerrainSplatLayer, type ITerrainSplatMaskedLayer, type ITerrainSplatTable, type ITerrainSplatWeightContext, type IWorldAsset, type IWorldAssetBounds, type IWorldAssetLod, type IWorldCapabilities, type IWorldCell, type IWorldCellProxy, type IWorldCellsBudget, type IWorldCellsFollow, type IWorldCellsLoadOptions, type IWorldCellsStats, type IWorldCellsTerrainOptions, type IWorldExtent, type IWorldGpuFrameValidation, type IWorldPackage, type IWorldPackageError, type IWorldPackageValidationOptions, type IWorldRegionReadiness, type IWorldRun, type IWorldTerrain, type IWorldTileColliderInput, type IWorldTilesTopologyObservation, SnowField, TERRAIN_VALIDATE_FLAG, TERRAIN_VALIDATE_MARKER, TerrainTiles, WorldCells, type WorldPackageErrorCode, cellPlacements, getWorldCapabilities, heightSamplerFromHeightmap, loadTerrainSplat, loadWorldHeightmap, snowDiscFootprint, terrainValidationRequested, validateWorldPackage };