@threenative/core 0.3.11 → 0.3.12

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 (157) hide show
  1. package/capabilities.json +1096 -26
  2. package/dist/camera-shake-CZKOfGn4.d.ts +46 -0
  3. package/dist/{canvas-layer-vCtanIeB.d.ts → canvas-layer-CWuFRT7G.d.ts} +1 -1
  4. package/dist/chunk-2Z44XSI2.js +35 -0
  5. package/dist/chunk-5O73CDMR.js +1849 -0
  6. package/dist/chunk-6KLNISRJ.js +153 -0
  7. package/dist/chunk-7UUT3TY5.js +133 -0
  8. package/dist/chunk-CFGTPFUH.js +231 -0
  9. package/dist/chunk-DBELTTTM.js +615 -0
  10. package/dist/chunk-GMHATRPW.js +7701 -0
  11. package/dist/chunk-GXY7B3JG.js +46 -0
  12. package/dist/chunk-KIRUKTBQ.js +187 -0
  13. package/dist/chunk-N5LRP4BR.js +220 -0
  14. package/dist/chunk-OKXUCASC.js +2238 -0
  15. package/dist/chunk-QWJEMUUT.js +94 -0
  16. package/dist/chunk-VAZM36TV.js +497 -0
  17. package/dist/{game-DzMcitDO.d.ts → game-D7pAzZUY.d.ts} +15 -3
  18. package/dist/hot.d.ts +3 -3
  19. package/dist/hot.js +2 -46
  20. package/dist/index.d.ts +329 -302
  21. package/dist/index.js +10566 -22552
  22. package/dist/{model-lod-CTpZ6imz.d.ts → model-lod-B6BMqS1r.d.ts} +33 -3
  23. package/dist/playtest.d.ts +3 -3
  24. package/dist/playtest.js +24 -75
  25. package/dist/react-css.js +1 -215
  26. package/dist/react.d.ts +2 -2
  27. package/dist/{renderer-rZm0hVqq.d.ts → renderer-DvFVoAgj.d.ts} +13 -4
  28. package/dist/spells/index.d.ts +643 -0
  29. package/dist/spells/index.js +1558 -0
  30. package/dist/spells/ultra/index.d.ts +1600 -0
  31. package/dist/spells/ultra/index.js +6804 -0
  32. package/dist/terrain-jobs-worker.js +1 -123
  33. package/dist/two-sided-foliage-W523J3UM.js +1 -0
  34. package/dist/ui-layer.js +5 -384
  35. package/dist/worker.js +4 -41
  36. package/dist/world.d.ts +725 -259
  37. package/dist/world.js +16714 -18284
  38. package/mcp/animation-server.mjs +1 -1
  39. package/mcp/animation.mjs +2 -3
  40. package/mcp/engine-server.mjs +142 -47
  41. package/mcp/servers.mjs +9 -2
  42. package/mcp/terrain.mjs +8 -0
  43. package/package.json +14 -6
  44. package/patches/three@0.187.0-prd269-upgrade.patch +2102 -0
  45. package/patches/three@0.187.0.patch +2004 -407
  46. package/src/assets.ts +9 -2
  47. package/src/card-lod.ts +152 -0
  48. package/src/compressed-texture-preparation.ts +1008 -0
  49. package/src/frame-budget.ts +31 -20
  50. package/src/game-dev-tools.ts +93 -0
  51. package/src/game-frame-loop.ts +995 -0
  52. package/src/game-renderer-metrics.ts +77 -0
  53. package/src/game-startup.ts +1001 -0
  54. package/src/game-validate.ts +70 -0
  55. package/src/game.ts +253 -1935
  56. package/src/index.ts +27 -2
  57. package/src/launch-diagnostics.ts +22 -12
  58. package/src/look/ao-admission.ts +24 -0
  59. package/src/look/filmic-tone-mapping.ts +15 -13
  60. package/src/look/look-diagnostics.ts +3 -3
  61. package/src/look/quality.ts +10 -5
  62. package/src/look/world-environment.ts +76 -9
  63. package/src/loop.ts +29 -0
  64. package/src/model-lod.ts +42 -3
  65. package/src/particle-kinds.ts +515 -0
  66. package/src/picking.ts +17 -3
  67. package/src/playtest.ts +27 -1
  68. package/src/projection-apply.ts +4 -1
  69. package/src/projection-plan.ts +9 -6
  70. package/src/render/mesh-pool.ts +1 -1
  71. package/src/render/resolution-subrect.ts +2 -0
  72. package/src/render/rough-diffuse.ts +46 -12
  73. package/src/render/soft-shadow.ts +27 -12
  74. package/src/render/virtual-shadow-adaptive.ts +55 -0
  75. package/src/render/virtual-shadow-casters.ts +175 -0
  76. package/src/render/virtual-shadow-layers.ts +76 -0
  77. package/src/render/virtual-shadow-level.ts +224 -0
  78. package/src/render/virtual-shadow-markers.ts +193 -0
  79. package/src/render/virtual-shadow-options.ts +370 -0
  80. package/src/render/virtual-shadow-pages.ts +5 -0
  81. package/src/render/virtual-shadow.ts +213 -992
  82. package/src/render/world-impostor-surface.ts +293 -34
  83. package/src/render-pass-budget.ts +34 -7
  84. package/src/renderProjection.ts +22 -0
  85. package/src/renderer.ts +92 -37
  86. package/src/snow-field.ts +1 -1
  87. package/src/spells/cast-pool.ts +361 -0
  88. package/src/spells/index.ts +177 -0
  89. package/src/spells/mechanisms.ts +295 -0
  90. package/src/spells/reaction-field.ts +415 -0
  91. package/src/spells/spell-lights.ts +139 -0
  92. package/src/spells/spell-world.ts +187 -0
  93. package/src/spells/spell.ts +397 -0
  94. package/src/spells/spells.ts +283 -0
  95. package/src/spells/ultra/engine/camera.ts +184 -0
  96. package/src/spells/ultra/engine/quality.ts +96 -0
  97. package/src/spells/ultra/index.ts +52 -0
  98. package/src/spells/ultra/main.ts +305 -0
  99. package/src/spells/ultra/scene/arenaMaterial.ts +325 -0
  100. package/src/spells/ultra/spells/cast.ts +233 -0
  101. package/src/spells/ultra/spells/fire.ts +1267 -0
  102. package/src/spells/ultra/vfx/FluidVolume.ts +816 -0
  103. package/src/spells/ultra/vfx/FluidVolume.tsl.ts +855 -0
  104. package/src/spells/ultra/vfx/FxTarget.ts +61 -0
  105. package/src/spells/ultra/vfx/GroundField.ts +1399 -0
  106. package/src/spells/ultra/vfx/Particles.ts +1475 -0
  107. package/src/spells/ultra/vfx/Ribbons.ts +645 -0
  108. package/src/spells/ultra/vfx/Shockwaves.ts +286 -0
  109. package/src/spells/ultra/vfx/Volumes.ts +489 -0
  110. package/src/spells/ultra/vfx/common.ts +1195 -0
  111. package/src/spells/ultra/vfx/noise.ts +441 -0
  112. package/src/startup-readiness.ts +128 -34
  113. package/src/version.ts +1 -1
  114. package/src/warmup.ts +56 -8
  115. package/src/water-surface.ts +9 -3
  116. package/src/world-bundle-safety.ts +401 -0
  117. package/src/world-cell-batches.ts +1216 -0
  118. package/src/world-cell-chunks.ts +1132 -0
  119. package/src/world-cell-data.ts +995 -0
  120. package/src/world-cell-impostors.ts +1449 -0
  121. package/src/world-cell-lod-bias.ts +151 -0
  122. package/src/world-cell-models.ts +1074 -0
  123. package/src/world-cell-options.ts +189 -0
  124. package/src/world-cell-placements.ts +694 -0
  125. package/src/world-cell-prewarm.ts +557 -0
  126. package/src/world-cell-readiness.ts +357 -0
  127. package/src/world-cell-render-bundles.ts +459 -0
  128. package/src/world-cell-render-gpu-dress.ts +714 -0
  129. package/src/world-cell-render-main-cull.ts +484 -0
  130. package/src/world-cell-render-shadow-claims.ts +198 -0
  131. package/src/world-cell-render-util.ts +246 -0
  132. package/src/world-cell-render.ts +1493 -0
  133. package/src/world-cell-residency.ts +745 -0
  134. package/src/world-cells.ts +1318 -10418
  135. package/src/world-chunk-shadow.ts +308 -0
  136. package/src/world-collar.ts +315 -0
  137. package/src/world-gpu-flags.ts +163 -0
  138. package/src/world-gpu-readback.ts +881 -0
  139. package/src/world-gpu-reference.ts +510 -0
  140. package/src/world-gpu-scene.ts +214 -2264
  141. package/src/world-gpu-shadow.ts +190 -0
  142. package/src/world-gpu-types.ts +381 -0
  143. package/src/world-gpu-validation.ts +518 -0
  144. package/src/world-heightfield.ts +802 -0
  145. package/src/world-load-limiter.ts +106 -0
  146. package/src/world-noise.ts +241 -0
  147. package/src/world-package.ts +42 -0
  148. package/src/world-region.ts +1 -1
  149. package/src/world-terrain-splat.ts +365 -149
  150. package/src/world-tile-budget.ts +256 -0
  151. package/src/world-tile-geometry.ts +469 -0
  152. package/src/world-tile-lod.ts +408 -0
  153. package/src/world-tile-observation.ts +566 -0
  154. package/src/world-tile-stitch.ts +166 -0
  155. package/src/world-tiles.ts +170 -1745
  156. package/src/world-water-bodies.ts +359 -0
  157. package/src/world.ts +35 -741
