@threenative/terrain 0.1.11 → 0.1.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 (218) hide show
  1. package/README.md +1 -0
  2. package/dist/bake-DJ5cxg0C.d.ts +82 -0
  3. package/dist/editor/index.d.ts +4 -4
  4. package/dist/editor/index.js +1 -1
  5. package/dist/editor/server.d.ts +2 -2
  6. package/dist/editor/worker.d.ts +1 -1
  7. package/dist/editor/worker.js +1 -1
  8. package/dist/export.d.ts +1 -1
  9. package/dist/index.d.ts +51 -222
  10. package/dist/index.js +111 -2
  11. package/dist/kit-world.d.ts +107 -0
  12. package/dist/kit-world.js +5134 -0
  13. package/dist/kit.d.ts +21 -4
  14. package/dist/kit.js +19 -4
  15. package/dist/mcp/cook-child.js +9 -6
  16. package/dist/mcp/server.js +14 -4
  17. package/dist/prop-package-Dwz0EWoB.d.ts +141 -0
  18. package/dist/{server-B5RdvEAC.d.ts → server-LnFwY8sr.d.ts} +1 -1
  19. package/dist/starter.d.ts +1141 -6
  20. package/dist/starter.js +1999 -17
  21. package/dist/{terrain-CAEaW0mQ.d.ts → terrain-DYCyAOCJ.d.ts} +1 -1
  22. package/dist/three.d.ts +1 -1
  23. package/dist/{types-BpH00qsx.d.ts → types-kpI0C4hW.d.ts} +1 -1
  24. package/dist/{world-package-B8QgHjAQ.d.ts → world-package-DqJC3-Nn.d.ts} +2 -2
  25. package/docs/authoring/new-environment.md +97 -0
  26. package/package.json +8 -8
  27. package/starter/alpine/README.md +22 -14
  28. package/starter/alpine/bake.mjs +14 -1
  29. package/starter/alpine/biome.data.json +187 -25
  30. package/starter/alpine/heightmap.r16 +0 -0
  31. package/starter/alpine/playerRig.ts +89 -0
  32. package/starter/alpine/recipe.json +169 -15
  33. package/starter/alpine/render/bakedFile.ts +17 -0
  34. package/starter/alpine/render/benchmark.ts +77 -0
  35. package/starter/alpine/render/biomeData.ts +14 -0
  36. package/starter/alpine/render/biomes.ts +687 -0
  37. package/starter/alpine/render/ground/cover.ts +565 -0
  38. package/starter/alpine/render/ground/horizon.ts +219 -0
  39. package/starter/alpine/render/ground/palette.d.ts +1 -0
  40. package/starter/alpine/render/ground/palette.js +11 -0
  41. package/starter/alpine/render/ground/scatter.ts +104 -0
  42. package/starter/alpine/render/ground/terrain.ts +1860 -0
  43. package/starter/alpine/render/kitAssets.ts +28 -0
  44. package/starter/alpine/render/loading.ts +354 -0
  45. package/starter/alpine/render/lookKnobs.ts +37 -0
  46. package/starter/alpine/render/orbitCamera.ts +155 -0
  47. package/starter/alpine/render/props/farForest.ts +94 -0
  48. package/starter/alpine/render/props/pack.ts +1114 -0
  49. package/starter/alpine/render/props/prepared.ts +225 -0
  50. package/starter/alpine/render/props/propMaterials.ts +1239 -0
  51. package/starter/alpine/render/props/propProgress.ts +2 -0
  52. package/starter/alpine/render/props/propWorld.ts +105 -0
  53. package/starter/alpine/render/props/props.ts +633 -0
  54. package/starter/alpine/render/props/spruce.ts +440 -0
  55. package/starter/alpine/render/sky/atmosphere.ts +329 -0
  56. package/starter/alpine/render/sky/sky.ts +382 -0
  57. package/starter/alpine/render/texturePreparation.ts +135 -0
  58. package/starter/alpine/render/water/river.ts +1132 -0
  59. package/starter/alpine/render/worldNames.ts +6 -0
  60. package/starter/alpine/scene.ts +715 -0
  61. package/starter/alpine/sceneProps.ts +561 -0
  62. package/starter/alpine/sceneState.ts +33 -0
  63. package/starter/alpine/world/terrainAssets.ts +145 -0
  64. package/starter/alpine/world/walkBand.ts +47 -0
  65. package/starter/alpine/world/water.ts +74 -0
  66. package/starter/alpine/worlds.ts +13 -0
  67. package/starter/coastal/README.md +26 -27
  68. package/starter/coastal/assets.json +10 -0
  69. package/starter/coastal/bake.mjs +14 -1
  70. package/starter/coastal/biome.data.json +18 -3
  71. package/starter/coastal/playerRig.ts +89 -0
  72. package/starter/coastal/recipe.json +220 -18
  73. package/starter/coastal/render/bakedFile.ts +17 -0
  74. package/starter/coastal/render/benchmark.ts +81 -0
  75. package/starter/coastal/render/biomeData.ts +14 -0
  76. package/starter/coastal/render/biomes.ts +678 -0
  77. package/starter/coastal/render/ground/cover.ts +565 -0
  78. package/starter/coastal/render/ground/horizon.ts +219 -0
  79. package/starter/coastal/render/ground/palette.d.ts +1 -0
  80. package/starter/coastal/render/ground/palette.js +11 -0
  81. package/starter/coastal/render/ground/scatter.ts +104 -0
  82. package/starter/coastal/render/ground/terrain.ts +1829 -0
  83. package/starter/coastal/render/kitAssets.ts +28 -0
  84. package/starter/coastal/render/loading.ts +354 -0
  85. package/starter/coastal/render/lookKnobs.ts +37 -0
  86. package/starter/coastal/render/orbitCamera.ts +155 -0
  87. package/starter/coastal/render/props/farForest.ts +94 -0
  88. package/starter/coastal/render/props/pack.ts +1109 -0
  89. package/starter/coastal/render/props/prepared.ts +225 -0
  90. package/starter/coastal/render/props/propMaterials.ts +1239 -0
  91. package/starter/coastal/render/props/propProgress.ts +2 -0
  92. package/starter/coastal/render/props/propWorld.ts +105 -0
  93. package/starter/coastal/render/props/props.ts +633 -0
  94. package/starter/coastal/render/props/spruce.ts +440 -0
  95. package/starter/coastal/render/sky/atmosphere.ts +329 -0
  96. package/starter/coastal/render/sky/sky.ts +382 -0
  97. package/starter/coastal/render/texturePreparation.ts +135 -0
  98. package/starter/coastal/render/water/ocean.ts +284 -0
  99. package/starter/coastal/render/water/river.ts +1132 -0
  100. package/starter/coastal/render/worldNames.ts +6 -0
  101. package/starter/coastal/scene.ts +740 -0
  102. package/starter/coastal/sceneProps.ts +559 -0
  103. package/starter/coastal/sceneState.ts +33 -0
  104. package/starter/coastal/world/terrainAssets.ts +151 -0
  105. package/starter/coastal/world/walkBand.ts +47 -0
  106. package/starter/coastal/world/water.ts +74 -0
  107. package/starter/coastal/worlds.ts +13 -0
  108. package/starter/desert/README.md +51 -25
  109. package/starter/desert/bake-flora.mjs +142 -0
  110. package/starter/desert/bake-rocks.mjs +291 -0
  111. package/starter/desert/bake.mjs +14 -1
  112. package/starter/desert/biome.data.json +24 -12
  113. package/starter/desert/playerRig.ts +89 -0
  114. package/starter/desert/recipe.json +63 -16
  115. package/starter/desert/render/bakedFile.ts +17 -0
  116. package/starter/desert/render/benchmark.ts +79 -0
  117. package/starter/desert/render/biomeData.ts +14 -0
  118. package/starter/desert/render/biomes.ts +660 -0
  119. package/starter/desert/render/ground/cover.ts +565 -0
  120. package/starter/desert/render/ground/debris.ts +136 -0
  121. package/starter/desert/render/ground/horizon.ts +219 -0
  122. package/starter/desert/render/ground/palette.d.ts +1 -0
  123. package/starter/desert/render/ground/palette.js +11 -0
  124. package/starter/desert/render/ground/scatter.ts +104 -0
  125. package/starter/desert/render/ground/terrain.ts +1854 -0
  126. package/starter/desert/render/kitAssets.ts +28 -0
  127. package/starter/desert/render/loading.ts +354 -0
  128. package/starter/desert/render/lookKnobs.ts +37 -0
  129. package/starter/desert/render/orbitCamera.ts +155 -0
  130. package/starter/desert/render/props/farForest.ts +96 -0
  131. package/starter/desert/render/props/formations.ts +630 -0
  132. package/starter/desert/render/props/pack.ts +1195 -0
  133. package/starter/desert/render/props/prepared.ts +225 -0
  134. package/starter/desert/render/props/propMaterials.ts +1255 -0
  135. package/starter/desert/render/props/propProgress.ts +2 -0
  136. package/starter/desert/render/props/propWorld.ts +105 -0
  137. package/starter/desert/render/props/props.ts +624 -0
  138. package/starter/desert/render/props/spruce.ts +440 -0
  139. package/starter/desert/render/sand.ts +581 -0
  140. package/starter/desert/render/sky/atmosphere.ts +329 -0
  141. package/starter/desert/render/sky/sky.ts +382 -0
  142. package/starter/desert/render/texturePreparation.ts +135 -0
  143. package/starter/desert/render/water/river.ts +1132 -0
  144. package/starter/desert/render/worldNames.ts +6 -0
  145. package/starter/desert/scene.ts +748 -0
  146. package/starter/desert/sceneProps.ts +562 -0
  147. package/starter/desert/sceneState.ts +33 -0
  148. package/starter/desert/world/terrainAssets.ts +162 -0
  149. package/starter/desert/world/walkBand.ts +47 -0
  150. package/starter/desert/world/water.ts +74 -0
  151. package/starter/desert/worlds.ts +13 -0
  152. package/starter/forest/README.md +8 -5
  153. package/starter/forest/bake.mjs +21 -413
  154. package/starter/forest/playerRig.ts +37 -171
  155. package/starter/forest/recipe.json +237 -47
  156. package/starter/forest/render/biomes.ts +2 -1
  157. package/starter/forest/render/ground/horizon.ts +4 -302
  158. package/starter/forest/render/ground/terrain.ts +14 -32
  159. package/starter/forest/render/kitAssets.ts +3 -2
  160. package/starter/forest/render/props/farForest.ts +2 -1
  161. package/starter/forest/render/props/pack.ts +4 -2
  162. package/starter/forest/render/props/prepared.ts +2 -1
  163. package/starter/forest/render/props/propProgress.ts +1 -11
  164. package/starter/forest/render/props/propWorld.ts +48 -662
  165. package/starter/forest/render/props/props.ts +64 -248
  166. package/starter/forest/render/sky/sky.ts +2 -1
  167. package/starter/forest/render/worldNames.ts +6 -2
  168. package/starter/forest/scene.ts +34 -25
  169. package/starter/forest/sceneProps.ts +2 -2
  170. package/starter/forest/sceneState.ts +5 -4
  171. package/starter/forest/surface.json +2 -2
  172. package/starter/forest/worlds.ts +3 -2
  173. package/starter/tundra/README.md +35 -16
  174. package/starter/tundra/bake.mjs +14 -1
  175. package/starter/tundra/biome.data.json +6 -6
  176. package/starter/tundra/playerRig.ts +89 -0
  177. package/starter/tundra/recipe.json +111 -110
  178. package/starter/tundra/render/bakedFile.ts +17 -0
  179. package/starter/tundra/render/benchmark.ts +79 -0
  180. package/starter/tundra/render/biomeData.ts +14 -0
  181. package/starter/tundra/render/biomes.ts +714 -0
  182. package/starter/tundra/render/ground/cover.ts +565 -0
  183. package/starter/tundra/render/ground/horizon.ts +219 -0
  184. package/starter/tundra/render/ground/palette.d.ts +1 -0
  185. package/starter/tundra/render/ground/palette.js +11 -0
  186. package/starter/tundra/render/ground/scatter.ts +104 -0
  187. package/starter/tundra/render/ground/terrain.ts +1874 -0
  188. package/starter/tundra/render/kitAssets.ts +28 -0
  189. package/starter/tundra/render/loading.ts +354 -0
  190. package/starter/tundra/render/lookKnobs.ts +37 -0
  191. package/starter/tundra/render/orbitCamera.ts +155 -0
  192. package/starter/tundra/render/props/farForest.ts +96 -0
  193. package/starter/tundra/render/props/pack.ts +1088 -0
  194. package/starter/tundra/render/props/prepared.ts +225 -0
  195. package/starter/tundra/render/props/propMaterials.ts +1247 -0
  196. package/starter/tundra/render/props/propProgress.ts +2 -0
  197. package/starter/tundra/render/props/propWorld.ts +105 -0
  198. package/starter/tundra/render/props/props.ts +624 -0
  199. package/starter/tundra/render/props/spruce.ts +440 -0
  200. package/starter/tundra/render/sky/atmosphere.ts +329 -0
  201. package/starter/tundra/render/sky/sky.ts +382 -0
  202. package/starter/tundra/render/texturePreparation.ts +135 -0
  203. package/starter/tundra/render/water/river.ts +1132 -0
  204. package/starter/tundra/render/worldNames.ts +6 -0
  205. package/starter/tundra/scene.ts +715 -0
  206. package/starter/tundra/sceneProps.ts +559 -0
  207. package/starter/tundra/sceneState.ts +33 -0
  208. package/starter/tundra/world/terrainAssets.ts +159 -0
  209. package/starter/tundra/world/walkBand.ts +47 -0
  210. package/starter/tundra/world/water.ts +74 -0
  211. package/starter/tundra/worlds.ts +13 -0
  212. package/starter-assets.json +4 -4
  213. package/starter-credits.json +613 -10
  214. package/starter/forest/diagnostics.ts +0 -1020
  215. package/starter/forest/render/sky/skyVisibility.ts +0 -121
  216. package/starter/forest/spawnGate.ts +0 -183
  217. package/starter/forest/viewStatistics.ts +0 -47
  218. package/starter/forest/world/streamedGround.ts +0 -139
