@threenative/core 0.3.12 → 0.3.15

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 (165) hide show
  1. package/README.md +1 -1
  2. package/capabilities.json +1047 -44
  3. package/dist/{assets-YUbXa3-Y.d.ts → assets-CfMKnOsK.d.ts} +78 -1
  4. package/dist/{canvas-layer-CWuFRT7G.d.ts → canvas-layer-G7ttVy7y.d.ts} +1 -1
  5. package/dist/{chunk-7UUT3TY5.js → chunk-2GPHICV6.js} +1 -1
  6. package/dist/{chunk-GMHATRPW.js → chunk-GEMQJBY4.js} +1650 -383
  7. package/dist/{chunk-VAZM36TV.js → chunk-H4J6IAJE.js} +17 -10
  8. package/dist/{chunk-5O73CDMR.js → chunk-QAMSM3Z5.js} +415 -27
  9. package/dist/{chunk-2Z44XSI2.js → chunk-QAQHYOWY.js} +3 -7
  10. package/dist/{chunk-DBELTTTM.js → chunk-U4YHUKKL.js} +1 -1
  11. package/dist/{chunk-OKXUCASC.js → chunk-VBBYWGAT.js} +3 -4
  12. package/dist/chunk-VP43GIWW.js +18 -0
  13. package/dist/{chunk-N5LRP4BR.js → chunk-VQRPEOKY.js} +66 -3
  14. package/dist/{chunk-6KLNISRJ.js → chunk-XDTZ4QMO.js} +11 -4
  15. package/dist/default-tone-mapping-GgKPTiBP.d.ts +4 -0
  16. package/dist/{game-D7pAzZUY.d.ts → game-k8K3hZai.d.ts} +72 -8
  17. package/dist/hot.d.ts +5 -4
  18. package/dist/hot.js +5 -8
  19. package/dist/index.d.ts +871 -1018
  20. package/dist/index.js +4786 -1631
  21. package/dist/{model-lod-B6BMqS1r.d.ts → model-lod-DPTzeCcD.d.ts} +4 -2
  22. package/dist/playtest.d.ts +5 -4
  23. package/dist/playtest.js +6 -5
  24. package/dist/quality-BADStsTn.d.ts +868 -0
  25. package/dist/react.d.ts +3 -2
  26. package/dist/render-environment.d.ts +170 -0
  27. package/dist/render-environment.js +352 -0
  28. package/dist/{renderer-DvFVoAgj.d.ts → renderer-BtOSseYf.d.ts} +29 -31
  29. package/dist/spells/index.js +1 -1
  30. package/dist/ui-layer.js +3 -2
  31. package/dist/worker.js +12 -5
  32. package/dist/world.d.ts +280 -16
  33. package/dist/world.js +1529 -642
  34. package/mcp/animation-server.mjs +1 -1
  35. package/mcp/engine-server.mjs +135 -11
  36. package/mcp/servers.mjs +4 -4
  37. package/package.json +10 -6
  38. package/scripts/ensure-mcp.mjs +6 -1
  39. package/src/animation-batch.ts +193 -0
  40. package/src/animation-layers.ts +7 -3
  41. package/src/animation.ts +209 -29
  42. package/src/asset-cache.ts +3 -3
  43. package/src/asset-memo.ts +202 -0
  44. package/src/assets.ts +436 -131
  45. package/src/auto-batch.ts +190 -44
  46. package/src/clustered-batch.ts +146 -3
  47. package/src/clustered-mesh.ts +548 -20
  48. package/src/compute-driven.ts +1 -1
  49. package/src/config.ts +8 -0
  50. package/src/debug.ts +119 -22
  51. package/src/dev-global.ts +54 -0
  52. package/src/displaced-surface.ts +428 -0
  53. package/src/engine-hooks.ts +37 -0
  54. package/src/frame-budget.ts +35 -3
  55. package/src/game-boot-phase.ts +269 -0
  56. package/src/game-dev-tools.ts +7 -14
  57. package/src/game-frame-loop.ts +45 -82
  58. package/src/game-startup.ts +145 -70
  59. package/src/game-ui.ts +84 -0
  60. package/src/game.ts +168 -552
  61. package/src/gamepad-mappings.ts +269 -0
  62. package/src/generated/console-markers.ts +14 -0
  63. package/src/geometry-capture.ts +28 -4
  64. package/src/gpu-readings.ts +98 -0
  65. package/src/gpu-scene-bvh.ts +149 -36
  66. package/src/grass-field.ts +628 -0
  67. package/src/hot.ts +4 -7
  68. package/src/index.ts +227 -8
  69. package/src/input.ts +237 -25
  70. package/src/instanced-batch-lod.ts +3 -8
  71. package/src/interpolation.ts +171 -40
  72. package/src/look/ao-admission.ts +4 -3
  73. package/src/look/auto-exposure.ts +5 -16
  74. package/src/look/default-tone-mapping.ts +41 -5
  75. package/src/look/local-exposure.ts +2 -7
  76. package/src/look/quad-pass.ts +21 -0
  77. package/src/look/quality.ts +4 -0
  78. package/src/look/unreal-bloom.ts +4 -13
  79. package/src/look/world-environment.ts +58 -115
  80. package/src/merge-parts.ts +20 -24
  81. package/src/model-lod.ts +97 -14
  82. package/src/particle-significance.ts +12 -0
  83. package/src/particles.ts +19 -10
  84. package/src/platform.ts +23 -4
  85. package/src/profiling/FrameStages.ts +5 -6
  86. package/src/profiling/Spans.ts +3 -17
  87. package/src/profiling/debug-telemetry.ts +2 -6
  88. package/src/profiling/render-list-validate.ts +6 -15
  89. package/src/projection-marker.ts +2 -1
  90. package/src/quiet-markers.ts +3 -10
  91. package/src/render/cpu-bvh.ts +100 -0
  92. package/src/render/depth-pyramid.ts +6 -14
  93. package/src/render/environment/environmentContribution.ts +202 -0
  94. package/src/render/environment/environmentRadiance.ts +44 -0
  95. package/src/render/environment/environmentSampleCache.ts +56 -0
  96. package/src/render/environment/environmentSampling.ts +201 -0
  97. package/src/render/environment/environmentSnapshot.ts +71 -0
  98. package/src/render/environment/gate.ts +57 -0
  99. package/src/render/material-key.ts +21 -1
  100. package/src/render/mesh-pool.ts +3 -19
  101. package/src/render/probe-trace.ts +872 -0
  102. package/src/render/probe-volume.ts +780 -34
  103. package/src/render/radiance-cache.ts +17 -0
  104. package/src/render/screen-probe-gather.ts +303 -0
  105. package/src/render/short-range-ao.ts +274 -0
  106. package/src/render/virtual-shadow-partial.ts +13 -0
  107. package/src/render/virtual-shadow.ts +18 -16
  108. package/src/render/world-impostor-surface.ts +207 -9
  109. package/src/render/world-impostor.ts +5 -2
  110. package/src/render-camera-cull.ts +105 -4
  111. package/src/render-environment.ts +41 -0
  112. package/src/renderer-config.ts +36 -0
  113. package/src/renderer-facts.ts +37 -0
  114. package/src/renderer.ts +78 -32
  115. package/src/resolution-scaler.ts +3 -2
  116. package/src/scatter-field.ts +496 -0
  117. package/src/scene-entry-inspectors.ts +61 -0
  118. package/src/snow-field.ts +1 -0
  119. package/src/startup-offscreen-bytes.ts +84 -0
  120. package/src/state.ts +16 -3
  121. package/src/static-transform.ts +100 -25
  122. package/src/streamed-textures.ts +112 -0
  123. package/src/streaming.ts +68 -4
  124. package/src/texture-streaming.ts +331 -0
  125. package/src/tile-ring.ts +294 -0
  126. package/src/version.ts +1 -1
  127. package/src/warmup.ts +15 -2
  128. package/src/worker.ts +12 -2
  129. package/src/world-bundle-safety.ts +55 -10
  130. package/src/world-cell-batches.ts +166 -200
  131. package/src/world-cell-chunks.ts +3 -7
  132. package/src/world-cell-data.ts +7 -0
  133. package/src/world-cell-impostors.ts +20 -8
  134. package/src/world-cell-models.ts +36 -8
  135. package/src/world-cell-options.ts +2 -14
  136. package/src/world-cell-placements.ts +194 -90
  137. package/src/world-cell-prewarm.ts +39 -4
  138. package/src/world-cell-records.ts +401 -0
  139. package/src/world-cell-render-bundles.ts +2 -2
  140. package/src/world-cell-render-gpu-dress.ts +17 -19
  141. package/src/world-cell-render-main-cull.ts +73 -17
  142. package/src/world-cell-render-util.ts +18 -5
  143. package/src/world-cell-render.ts +13 -5
  144. package/src/world-cell-residency.ts +15 -6
  145. package/src/world-cell-stale.ts +238 -0
  146. package/src/world-cells.ts +23 -6
  147. package/src/world-gpu-flags.ts +18 -50
  148. package/src/world-gpu-reference.ts +22 -8
  149. package/src/world-gpu-scene.ts +44 -24
  150. package/src/world-gpu-shadow.ts +21 -8
  151. package/src/world-gpu-types.ts +41 -13
  152. package/src/world-load-limiter.ts +5 -0
  153. package/src/world-model-sections.ts +80 -0
  154. package/src/world-river-ribbon.ts +273 -0
  155. package/src/world-root-frame.ts +39 -0
  156. package/src/world-shore-field.ts +91 -0
  157. package/src/world-static-pose.ts +163 -0
  158. package/src/world-surface-sampler.ts +48 -0
  159. package/src/world-terrain-splat.ts +10 -18
  160. package/src/world-tile-budget.ts +4 -11
  161. package/src/world-tiles.ts +79 -12
  162. package/src/world-validate.ts +6 -14
  163. package/src/world-warm.ts +51 -0
  164. package/src/world-water-bodies.ts +113 -3
  165. package/src/world.ts +13 -0
