@threenative/core 0.3.11 → 0.3.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (236) hide show
  1. package/README.md +1 -1
  2. package/capabilities.json +1988 -204
  3. package/dist/{assets-YUbXa3-Y.d.ts → assets-CfMKnOsK.d.ts} +78 -1
  4. package/dist/camera-shake-CZKOfGn4.d.ts +46 -0
  5. package/dist/{canvas-layer-vCtanIeB.d.ts → canvas-layer-G7ttVy7y.d.ts} +1 -1
  6. package/dist/chunk-4SRAQFTU.js +133 -0
  7. package/dist/chunk-CFGTPFUH.js +231 -0
  8. package/dist/chunk-DIPIJICH.js +8916 -0
  9. package/dist/chunk-EEABDLUC.js +2237 -0
  10. package/dist/chunk-EFWZWLPY.js +1895 -0
  11. package/dist/chunk-GXY7B3JG.js +46 -0
  12. package/dist/chunk-GYUZJQ7U.js +280 -0
  13. package/dist/chunk-H4J6IAJE.js +504 -0
  14. package/dist/chunk-KIRUKTBQ.js +187 -0
  15. package/dist/chunk-QWJEMUUT.js +94 -0
  16. package/dist/chunk-SV4QVUTQ.js +31 -0
  17. package/dist/chunk-U4YHUKKL.js +615 -0
  18. package/dist/chunk-VP43GIWW.js +18 -0
  19. package/dist/chunk-XDTZ4QMO.js +160 -0
  20. package/dist/default-tone-mapping-GgKPTiBP.d.ts +4 -0
  21. package/dist/{game-DzMcitDO.d.ts → game-k8K3hZai.d.ts} +85 -9
  22. package/dist/hot.d.ts +5 -4
  23. package/dist/hot.js +5 -52
  24. package/dist/index.d.ts +633 -1351
  25. package/dist/index.js +12873 -23068
  26. package/dist/{model-lod-CTpZ6imz.d.ts → model-lod-DPTzeCcD.d.ts} +35 -3
  27. package/dist/playtest.d.ts +5 -4
  28. package/dist/playtest.js +25 -75
  29. package/dist/quality-BYqKGAwo.d.ts +868 -0
  30. package/dist/react-css.js +1 -215
  31. package/dist/react.d.ts +3 -2
  32. package/dist/render-environment.d.ts +170 -0
  33. package/dist/render-environment.js +352 -0
  34. package/dist/{renderer-rZm0hVqq.d.ts → renderer-BtOSseYf.d.ts} +42 -35
  35. package/dist/spells/index.d.ts +643 -0
  36. package/dist/spells/index.js +1558 -0
  37. package/dist/spells/ultra/index.d.ts +1600 -0
  38. package/dist/spells/ultra/index.js +6804 -0
  39. package/dist/terrain-jobs-worker.js +1 -123
  40. package/dist/two-sided-foliage-W523J3UM.js +1 -0
  41. package/dist/ui-layer.js +6 -384
  42. package/dist/worker.js +13 -43
  43. package/dist/world.d.ts +988 -268
  44. package/dist/world.js +17464 -18290
  45. package/mcp/animation-server.mjs +1 -1
  46. package/mcp/animation.mjs +2 -3
  47. package/mcp/engine-server.mjs +245 -52
  48. package/mcp/servers.mjs +10 -3
  49. package/mcp/terrain.mjs +8 -0
  50. package/package.json +19 -7
  51. package/patches/three@0.187.0-prd269-upgrade.patch +2102 -0
  52. package/patches/three@0.187.0.patch +2004 -407
  53. package/src/animation-batch.ts +193 -0
  54. package/src/animation-layers.ts +7 -3
  55. package/src/animation.ts +209 -29
  56. package/src/asset-cache.ts +3 -3
  57. package/src/asset-memo.ts +202 -0
  58. package/src/assets.ts +437 -125
  59. package/src/auto-batch.ts +190 -44
  60. package/src/card-lod.ts +152 -0
  61. package/src/compressed-texture-preparation.ts +1008 -0
  62. package/src/compute-driven.ts +1 -1
  63. package/src/config.ts +8 -0
  64. package/src/debug.ts +103 -22
  65. package/src/dev-global.ts +54 -0
  66. package/src/engine-hooks.ts +37 -0
  67. package/src/frame-budget.ts +50 -23
  68. package/src/game-boot-phase.ts +269 -0
  69. package/src/game-dev-tools.ts +86 -0
  70. package/src/game-frame-loop.ts +958 -0
  71. package/src/game-renderer-metrics.ts +77 -0
  72. package/src/game-startup.ts +1076 -0
  73. package/src/game-ui.ts +84 -0
  74. package/src/game-validate.ts +70 -0
  75. package/src/game.ts +198 -2264
  76. package/src/gamepad-mappings.ts +269 -0
  77. package/src/generated/console-markers.ts +13 -0
  78. package/src/geometry-capture.ts +28 -4
  79. package/src/gpu-readings.ts +98 -0
  80. package/src/gpu-scene-bvh.ts +149 -36
  81. package/src/hot.ts +4 -7
  82. package/src/index.ts +141 -9
  83. package/src/input.ts +237 -25
  84. package/src/instanced-batch-lod.ts +3 -8
  85. package/src/interpolation.ts +171 -40
  86. package/src/launch-diagnostics.ts +22 -12
  87. package/src/look/ao-admission.ts +25 -0
  88. package/src/look/auto-exposure.ts +5 -16
  89. package/src/look/default-tone-mapping.ts +41 -5
  90. package/src/look/filmic-tone-mapping.ts +15 -13
  91. package/src/look/local-exposure.ts +2 -7
  92. package/src/look/look-diagnostics.ts +3 -3
  93. package/src/look/quad-pass.ts +21 -0
  94. package/src/look/quality.ts +14 -5
  95. package/src/look/unreal-bloom.ts +4 -13
  96. package/src/look/world-environment.ts +113 -103
  97. package/src/loop.ts +29 -0
  98. package/src/merge-parts.ts +20 -24
  99. package/src/model-lod.ts +139 -17
  100. package/src/particle-kinds.ts +515 -0
  101. package/src/particle-significance.ts +12 -0
  102. package/src/particles.ts +19 -10
  103. package/src/picking.ts +17 -3
  104. package/src/platform.ts +23 -4
  105. package/src/playtest.ts +27 -1
  106. package/src/profiling/FrameStages.ts +5 -6
  107. package/src/profiling/Spans.ts +3 -17
  108. package/src/profiling/debug-telemetry.ts +2 -6
  109. package/src/profiling/render-list-validate.ts +6 -15
  110. package/src/projection-apply.ts +4 -1
  111. package/src/projection-marker.ts +2 -1
  112. package/src/projection-plan.ts +9 -6
  113. package/src/quiet-markers.ts +3 -10
  114. package/src/render/cpu-bvh.ts +100 -0
  115. package/src/render/depth-pyramid.ts +6 -14
  116. package/src/render/environment/environmentContribution.ts +202 -0
  117. package/src/render/environment/environmentRadiance.ts +44 -0
  118. package/src/render/environment/environmentSampleCache.ts +56 -0
  119. package/src/render/environment/environmentSampling.ts +201 -0
  120. package/src/render/environment/environmentSnapshot.ts +71 -0
  121. package/src/render/environment/gate.ts +57 -0
  122. package/src/render/mesh-pool.ts +4 -20
  123. package/src/render/probe-trace.ts +872 -0
  124. package/src/render/probe-volume.ts +780 -34
  125. package/src/render/radiance-cache.ts +17 -0
  126. package/src/render/resolution-subrect.ts +2 -0
  127. package/src/render/rough-diffuse.ts +46 -12
  128. package/src/render/soft-shadow.ts +27 -12
  129. package/src/render/virtual-shadow-adaptive.ts +55 -0
  130. package/src/render/virtual-shadow-casters.ts +175 -0
  131. package/src/render/virtual-shadow-layers.ts +76 -0
  132. package/src/render/virtual-shadow-level.ts +224 -0
  133. package/src/render/virtual-shadow-markers.ts +193 -0
  134. package/src/render/virtual-shadow-options.ts +370 -0
  135. package/src/render/virtual-shadow-pages.ts +5 -0
  136. package/src/render/virtual-shadow-partial.ts +13 -0
  137. package/src/render/virtual-shadow.ts +231 -1008
  138. package/src/render/world-impostor-surface.ts +402 -40
  139. package/src/render/world-impostor.ts +5 -2
  140. package/src/render-camera-cull.ts +98 -3
  141. package/src/render-environment.ts +41 -0
  142. package/src/render-pass-budget.ts +34 -7
  143. package/src/renderProjection.ts +22 -0
  144. package/src/renderer-config.ts +36 -0
  145. package/src/renderer-facts.ts +37 -0
  146. package/src/renderer.ts +144 -65
  147. package/src/resolution-scaler.ts +3 -2
  148. package/src/scene-entry-inspectors.ts +61 -0
  149. package/src/snow-field.ts +2 -1
  150. package/src/spells/cast-pool.ts +361 -0
  151. package/src/spells/index.ts +177 -0
  152. package/src/spells/mechanisms.ts +295 -0
  153. package/src/spells/reaction-field.ts +415 -0
  154. package/src/spells/spell-lights.ts +139 -0
  155. package/src/spells/spell-world.ts +187 -0
  156. package/src/spells/spell.ts +397 -0
  157. package/src/spells/spells.ts +283 -0
  158. package/src/spells/ultra/engine/camera.ts +184 -0
  159. package/src/spells/ultra/engine/quality.ts +96 -0
  160. package/src/spells/ultra/index.ts +52 -0
  161. package/src/spells/ultra/main.ts +305 -0
  162. package/src/spells/ultra/scene/arenaMaterial.ts +325 -0
  163. package/src/spells/ultra/spells/cast.ts +233 -0
  164. package/src/spells/ultra/spells/fire.ts +1267 -0
  165. package/src/spells/ultra/vfx/FluidVolume.ts +816 -0
  166. package/src/spells/ultra/vfx/FluidVolume.tsl.ts +855 -0
  167. package/src/spells/ultra/vfx/FxTarget.ts +61 -0
  168. package/src/spells/ultra/vfx/GroundField.ts +1399 -0
  169. package/src/spells/ultra/vfx/Particles.ts +1475 -0
  170. package/src/spells/ultra/vfx/Ribbons.ts +645 -0
  171. package/src/spells/ultra/vfx/Shockwaves.ts +286 -0
  172. package/src/spells/ultra/vfx/Volumes.ts +489 -0
  173. package/src/spells/ultra/vfx/common.ts +1195 -0
  174. package/src/spells/ultra/vfx/noise.ts +441 -0
  175. package/src/startup-offscreen-bytes.ts +78 -0
  176. package/src/startup-readiness.ts +128 -34
  177. package/src/static-transform.ts +25 -19
  178. package/src/streamed-textures.ts +112 -0
  179. package/src/streaming.ts +68 -4
  180. package/src/texture-streaming.ts +331 -0
  181. package/src/version.ts +1 -1
  182. package/src/warmup.ts +56 -8
  183. package/src/water-surface.ts +9 -3
  184. package/src/worker.ts +12 -2
  185. package/src/world-bundle-safety.ts +446 -0
  186. package/src/world-cell-batches.ts +1178 -0
  187. package/src/world-cell-chunks.ts +1128 -0
  188. package/src/world-cell-data.ts +995 -0
  189. package/src/world-cell-impostors.ts +1461 -0
  190. package/src/world-cell-lod-bias.ts +151 -0
  191. package/src/world-cell-models.ts +1074 -0
  192. package/src/world-cell-options.ts +177 -0
  193. package/src/world-cell-placements.ts +798 -0
  194. package/src/world-cell-prewarm.ts +592 -0
  195. package/src/world-cell-readiness.ts +357 -0
  196. package/src/world-cell-records.ts +401 -0
  197. package/src/world-cell-render-bundles.ts +459 -0
  198. package/src/world-cell-render-gpu-dress.ts +710 -0
  199. package/src/world-cell-render-main-cull.ts +540 -0
  200. package/src/world-cell-render-shadow-claims.ts +198 -0
  201. package/src/world-cell-render-util.ts +259 -0
  202. package/src/world-cell-render.ts +1501 -0
  203. package/src/world-cell-residency.ts +754 -0
  204. package/src/world-cell-stale.ts +238 -0
  205. package/src/world-cells.ts +1335 -10418
  206. package/src/world-chunk-shadow.ts +308 -0
  207. package/src/world-collar.ts +315 -0
  208. package/src/world-gpu-flags.ts +131 -0
  209. package/src/world-gpu-readback.ts +881 -0
  210. package/src/world-gpu-reference.ts +524 -0
  211. package/src/world-gpu-scene.ts +256 -2286
  212. package/src/world-gpu-shadow.ts +203 -0
  213. package/src/world-gpu-types.ts +409 -0
  214. package/src/world-gpu-validation.ts +518 -0
  215. package/src/world-heightfield.ts +802 -0
  216. package/src/world-load-limiter.ts +111 -0
  217. package/src/world-model-sections.ts +80 -0
  218. package/src/world-noise.ts +241 -0
  219. package/src/world-package.ts +42 -0
  220. package/src/world-region.ts +1 -1
  221. package/src/world-river-ribbon.ts +282 -0
  222. package/src/world-root-frame.ts +39 -0
  223. package/src/world-shore-field.ts +91 -0
  224. package/src/world-static-pose.ts +163 -0
  225. package/src/world-surface-sampler.ts +48 -0
  226. package/src/world-terrain-splat.ts +361 -153
  227. package/src/world-tile-budget.ts +249 -0
  228. package/src/world-tile-geometry.ts +469 -0
  229. package/src/world-tile-lod.ts +408 -0
  230. package/src/world-tile-observation.ts +566 -0
  231. package/src/world-tile-stitch.ts +166 -0
  232. package/src/world-tiles.ts +247 -1755
  233. package/src/world-validate.ts +6 -14
  234. package/src/world-warm.ts +51 -0
  235. package/src/world-water-bodies.ts +359 -0
  236. package/src/world.ts +48 -741