package/src/renderer.ts CHANGED
@@ -9,6 +9,10 @@ import {
9
9
  type StorageBufferAttribute,
10
10
  type Renderer as ThreeRenderer,
11
11
  } from "three/webgpu";
12
+ import {
13
+ CompressedTextureUploads,
14
+ type ICompressedUploadDevice,
15
+ } from "./compressed-texture-preparation.js";
12
16
  import { ComputeTimingScopes, type IComputeTimingReceipt } from "./compute-timing.js";
13
17
  import type { IFrameSurfaceState } from "./frame-budget.js";
14
18
  import {
@@ -30,7 +34,7 @@ import {
30
34
  createPipelineCensus,
31
35
  } from "./pipeline-census.js";
32
36
  import { hostDocument, hostResizeObserver } from "./platform.js";
33
- import type { ITimestampQueryPool } from "./render-pass-budget.js";
37
+ import { type ITimestampQueryPool, RenderPassBudget } from "./render-pass-budget.js";
34
38
  import { AlphaAntialiasing, type IAlphaAntialiasingReport } from "./render/alpha-antialiasing.js";
35
39
  import {
36
40
  type IRenderChainBudgetWindow,
@@ -289,11 +293,18 @@ export interface IRendererLike {
289
293
  * Ordinary textures and the WebGL fallback retain their existing paths and report no work.
290
294
  * `onProgress` receives the completed unique compressed texture count after each preparation
291
295
  * promise resolves; queued textures and writes that have not settled receive no credit.
296
+ *
297
+ * Pass `replacements` to receive caller-owned `original -> prepared` pairs. The renderer owns
298
+ * the prepared GPU textures and publishes the map only after the whole call succeeds; an abort
299
+ * or failure leaves the caller's map unchanged. Without it the call keeps the numeric contract
300
+ * and prepared compressed replacements stay unpublished, so a material that samples the
301
+ * original keeps its borrowed identity.
292
302
  */
293
303
  prepareTextures?(
294
304
  textures: Iterable<Texture>,
295
305
  signal?: AbortSignal,
296
306
  onProgress?: (completed: number) => void,
307
+ replacements?: Map<Texture, Texture>,
297
308
  ): Promise<number>;
298
309
  /**
299
310
  * Copies one GPU storage attribute back to the CPU, asynchronously.
@@ -520,10 +531,6 @@ type RendererInstance = IStorageBufferSource & {
520
531
  domElement: HTMLCanvasElement;
521
532
  init?: () => Promise<void>;
522
533
  compileAsync?: (scene: Object3D, camera: Camera, targetScene?: Object3D) => Promise<void>;
523
- prepareTextureAsync?: (
524
- texture: Texture,
525
- options: { budgetMs: number; maxBytesPerWrite: number; signal: AbortSignal },
526
- ) => Promise<void>;
527
534
  compute?: (node: unknown) => void;
528
535
  getArrayBufferAsync?: (
529
536
  attribute: unknown,
@@ -682,8 +689,14 @@ function wrapRenderer(
682
689
  let renderChainUsesPerObjectVelocity = false;
683
690
  let activeCompiles = 0;
684
691
  let compileCount = 0;
692
+ // Compiles that overlap while drawing to the screen share three's one frame-buffer target. Only
693
+ // the first claim captures the name it found, and only the last one out puts it back; without
694
+ // that, a second claim captures the first one's temporary name and leaves it on the target.
695
+ const frameBufferNames = new WeakMap<object, { depth: number; saved: string }>();
685
696
  let disposed = false;
686
- const texturePreparations = new Set<AbortController>();
697
+ const texturePreparations = new CompressedTextureUploads(
698
+ () => (raw.backend as { device?: ICompressedUploadDevice } | undefined)?.device,
699
+ );
687
700
  const storageBuffers = new StorageBufferLeases(() => raw);
688
701
  let computeTimings: ComputeTimingScopes | undefined;
689
702
  let pendingScale: { scale: number; source: "auto" | "auto-pinned" } | undefined;
@@ -866,7 +879,9 @@ function wrapRenderer(
866
879
  pipelineCensus.warmUpScopeSettled(label, target),
867
880
  }),
868
881
  get warmUpWorldPass() {
869
- if (outputPipeline === undefined) return undefined;
882
+ // The ThreeNative engine refuses RendererUtils, so the pass could not restore the renderer
883
+ // state it changes there; the engine compiles the output pass at its first frame instead.
884
+ if (outputPipeline === undefined || !restoresRendererState()) return undefined;
870
885
  const drawOnce = (
871
886
  scene: Object3D,
872
887
  camera: Camera,
@@ -1178,6 +1193,24 @@ function wrapRenderer(
1178
1193
  (previousGetRenderTarget as () => unknown).call(raw) ??
1179
1194
  (renderingFrame > 0 ? null : overrideTarget);
1180
1195
  }
1196
+ // Three's frame-buffer target carries one unnamed texture. An MRT node resolves its outputs by
1197
+ // name, so a material with an `mrtNode` (a transparent sea, say) compiled against it builds an
1198
+ // empty output struct and its pipeline fails. Name that texture after the pass's first output
1199
+ // for this compile only. ponytail: first output only; a material needing a later output still
1200
+ // warms up empty.
1201
+ const frameBufferTexture = (overrideTarget as { textures?: { name: string }[] } | undefined)
1202
+ ?.textures?.[0];
1203
+ const firstOutputName = outputPass?.renderTarget?.textures[0]?.name;
1204
+ let frameBufferClaim: { depth: number; saved: string } | undefined;
1205
+ if (frameBufferTexture !== undefined) {
1206
+ frameBufferClaim = frameBufferNames.get(frameBufferTexture);
1207
+ if (frameBufferClaim === undefined) {
1208
+ frameBufferClaim = { depth: 0, saved: frameBufferTexture.name };
1209
+ frameBufferNames.set(frameBufferTexture, frameBufferClaim);
1210
+ }
1211
+ frameBufferClaim.depth += 1;
1212
+ if (firstOutputName) frameBufferTexture.name = firstOutputName;
1213
+ }
1181
1214
  activeCompiles += 1;
1182
1215
  compileCount += 1;
1183
1216
  try {
@@ -1191,6 +1224,13 @@ function wrapRenderer(
1191
1224
  else await raw.compileAsync(scene, camera, targetScene);
1192
1225
  }
1193
1226
  } finally {
1227
+ if (frameBufferTexture !== undefined && frameBufferClaim !== undefined) {
1228
+ frameBufferClaim.depth -= 1;
1229
+ if (frameBufferClaim.depth === 0) {
1230
+ frameBufferTexture.name = frameBufferClaim.saved;
1231
+ frameBufferNames.delete(frameBufferTexture);
1232
+ }
1233
+ }
1194
1234
  if (overrideTarget !== undefined) {
1195
1235
  if (hadOwnGetRenderTarget) raw.getRenderTarget = previousGetRenderTarget;
1196
1236
  else Reflect.deleteProperty(raw as object, "getRenderTarget");
@@ -1273,39 +1313,47 @@ function wrapRenderer(
1273
1313
  }
1274
1314
  return created;
1275
1315
  },
1276
- prepareTextures: async (textures, signal, onProgress) => {
1316
+ prepareTextures: async (textures, signal, onProgress, replacements) => {
1277
1317
  if (disposed) throw new Error("Renderer disposed during texture preparation.");
1278
1318
  if (kind !== "webgpu") return 0;
1279
- const unique = new Set(
1280
- [...textures].filter(
1281
- (texture) => "isCompressedTexture" in texture && texture.isCompressedTexture === true,
1282
- ),
1283
- );
1284
- if (unique.size === 0) return 0;
1285
- if (typeof raw.prepareTextureAsync !== "function")
1286
- throw new Error("WebGPU renderer lacks bounded compressed texture preparation.");
1287
- const controller = new AbortController();
1288
- const abort = () => controller.abort(signal?.reason);
1289
- if (signal?.aborted) abort();
1290
- else signal?.addEventListener("abort", abort, { once: true });
1291
- texturePreparations.add(controller);
1319
+ // Snapshot the caller's iterable once. An owned replacement resolves back to its original,
1320
+ // so a repeated call that hands back a published replacement keeps a stable identity instead
1321
+ // of looking like an unrelated texture and returning stale work.
1322
+ const inputs: Texture[] = [];
1323
+ const originals = new Set<Texture>();
1324
+ for (const texture of textures) {
1325
+ inputs.push(texture);
1326
+ const original = texturePreparations.resolveOriginal(texture);
1327
+ const compressed =
1328
+ "isCompressedTexture" in original && original.isCompressedTexture === true;
1329
+ const compressedArray =
1330
+ "isCompressedArrayTexture" in original && original.isCompressedArrayTexture === true;
1331
+ if (original !== texture || compressed || compressedArray) originals.add(original);
1332
+ }
1333
+ if (originals.size === 0) return 0;
1334
+ const preparedReplacements = new Map<Texture, Texture>();
1292
1335
  let completed = 0;
1293
- try {
1294
- for (const texture of unique) {
1295
- if (controller.signal.aborted) throw controller.signal.reason;
1296
- await raw.prepareTextureAsync(texture, {
1297
- budgetMs: 2,
1298
- maxBytesPerWrite: 65_536,
1299
- signal: controller.signal,
1300
- });
1336
+ for (const original of originals) {
1337
+ if (signal?.aborted) throw signal.reason;
1338
+ const prepared = await texturePreparations.upload(original, signal);
1339
+ if (prepared !== original) {
1340
+ preparedReplacements.set(original, prepared);
1301
1341
  completed += 1;
1302
1342
  onProgress?.(completed);
1303
1343
  }
1304
- return unique.size;
1305
- } finally {
1306
- texturePreparations.delete(controller);
1307
- signal?.removeEventListener("abort", abort);
1308
1344
  }
1345
+ if (disposed) throw new Error("Renderer disposed during texture preparation.");
1346
+ if (signal?.aborted) throw signal.reason;
1347
+ // Publish only after every texture in this call succeeded; abort or failure left this local.
1348
+ if (replacements !== undefined) {
1349
+ for (const [original, prepared] of preparedReplacements) {
1350
+ replacements.set(original, prepared);
1351
+ for (const input of inputs)
1352
+ if (texturePreparations.resolveOriginal(input) === original)
1353
+ replacements.set(input, prepared);
1354
+ }
1355
+ }
1356
+ return completed;
1309
1357
  },
1310
1358
  scenePassDepth: () => {
1311
1359
  // Three's implicit depth is in Textures.updateRenderTarget's data, not target.depthTexture.
@@ -1411,9 +1459,7 @@ function wrapRenderer(
1411
1459
  disposed = true;
1412
1460
  state.resolutionSubrect?.deactivate?.();
1413
1461
  state.resolutionSubrect = undefined;
1414
- for (const preparation of texturePreparations)
1415
- preparation.abort(new Error("Renderer disposed during texture preparation."));
1416
- texturePreparations.clear();
1462
+ texturePreparations.dispose();
1417
1463
  gpuObservation?.dispose();
1418
1464
  gpuObservation = undefined;
1419
1465
  pendingScale = undefined;
@@ -1442,7 +1488,7 @@ function wrapRenderer(
1442
1488
  if (!timestampFramesManaged) setTimestampTracking();
1443
1489
  renderingFrame += 1;
1444
1490
  try {
1445
- renderFrame(scene, camera);
1491
+ RenderPassBudget.renderWorld(raw, scene, camera, () => renderFrame(scene, camera));
1446
1492
  } finally {
1447
1493
  renderingFrame -= 1;
1448
1494
  }
@@ -1974,6 +2020,15 @@ export async function adapterTextureLimits(): Promise<{ requiredLimits?: Record<
1974
2020
  }
1975
2021
  }
1976
2022
 
2023
+ /** False on the ThreeNative engine, whose RendererUtils throws its catalog diagnostic on access. */
2024
+ function restoresRendererState(): boolean {
2025
+ try {
2026
+ return typeof RendererUtils.restoreRendererState === "function";
2027
+ } catch {
2028
+ return false;
2029
+ }
2030
+ }
2031
+
1977
2032
  function newPageCanvas(): HTMLCanvasElement {
1978
2033
  const page = hostDocument();
1979
2034
  if (page === undefined)
package/src/snow-field.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import type { Vector3 } from "three";
2
+ import type { Heightfield, IHeightfieldRegionBounds } from "./world-heightfield.js";
2
3
  import { unionBounds } from "./world-region.js";
3
- import type { Heightfield, IHeightfieldRegionBounds } from "./world.js";
4
4
 
5
5
  /**
6
6
  * What one contact footprint wants at a local offset, sampled in the contact's own frame.
@@ -0,0 +1,361 @@
1
+ /**
2
+ * A spell is not an effect: it is a timeline. Charge, release, travel, impact and linger drive
3
+ * several systems in turn, and the sequence is the same every cast, so the engine owns the clock
4
+ * and the spell only answers "what does this phase look like".
5
+ *
6
+ * This is the upstream Ultra Elements `cast.js` phase machine, with the arena removed: a cast
7
+ * never asks where the floor is. It integrates a projectile in a straight line, hands the spell
8
+ * every frame to steer, and retires each record back into a fixed pool. Nothing is allocated per
9
+ * cast, so a game that casts on every frame at 60 Hz allocates nothing at all.
10
+ */
11
+
12
+ import { Vector3 } from "three";
13
+
14
+ /** The beats of a spell, in order. `release` is instantaneous and never observed by a game. */
15
+ export type CastPhase = "charge" | "travel" | "impact" | "linger" | "done";
16
+
17
+ /**
18
+ * How a spell reaches its target.
19
+ * - `projectile` integrates a velocity through `travel`, and lands on the target or on `groundAt`.
20
+ * - `beam` holds at the target while `held`, then lands.
21
+ * - `strike`, `area` and `self` skip travel and land on `release`.
22
+ */
23
+ export type CastShape = "projectile" | "beam" | "strike" | "area" | "self";
24
+
25
+ const PHASES: readonly CastPhase[] = ["charge", "travel", "impact", "linger", "done"];
26
+
27
+ export interface ICastTiming {
28
+ /** Seconds of wind-up. Defaults to 0.5. */
29
+ readonly charge?: number;
30
+ /** Longest seconds of travel before the spell lands anyway. Defaults to 4. */
31
+ readonly travel?: number;
32
+ /** Seconds the impact reads on screen. Defaults to 0.2. */
33
+ readonly impact?: number;
34
+ /** Seconds the aftermath stays. Defaults to 2. */
35
+ readonly linger?: number;
36
+ }
37
+
38
+ /** One cast's worth of reusable state. The spell owns what goes in `data`. */
39
+ export interface ICast {
40
+ /** Pool slot, stable for the pool's lifetime: a spell may key per-slot state by it. */
41
+ readonly index: number;
42
+ spell: ISpell;
43
+ shape: CastShape;
44
+ phase: CastPhase;
45
+ /** Seconds inside the current phase, reset on every `enter`. */
46
+ t: number;
47
+ /** Seconds since the cast started. The pool recycles the largest `age` when it is full. */
48
+ age: number;
49
+ seed: number;
50
+ /** Where the spell was released from. */
51
+ readonly from: Vector3;
52
+ /** The target the game asked for. */
53
+ readonly to: Vector3;
54
+ /** Current world position: `from` while charging, integrated through travel. */
55
+ readonly pos: Vector3;
56
+ readonly vel: Vector3;
57
+ /** Unit vector `from` -> `to`. */
58
+ readonly dir: Vector3;
59
+ /** A held beam stays in `travel` until the game releases it. */
60
+ held: boolean;
61
+ /** Metres travelled. A spell may read it, the pool only accumulates it. */
62
+ travelled: number;
63
+ /** Impact radius in metres, validated once when the cast started. */
64
+ radius: number;
65
+ readonly durations: {
66
+ charge: number;
67
+ impact: number;
68
+ linger: number;
69
+ travel: number;
70
+ };
71
+ /** Spell-owned per-slot scratch, preallocated with the record and reset by the spell at charge. */
72
+ readonly data: Record<string, unknown>;
73
+ }
74
+
75
+ /**
76
+ * A spell as the pool sees it. Every factory on `@threenative/core/spells` returns one of these:
77
+ * it is the only shape the pool drives, and the spell reads the world through `SpellWorld`.
78
+ */
79
+ export interface ISpell {
80
+ /** The factory name without its `create` prefix, lowercase: `fireball`. */
81
+ readonly name: string;
82
+ /** How the spell reaches its target. Defaults to `projectile`. */
83
+ readonly shape?: CastShape;
84
+ /** Per-spell beat lengths. Missing beats take the pool defaults. */
85
+ readonly timing?: ICastTiming;
86
+ /** Metres per second for a projectile. Defaults to 15. */
87
+ readonly speed?: number;
88
+ /** Metres of collision radius at impact. Defaults to 0.3. */
89
+ readonly radius?: number;
90
+ /** Called on each beat change, including `done`. */
91
+ readonly phase?: (cast: ICast, phase: CastPhase) => void;
92
+ /**
93
+ * Owns the travel step for a spell that steers or arcs. The pool then skips its own straight-line
94
+ * integration and floor test for this cast; return true to land it. A spell with no `travel` hook
95
+ * is integrated by the pool and cannot miss.
96
+ */
97
+ readonly travel?: (cast: ICast, dt: number) => boolean | undefined;
98
+ /** Called once per frame while the cast is alive, in every phase. */
99
+ readonly update?: (cast: ICast, dt: number) => void;
100
+ }
101
+
102
+ export interface ICastOptions {
103
+ /** World point to travel from. Defaults to the world's `focus`. */
104
+ readonly from?: Vector3;
105
+ /** Hold a beam open past its sustain time. Defaults to false. */
106
+ readonly held?: boolean;
107
+ /** Override the generated seed, so a replay reproduces the same scatter. */
108
+ readonly seed?: number;
109
+ /** Override `spell.shape`, for a spell that carries several forms. */
110
+ readonly shape?: CastShape;
111
+ }
112
+
113
+ /** What a pool needs from the world: the floor, and how many records to keep. */
114
+ export interface ICastEnvironment {
115
+ /** Floor height under a point, so a projectile lands on a hill and not at y = 0. */
116
+ readonly groundAt?: (x: number, z: number) => number;
117
+ /** Records in the pool. Defaults to 16. */
118
+ readonly castSlots?: number;
119
+ /**
120
+ * Where a cast with no `from` starts: the caster's hand. `SpellWorld` supplies its own `focus`,
121
+ * so a game that moves that point gets it here with no extra wiring.
122
+ */
123
+ readonly focus?: Vector3;
124
+ }
125
+
126
+ const finite = (value: number, label: string): number => {
127
+ if (!Number.isFinite(value)) throw new TypeError(`${label} must be finite`);
128
+ return value;
129
+ };
130
+
131
+ /** Deterministic 32-bit hash, so a seed alone reproduces a scatter without touching `Math.random`. */
132
+ const mixSeed = (seed: number, salt: number): number => {
133
+ let x = (seed ^ (salt * 0x9e3779b1)) | 0;
134
+ x = Math.imul(x ^ (x >>> 16), 0x21f0aaad);
135
+ x = Math.imul(x ^ (x >>> 15), 0x735a2d97);
136
+ return (x ^ (x >>> 15)) >>> 0;
137
+ };
138
+
139
+ /** The spell a retired record reports, so `spell` is never undefined and never a cast. */
140
+ const IDLE_SPELL: ISpell = { name: "idle", shape: "self" };
141
+
142
+ function emptyRecord(index: number): ICast {
143
+ return {
144
+ age: 0,
145
+ data: {},
146
+ dir: new Vector3(),
147
+ durations: { charge: 0.5, impact: 0.2, linger: 2, travel: 4 },
148
+ from: new Vector3(),
149
+ held: false,
150
+ index,
151
+ phase: "done",
152
+ pos: new Vector3(),
153
+ seed: 0,
154
+ shape: "projectile",
155
+ spell: IDLE_SPELL,
156
+ t: 0,
157
+ to: new Vector3(),
158
+ radius: 0.3,
159
+ travelled: 0,
160
+ vel: new Vector3(),
161
+ };
162
+ }
163
+
164
+ const scratch = new Vector3();
165
+ /** Where a cast starts when neither the call nor the world named a point. */
166
+ const ORIGIN = new Vector3();
167
+
168
+ /**
169
+ * Drive spell timelines from a fixed pool of records.
170
+ *
171
+ * The pool is full at capacity and never grows: a full pool recycles the record that has been alive
172
+ * longest, which is the cast the player has already stopped watching. Every record keeps its
173
+ * identity across casts, so a spell's per-slot state and any pooled mesh it binds stay warm.
174
+ */
175
+ export class CastPool {
176
+ /** Every slot, alive or not. Read `phase !== "done"` for the live ones. */
177
+ readonly casts: readonly ICast[];
178
+ readonly #groundAt: ((x: number, z: number) => number) | undefined;
179
+ readonly #focus: Vector3 | undefined;
180
+ /** The newest live cast, or undefined. */
181
+ #last: ICast | undefined;
182
+ #seed = 0;
183
+
184
+ constructor(world: ICastEnvironment = {}) {
185
+ const capacity = world.castSlots ?? 16;
186
+ if (!Number.isInteger(capacity) || capacity < 1 || capacity > 256)
187
+ throw new RangeError("CastPool capacity must be an integer in 1..256");
188
+ this.#groundAt = world.groundAt;
189
+ this.#focus = world.focus;
190
+ this.casts = Array.from({ length: capacity }, (_, index) => emptyRecord(index));
191
+ }
192
+
193
+ /** The newest live cast. What a HUD reads for the phase strip. */
194
+ get active(): ICast | undefined {
195
+ return this.#last?.phase === "done" ? undefined : this.#last;
196
+ }
197
+
198
+ get count(): number {
199
+ let live = 0;
200
+ for (const cast of this.casts) live += cast.phase === "done" ? 0 : 1;
201
+ return live;
202
+ }
203
+
204
+ /** Start a spell. Returns the record, which the caller may read but the pool advances. */
205
+ cast(spell: ISpell, to: Vector3, options: ICastOptions = {}): ICast {
206
+ const record = this.#reserve();
207
+ // A cast with no origin starts at the caster's hand, never at whatever the slot last held.
208
+ const from = options.from ?? this.#focus ?? ORIGIN;
209
+ this.#validate(spell, to, from);
210
+ this.#arm(record, spell, to, from, options);
211
+ this.#enter(record, "charge");
212
+ this.#last = record;
213
+ return record;
214
+ }
215
+
216
+ /** The record this cast will use: a free slot, else the stale one, never a held beam if avoidable. */
217
+ #reserve(): ICast {
218
+ const free = this.casts.find((candidate) => candidate.phase === "done");
219
+ if (free !== undefined) return free;
220
+ // The cast alive longest is the one the player stopped watching, but a held beam is still under
221
+ // their finger, so it is only recycled when nothing else is left.
222
+ const unheld = this.casts.filter((candidate) => !candidate.held);
223
+ const pool = unheld.length > 0 ? unheld : this.casts;
224
+ const oldest = pool.reduce((a, b) => (b.age > a.age ? b : a));
225
+ this.#enter(oldest, "done");
226
+ return oldest;
227
+ }
228
+
229
+ /** Reject a cast the pool cannot honour, before any record is touched. */
230
+ #validate(spell: ISpell, to: Vector3, from: Vector3): void {
231
+ finite(to.x, "to.x");
232
+ finite(to.y, "to.y");
233
+ finite(to.z, "to.z");
234
+ finite(from.x, "from.x");
235
+ finite(from.y, "from.y");
236
+ finite(from.z, "from.z");
237
+ const radius = spell.radius ?? 0.3;
238
+ if (!Number.isFinite(radius) || radius < 0)
239
+ throw new RangeError(`${spell.name}.radius must be finite and non-negative`);
240
+ }
241
+
242
+ /** Fill a reserved record for a new cast. */
243
+ #arm(record: ICast, spell: ISpell, to: Vector3, from: Vector3, options: ICastOptions): void {
244
+ const durations = record.durations;
245
+ const timing = spell.timing ?? {};
246
+ durations.charge = finite(timing.charge ?? 0.5, "timing.charge");
247
+ durations.travel = finite(timing.travel ?? 4, "timing.travel");
248
+ durations.impact = finite(timing.impact ?? 0.2, "timing.impact");
249
+ durations.linger = finite(timing.linger ?? 2, "timing.linger");
250
+ record.spell = spell;
251
+ record.shape = options.shape ?? spell.shape ?? "projectile";
252
+ record.radius = spell.radius ?? 0.3;
253
+ record.held = options.held ?? false;
254
+ record.t = 0;
255
+ record.age = 0;
256
+ record.travelled = 0;
257
+ record.seed = options.seed ?? mixSeed(++this.#seed, 0x51ed);
258
+ record.from.copy(from);
259
+ record.to.copy(to);
260
+ record.pos.copy(from);
261
+ record.dir.subVectors(to, from);
262
+ if (record.dir.lengthSq() > 0) record.dir.normalize();
263
+ else record.dir.set(0, 0, 1);
264
+ record.vel.set(0, 0, 0);
265
+ }
266
+
267
+ /** End every held beam. A game calls this when the button comes up. */
268
+ releaseHeld(): void {
269
+ for (const cast of this.casts) cast.held = false;
270
+ }
271
+
272
+ /** Retire every live cast without running linger. */
273
+ clear(): void {
274
+ for (const cast of this.casts) if (cast.phase !== "done") this.#enter(cast, "done");
275
+ }
276
+
277
+ /**
278
+ * Advance every live cast. A projectile lands on the target, on the world's floor, or when its
279
+ * travel time runs out, whichever comes first.
280
+ */
281
+ update(dt: number): void {
282
+ if (!Number.isFinite(dt) || dt < 0)
283
+ throw new RangeError("CastPool.update delta must be finite and non-negative");
284
+ for (const cast of this.casts) {
285
+ if (cast.phase === "done") continue;
286
+ cast.t += dt;
287
+ cast.age += dt;
288
+ const state = this.#advanceBeat(cast, dt);
289
+ if (state === "retired") continue;
290
+ cast.spell.update?.(cast, dt);
291
+ // A spell can only ask to land while it is in the air. Honouring the request in charge or
292
+ // linger would land it every frame and its impact callback would never stop firing.
293
+ if (state === "landed") this.#enter(cast, "impact");
294
+ }
295
+ }
296
+
297
+ /** Advance one record's beat: still running, landed on the spell's own word, or retired. */
298
+ #advanceBeat(cast: ICast, dt: number): "running" | "landed" | "retired" {
299
+ if (cast.phase === "charge") this.#advanceCharge(cast);
300
+ else if (cast.phase === "travel") return this.#advanceTravel(cast, dt) ? "landed" : "running";
301
+ else if (cast.phase === "impact") {
302
+ if (cast.t >= cast.durations.impact) this.#enter(cast, "linger");
303
+ } else if (cast.t >= cast.durations.linger) {
304
+ this.#enter(cast, "done");
305
+ return "retired";
306
+ }
307
+ return "running";
308
+ }
309
+
310
+ #advanceCharge(cast: ICast): void {
311
+ cast.pos.copy(cast.from);
312
+ if (cast.t < cast.durations.charge) return;
313
+ const spell = cast.spell;
314
+ if (cast.shape === "projectile") {
315
+ cast.vel.copy(cast.dir).multiplyScalar(finite(spell.speed ?? 15, `${spell.name}.speed`));
316
+ this.#enter(cast, "travel");
317
+ } else if (cast.shape === "beam") this.#enter(cast, "travel");
318
+ else {
319
+ if (cast.shape !== "self") cast.pos.copy(cast.to);
320
+ this.#enter(cast, "impact");
321
+ }
322
+ }
323
+
324
+ /** True only when the spell's own travel hook says it landed; the pool lands its own shots. */
325
+ #advanceTravel(cast: ICast, dt: number): boolean {
326
+ const spell = cast.spell;
327
+ if (cast.shape !== "projectile") {
328
+ if (!cast.held && cast.t >= cast.durations.travel) this.#enter(cast, "impact");
329
+ return false;
330
+ }
331
+ // A spell with a `travel` hook owns its own integration (a homing ball, a lobbed arc); the pool
332
+ // then only steps the rest of the record and waits to be told it landed.
333
+ if (spell.travel !== undefined) return spell.travel(cast, dt) === true;
334
+ cast.pos.addScaledVector(cast.vel, dt);
335
+ cast.travelled += cast.vel.length() * dt;
336
+ const radius = cast.radius;
337
+ const past = scratch.subVectors(cast.to, cast.pos).dot(cast.dir) <= 0;
338
+ const groundAt = this.#groundAt;
339
+ // A floor the game cannot answer for is not a floor: a NaN would make `buried` false forever and
340
+ // the cast would fly until its travel time ran out.
341
+ const floor =
342
+ groundAt === undefined ? Number.NEGATIVE_INFINITY : groundAt(cast.pos.x, cast.pos.z);
343
+ const buried = Number.isFinite(floor) && cast.travelled > 1 && cast.pos.y < floor + radius;
344
+ // A ball that has passed its target lands on it, however late the frame notices. Only a spell
345
+ // that never reached the target spends its whole travel time and stops where it is.
346
+ if (past) {
347
+ cast.pos.copy(cast.to);
348
+ this.#enter(cast, "impact");
349
+ return false;
350
+ }
351
+ if (buried || cast.t >= cast.durations.travel) this.#enter(cast, "impact");
352
+ return false;
353
+ }
354
+
355
+ #enter(cast: ICast, phase: CastPhase): void {
356
+ if (!PHASES.includes(phase)) throw new RangeError(`unknown cast phase ${phase}`);
357
+ cast.phase = phase;
358
+ cast.t = 0;
359
+ cast.spell.phase?.(cast, phase);
360
+ }
361
+ }