@@ -0,0 +1,496 @@
1
+ import {
2
+ type BufferGeometry,
3
+ Group,
4
+ InstancedMesh,
5
+ type Material,
6
+ Matrix4,
7
+ Quaternion,
8
+ Vector3,
9
+ } from "three";
10
+ import {
11
+ type ITileBounds,
12
+ type ITileRingField,
13
+ TileRing,
14
+ clamp01,
15
+ groundGrid,
16
+ hashInt,
17
+ mulberry32,
18
+ sample,
19
+ shuffled,
20
+ smoothstep,
21
+ } from "./tile-ring.js";
22
+
23
+ const DEG = Math.PI / 180;
24
+
25
+ /** One part of the scattered mesh — a glTF primitive — and the baked levels to draw it at. */
26
+ export interface IScatterPart {
27
+ /** Near to far: `lods[0]` is the full mesh, the last is the farthest level. */
28
+ readonly lods: readonly BufferGeometry[];
29
+ /** The game's material for this part. The field chooses neither geometry nor look. */
30
+ readonly material: Material;
31
+ }
32
+
33
+ /** The ground under a candidate, in field-local metres, with its unit normal. */
34
+ export interface IScatterPoint {
35
+ readonly x: number;
36
+ readonly y: number;
37
+ readonly z: number;
38
+ readonly nx: number;
39
+ readonly ny: number;
40
+ readonly nz: number;
41
+ }
42
+
43
+ /** Where a candidate goes. The game writes the transform; the field owns `priority`. */
44
+ export interface IScatterPlacement {
45
+ x: number;
46
+ y: number;
47
+ z: number;
48
+ /** Radians about the ground normal, so a prop's own facing is the game's choice. */
49
+ yaw: number;
50
+ /** Uniform scale on the baked metres. */
51
+ scale: number;
52
+ /** 0..1: the candidate's order in the seeded shuffle. Lower instances thin away first. */
53
+ readonly priority: number;
54
+ }
55
+
56
+ export type IScatterFieldBounds = ITileBounds;
57
+
58
+ export interface IScatterField3DOptions {
59
+ /** One entry per part of the baked mesh; a log's bark and its foliage are two. */
60
+ readonly parts: readonly IScatterPart[];
61
+ /**
62
+ * Decides one candidate: write `out` and return true to place it, or return false to leave the
63
+ * spot empty (a path, a rock, a stump's own footprint). Called once per candidate per tile build.
64
+ */
65
+ readonly place: (point: IScatterPoint, out: IScatterPlacement) => boolean;
66
+ /** Ground height at (x, z), field-local metres. */
67
+ readonly getHeight: (x: number, z: number) => number;
68
+ /** Coverage 0..1 at (x, z, height, normal y): paths, clearings, biome masks. */
69
+ readonly getDensity?: (x: number, z: number, height: number, normalY: number) => number;
70
+ readonly bounds?: IScatterFieldBounds | null;
71
+ /** Candidates per square metre at full coverage. */
72
+ readonly density?: number;
73
+ readonly chunkSize?: number;
74
+ readonly seed?: number;
75
+ readonly heightSampleSpacing?: number;
76
+ /** Degrees: nothing is placed on ground steeper than `maxSlope`, thinning over `slopeFade`. */
77
+ readonly maxSlope?: number;
78
+ readonly slopeFade?: number;
79
+ readonly minAltitude?: number;
80
+ readonly maxAltitude?: number;
81
+ readonly drawDistance?: number;
82
+ /** Distances at which the next level takes over, one per step down a part's `lods`. */
83
+ readonly lodDistances?: readonly number[];
84
+ readonly thinStart?: number;
85
+ readonly thinEnd?: number;
86
+ /** The share of instances left past `thinEnd`. */
87
+ readonly farDensity?: number;
88
+ /** Milliseconds per frame allowed for building tiles; one tile always builds. */
89
+ readonly buildBudgetMs?: number;
90
+ /** Tilt each instance onto the ground normal. Off keeps every instance upright. */
91
+ readonly alignToGround?: boolean;
92
+ readonly receiveShadow?: boolean;
93
+ readonly castShadow?: boolean;
94
+ /** Scales every density at once, as Unreal's `grass.densityScale`. */
95
+ readonly densityScale?: number;
96
+ /** Scales every distance at once, as Unreal's `grass.CullDistanceScale`. */
97
+ readonly cullDistanceScale?: number;
98
+ }
99
+
100
+ export interface IScatterFieldStats {
101
+ tiles: number;
102
+ visibleTiles: number;
103
+ instances: number;
104
+ pending: number;
105
+ /** Tiles built since the field was made. */
106
+ built: number;
107
+ }
108
+
109
+ interface IScatterTile {
110
+ /** One mesh per part, then per level; parts need not have the same number of levels. */
111
+ readonly meshes: InstancedMesh[][];
112
+ /** Per instance, in buffer order: the shuffled prefix the thinning rule walks. */
113
+ readonly priority: Float32Array;
114
+ readonly count: number;
115
+ }
116
+
117
+ const scratchPosition = new Vector3();
118
+ const scratchScale = new Vector3();
119
+ const scratchQuaternion = new Quaternion();
120
+ const scratchTilt = new Quaternion();
121
+ const scratchMatrix = new Matrix4();
122
+ const up = new Vector3(0, 1, 0);
123
+ const normal = new Vector3();
124
+
125
+ /**
126
+ * Streamed, seeded, instanced scatter of any baked mesh around a follow point; the game owns the
127
+ * mesh, the material and where each instance lands.
128
+ *
129
+ * Square tiles round the follow point, built nearest first inside `buildBudgetMs` through the same
130
+ * ring `GrassField3D` uses (`TileRing`): a tile is built inside 1.3 × the draw distance and freed
131
+ * past 1.4 ×, Unreal Landscape grass's guard band (UE 5.8.3:
132
+ * Engine/Source/Runtime/Landscape/Private/LandscapeGrass.cpp:88, :94). Each part draws one
133
+ * `InstancedMesh` per level, so swapping detail is a visibility toggle on a baked level the game
134
+ * loaded. Thinning is a plain instance count: the ring's tiles hold instances in the seeded shuffle
135
+ * order, so any prefix covers the tile evenly and the far edge keeps a share of them.
136
+ *
137
+ * The field creates no colour, shading or shape: `parts` and `place` come from the game, and so does
138
+ * every appearance constant.
139
+ *
140
+ * @situation scatter fallen logs, twigs, leaf litter, stones and ferns over a forest floor
141
+ * @situation stream instanced props of any baked mesh round the player without one draw per prop
142
+ * @situation place rocks, debris or plants on a heightfield with distance thinning and level of detail
143
+ * @constraint call `update(follow)` once per rendered frame
144
+ * @constraint `place` runs once per candidate per tile build: return false for paths and clearings
145
+ * @constraint rotating or scaling the field is not supported; translating it is
146
+ * @example
147
+ * import { ScatterField3D } from "@threenative/core";
148
+ * const floor = new ScatterField3D({
149
+ * parts: [{ lods: [logLod0, logLod1], material }],
150
+ * getHeight: (x, z) => height(x, z),
151
+ * density: 0.05,
152
+ * place: (point, out) => { out.x = point.x; out.y = point.y; out.z = point.z; out.yaw = point.x * 0.7; out.scale = 1; return !onPath(point.x, point.z); },
153
+ * });
154
+ * ctx.add(floor);
155
+ * ctx.beforeRender(() => floor.update(hero.position));
156
+ */
157
+ export class ScatterField3D extends Group {
158
+ readonly parts: readonly IScatterPart[];
159
+ place: (point: IScatterPoint, out: IScatterPlacement) => boolean;
160
+ getHeight: (x: number, z: number) => number;
161
+ getDensity: ((x: number, z: number, height: number, normalY: number) => number) | null;
162
+ bounds: IScatterFieldBounds | null;
163
+ density: number;
164
+ chunkSize: number;
165
+ seed: number;
166
+ heightSampleSpacing: number;
167
+ maxSlope: number;
168
+ slopeFade: number;
169
+ minAltitude: number;
170
+ maxAltitude: number;
171
+ drawDistance: number;
172
+ lodDistances: readonly number[];
173
+ thinStart: number;
174
+ thinEnd: number;
175
+ farDensity: number;
176
+ buildBudgetMs: number;
177
+ alignToGround: boolean;
178
+ override receiveShadow: boolean;
179
+ override castShadow: boolean;
180
+ densityScale: number;
181
+ cullDistanceScale: number;
182
+ readonly #ring: TileRing<IScatterTile>;
183
+ readonly #shown = { instances: 0, visibleTiles: 0 };
184
+ #version = 0;
185
+ #layout = "";
186
+
187
+ constructor(options: IScatterField3DOptions) {
188
+ super();
189
+ this.name = "ScatterField3D";
190
+ if (typeof options.place !== "function")
191
+ throw new Error("ScatterField3D.place must be a function (point, out) => boolean.");
192
+ if (typeof options.getHeight !== "function")
193
+ throw new Error("ScatterField3D.getHeight must be a function (x, z) => height.");
194
+ if (!Array.isArray(options.parts) || options.parts.length === 0)
195
+ throw new Error("ScatterField3D.parts must list at least one part.");
196
+ options.parts.forEach((part, index) => {
197
+ if (!Array.isArray(part.lods) || part.lods.length === 0)
198
+ throw new Error(`ScatterField3D.parts[${index}].lods must list at least one geometry.`);
199
+ if (!part.material)
200
+ throw new Error(`ScatterField3D.parts[${index}] has no material; the game owns the look.`);
201
+ });
202
+ this.parts = options.parts;
203
+ this.place = options.place;
204
+ this.getHeight = options.getHeight;
205
+ this.getDensity = options.getDensity ?? null;
206
+ this.bounds = options.bounds ?? null;
207
+ this.density = options.density ?? 0.1;
208
+ this.chunkSize = options.chunkSize ?? 16;
209
+ this.seed = options.seed ?? 1337;
210
+ this.heightSampleSpacing = options.heightSampleSpacing ?? 0.75;
211
+ this.maxSlope = options.maxSlope ?? 42;
212
+ this.slopeFade = options.slopeFade ?? 12;
213
+ this.minAltitude = options.minAltitude ?? Number.NEGATIVE_INFINITY;
214
+ this.maxAltitude = options.maxAltitude ?? Number.POSITIVE_INFINITY;
215
+ this.drawDistance = options.drawDistance ?? 60;
216
+ this.lodDistances = options.lodDistances ?? [20, 45];
217
+ this.thinStart = options.thinStart ?? 10;
218
+ this.thinEnd = options.thinEnd ?? 50;
219
+ this.farDensity = options.farDensity ?? 0.3;
220
+ this.buildBudgetMs = options.buildBudgetMs ?? 4;
221
+ this.alignToGround = options.alignToGround ?? true;
222
+ this.receiveShadow = options.receiveShadow ?? true;
223
+ this.castShadow = options.castShadow ?? true;
224
+ this.densityScale = options.densityScale ?? 1;
225
+ this.cullDistanceScale = options.cullDistanceScale ?? 1;
226
+ this.#validate();
227
+ this.#ring = new TileRing<IScatterTile>(this.#hooks());
228
+ }
229
+
230
+ get stats(): IScatterFieldStats {
231
+ return {
232
+ built: this.#ring.stats.built,
233
+ instances: this.#shown.instances,
234
+ pending: this.#ring.stats.pending,
235
+ tiles: this.#ring.stats.tiles,
236
+ visibleTiles: this.#shown.visibleTiles,
237
+ };
238
+ }
239
+
240
+ /** Builds every tile in range on the next `update` regardless of budget: on load or after a teleport. */
241
+ prewarm(): void {
242
+ this.#ring.prewarm();
243
+ }
244
+
245
+ /** Re-scatter after the ground or the coverage changed: all tiles, or those touching a rectangle. */
246
+ refresh(rect?: IScatterFieldBounds): void {
247
+ if (rect === undefined) {
248
+ this.#version++;
249
+ return;
250
+ }
251
+ this.#ring.disposeInside(rect);
252
+ }
253
+
254
+ /** Streams, thins and LODs the tiles round `follow`. Call once per rendered frame. */
255
+ update(follow: Vector3): void {
256
+ this.#validate();
257
+ const layout = this.#layoutKey();
258
+ if (layout !== this.#layout) {
259
+ this.#ring.clear();
260
+ this.#layout = layout;
261
+ }
262
+ scratchPosition.copy(follow);
263
+ this.worldToLocal(scratchPosition);
264
+ this.#shown.visibleTiles = this.#shown.instances = 0;
265
+ this.#ring.update(scratchPosition.x, scratchPosition.z);
266
+ }
267
+
268
+ override dispose(): void {
269
+ this.#ring.clear();
270
+ }
271
+
272
+ #hooks(): ITileRingField<IScatterTile> {
273
+ const field = this;
274
+ return {
275
+ build: (ix, iz) => this.#build(ix, iz),
276
+ get buildBudgetMs() {
277
+ return field.buildBudgetMs;
278
+ },
279
+ get chunkSize() {
280
+ return field.chunkSize;
281
+ },
282
+ get drawDistance() {
283
+ return field.drawDistance * field.cullDistanceScale;
284
+ },
285
+ dispose: (tile) => this.#disposeTile(tile),
286
+ hide: (tile) => {
287
+ for (const part of tile.meshes)
288
+ for (const mesh of part) if (mesh.visible) mesh.visible = false;
289
+ },
290
+ inBounds: (ix, iz) => this.#inBounds(ix, iz),
291
+ show: (tile, distance) => this.#show(tile, distance),
292
+ };
293
+ }
294
+
295
+ #validate(): void {
296
+ if (!(this.chunkSize > 0))
297
+ throw new Error(`ScatterField3D.chunkSize must be > 0, got ${this.chunkSize}.`);
298
+ if (!(this.density >= 0))
299
+ throw new Error(`ScatterField3D.density must be >= 0, got ${this.density}.`);
300
+ if (!(this.drawDistance > 0))
301
+ throw new Error(`ScatterField3D.drawDistance must be > 0, got ${this.drawDistance}.`);
302
+ if (!(this.buildBudgetMs >= 0))
303
+ throw new Error(`ScatterField3D.buildBudgetMs must be >= 0, got ${this.buildBudgetMs}.`);
304
+ if (!(this.densityScale >= 0) || !(this.cullDistanceScale > 0))
305
+ throw new Error("ScatterField3D.densityScale must be >= 0 and cullDistanceScale > 0.");
306
+ const b = this.bounds;
307
+ if (b === null) return;
308
+ for (const key of ["minX", "minZ", "maxX", "maxZ"] as const)
309
+ if (!Number.isFinite(b[key])) throw new Error(`ScatterField3D.bounds.${key} must be finite.`);
310
+ if (b.minX >= b.maxX) throw new Error("ScatterField3D.bounds.minX must be below bounds.maxX.");
311
+ if (b.minZ >= b.maxZ) throw new Error("ScatterField3D.bounds.minZ must be below bounds.maxZ.");
312
+ }
313
+
314
+ #layoutKey(): string {
315
+ return [
316
+ this.#version,
317
+ this.density * this.densityScale,
318
+ this.chunkSize,
319
+ this.seed,
320
+ this.heightSampleSpacing,
321
+ this.maxSlope,
322
+ this.slopeFade,
323
+ this.minAltitude,
324
+ this.maxAltitude,
325
+ this.alignToGround,
326
+ this.parts.length,
327
+ ].join("|");
328
+ }
329
+
330
+ #inBounds(ix: number, iz: number): boolean {
331
+ const b = this.bounds;
332
+ const S = this.chunkSize;
333
+ return (
334
+ b === null ||
335
+ !(ix * S >= b.maxX || (ix + 1) * S <= b.minX || iz * S >= b.maxZ || (iz + 1) * S <= b.minZ)
336
+ );
337
+ }
338
+
339
+ #pointInBounds(x: number, z: number): boolean {
340
+ const b = this.bounds;
341
+ return b === null || (x >= b.minX && x <= b.maxX && z >= b.minZ && z <= b.maxZ);
342
+ }
343
+
344
+ /** Slope limit times the game's coverage mask, 0..1. */
345
+ #coverage(x: number, z: number, y: number, ny: number, cosMax: number, span: number): number {
346
+ const m = clamp01((ny - cosMax) / span);
347
+ return m > 0 && this.getDensity ? m * clamp01(this.getDensity(x, z, y, ny)) : m;
348
+ }
349
+
350
+ /** The thinning cut-off at a tile's nearest point: the same rule the material cannot apply here. */
351
+ #kept(tile: IScatterTile, distance: number): number {
352
+ const k = this.cullDistanceScale;
353
+ const thinEnd = Math.max(this.thinEnd, this.thinStart + 0.01) * k;
354
+ const edge = 1.1 + (this.farDensity - 1.1) * smoothstep(this.thinStart * k, thinEnd, distance);
355
+ if (edge >= 1) return tile.count;
356
+ // Instances sit in the seeded shuffle order, so the kept ones are a prefix of the buffer.
357
+ const pr = tile.priority;
358
+ let lo = 0;
359
+ let hi = tile.count;
360
+ while (lo < hi) {
361
+ const mid = (lo + hi) >> 1;
362
+ if ((pr[mid] as number) < edge) lo = mid + 1;
363
+ else hi = mid;
364
+ }
365
+ return lo;
366
+ }
367
+
368
+ #show(tile: IScatterTile, distance: number): void {
369
+ const R = this.drawDistance * this.cullDistanceScale;
370
+ const k = this.cullDistanceScale;
371
+ const n = this.#kept(tile, distance);
372
+ const inRange = n > 0 && distance < R;
373
+ if (inRange) {
374
+ this.#shown.visibleTiles++;
375
+ this.#shown.instances += n;
376
+ }
377
+ for (let part = 0; part < this.parts.length; part++) {
378
+ const meshes = tile.meshes[part] as InstancedMesh[];
379
+ let level = 0;
380
+ while (
381
+ level < meshes.length - 1 &&
382
+ distance >= (this.lodDistances[level] ?? Number.POSITIVE_INFINITY) * k
383
+ )
384
+ level++;
385
+ for (let l = 0; l < meshes.length; l++) {
386
+ const mesh = meshes[l] as InstancedMesh;
387
+ // Every write below is guarded: a standing follow point re-plans nothing on the owned engine.
388
+ const visible = inRange && l === level;
389
+ if (mesh.visible !== visible) mesh.visible = visible;
390
+ if (mesh.count !== n) mesh.count = n;
391
+ if (mesh.receiveShadow !== this.receiveShadow) mesh.receiveShadow = this.receiveShadow;
392
+ if (mesh.castShadow !== this.castShadow) mesh.castShadow = this.castShadow;
393
+ }
394
+ }
395
+ }
396
+
397
+ #build(ix: number, iz: number): IScatterTile | null {
398
+ const S = this.chunkSize;
399
+ const ox = ix * S;
400
+ const oz = iz * S;
401
+ const rng = mulberry32(hashInt(ix, iz, this.seed | 0));
402
+ const ground = groundGrid(this.getHeight, ox, oz, S, this.heightSampleSpacing);
403
+ const n = Math.max(1, Math.ceil(Math.sqrt(this.density * this.densityScale * S * S)));
404
+ const total = this.density * this.densityScale > 0 ? n * n : 0;
405
+ const cell = S / n;
406
+ const order = shuffled(total, rng);
407
+ const matrices: Matrix4[] = [];
408
+ const priority = new Float32Array(total);
409
+ const cosMax = Math.cos(this.maxSlope * DEG);
410
+ const slopeSpan = Math.max(
411
+ Math.cos(Math.max(this.maxSlope - this.slopeFade, 0) * DEG) - cosMax,
412
+ 1e-5,
413
+ );
414
+ // Mutable in here, readonly to the game: the field owns `priority`.
415
+ const out = { priority: 0, scale: 1, x: 0, y: 0, z: 0, yaw: 0 };
416
+ let k = 0;
417
+ for (let q = 0; q < total; q++) {
418
+ const c = order[q] as number;
419
+ const lx = ((c % n) + rng()) * cell;
420
+ const lz = (((c / n) | 0) + rng()) * cell;
421
+ const rKeep = rng();
422
+ const wx = ox + lx;
423
+ const wz = oz + lz;
424
+ if (!this.#pointInBounds(wx, wz)) continue;
425
+ ground.sample(lx, lz);
426
+ const y = sample[0] as number;
427
+ const dx = sample[1] as number;
428
+ const dz = sample[2] as number;
429
+ if (y < this.minAltitude || y > this.maxAltitude) continue;
430
+ const ny = 1 / Math.sqrt(dx * dx + dz * dz + 1);
431
+ const m = this.#coverage(wx, wz, y, ny, cosMax, slopeSpan);
432
+ if (m <= 0.001 || rKeep > m * 2) continue;
433
+ out.x = wx;
434
+ out.y = y;
435
+ out.z = wz;
436
+ out.yaw = 0;
437
+ out.scale = 1;
438
+ out.priority = q / total;
439
+ const placed = this.place({ nx: -dx * ny, ny, nz: -dz * ny, x: wx, y, z: wz }, out);
440
+ if (!placed) continue;
441
+ if (!Number.isFinite(out.scale) || out.scale <= 0 || !Number.isFinite(out.yaw))
442
+ throw new Error(
443
+ `ScatterField3D.place returned scale ${out.scale} and yaw ${out.yaw} at (${wx}, ${wz}); both must be finite and the scale positive.`,
444
+ );
445
+ priority[k] = q / total;
446
+ scratchPosition.set(out.x, out.y, out.z);
447
+ scratchScale.setScalar(out.scale);
448
+ if (this.alignToGround) {
449
+ normal.set(-dx, 1, -dz).normalize();
450
+ scratchTilt.setFromUnitVectors(up, normal);
451
+ scratchQuaternion.setFromAxisAngle(up, out.yaw);
452
+ scratchQuaternion.premultiply(scratchTilt);
453
+ } else {
454
+ scratchQuaternion.setFromAxisAngle(up, out.yaw);
455
+ }
456
+ matrices.push(
457
+ scratchMatrix.clone().compose(scratchPosition, scratchQuaternion, scratchScale),
458
+ );
459
+ k++;
460
+ }
461
+ // Remembered as empty by the ring, so it is not rebuilt every frame.
462
+ if (k === 0) return null;
463
+ const meshes: InstancedMesh[][] = [];
464
+ for (let part = 0; part < this.parts.length; part++) {
465
+ const source = this.parts[part] as IScatterPart;
466
+ const levels: InstancedMesh[] = [];
467
+ for (let l = 0; l < source.lods.length; l++) {
468
+ const geometry = source.lods[l] as BufferGeometry;
469
+ const mesh = new InstancedMesh(geometry, source.material, k);
470
+ mesh.name = `scatter part${part} lod${l} ${ix},${iz}`;
471
+ for (let i = 0; i < k; i++) mesh.setMatrixAt(i, matrices[i] as Matrix4);
472
+ mesh.instanceMatrix.needsUpdate = true;
473
+ mesh.position.set(ox, 0, oz);
474
+ mesh.matrixAutoUpdate = false;
475
+ mesh.updateMatrix();
476
+ mesh.visible = false;
477
+ mesh.raycast = () => {};
478
+ // InstancedMesh's own bounds, not the shared geometry's: a tile culls by the instances it holds.
479
+ mesh.computeBoundingSphere();
480
+ this.add(mesh);
481
+ levels.push(mesh);
482
+ }
483
+ meshes.push(levels);
484
+ }
485
+ return { count: k, meshes, priority: priority.slice(0, k) };
486
+ }
487
+
488
+ #disposeTile(tile: IScatterTile): void {
489
+ for (const part of tile.meshes)
490
+ for (const mesh of part) {
491
+ this.remove(mesh);
492
+ // The geometry belongs to the game: only the instance buffer this tile allocated is freed.
493
+ mesh.dispose();
494
+ }
495
+ }
496
+ }
@@ -0,0 +1,61 @@
1
+ /**
2
+ * What a scene entry checks, in one ordered list.
3
+ *
4
+ * Every audit a scene entry runs used to be welded into `Game.#enterScene` — the opacity
5
+ * convention, the render trap audit, the unlit foliage warning — so a fourth one meant editing the
6
+ * lifecycle file that every other feature already edits. A kit or a game can add its own here, and
7
+ * the order the list states is the order the warnings appear in.
8
+ *
9
+ * Nothing here decides how anything looks: each inspector reads the scene the game just entered and
10
+ * returns what a reader should be told about it.
11
+ */
12
+ import type { Object3D } from "three";
13
+ import { applyOpacityConvention } from "./profiling/opacity-convention.js";
14
+ import { renderTrapAudit } from "./profiling/render-trap-audit.js";
15
+ import {
16
+ UNLIT_FOLIAGE_FIX,
17
+ formatUnlitFoliageWarning,
18
+ unlitFoliageWarning,
19
+ } from "./profiling/unlit-foliage-warning.js";
20
+
21
+ /** One line a scene entry reports, and the console level it belongs at. */
22
+ export interface ISceneEntryFinding {
23
+ readonly level: "error" | "warn";
24
+ readonly line: string;
25
+ }
26
+
27
+ /** A check that runs once per scene entry, after the game's `enter()` has built the scene. */
28
+ export type SceneEntryInspector = (scene: Object3D) => readonly ISceneEntryFinding[];
29
+
30
+ /**
31
+ * The engine's own inspectors, in the order their findings must appear.
32
+ *
33
+ * The opacity convention runs first: it makes an author's opacity take effect, and the render trap
34
+ * audit then reports what that effect is — the other order reports the state before the convention.
35
+ */
36
+ export const SCENE_ENTRY_INSPECTORS: readonly SceneEntryInspector[] = [
37
+ (scene) => {
38
+ const line = applyOpacityConvention(scene);
39
+ return line === undefined ? [] : [{ level: "warn", line }];
40
+ },
41
+ (scene) => renderTrapAudit(scene).map((line) => ({ level: "error", line })),
42
+ (scene) => {
43
+ const warning = unlitFoliageWarning(scene);
44
+ return warning === undefined
45
+ ? []
46
+ : [{ level: "warn", line: `${formatUnlitFoliageWarning(warning)} ${UNLIT_FOLIAGE_FIX}` }];
47
+ },
48
+ ];
49
+
50
+ /** Runs every inspector against a scene the game has just entered, reporting each finding once. */
51
+ export function inspectSceneEntry(
52
+ scene: Object3D,
53
+ inspectors: readonly SceneEntryInspector[] = SCENE_ENTRY_INSPECTORS,
54
+ ): void {
55
+ for (const inspector of inspectors) {
56
+ for (const finding of inspector(scene)) {
57
+ if (finding.level === "error") console.error(finding.line);
58
+ else console.warn(finding.line);
59
+ }
60
+ }
61
+ }
package/src/snow-field.ts CHANGED
@@ -213,6 +213,7 @@ export function snowDiscFootprint(
213
213
  * recovery. It is a heightfield approximation — not granular snow, displaced-volume
214
214
  * conservation, avalanches, melting or a calibrated material law.
215
215
  * @situation leave footprints, tracks and tyre ruts in snow that persist and fill in over time
216
+ * @situation let a fresh snowfall slowly fill older tracks back in as the field recovers
216
217
  * @situation let a pushed sphere carve a connected track and a dropped one settle into a crater
217
218
  * @situation store snow deformation that rendered geometry and collision both read
218
219
  * @situation reset a snowfield between rounds or change its depth at runtime
@@ -166,3 +166,87 @@ export function measureStartupOffscreenBytes(
166
166
  warn: offscreenBytes > visibleBytes,
167
167
  };
168
168
  }