@@ -0,0 +1,540 @@
1
+ import { Box3, type Camera, Matrix4, type Object3D, Quaternion, Vector3 } from "three";
2
+ import { Frustum } from "three";
3
+ import type { BundleGroup } from "three/webgpu";
4
+ import type { IRendererLike } from "./renderer.js";
5
+ import type { SharedBatch } from "./world-cell-batches.js";
6
+ import { sameSquares } from "./world-cell-batches.js";
7
+ import { levelTriangles } from "./world-cell-chunks.js";
8
+ import type {
9
+ ICamera,
10
+ IKeyDescriptor,
11
+ IResidentCell,
12
+ IShadowRegion,
13
+ IWorldCellsStats,
14
+ } from "./world-cell-data.js";
15
+ import { clusterOf } from "./world-cell-data.js";
16
+ import { PLACEMENT_RECORD_FLOATS } from "./world-cell-impostors.js";
17
+ import { placedBox } from "./world-cell-records.js";
18
+ import {
19
+ GPU_KEY_SUFFIX,
20
+ MAIN_CULL_MARKER_MS,
21
+ MAIN_CULL_PAD_METRES,
22
+ } from "./world-cell-render-util.js";
23
+ import type { ICellRenderHost } from "./world-cell-render.js";
24
+ import type { WorldGpuScene } from "./world-gpu-scene.js";
25
+ import {
26
+ type IWorldAsset,
27
+ type IWorldCell,
28
+ type IWorldPackage,
29
+ cellPlacements,
30
+ } from "./world-package.js";
31
+ import { localClip } from "./world-root-frame.js";
32
+
33
+ /**
34
+ * The main pass's coarse cull: one volume per resident visibility cell, one frustum a frame, and the
35
+ * per-batch window each key's mesh narrows itself to.
36
+ *
37
+ * This is the part of the renderer that answers "which squares are in this frame" and what it costs.
38
+ * The answer is derived from the camera alone, so it holds nothing of the world but the volumes it
39
+ * has admitted and the counters that report what the frame paid — see `IWorldCellsStats.mainCull`.
40
+ */
41
+
42
+ /** What the cull asks the renderer it runs in. */
43
+ export interface ICellMainCullHost {
44
+ render(): ICellRenderHost;
45
+ /** Every shared batch, which is what a frame narrows. */
46
+ shared(): Map<string, SharedBatch>;
47
+ gpuScene(): WorldGpuScene;
48
+ /** Every resident cell's frozen chunk record, and the square whose answer shows it. */
49
+ chunkGroups(): Map<string, { readonly cluster: string; readonly group: BundleGroup }>;
50
+ /** Reset the bundle eligibility counters at the top of the pass. */
51
+ beginBundleFrame(): void;
52
+ recordCpuMain(shared: SharedBatch, outcome: "settled" | "narrowed" | "repacked"): void;
53
+ dressGpu(shared: SharedBatch, key: IKeyDescriptor): void;
54
+ dressShadowKey(shared: SharedBatch, key: string): void;
55
+ applyGpuMain(dressed: readonly { asset: string; shared: SharedBatch }[]): void;
56
+ /** Whether the prewarm has already named every key the scene should draw. */
57
+ gpuSeeded(): boolean;
58
+ }
59
+
60
+ /** The grid and the tables a cull derives its volumes from, fixed for the world's life. */
61
+ export interface ICellMainCullSettings {
62
+ readonly cellSize: number;
63
+ readonly minX: number;
64
+ readonly minZ: number;
65
+ readonly manifest: IWorldPackage;
66
+ readonly placements: ArrayBuffer;
67
+ readonly cellsPerCullCell: number;
68
+ readonly mainCullToldAt: number;
69
+ }
70
+
71
+ /** The two scratch objects a cull builds its frustum in. */
72
+ const _cullFrustum = new Frustum();
73
+ const _cullProjScreen = new Matrix4();
74
+ const _cullBox = new Box3();
75
+
76
+ /** The owned engine's whole-set test (PRD-879): the indices of the packed boxes the frustum holds. */
77
+ type IBoxesInFrustum = (this: Frustum, boxes: Float64Array) => ArrayLike<number>;
78
+
79
+ /**
80
+ * Every packed box (min xyz, max xyz) the frustum intersects, by index. The owned engine answers the
81
+ * set in one call; upstream three, the `engine: "threejs"` arm, has no such method and tests each box.
82
+ */
83
+ function boxesInFrustum(frustum: Frustum, boxes: Float64Array): ArrayLike<number> {
84
+ const engine = (frustum as Frustum & { __tnIntersectsBoxes?: IBoxesInFrustum })
85
+ .__tnIntersectsBoxes;
86
+ if (typeof engine === "function") return engine.call(frustum, boxes);
87
+ const hits: number[] = [];
88
+ for (let at = 0; at < boxes.length; at += 6) {
89
+ _cullBox.min.fromArray(boxes, at);
90
+ _cullBox.max.fromArray(boxes, at + 3);
91
+ if (frustum.intersectsBox(_cullBox)) hits.push(at / 6);
92
+ }
93
+ return hits;
94
+ }
95
+
96
+ export class CellMainCull {
97
+ readonly #host: ICellMainCullHost;
98
+
99
+ readonly #cellSize: number;
100
+
101
+ readonly #minX: number;
102
+
103
+ readonly #minZ: number;
104
+
105
+ readonly #manifest: IWorldPackage;
106
+
107
+ readonly #placements: ArrayBuffer;
108
+
109
+ readonly #cellsPerCullCell: number;
110
+
111
+ constructor(settings: ICellMainCullSettings, host: ICellMainCullHost) {
112
+ this.#host = host;
113
+ this.#cellSize = settings.cellSize;
114
+ this.#minX = settings.minX;
115
+ this.#minZ = settings.minZ;
116
+ this.#manifest = settings.manifest;
117
+ this.#placements = settings.placements;
118
+ this.#cellsPerCullCell = settings.cellsPerCullCell;
119
+ this.#mainCullToldAt = settings.mainCullToldAt;
120
+ }
121
+
122
+ /** When `TN_WORLD_MAIN_CULL` was last printed; see {@link #reportMainCull}. */
123
+ #mainCullToldAt = 0;
124
+
125
+ /** Window repacks since the last marker; see {@link #reportMainCull}. */
126
+ #mainCullRepacks = 0;
127
+
128
+ /** Frusta the main cull has built, one a frame; see `IWorldCellsStats.mainCull`. */
129
+ #mainCullFrustums = 0;
130
+
131
+ /** Windows main batches have had to re-derive, cumulative; see `IWorldCellsStats.mainCull`. */
132
+ #mainCullWindows = 0;
133
+
134
+ /** Window repacks, cumulative; see `IWorldCellsStats.mainCull`. */
135
+ #mainCullPacks = 0;
136
+
137
+ /**
138
+ * One AABB per resident visibility cell, and how many resident world cells hold it. Shared by
139
+ * every key, so the main cull is O(visibility cells) a frame rather than O(keys × cells); see
140
+ * {@link #cullMainPass}.
141
+ */
142
+ readonly #cullCells = new Map<string, { cells: number; box: Box3 }>();
143
+
144
+ /**
145
+ * The non-empty volumes of `#cullCells` packed for the frame's one frustum test, and their names
146
+ * by index. Repacked only after a volume was admitted, widened or dropped, so a frame reads no box.
147
+ */
148
+ #cullBoxes = new Float64Array(0);
149
+
150
+ #cullNames: string[] = [];
151
+
152
+ #cullPacked = false;
153
+
154
+ /** The visibility cells the last cull kept and the frame's set, trading places; see `#cullMainPass`. */
155
+ #visibleSquares: Set<string> = new Set();
156
+
157
+ #cullScratch: Set<string> = new Set();
158
+
159
+ /** Bumped only when `#visibleSquares` changed, so a settled camera repacks no batch at all. */
160
+ #visibleEpoch = 0;
161
+
162
+ readonly #position = new Vector3();
163
+
164
+ readonly #rotation = new Quaternion();
165
+
166
+ readonly #scale = new Vector3();
167
+
168
+ readonly #matrix = new Matrix4();
169
+
170
+ /** Reused transformed authored bounds for admission and conservative visibility volumes. */
171
+ readonly #recordBounds = new Box3();
172
+
173
+ /**
174
+ * Narrow every main batch's draw window to the world-grid squares `camera`'s frustum covers, once
175
+ * per frame, for the whole set at once.
176
+ *
177
+ * This used to be each main mesh's own `onBeforeRender`, which three never calls for an invisible
178
+ * mesh — so the moment a batch that draws nothing was hidden, the one thing that could show it
179
+ * again when the camera turned back was gone with it, and the world lost its trees for good. The
180
+ * decision therefore moved to the frame's own driver: the render-cadence compute dispatch, which
181
+ * the engine already runs once per rendered frame — on the same readiness gate residency itself
182
+ * sits behind, so a frame that skips this skipped the world's records too — and which now hands the
183
+ * render camera to the world, so it reaches every main mesh whether it is drawn or not.
184
+ *
185
+ * The camera rules are the ones the hook had, and they are the whole of what decides a window:
186
+ *
187
+ * - **An orthographic camera never repacks.** A virtual-shadow level's camera is a
188
+ * `DirectionalLightShadow`'s own, which three makes orthographic, so a level's window — one shadow
189
+ * slice of the ring, deliberately not the main view's — can never overwrite the main pass's. A
190
+ * game whose own camera is orthographic keeps the old behaviour: everything resident is drawn, and
191
+ * nothing pops. That is a lost saving, never a wrong picture.
192
+ * - **The render camera is the one that decides.** The engine dispatches this with the camera it
193
+ * is about to draw the main pass with, so the second-perspective-camera race the hook had to
194
+ * arbitrate per mesh cannot arise: a mirror or a minimap is drawn with its own camera and is
195
+ * served the main view's window, which is the honest trade for a world with one main view.
196
+ * - **A set that did not change touches nothing.** The frustum, the visible cells and the epoch
197
+ * are the frame's, derived once for the whole pass; a batch whose records have not moved since it
198
+ * packed at that epoch compares two integers and returns. A camera at rest costs one frustum and
199
+ * one test per resident visibility cell a frame, and nothing at all per mesh.
200
+ */
201
+ cullMainPass(camera: Camera | undefined): void {
202
+ if (camera === undefined || (camera as ICamera).isOrthographicCamera === true) return;
203
+ this.#host.beginBundleFrame();
204
+ this.#mainCullFrustums += 1;
205
+ // The volumes this tests and the records it narrows are the root's own, so the frustum is taken
206
+ // in the root's frame: a game that moves its world draws the squares that are over the camera.
207
+ const root = this.#host.render().root();
208
+ const frustum = _cullFrustum.setFromProjectionMatrix(localClip(_cullProjScreen, camera, root));
209
+ // The visible visibility cells, for the whole pass, into a set that is reused and compared
210
+ // rather than allocated: two sets trading places, so a settled camera allocates nothing at all.
211
+ const next = this.#cullScratch;
212
+ next.clear();
213
+ if (!this.#cullPacked) this.#packCullBoxes();
214
+ const hits = boxesInFrustum(frustum, this.#cullBoxes);
215
+ for (let at = 0; at < hits.length; at += 1)
216
+ next.add(this.#cullNames[hits[at] as number] as string);
217
+ if (!sameSquares(next, this.#visibleSquares)) {
218
+ this.#visibleEpoch += 1;
219
+ const was = this.#visibleSquares;
220
+ this.#visibleSquares = next;
221
+ this.#cullScratch = was;
222
+ this.#cullScratch.clear();
223
+ }
224
+ // A chunk's record is frozen, so its cell's answer is the only thing that can take it out of the
225
+ // frame without re-recording it: a write per resident cell that has chunks, at the same
226
+ // granularity every other coarse gate in this pass uses. See the `bundles` option.
227
+ for (const entry of this.#host.chunkGroups().values()) {
228
+ const visible = this.#visibleSquares.has(entry.cluster);
229
+ if (entry.group.visible !== visible) entry.group.visible = visible;
230
+ }
231
+ const gpu = this.#host.gpuScene();
232
+ const dressed: Array<{ asset: string; shared: SharedBatch }> = [];
233
+ const version = gpu.version;
234
+ for (const shared of [...this.#host.shared().values()]) {
235
+ if (shared.role !== "main") continue;
236
+ // A dressed batch draws from the GPU scene's own buffers, so the frame's per-instance answer is
237
+ // the dispatch's and this mesh's own window would be a second, stale copy of it.
238
+ if (gpu.on && shared.gpu !== undefined) {
239
+ this.#host.dressGpu(shared, shared.gpu);
240
+ // A bundled mesh is in a render list three fixed when it recorded the bundle, and the
241
+ // dispatch has already culled per instance: there is nothing coarse left to hide, and a
242
+ // `visible` written here is one the replay never reads. See `#bundleIn`.
243
+ if (shared.bundled === false) dressed.push({ asset: shared.gpu.asset, shared });
244
+ continue;
245
+ }
246
+ // A batch the GPU scene does not own, and every one of a world without it: its own window is
247
+ // the CPU path's answer, and it is a per-frame answer a frozen render list never re-reads. So
248
+ // the record answers the gate instead of the gate writing `visible` into it — a batch the gate
249
+ // shows joins, one it hides leaves, and a window that moved is one more record, because the
250
+ // record holds the layout the move made. The same trade a cell's chunk record makes, at the
251
+ // granularity this gate already uses. See `#bundleIn`.
252
+ const outcome = shared.cullFrom(this.#visibleSquares, this.#visibleEpoch);
253
+ this.#host.recordCpuMain(shared, outcome);
254
+ if (outcome === "settled") continue;
255
+ this.#mainCullWindows += 1;
256
+ if (outcome === "repacked") {
257
+ this.#mainCullRepacks += 1;
258
+ this.#mainCullPacks += 1;
259
+ }
260
+ }
261
+ // A regrow late in the loop replaces the scene's `drawn` — and, a non-grouped key, its `args` —
262
+ // after an earlier mesh in the same loop was dressed against the generation before it, so that
263
+ // mesh would read a buffer the dispatch no longer writes for one frame. One more pass over the
264
+ // same settled set, only when the scene changed under the first, rebinds every mesh to the final
265
+ // buffers. Registration is idempotent and every key is already minted and sized, so this pass
266
+ // mints nothing and cannot grow the scene again.
267
+ if (gpu.on && gpu.version !== version) {
268
+ for (const shared of [...this.#host.shared().values()])
269
+ if (shared.role === "main" && shared.gpu !== undefined)
270
+ this.#host.dressGpu(shared, shared.gpu);
271
+ // And every shadow key, for the same reason: minting one grew the twin buffers every other
272
+ // key was dressed against, so a sibling dressed earlier in the loop above is holding the
273
+ // generation the dispatch replaced. The main key's own dress brings its twin with it; this is
274
+ // what closes the seam for the keys whose main key was dressed before the grow.
275
+ for (const shared of [...this.#host.shared().values()])
276
+ if (shared.role === "key")
277
+ this.#host.dressShadowKey(shared, shared.mesh.name.slice(0, -GPU_KEY_SUFFIX.length));
278
+ }
279
+ // After every key has been dressed, so the asset's answer is the union across its levels and
280
+ // parts.
281
+ this.#host.applyGpuMain(dressed);
282
+ // After the coarse gate, and only for the main camera: an orthographic one — every shadow
283
+ // level's own — returned at the top, so a level's render never dispatches over the main pass's
284
+ // compaction.
285
+ if (gpu.on) gpu.dispatch(this.#host.render().renderer() as IRendererLike, camera, root);
286
+ }
287
+
288
+ /**
289
+ * An occupied cell whose placements have not been decoded yet holds nothing to draw, and its Y
290
+ * range is still empty — a volume that cannot be tested against ±Infinity is not one a frame's
291
+ * answer may rest on, so it is not packed.
292
+ */
293
+ #packCullBoxes(): void {
294
+ this.#cullNames.length = 0;
295
+ this.#cullBoxes = new Float64Array(this.#cullCells.size * 6);
296
+ for (const [cell, { box }] of this.#cullCells) {
297
+ if (box.isEmpty()) continue;
298
+ const at = this.#cullNames.length * 6;
299
+ box.min.toArray(this.#cullBoxes, at);
300
+ box.max.toArray(this.#cullBoxes, at + 3);
301
+ this.#cullNames.push(cell);
302
+ }
303
+ this.#cullBoxes = this.#cullBoxes.subarray(0, this.#cullNames.length * 6);
304
+ this.#cullPacked = true;
305
+ }
306
+
307
+ /** Borrowed scratch box: consume its transformed volume before the next bounds query. */
308
+ #boundsAt(bounds: IWorldAsset["bounds"], matrix: Matrix4): Box3 {
309
+ return placedBox(this.#recordBounds, bounds.min, bounds.max, matrix);
310
+ }
311
+
312
+ /**
313
+ * The one volume per resident visibility cell, shared by every key: its own XZ footprint, and in Y
314
+ * the range its resident placements actually reach once their assets' own bounds are added to them,
315
+ * padded by `MAIN_CULL_PAD_METRES`.
316
+ *
317
+ * It is derived here, on admission, and never a frame — a volume walked every frame to answer a
318
+ * question about placements that never move is a frame's work for an admission's answer.
319
+ *
320
+ * It is deliberately not per key. Every key drew the same cell set, so deriving it per key meant
321
+ * ~230 frusta and ~230 sets a frame to learn the same answer; one volume per cell is what makes the
322
+ * pass O(cells) instead of O(keys × cells).
323
+ *
324
+ * The Y is what makes it a volume rather than a slab. It used to be the whole terrain height range
325
+ * widened by the tallest asset bound in the world — ~100 m of Y on a map with a 10 m relief, which
326
+ * made every cell's bounding sphere a ~90 m radius that a view beside the world still cleared, and
327
+ * handed the vertex stage the whole ring. This is per placement instead: a sub-square of flat
328
+ * ground with ferns on it is the height of its ferns.
329
+ */
330
+
331
+ cullResident(cell: IWorldCell): void {
332
+ const per = this.#cellsPerCullCell;
333
+ const side = per * this.#cellSize;
334
+ const first = Math.floor(cell.x / per);
335
+ const firstZ = Math.floor(cell.z / per);
336
+ const name = clusterOf(cell.x, cell.z, per);
337
+ let entry = this.#cullCells.get(name);
338
+ if (entry === undefined) {
339
+ // XZ from the grid, padded, and an empty Y: this cell's own placements are unioned in below,
340
+ // and a cell holding none of them yet is never visible rather than visible by its footprint.
341
+ const box = new Box3(
342
+ new Vector3(
343
+ this.#minX + first * side - MAIN_CULL_PAD_METRES,
344
+ Number.POSITIVE_INFINITY,
345
+ this.#minZ + firstZ * side - MAIN_CULL_PAD_METRES,
346
+ ),
347
+ new Vector3(
348
+ this.#minX + (first + 1) * side + MAIN_CULL_PAD_METRES,
349
+ Number.NEGATIVE_INFINITY,
350
+ this.#minZ + (firstZ + 1) * side + MAIN_CULL_PAD_METRES,
351
+ ),
352
+ );
353
+ entry = { box, cells: 0 };
354
+ this.#cullCells.set(name, entry);
355
+ }
356
+ entry.cells += 1;
357
+ this.#cullPacked = false;
358
+ const box = entry.box;
359
+ for (const run of cell.runs) {
360
+ const bounds = this.#manifest.assets[this.#host.render().canonical(run.asset)]?.bounds;
361
+ if (bounds === undefined || run.count === 0) continue;
362
+ const records = cellPlacements(this.#placements, run);
363
+ for (let index = 0; index < run.count; index += 1) {
364
+ const at = index * PLACEMENT_RECORD_FLOATS;
365
+ // The placement, widened by its own asset's bounds at the scale it is drawn at, and by the
366
+ // pad — a union, so the pad is counted once however many placements there are.
367
+ const scale = records[at + 7] as number;
368
+ this.#position.fromArray(records, at);
369
+ this.#rotation.fromArray(records, at + 3);
370
+ this.#scale.setScalar(scale);
371
+ this.#matrix.compose(this.#position, this.#rotation, this.#scale);
372
+ box.union(
373
+ this.#boundsAt(bounds, this.#matrix).expandByScalar(
374
+ MAIN_CULL_PAD_METRES * Math.max(1, Math.abs(scale)),
375
+ ),
376
+ );
377
+ }
378
+ }
379
+ }
380
+
381
+ /**
382
+ * Drop the visibility cell an evicted cell sat in once nothing resident is left in it. Records are
383
+ * cleared before this runs, so a batch can never be holding a cell the cull no longer knows: an
384
+ * unknown cell is not in the visible set, and that would be a tree nobody draws.
385
+ *
386
+ * The box goes with it, so a cell that comes back derives its volume again — which is what keeps a
387
+ * released asset's height out of a cell that no longer holds it.
388
+ */
389
+ cullEvicted(cell: IResidentCell): void {
390
+ const name = clusterOf(cell.x, cell.z, this.#cellsPerCullCell);
391
+ const entry = this.#cullCells.get(name);
392
+ if (entry === undefined) return;
393
+ entry.cells -= 1;
394
+ if (entry.cells <= 0) {
395
+ this.#cullCells.delete(name);
396
+ this.#cullPacked = false;
397
+ }
398
+ }
399
+
400
+ /**
401
+ * `TN_WORLD_MAIN_CULL`, every `MAIN_CULL_MARKER_MS`: what the main pass holds, what it is drawing,
402
+ * how many of its meshes are submitted at all, and how many times the window moved to get there.
403
+ *
404
+ * `instances` is every live record the main batches hold — the whole resident ring, which is what
405
+ * three's whole-mesh test used to hand the vertex stage — and `drawn` is what the cull left in the
406
+ * windows. The gap between them is the saving, `repacks` says what it cost to get: a settled camera
407
+ * repacks nothing, so a walk that repacks dozens of times a second is a window that is chasing the
408
+ * camera, not one that is thrashing. `hidden` and `castersHidden` are the batches with nothing to
409
+ * draw that are now not submitted at all: in three r185's WebGPU path a zero-count `InstancedMesh`
410
+ * still runs the whole per-draw JS chain, so an empty batch was CPU a frame for no draw — the number
411
+ * is the part of the census that no longer costs anything.
412
+ *
413
+ * `dressed=N/M` is the GPU scene's own claim, repeated every five seconds: a scene that is on over
414
+ * meshes nothing is dressed into compacts a set the CPU path is still drawing, and `keys` alone
415
+ * cannot say so — a ring built before the scene came up has no keys at all and looks healthy.
416
+ */
417
+ reportMainCull(): void {
418
+ const now = this.#host.render().now();
419
+ if (now - this.#mainCullToldAt < MAIN_CULL_MARKER_MS) return;
420
+ this.#mainCullToldAt = now;
421
+ const repacks = this.#mainCullRepacks;
422
+ this.#mainCullRepacks = 0;
423
+ let instances = 0;
424
+ let drawn = 0;
425
+ let hidden = 0;
426
+ let castersHidden = 0;
427
+ let clusterWithheld = 0;
428
+ let clusterRecords = 0;
429
+ let clusterMissing = 0;
430
+ let wideWithheld = 0;
431
+ let wideRecords = 0;
432
+ let wideMissing = 0;
433
+ // What the two caster layers hold between them, per layer: the resident triangle bill a shadow
434
+ // level that picked that layer submits. Two numbers that must not be equal is the whole claim —
435
+ // the wide half draws the asset's coarsest level, so it is the one that falls.
436
+ let clusterTriangles = 0;
437
+ let wideTriangles = 0;
438
+ let dressed = 0;
439
+ let mainMeshes = 0;
440
+ for (const shared of this.#host.shared().values()) {
441
+ if (shared.role !== "main") {
442
+ if (shared.mesh.visible === false) castersHidden += 1;
443
+ if (shared.mesh.mainAdmitted === false && shared.live > 0) {
444
+ if (shared.role === "cluster") {
445
+ clusterWithheld += 1;
446
+ clusterRecords += shared.live;
447
+ clusterMissing += Math.max(0, shared.live - shared.gpuPlaced);
448
+ } else if (shared.role === "wide") {
449
+ wideWithheld += 1;
450
+ wideRecords += shared.live;
451
+ wideMissing += Math.max(0, shared.live - shared.gpuPlaced);
452
+ }
453
+ }
454
+ // Zero records add zero, so an empty batch needs no test of its own here.
455
+ const triangles = levelTriangles(shared.mesh.geometry) * shared.live;
456
+ if (shared.role === "cluster") clusterTriangles += triangles;
457
+ else wideTriangles += triangles;
458
+ continue;
459
+ }
460
+ mainMeshes += 1;
461
+ if (shared.gpu !== undefined) dressed += 1;
462
+ instances += shared.live;
463
+ drawn += shared.drawn;
464
+ if (shared.mesh.visible === false) hidden += 1;
465
+ }
466
+ const stats = this.#host.render().stats();
467
+ console.info(
468
+ `TN_WORLD_MAIN_CULL instances=${String(instances)} drawn=${String(drawn)} ` +
469
+ `hidden=${String(hidden)} castersHidden=${String(castersHidden)} repacks=${String(repacks)} ` +
470
+ `refilters=${String(stats.refilters)} levelRefilters=${String(stats.levelRefilters)} ` +
471
+ `lodFrom=${stats.lodFrom} ` +
472
+ `clusterTris=${String(clusterTriangles)} wideTris=${String(wideTriangles)} ` +
473
+ `dressed=${String(dressed)}/${String(mainMeshes)}`,
474
+ );
475
+ console.info(
476
+ `TN_WORLD_SHADOW_ADMISSION clusterWithheld=${String(clusterWithheld)} ` +
477
+ `clusterRecords=${String(clusterRecords)} clusterMissing=${String(clusterMissing)} ` +
478
+ `wideWithheld=${String(wideWithheld)} wideRecords=${String(wideRecords)} ` +
479
+ `wideMissing=${String(wideMissing)} seeded=${String(this.#host.gpuSeeded())} ` +
480
+ `queued=${String(this.#host.render().queuedBuilds())}`,
481
+ );
482
+ const hlod = stats.hlod;
483
+ let proxyDraws = 0;
484
+ let replacedSources = 0;
485
+ for (const cell of this.#host.render().residentCells()) {
486
+ const state = cell.proxy;
487
+ if (state === undefined || !state.active) continue;
488
+ proxyDraws += state.prepared?.meshes.length ?? 0;
489
+ replacedSources += state.hidden.size + state.mainMasks.size;
490
+ }
491
+ const why = hlod.reason === "" ? "" : ` reason=${JSON.stringify(hlod.reason)}`;
492
+ console.info(
493
+ `TN_WORLD_HLOD on=${String(hlod.on)} loaded=${String(hlod.loaded)} ` +
494
+ `compiled=${String(hlod.compiled)} observed=${String(hlod.observed)} ` +
495
+ `active=${String(hlod.active)} pending=${String(hlod.pending)} ` +
496
+ `draws=${String(proxyDraws)} replaced=${String(replacedSources)} ` +
497
+ `bytes=${String(hlod.bytes)} refused=${String(hlod.refused)} failures=${String(hlod.failures)}${why}`,
498
+ );
499
+ // The bundles on their own line, because the pair reads against a different question: how many
500
+ // objects are recorded, and how many times the recording was thrown away and redone. A walk
501
+ // streaming and culling holds `records` at the keys and chunks that came and went; a walk that
502
+ // repacks it every frame is drawing a moving set, which is the bug a bundle cannot have. `reason`
503
+ // is on it because the default is now on: a reader has to be able to tell a run that turned it
504
+ // off from a run where recording never happened.
505
+ const bundles = stats.bundle;
506
+ console.info(
507
+ `TN_WORLD_BUNDLE ${bundles.on ? "on" : "off"} reason=${bundles.reason} ` +
508
+ `children=${String(bundles.children)} cpuMeshes=${String(bundles.cpuMeshes)} gpuMeshes=${String(bundles.gpuMeshes)} records=${String(bundles.records)}`,
509
+ );
510
+ }
511
+
512
+ mainCullStats(): IWorldCellsStats["mainCull"] {
513
+ return {
514
+ frustums: this.#mainCullFrustums,
515
+ repacks: this.#mainCullPacks,
516
+ visibleEpoch: this.#visibleEpoch,
517
+ windows: this.#mainCullWindows,
518
+ };
519
+ }
520
+ /**
521
+ * Whether the frame's own frustum holds this object. It is the frustum the last cull built, which
522
+ * is why it lives here: a caller that answered from a copy no frame wrote would hold everything.
523
+ */
524
+ intersectsObject(mesh: Object3D): boolean {
525
+ return _cullFrustum.intersectsObject(mesh);
526
+ }
527
+
528
+ /** Widen a resident visibility cell's volume by a chunk's bounds; an unknown cell is left alone. */
529
+ widenCell(name: string, box: Box3): void {
530
+ const entry = this.#cullCells.get(name);
531
+ if (entry === undefined) return;
532
+ entry.box.union(box);
533
+ this.#cullPacked = false;
534
+ }
535
+
536
+ /** The visibility cells the last cull kept, which the GPU dress's coarse gate reads. */
537
+ get visible(): Set<string> {
538
+ return this.#visibleSquares;
539
+ }
540
+ }