@@ -1,121 +0,0 @@
1
- /**
2
- * The share of the sky each heightfield vertex sees past the terrain around it: 1 on open ground,
3
- * lower on a valley floor, at a cliff foot or in a crater.
4
- *
5
- * The logic follows TerraForge3D's horizon ambient pass (MIT, `heightfield/ambient/compute.glsl`):
6
- * march outward along evenly spaced azimuths, keep the highest horizon each one meets, and integrate
7
- * the cosine-weighted sky above it, which is `cos²` of the horizon angle per azimuth. Only ground
8
- * that rises over both the vertex's tangent plane and the horizontal occludes, so a straight slope
9
- * and a steep face over a flat floor stay open: the lighting already counts the slope's own tilt.
10
- *
11
- * Heights are row-major Z then X, centred on the origin, as the baked world stores them. Every node
12
- * marches: a strided march filled bilinearly erred by 0.13 at p99 on the alpine survey's creases.
13
- * About 0.4 s of CPU a world, so `scripts/bake/bake.mjs` runs it and the game loads `<world>.sky.bin`.
14
- */
15
- export function skyVisibility(
16
- heights: ArrayLike<number>,
17
- resolution: number,
18
- size: number,
19
- { azimuths = 16, reach = 160 }: { azimuths?: number; reach?: number } = {},
20
- ): Float32Array {
21
- if (resolution < 2 || heights.length !== resolution * resolution)
22
- throw new RangeError(
23
- `skyVisibility: ${heights.length} heights do not fill a ${resolution}² grid`,
24
- );
25
- const spacing = size / (resolution - 1);
26
- const last = resolution - 1;
27
- const grid = Float32Array.from(heights);
28
- // One cell at a time near the vertex, then 10 % further each step: ~32 samples reach 160 m.
29
- const radii: number[] = [];
30
- for (let r = spacing; r <= reach; r += Math.max(spacing, r * 0.1)) radii.push(r);
31
- // Per azimuth and step: the offset in grid cells and 1/r, so the inner loop only adds.
32
- const steps = radii.length;
33
- const offsetColumn = new Float32Array(azimuths * steps);
34
- const offsetRow = new Float32Array(azimuths * steps);
35
- const directionX = new Float32Array(azimuths);
36
- const directionZ = new Float32Array(azimuths);
37
- for (let a = 0; a < azimuths; a++) {
38
- const angle = (a / azimuths) * Math.PI * 2;
39
- directionX[a] = Math.cos(angle);
40
- directionZ[a] = Math.sin(angle);
41
- for (let k = 0; k < steps; k++) {
42
- offsetColumn[a * steps + k] = (Math.cos(angle) * (radii[k] as number)) / spacing;
43
- offsetRow[a * steps + k] = (Math.sin(angle) * (radii[k] as number)) / spacing;
44
- }
45
- }
46
- const march: IMarch = {
47
- grid,
48
- resolution,
49
- steps,
50
- offsetColumn,
51
- offsetRow,
52
- inverseRadius: Float32Array.from(radii, (r) => 1 / r),
53
- };
54
- const visibility = new Float32Array(resolution * resolution);
55
- for (let row = 0; row < resolution; row++) {
56
- const up = Math.min(row + 1, last);
57
- const down = Math.max(row - 1, 0);
58
- for (let column = 0; column < resolution; column++) {
59
- const right = Math.min(column + 1, last);
60
- const left = Math.max(column - 1, 0);
61
- const gradientX =
62
- ((grid[row * resolution + right] as number) - (grid[row * resolution + left] as number)) /
63
- ((right - left) * spacing);
64
- const gradientZ =
65
- ((grid[up * resolution + column] as number) -
66
- (grid[down * resolution + column] as number)) /
67
- ((up - down) * spacing);
68
- let sky = 0;
69
- for (let a = 0; a < azimuths; a++) {
70
- // Above the tangent plane and above the horizon both: downhill, the plane dips under the
71
- // valley floor, and that ground already darkens a tilted normal through the lighting.
72
- const plane = Math.max(
73
- 0,
74
- gradientX * (directionX[a] as number) + gradientZ * (directionZ[a] as number),
75
- );
76
- const horizon = horizonTangent(march, row, column, a, plane);
77
- sky += 1 / (1 + horizon * horizon);
78
- }
79
- visibility[row * resolution + column] = sky / azimuths;
80
- }
81
- }
82
- return visibility;
83
- }
84
-
85
- interface IMarch {
86
- readonly grid: Float32Array;
87
- readonly resolution: number;
88
- readonly steps: number;
89
- readonly offsetColumn: Float32Array;
90
- readonly offsetRow: Float32Array;
91
- readonly inverseRadius: Float32Array;
92
- }
93
-
94
- /** The highest ground over `plane` along one azimuth, as a tangent; 0 when nothing rises over it. */
95
- function horizonTangent(
96
- { grid, resolution, steps, offsetColumn, offsetRow, inverseRadius }: IMarch,
97
- row: number,
98
- column: number,
99
- azimuth: number,
100
- plane: number,
101
- ): number {
102
- const last = resolution - 1;
103
- const h0 = grid[row * resolution + column] as number;
104
- let horizon = 0;
105
- for (let k = 0; k < steps; k++) {
106
- const c = column + (offsetColumn[azimuth * steps + k] as number);
107
- const w = row + (offsetRow[azimuth * steps + k] as number);
108
- if (c < 0 || c > last || w < 0 || w > last) break;
109
- // Bilinear between the four cells around the sample.
110
- const c0 = c < last ? c | 0 : last - 1;
111
- const w0 = w < last ? w | 0 : last - 1;
112
- const i = w0 * resolution + c0;
113
- const top = (grid[i] as number) + ((grid[i + 1] as number) - (grid[i] as number)) * (c - c0);
114
- const bottom =
115
- (grid[i + resolution] as number) +
116
- ((grid[i + resolution + 1] as number) - (grid[i + resolution] as number)) * (c - c0);
117
- const tangent = (top + (bottom - top) * (w - w0) - h0) * (inverseRadius[k] as number) - plane;
118
- if (tangent > horizon) horizon = tangent;
119
- }
120
- return horizon;
121
- }
@@ -1,183 +0,0 @@
1
- import type { TerrainCtx } from "./sceneState.js";
2
-
3
- /** How much of the spawn's own region landed: the two counts the run report publishes. */
4
- export interface ISpawnRegion {
5
- readonly required: number;
6
- readonly loaded: number;
7
- }
8
-
9
- /**
10
- * The one deadline a scene allows its spawn to land, taken at entry and not extended.
11
- *
12
- * A scene destroys and rebuilds its world on every `ctx.goto`, so the gate is scene-local: the
13
- * promise it settles is that scene's loading screen, and a scene that was left behind settles it
14
- * rather than leaving the next world's loader waiting on a world that will not arrive.
15
- */
16
- const SPAWN_BUDGET_MS = 120_000;
17
- const EXPIRED = `Strata spawn admission exceeded ${SPAWN_BUDGET_MS} ms`;
18
-
19
- /** Where the scene's own preparation stands, for the failure report. */
20
- export interface ISpawnWitness {
21
- /** The preparation phase the scene is in, when it has one. */
22
- readonly phase: string | undefined;
23
- /** The streamed or staged build's own stage name. */
24
- readonly stage: string;
25
- readonly bucket: string | null;
26
- readonly added: number | null;
27
- readonly total: number | null;
28
- readonly buildStartedAt: number | undefined;
29
- readonly phaseStartedAt: number | undefined;
30
- readonly lastProgressAt: number | undefined;
31
- }
32
-
33
- export interface ISpawnGateOptions {
34
- readonly world: string;
35
- /** Completed work units, so the loading screen's percentage cannot claim progress a stall did not make. */
36
- readonly progress: () => number;
37
- /**
38
- * Where preparation stands when the spawn fails, so the failure names the phase it died in.
39
- * Absent until the scene's own build exists: a failure before that reports nulls, not a guess.
40
- */
41
- readonly witness: () => ISpawnWitness | undefined;
42
- /** True once the scene tore its world down: a join that lands afterwards must not revive it. */
43
- readonly released: () => boolean;
44
- }
45
-
46
- export interface ISpawnGate {
47
- readonly deadlineAt: number;
48
- /** Settles when the spawn's data and draws both landed; rejects when it failed or was cancelled. */
49
- readonly promise: Promise<void>;
50
- readonly ready: boolean;
51
- readonly error: string;
52
- readonly cells: ISpawnRegion;
53
- /** Keeps the loading screen up until the spawn promise settles. */
54
- readonly hold: () => void;
55
- /** Await one readiness join under the gate's deadline. */
56
- readonly watch: (
57
- join: (remainingMs: number) => Promise<{ requiredCells: number; loadedCells: number }>,
58
- ) => void;
59
- /** The join landed: publish the cells it covers and release the gate. */
60
- readonly land: (region: { requiredCells: number; loadedCells: number }) => void;
61
- /** Release the gate without a failure receipt: the spawn landed, or the scene left. */
62
- readonly settle: (error?: Error) => void;
63
- /** Kill the gate with a receipt: the spawn failed. */
64
- readonly fail: (reason?: unknown) => void;
65
- }
66
-
67
- /**
68
- * The spawn gate: one deadline, one settlement, one failure report.
69
- *
70
- * `WorldCells.whenSpawnReady` is the data authority and each streamed world's `prewarmed` is the
71
- * draw gate; this gate turns their landing into the loading screen's release, and writes the one
72
- * console line a failed spawn leaves behind.
73
- */
74
- export function createSpawnGate(ctx: TerrainCtx, options: ISpawnGateOptions): ISpawnGate {
75
- const { progress, released, witness, world } = options;
76
- const deadlineAt = performance.now() + SPAWN_BUDGET_MS;
77
- let spawnCells: ISpawnRegion = { loaded: 0, required: 0 };
78
- let spawnReady = false;
79
- let spawnError = "";
80
- let spawnSettled = false;
81
- let capturingSpawnFailure = false;
82
- let resolveSpawn: () => void = () => undefined;
83
- let rejectSpawn: (reason: Error) => void = () => undefined;
84
- const spawnPromise = new Promise<void>((done, failed) => {
85
- resolveSpawn = done;
86
- rejectSpawn = failed;
87
- });
88
-
89
- function settleSpawn(error?: Error): void {
90
- if (spawnSettled || capturingSpawnFailure) return;
91
- spawnSettled = true;
92
- clearTimeout(spawnTimer);
93
- if (error === undefined) {
94
- spawnReady = true;
95
- resolveSpawn();
96
- } else {
97
- rejectSpawn(error);
98
- }
99
- }
100
-
101
- function failSpawn(reason?: unknown): void {
102
- if (spawnSettled || capturingSpawnFailure) return;
103
- const message =
104
- (reason instanceof Error ? reason.message : String(reason ?? "")) || "Strata spawn failed";
105
- capturingSpawnFailure = true;
106
- try {
107
- captureSpawnFailure(message);
108
- } catch {
109
- // A diagnostic must never replace the admission failure or leave its promise pending.
110
- }
111
- capturingSpawnFailure = false;
112
- spawnError = message;
113
- settleSpawn(new Error(message));
114
- ctx.state.set({ worldReady: spawnReady, loadingError: spawnError });
115
- }
116
-
117
- const spawnTimer: ReturnType<typeof setTimeout> = setTimeout(() => failSpawn(EXPIRED), 120_000);
118
-
119
- function captureSpawnFailure(reason: string): void {
120
- const failedAt = performance.now();
121
- const sceneStartedAt = deadlineAt - SPAWN_BUDGET_MS;
122
- const preparation = witness();
123
- const propsStage = preparation?.stage ?? "before-build";
124
- const since = (stamp: number | undefined): number | null =>
125
- stamp === undefined ? null : Math.max(0, Math.round(stamp - sceneStartedAt));
126
- console.error(
127
- `TN_STRATA_SPAWN_FAILURE ${JSON.stringify({
128
- reason: reason.slice(0, 256),
129
- world,
130
- stage: (preparation?.phase ?? propsStage).slice(0, 64),
131
- bucket: preparation?.bucket?.slice(0, 64) ?? null,
132
- added: preparation?.added ?? null,
133
- total: preparation?.total ?? null,
134
- deadlineElapsedMs: Math.max(0, Math.round(failedAt - sceneStartedAt)),
135
- buildStartedMs: since(preparation?.buildStartedAt),
136
- phaseStartedMs: since(preparation?.phaseStartedAt),
137
- lastProgressMs: since(preparation?.lastProgressAt),
138
- })}`,
139
- );
140
- }
141
-
142
- const hold = (): void => {
143
- if (ctx.startup.phase !== "ready")
144
- ctx.startup.hold("strata-spawn", spawnPromise, SPAWN_BUDGET_MS, progress);
145
- };
146
-
147
- const land = (region: { requiredCells: number; loadedCells: number }): void => {
148
- if (released() || spawnSettled) return;
149
- spawnCells = { loaded: region.loadedCells, required: region.requiredCells };
150
- settleSpawn();
151
- };
152
-
153
- const watch = (
154
- join: (remainingMs: number) => Promise<{ requiredCells: number; loadedCells: number }>,
155
- ): void => {
156
- const remaining = deadlineAt - performance.now();
157
- if (remaining <= 0) {
158
- failSpawn(EXPIRED);
159
- return;
160
- }
161
- void join(remaining).then(land, (reason) => failSpawn(reason));
162
- };
163
-
164
- return {
165
- deadlineAt,
166
- promise: spawnPromise,
167
- fail: failSpawn,
168
- hold,
169
- land,
170
- settle: settleSpawn,
171
- watch,
172
- // The frame report reads these every step, so they are live values, not a snapshot.
173
- get cells(): ISpawnRegion {
174
- return spawnCells;
175
- },
176
- get error(): string {
177
- return spawnError;
178
- },
179
- get ready(): boolean {
180
- return spawnReady;
181
- },
182
- };
183
- }
@@ -1,47 +0,0 @@
1
- const medians = new WeakMap<readonly number[], { length: number; value: number }>();
2
-
3
- /** The upper middle of append-only frame-window samples, without changing their order. */
4
- export function medianOfGrowingSamples(values: readonly number[]): number {
5
- if (values.length === 0) return 0;
6
- const cached = medians.get(values);
7
- if (cached?.length === values.length) return cached.value;
8
- const sorted = [...values].sort((a, b) => a - b);
9
- const value = sorted[Math.floor(sorted.length / 2)] ?? 0;
10
- medians.set(values, { length: values.length, value });
11
- return value;
12
- }
13
-
14
- export interface IViewVisit {
15
- windows: number;
16
- discard: boolean;
17
- ready: boolean;
18
- }
19
-
20
- export function beginViewVisit(): IViewVisit {
21
- return { windows: 0, discard: true, ready: false };
22
- }
23
-
24
- /** Accept one retained window for the current camera visit. */
25
- export function retainViewWindow(
26
- visit: IViewVisit,
27
- window: Pick<import("@threenative/core").IFrameBudgetWindow, "gpuMs" | "gpuFrames" | "surface">,
28
- firstGpuFrame: number,
29
- ): boolean {
30
- if (!visit.ready || window.surface?.compiling === true) {
31
- visit.discard = true;
32
- return false;
33
- }
34
- if (
35
- !Number.isFinite(firstGpuFrame) ||
36
- window.gpuMs === undefined ||
37
- window.gpuFrames === undefined ||
38
- window.gpuFrames.first < firstGpuFrame
39
- )
40
- return false;
41
- if (visit.discard) {
42
- visit.discard = false;
43
- return false;
44
- }
45
- visit.windows++;
46
- return true;
47
- }
@@ -1,139 +0,0 @@
1
- import type { ICtx } from "@threenative/core";
2
- import {
3
- AdmissionBudget,
4
- type HeightfieldCollar,
5
- type IWorldTileColliderInput,
6
- TerrainTiles,
7
- warmUnculled,
8
- } from "@threenative/core/world";
9
- import { CollisionShape3D, type IPhysicsContext, RigidBody3D } from "@threenative/physics";
10
- import type { Object3D } from "three";
11
- import type { MeshStandardNodeMaterial } from "three/webgpu";
12
- import type { WorldName } from "../render/biomes.js";
13
- import {
14
- HORIZON_REACH,
15
- STREAM_TILE,
16
- collarSeamGap,
17
- createMorphedHeight,
18
- createWorldHeight,
19
- } from "../render/ground/horizon.js";
20
- import type { IBakedWorld, ITerrainStream } from "../render/ground/terrain.js";
21
-
22
- /** Tile width in metres: 32 cells of the square's own 2 m spacing, so tile and square share vertices. */
23
- const TILE = STREAM_TILE;
24
- /** Tiles each side of the player's: a 576 m square, wider than the playable square itself. */
25
- const RADIUS = 4;
26
- /** Tiles each side of the player's that collide: the player only ever stands on its own or a neighbour. */
27
- const COLLIDER_RADIUS = 1;
28
- /** One frame's tile building, in milliseconds; the rest waits for the next frame. */
29
- const ADMISSION_MS = 2;
30
-
31
- /**
32
- * PRD-790: the ground past the playable square, streamed around the player by `TerrainTiles` out to
33
- * the collar's reach. Tiles sample `createWorldHeight`, the surface the square and the collar's
34
- * vertices stand on, so a tile meets the square and its neighbours with no step. The tile material
35
- * slides the outermost tile onto the collar's drawn height (`collarMorph`), so at the collar every
36
- * tile vertex stands on it; `?tnTerrainValidate=1` reports `streamCollarGap`. The largest block of
37
- * resident tiles around the player is written to `split` each frame: the tiles draw inside it, the collar everywhere else, so a tile that
38
- * is still building leaves the collar showing, never a hole.
39
- */
40
- export function addStreamedGround(
41
- ctx: ICtx<Record<string, unknown>, IPhysicsContext>,
42
- data: IBakedWorld,
43
- world: WorldName,
44
- surface: MeshStandardNodeMaterial,
45
- collar: HeightfieldCollar,
46
- split: ITerrainStream,
47
- follow: Object3D,
48
- report: (facts: {
49
- streamTiles: number;
50
- streamCoveredHalf: number;
51
- streamSeamGap: number;
52
- streamCollarGap: number;
53
- streamCollarFold: number;
54
- }) => void,
55
- ): { dispose(): void; readonly ready: Promise<void>; readonly tiles: TerrainTiles } {
56
- const half = data.size / 2;
57
- const reach = half + HORIZON_REACH;
58
- const height = createWorldHeight(data, world);
59
- const spacing = data.size / (data.resolution - 1);
60
- const tiles = new TerrainTiles({
61
- surface,
62
- sampleHeight: height,
63
- tileSize: TILE,
64
- tileResolution: TILE / spacing + 1,
65
- // One level: 81 tiles of 33² vertices are ~166 k triangles, and a single level meets its
66
- // neighbour vertex for vertex (mixed levels left a raw 2 m step for the stitches to close).
67
- lodFactors: [1],
68
- lodDistances: [],
69
- streamRadius: RADIUS,
70
- colliderRadius: COLLIDER_RADIUS,
71
- residentTileBudget: (2 * RADIUS + 1) ** 2,
72
- residentByteBudget: Number.MAX_SAFE_INTEGER,
73
- receiveShadow: true,
74
- extent: { minX: -reach, maxX: reach, minZ: -reach, maxZ: reach },
75
- // The square draws and collides its own ground.
76
- hole: { minX: -half, maxX: half, minZ: -half, maxZ: half },
77
- createCollider: ({ field, key, object }: IWorldTileColliderInput) =>
78
- new RigidBody3D({
79
- object,
80
- physics: ctx.physics,
81
- type: "fixed",
82
- entity: `terrain.${key}`,
83
- // 4: what the player walks on. 8: the ground alone, for ground queries.
84
- collisionLayer: 4 | 8,
85
- shape: CollisionShape3D.heightfield(field.rows, field.columns, field.toColliderHeights(), {
86
- x: TILE,
87
- y: 1,
88
- z: TILE,
89
- }),
90
- }),
91
- });
92
- ctx.add(tiles);
93
- // `?tnTerrainValidate=1`: the tile-to-collar seam, read along the split square's edge each time it
94
- // moves; tile-to-tile seams are core's `maxSeamGap`.
95
- const collarSeam = { fold: 0, gap: 0, key: "" };
96
- ctx.beforeRender(() => {
97
- tiles.follow(follow.position, new AdmissionBudget(ADMISSION_MS, () => performance.now()));
98
- split.centre.value.set(
99
- Math.floor((follow.position.x + TILE / 2) / TILE) * TILE,
100
- Math.floor((follow.position.z + TILE / 2) / TILE) * TILE,
101
- );
102
- split.half.value = tiles.settledHalf(follow.position);
103
- const tileSeam = tiles.maxSeamGap;
104
- const { x, y } = split.centre.value;
105
- const key = `${x},${y},${split.half.value}`;
106
- if (tileSeam !== undefined && split.half.value > 0 && key !== collarSeam.key) {
107
- // Every 0.5 m, 0.7 ms per move; 0.1 m cost 4.2 ms and read the same fold on the route.
108
- const morphed = createMorphedHeight(collar, height, x, y, split.half.value, TILE);
109
- const seam = collarSeamGap(collar, morphed, x, y, split.half.value, spacing, 0.5);
110
- collarSeam.gap = Math.max(collarSeam.gap, seam.gap);
111
- collarSeam.fold = Math.max(collarSeam.fold, seam.fold);
112
- collarSeam.key = key;
113
- }
114
- report({
115
- streamTiles: tiles.residentTileCount,
116
- streamCoveredHalf: split.half.value,
117
- streamSeamGap: tileSeam ?? -1,
118
- // The tile-to-collar step at the tile vertices, as core measures a tile-to-tile seam, and the
119
- // step between them where a collar fold crosses a tile's edge; -1 when not measured.
120
- streamCollarGap: tileSeam === undefined ? -1 : collarSeam.gap,
121
- streamCollarFold: tileSeam === undefined ? -1 : collarSeam.fold,
122
- });
123
- });
124
- // The tiles around the spawn draw unculled behind the curtain until the whole block has drawn
125
- // twice, so their pipelines are built before the reveal (the spawn view sees few of them). The
126
- // stream runs once per world draw, because the fixed step does not run while the curtain is up.
127
- const full = (RADIUS + 0.5) * TILE;
128
- const ready = warmUnculled(ctx, tiles, { when: () => split.half.value === full });
129
- return {
130
- ready,
131
- tiles,
132
- dispose: () => {
133
- split.half.value = 0;
134
- tiles.removeFromParent();
135
- tiles.dispose();
136
- surface.dispose();
137
- },
138
- };
139
- }