169
+
170
+ export const ASSET_UNUSED_MARKER = "TN_ASSET_UNUSED";
171
+
172
+ /**
173
+ * When to look: long enough for a game to build what its first minute needs, short enough that a
174
+ * playtest sees it. Not a game constant — the report states it, and a model the game builds later
175
+ * than this is still a launch wait to move, so the advice holds either way.
176
+ */
177
+ export const ASSET_UNUSED_AFTER_MS = 60_000;
178
+
179
+ export const ASSET_UNUSED_FIX =
180
+ "Nothing in the scene came from these models, which the reveal waited for. If nothing ever " +
181
+ "builds one, delete its load; if the game builds it later, ctx.assets.prefetch it after the " +
182
+ "reveal and load it then. A listed file may also be geometry the game merged into a new buffer, " +
183
+ "which drops its provenance: check that before deleting it.";
184
+
185
+ /** Models the reveal waited for that no scene object came from, `sinceRevealMs` after the reveal. */
186
+ export interface IUnusedModels {
187
+ /** The sum over the files whose size the manifest records. */
188
+ readonly bytes: number;
189
+ /** `bytes` is absent where the manifest records no size: unknown, not zero. */
190
+ readonly files: readonly { readonly bytes?: number; readonly path: string }[];
191
+ readonly fix: string;
192
+ readonly sinceRevealMs: number;
193
+ /** Listed files whose size the manifest does not record, so they are in no byte count. */
194
+ readonly unsizedFiles: number;
195
+ }
196
+
197
+ /**
198
+ * Which awaited models have no stamped object or geometry anywhere under `root`, hidden nodes
199
+ * included: a hidden hull is in use, a model nothing ever cloned is dead weight. `undefined` when
200
+ * every awaited model is in the scene. One stamp walk, no bounds and no frustum.
201
+ */
202
+ export function measureUnusedModels(
203
+ resolved: ReadonlyMap<string, IResolvedAsset>,
204
+ root: Object3D,
205
+ sinceRevealMs: number,
206
+ ): IUnusedModels | undefined {
207
+ const present = unbilled(() => {
208
+ const paths = new Set<string>();
209
+ root.traverse((object) => {
210
+ const geometry = (object as Object3D & { geometry?: { userData?: unknown } }).geometry;
211
+ for (const path of [stampOf(object.userData), stampOf(geometry?.userData)])
212
+ if (path !== undefined) paths.add(path);
213
+ });
214
+ return paths;
215
+ });
216
+ const files = [...resolved]
217
+ .filter(([path, asset]) => asset.kind === "model" && !present.has(path))
218
+ .map(([path, asset]) => (asset.bytes === undefined ? { path } : { bytes: asset.bytes, path }))
219
+ .sort((a, b) => (b.bytes ?? -1) - (a.bytes ?? -1));
220
+ if (files.length === 0) return undefined;
221
+ return {
222
+ bytes: files.reduce((sum, file) => sum + (file.bytes ?? 0), 0),
223
+ files,
224
+ fix: ASSET_UNUSED_FIX,
225
+ sinceRevealMs,
226
+ unsizedFiles: files.filter((file) => file.bytes === undefined).length,
227
+ };
228
+ }
229
+
230
+ /**
231
+ * Report `TN_ASSET_UNUSED` once, `ASSET_UNUSED_AFTER_MS` after the reveal: the awaited models no
232
+ * scene object came from — a load the launch paid for that nothing drew (Midway paid 22.9 MB for
233
+ * three). Measurement only: a throw costs the report, never the game. Returns the cancel.
234
+ */
235
+ export function reportUnusedModelsLater(
236
+ awaited: ReadonlyMap<string, IResolvedAsset>,
237
+ root: Object3D,
238
+ gone: () => boolean,
239
+ ): () => void {
240
+ const timer = setTimeout(() => {
241
+ if (gone()) return;
242
+ try {
243
+ const unused = measureUnusedModels(awaited, root, ASSET_UNUSED_AFTER_MS);
244
+ if (unused !== undefined) console.warn(`${ASSET_UNUSED_MARKER}:${JSON.stringify(unused)}`);
245
+ } catch (error) {
246
+ console.warn(
247
+ `${ASSET_UNUSED_MARKER}_FAILED: ${error instanceof Error ? error.message : String(error)}`,
248
+ );
249
+ }
250
+ }, ASSET_UNUSED_AFTER_MS);
251
+ return () => clearTimeout(timer);
252
+ }
package/src/state.ts CHANGED
@@ -13,6 +13,11 @@ export type GameStore<T extends Record<string, unknown>> = StoreApi<T> & {
13
13
  /**
14
14
  * A store the UI reads, coalesced to one publication per frame unless a game names an interval.
15
15
  *
16
+ * A key whose new value is `Object.is`-equal to the current value does not enter `pending`, so a
17
+ * frame that changed nothing publishes nothing and `flush` stays quiet. The flip side: mutating an
18
+ * object in place and setting it again is the same object, so nothing publishes — publish a new
19
+ * object or bump a version field on the value.
20
+ *
16
21
  * `intervalMs` is an override, not the rule. A fixed 100 ms default published the HUD ten times a
17
22
  * second whatever the frame rate was, which reads as a HUD that is not live — the number a player
18
23
  * watches moves in visible steps while the scene beside it runs smoothly. Left unset, `flush` is
@@ -47,9 +52,17 @@ export function createGameStore<T extends Record<string, unknown>>(
47
52
  gameStore.getState = () => current;
48
53
  gameStore.set = (patch: StatePatch<T>) => {
49
54
  const next = typeof patch === "function" ? patch(current) : patch;
50
- Object.assign(pending, next);
51
- Object.assign(current, next);
52
- hasPending = true;
55
+ let changed = false;
56
+ for (const key in next) {
57
+ const value = next[key];
58
+ // The value the HUD would publish is the one it already has: no publish, no cross-process
59
+ // write on native. Five kits hand-wrote this comparison before every `set`.
60
+ if (Object.is(value, current[key])) continue;
61
+ Reflect.set(pending, key, value);
62
+ Reflect.set(current, key, value);
63
+ changed = true;
64
+ }
65
+ if (changed) hasPending = true;
53
66
  };
54
67
  gameStore.flush = flush;
55
68
  gameStore.start = () => {