@threenative/terrain 0.1.7 → 0.1.9

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 (129) hide show
  1. package/AGENT_GUIDE.md +19 -4
  2. package/dist/editor/index.d.ts +218 -5
  3. package/dist/editor/index.js +4093 -1399
  4. package/dist/editor/server.d.ts +2 -2
  5. package/dist/editor/server.js +752 -124
  6. package/dist/editor/worker.d.ts +33 -1
  7. package/dist/editor/worker.js +642 -114
  8. package/dist/export.d.ts +11 -9
  9. package/dist/export.js +22 -34
  10. package/dist/index.d.ts +866 -73
  11. package/dist/index.js +3003 -523
  12. package/dist/kit.d.ts +57 -0
  13. package/dist/kit.js +2718 -0
  14. package/dist/mcp/cook-child.d.ts +2 -0
  15. package/dist/mcp/cook-child.js +5346 -0
  16. package/dist/mcp/server.d.ts +7 -0
  17. package/dist/mcp/server.js +3970 -0
  18. package/dist/{server-ByM2hmYJ.d.ts → server-B5RdvEAC.d.ts} +3 -2
  19. package/dist/starter.d.ts +143 -0
  20. package/dist/starter.js +1031 -0
  21. package/dist/{terrain-gPnkCU6S.d.ts → terrain-CAEaW0mQ.d.ts} +3 -2
  22. package/dist/three.d.ts +1 -1
  23. package/dist/{types-Ant8-Axc.d.ts → types-BpH00qsx.d.ts} +20 -4
  24. package/dist/world-package-B8QgHjAQ.d.ts +53 -0
  25. package/package.json +28 -6
  26. package/starter/alpine/README.md +77 -1
  27. package/starter/alpine/bake.mjs +4 -116
  28. package/starter/alpine/biome.data.json +134 -0
  29. package/starter/alpine/heightmap.r16 +0 -0
  30. package/starter/alpine/recipe.json +3 -66051
  31. package/starter/alpine/world.ts +45 -293
  32. package/starter/coastal/README.md +82 -3
  33. package/starter/coastal/assets.json +2 -1
  34. package/starter/coastal/bake.mjs +4 -116
  35. package/starter/coastal/biome.data.json +156 -0
  36. package/starter/coastal/heightmap.r16 +0 -0
  37. package/starter/coastal/recipe.json +3 -66051
  38. package/starter/coastal/sea.ts +51 -66
  39. package/starter/coastal/world.ts +53 -318
  40. package/starter/desert/README.md +77 -1
  41. package/starter/desert/bake.mjs +4 -116
  42. package/starter/desert/biome.data.json +124 -0
  43. package/starter/desert/heightmap.r16 +0 -0
  44. package/starter/desert/recipe.json +3 -66051
  45. package/starter/desert/world.ts +45 -293
  46. package/starter/forest/README.md +85 -5
  47. package/starter/forest/assets.json +34 -1
  48. package/starter/forest/bake.mjs +6 -116
  49. package/starter/forest/biome.data.json +173 -0
  50. package/starter/forest/heightmap.r16 +0 -0
  51. package/starter/forest/recipe.json +192 -4428
  52. package/starter/forest/sky.ts +11 -0
  53. package/starter/forest/water.ts +39 -48
  54. package/starter/forest/world.ts +92 -323
  55. package/starter/tundra/README.md +77 -1
  56. package/starter/tundra/bake.mjs +4 -116
  57. package/starter/tundra/biome.data.json +141 -0
  58. package/starter/tundra/heightmap.r16 +0 -0
  59. package/starter/tundra/recipe.json +18 -66066
  60. package/starter/tundra/water.ts +9 -28
  61. package/starter/tundra/world.ts +65 -319
  62. package/starter-assets.json +6 -0
  63. package/{starter-assets/credits.json → starter-credits.json} +12 -105
  64. package/starter-assets/bark_brown_02/bark_brown_02_diff_1k.jpg +0 -0
  65. package/starter-assets/bark_brown_02/bark_brown_02_nor_gl_1k.jpg +0 -0
  66. package/starter-assets/bark_brown_02/bark_brown_02_rough_1k.jpg +0 -0
  67. package/starter-assets/boulder_01/boulder-mid.glb +0 -0
  68. package/starter-assets/boulder_01/boulder-near.glb +0 -0
  69. package/starter-assets/cliff_side/cliff_side_ao_1k.jpg +0 -0
  70. package/starter-assets/cliff_side/cliff_side_diff_1k.jpg +0 -0
  71. package/starter-assets/cliff_side/cliff_side_nor_gl_1k.jpg +0 -0
  72. package/starter-assets/cliff_side/cliff_side_rough_1k.jpg +0 -0
  73. package/starter-assets/fern_02/fern_02_alpha_512.png +0 -0
  74. package/starter-assets/fern_02/fern_02_diff_512.jpg +0 -0
  75. package/starter-assets/fern_02/fern_02_nor_gl_512.jpg +0 -0
  76. package/starter-assets/fir_tree_01/fir-b-lod1.glb +0 -0
  77. package/starter-assets/fir_tree_01/fir-b-lod2.glb +0 -0
  78. package/starter-assets/fir_tree_01/fir-c-lod1.glb +0 -0
  79. package/starter-assets/fir_tree_01/fir-c-lod2.glb +0 -0
  80. package/starter-assets/fir_tree_01/fir_tree_01_twig_arm_1k.jpg +0 -0
  81. package/starter-assets/fir_tree_01/fir_tree_01_twig_diff_1k.jpg +0 -0
  82. package/starter-assets/fir_tree_01/fir_tree_01_twig_nor_gl_1k.jpg +0 -0
  83. package/starter-assets/forest_ground_04/forest_ground_04_ao_1k.jpg +0 -0
  84. package/starter-assets/forest_ground_04/forest_ground_04_diff_1k.jpg +0 -0
  85. package/starter-assets/forest_ground_04/forest_ground_04_nor_gl_1k.jpg +0 -0
  86. package/starter-assets/forest_ground_04/forest_ground_04_rough_1k.jpg +0 -0
  87. package/starter-assets/forest_leaves_02/forest_leaves_02_arm_512.jpg +0 -0
  88. package/starter-assets/forest_leaves_02/forest_leaves_02_diff_512.jpg +0 -0
  89. package/starter-assets/forest_leaves_02/forest_leaves_02_nor_gl_512.jpg +0 -0
  90. package/starter-assets/grass_medium_02/grass_medium_02_alpha_512.png +0 -0
  91. package/starter-assets/grass_medium_02/grass_medium_02_diff_512.jpg +0 -0
  92. package/starter-assets/grass_medium_02/grass_medium_02_nor_gl_512.jpg +0 -0
  93. package/starter-assets/hdri/kloofendal_48d_partly_cloudy_1k.hdr +0 -0
  94. package/starter-assets/leafy_grass/leafy_grass_ao_1k.jpg +0 -0
  95. package/starter-assets/leafy_grass/leafy_grass_diff_1k.jpg +0 -0
  96. package/starter-assets/leafy_grass/leafy_grass_nor_gl_1k.jpg +0 -0
  97. package/starter-assets/leafy_grass/leafy_grass_rough_1k.jpg +0 -0
  98. package/starter-assets/lichen_rock/lichen_rock_arm_512.jpg +0 -0
  99. package/starter-assets/lichen_rock/lichen_rock_diff_512.jpg +0 -0
  100. package/starter-assets/lichen_rock/lichen_rock_nor_gl_512.jpg +0 -0
  101. package/starter-assets/mossy_rock/mossy_rock_ao_1k.jpg +0 -0
  102. package/starter-assets/mossy_rock/mossy_rock_diff_1k.jpg +0 -0
  103. package/starter-assets/mossy_rock/mossy_rock_nor_gl_1k.jpg +0 -0
  104. package/starter-assets/mossy_rock/mossy_rock_rough_1k.jpg +0 -0
  105. package/starter-assets/needle-atlas.png +0 -0
  106. package/starter-assets/needle-surface.png +0 -0
  107. package/starter-assets/river_small_rocks/river_small_rocks_arm_512.jpg +0 -0
  108. package/starter-assets/river_small_rocks/river_small_rocks_diff_512.jpg +0 -0
  109. package/starter-assets/river_small_rocks/river_small_rocks_nor_gl_512.jpg +0 -0
  110. package/starter-assets/rock_boulder_dry/rock_boulder_dry_arm_512.jpg +0 -0
  111. package/starter-assets/rock_boulder_dry/rock_boulder_dry_diff_512.jpg +0 -0
  112. package/starter-assets/rock_boulder_dry/rock_boulder_dry_nor_gl_512.jpg +0 -0
  113. package/starter-assets/rocks/boulder-mid.glb +0 -0
  114. package/starter-assets/rocks/boulder-near.glb +0 -0
  115. package/starter-assets/rocks/boulder-prep.json +0 -37
  116. package/starter-assets/rocks/rock01-mid.glb +0 -0
  117. package/starter-assets/rocks/rock01-near.glb +0 -0
  118. package/starter-assets/rocks/rock01-prep.json +0 -37
  119. package/starter-assets/rocks/rock04-mid.glb +0 -0
  120. package/starter-assets/rocks/rock04-near.glb +0 -0
  121. package/starter-assets/rocks/rock04-prep.json +0 -37
  122. package/starter-assets/sand_01/sand_01_ao_1k.jpg +0 -0
  123. package/starter-assets/sand_01/sand_01_diff_1k.jpg +0 -0
  124. package/starter-assets/sand_01/sand_01_nor_gl_1k.jpg +0 -0
  125. package/starter-assets/sand_01/sand_01_rough_1k.jpg +0 -0
  126. package/starter-assets/snow_02/snow_02_ao_1k.jpg +0 -0
  127. package/starter-assets/snow_02/snow_02_diff_1k.jpg +0 -0
  128. package/starter-assets/snow_02/snow_02_nor_gl_1k.jpg +0 -0
  129. package/starter-assets/snow_02/snow_02_rough_1k.jpg +0 -0
@@ -0,0 +1,3970 @@
1
+ #!/usr/bin/env node
2
+ import { createHash } from 'crypto';
3
+ import { realpathSync } from 'fs';
4
+ import { readFile, mkdir, writeFile, rm, lstat, realpath, readdir, stat, cp, rename } from 'fs/promises';
5
+ import { resolve, relative, join, sep, isAbsolute, basename, dirname } from 'path';
6
+ import { createInterface } from 'readline';
7
+ import { fileURLToPath } from 'url';
8
+ import { spawn } from 'child_process';
9
+
10
+ function childExecArgv(execArgv) {
11
+ const out = [];
12
+ for (let i = 0; i < execArgv.length; i += 1) {
13
+ const flag2 = execArgv[i];
14
+ if (!/^--(inspect(-brk|-wait|-port|-publish-uid)?|debug-port|(cpu|heap)-prof(-[a-z]+)?)(=|$)/.test(
15
+ flag2
16
+ )) {
17
+ out.push(flag2);
18
+ continue;
19
+ }
20
+ if (!flag2.includes("=") && /-(port|dir|name|interval|uid)$/.test(flag2)) i += 1;
21
+ }
22
+ return out;
23
+ }
24
+ var IsolatedKillError = class extends Error {
25
+ };
26
+ function runIsolated({
27
+ command,
28
+ args,
29
+ timeoutMs,
30
+ signal
31
+ }) {
32
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
33
+ return Promise.reject(new RangeError("runIsolated: timeoutMs must be a positive number."));
34
+ }
35
+ if (signal?.aborted) {
36
+ return Promise.reject(
37
+ new IsolatedKillError("runIsolated: child was cancelled before it started.")
38
+ );
39
+ }
40
+ return new Promise((resolve3, reject) => {
41
+ const child = spawn(command, [...args], {
42
+ detached: process.platform !== "win32",
43
+ stdio: ["ignore", "pipe", "pipe"]
44
+ });
45
+ let stdout = "";
46
+ let stderr = "";
47
+ let killed;
48
+ let settled = false;
49
+ const finish = (error, result) => {
50
+ if (settled) return;
51
+ settled = true;
52
+ clearTimeout(timer);
53
+ signal?.removeEventListener("abort", onAbort);
54
+ if (error !== void 0) reject(error);
55
+ else resolve3(result);
56
+ };
57
+ const stop = (reason) => {
58
+ killed ??= new IsolatedKillError(reason);
59
+ try {
60
+ if (child.pid !== void 0 && process.platform !== "win32")
61
+ process.kill(-child.pid, "SIGKILL");
62
+ else child.kill("SIGKILL");
63
+ } catch {
64
+ }
65
+ };
66
+ const timer = setTimeout(
67
+ () => stop(`runIsolated: child timed out after ${timeoutMs} ms and was killed.`),
68
+ timeoutMs
69
+ );
70
+ const onAbort = () => stop("runIsolated: child was cancelled and was killed.");
71
+ signal?.addEventListener("abort", onAbort, { once: true });
72
+ child.stdout.setEncoding("utf8");
73
+ child.stderr.setEncoding("utf8");
74
+ child.stdout.on("data", (chunk) => {
75
+ stdout += chunk;
76
+ });
77
+ child.stderr.on("data", (chunk) => {
78
+ stderr += chunk;
79
+ });
80
+ child.on("error", (error) => finish(error));
81
+ child.on("close", (code) => {
82
+ if (killed !== void 0) finish(killed);
83
+ else if (code === 0) finish(void 0, { stdout, stderr });
84
+ else finish(new Error(`runIsolated: child exited with code ${code}: ${stderr.trim()}`));
85
+ });
86
+ });
87
+ }
88
+
89
+ // src/core/kits.ts
90
+ var TERRAIN_KITS = ["forest", "coastal", "alpine", "desert", "tundra"];
91
+
92
+ // src/core/biome-words.ts
93
+ var BIOME_WORDS = {
94
+ alpine: [
95
+ "alpine",
96
+ "mountain",
97
+ "mountains",
98
+ "snowy",
99
+ "peaks",
100
+ "alps",
101
+ "glacier",
102
+ "glaciers",
103
+ "snow"
104
+ ],
105
+ coastal: [
106
+ "coastal",
107
+ "beach",
108
+ "coast",
109
+ "sea",
110
+ "ocean",
111
+ "tropical",
112
+ "shore",
113
+ "lagoon",
114
+ "fjord",
115
+ "fjords"
116
+ ],
117
+ desert: ["desert", "dune", "dunes", "sand", "canyon", "canyons", "arid", "badlands", "mesa"],
118
+ forest: [
119
+ "forest",
120
+ "pine",
121
+ "pines",
122
+ "woods",
123
+ "woodland",
124
+ "spruce",
125
+ "fir",
126
+ "trees",
127
+ "jungle",
128
+ "rainforest",
129
+ "grove"
130
+ ],
131
+ tundra: ["tundra", "arctic", "ice", "frozen", "permafrost", "glacial"]
132
+ };
133
+ var BIOME_WORD_ROWS = TERRAIN_KITS.map((kit) => [kit, BIOME_WORDS[kit]]);
134
+ function biomeWordList() {
135
+ return BIOME_WORD_ROWS.map(([kit, words]) => `${kit} (${words.slice(1).join(", ")})`).join("; ");
136
+ }
137
+
138
+ // src/core/math.ts
139
+ var clamp = (x, a = 0, b = 1) => Math.max(a, Math.min(b, x));
140
+ var lerp = (a, b, t) => a + (b - a) * t;
141
+ var smoothstep = (a, b, x) => {
142
+ if (a === b) return x >= b ? 1 : 0;
143
+ const t = clamp((x - a) / (b - a));
144
+ return t * t * (3 - 2 * t);
145
+ };
146
+ var hashString = (text2) => {
147
+ let h = 2166136261;
148
+ for (const c of text2) h = Math.imul(h ^ c.charCodeAt(0), 16777619);
149
+ return h >>> 0;
150
+ };
151
+ function random(seed) {
152
+ let a = seed >>> 0;
153
+ return () => {
154
+ a |= 0;
155
+ a = a + 1831565813 | 0;
156
+ let t = Math.imul(a ^ a >>> 15, 1 | a);
157
+ t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t;
158
+ return ((t ^ t >>> 14) >>> 0) / 4294967296;
159
+ };
160
+ }
161
+ var hash2 = (x, z, seed) => {
162
+ let n = Math.imul(x | 0, 374761393) ^ Math.imul(z | 0, 668265263) ^ seed;
163
+ n = Math.imul(n ^ n >>> 13, 1274126177);
164
+ return (n ^ n >>> 16) >>> 0;
165
+ };
166
+ var diagonalGradient = 0.7071;
167
+ var grad = (h, x, z) => {
168
+ switch (h & 7) {
169
+ case 0:
170
+ return x;
171
+ case 1:
172
+ return -x;
173
+ case 2:
174
+ return z;
175
+ case 3:
176
+ return -z;
177
+ case 4:
178
+ return (x + z) * diagonalGradient;
179
+ case 5:
180
+ return (x - z) * diagonalGradient;
181
+ case 6:
182
+ return (-x + z) * diagonalGradient;
183
+ default:
184
+ return (-x - z) * diagonalGradient;
185
+ }
186
+ };
187
+ function noise2(x, z, seed = 1) {
188
+ const ix = Math.floor(x);
189
+ const iz = Math.floor(z);
190
+ const fx = x - ix;
191
+ const fz = z - iz;
192
+ const u = fx * fx * fx * (fx * (fx * 6 - 15) + 10);
193
+ const v = fz * fz * fz * (fz * (fz * 6 - 15) + 10);
194
+ return lerp(
195
+ lerp(grad(hash2(ix, iz, seed), fx, fz), grad(hash2(ix + 1, iz, seed), fx - 1, fz), u),
196
+ lerp(
197
+ grad(hash2(ix, iz + 1, seed), fx, fz - 1),
198
+ grad(hash2(ix + 1, iz + 1, seed), fx - 1, fz - 1),
199
+ u
200
+ ),
201
+ v
202
+ ) * 1.65;
203
+ }
204
+ function fbm(inputX, inputZ, { seed = 1, octaves = 5, persistence = 0.5, lacunarity = 2, mode = "fbm" } = {}) {
205
+ let x = inputX;
206
+ let z = inputZ;
207
+ let value = 0;
208
+ let amplitude = 1;
209
+ let total = 0;
210
+ for (let i = 0; i < octaves; i += 1) {
211
+ let n = noise2(x + 13.17, z - 8.71, seed + i * 71);
212
+ if (mode === "ridged") n = (1 - Math.abs(n)) ** 2 * 2 - 1;
213
+ if (mode === "billow") n = Math.abs(n) * 2 - 1;
214
+ value += n * amplitude;
215
+ total += amplitude;
216
+ amplitude *= persistence;
217
+ x *= lacunarity;
218
+ z *= lacunarity;
219
+ }
220
+ return total ? value / total : 0;
221
+ }
222
+ var world = (grid, x) => x / (grid.resolution - 1) * grid.size - grid.size / 2;
223
+ function sampleGrid(a, width, height, u, v) {
224
+ const gx = clamp(u, 0, 1) * (width - 1);
225
+ const gz = clamp(v, 0, 1) * (height - 1);
226
+ const x = Math.min(width - 2, Math.floor(gx));
227
+ const z = Math.min(height - 2, Math.floor(gz));
228
+ const tx = gx - x;
229
+ const tz = gz - z;
230
+ return lerp(
231
+ lerp(a[z * width + x], a[z * width + x + 1], tx),
232
+ lerp(a[(z + 1) * width + x], a[(z + 1) * width + x + 1], tx),
233
+ tz
234
+ );
235
+ }
236
+ var sampleHeight = (grid, x, z) => sampleGrid(
237
+ grid.height,
238
+ grid.resolution,
239
+ grid.resolution,
240
+ x / grid.size + 0.5,
241
+ z / grid.size + 0.5
242
+ );
243
+ function gradientAt(grid, x, z) {
244
+ const d = grid.size / (grid.resolution - 1);
245
+ return [
246
+ (sampleHeight(grid, x + d, z) - sampleHeight(grid, x - d, z)) / (Math.min(grid.size / 2, x + d) - Math.max(-grid.size / 2, x - d) || d),
247
+ (sampleHeight(grid, x, z + d) - sampleHeight(grid, x, z - d)) / (Math.min(grid.size / 2, z + d) - Math.max(-grid.size / 2, z - d) || d)
248
+ ];
249
+ }
250
+ function slopeAtIndex(grid, i) {
251
+ const n = grid.resolution;
252
+ const x = i % n;
253
+ const z = Math.floor(i / n);
254
+ const dx = x > 0 && x < n - 1 ? 2 : 1;
255
+ const dz = z > 0 && z < n - 1 ? 2 : 1;
256
+ const cell = grid.size / (n - 1);
257
+ const gx = (grid.height[z * n + Math.min(x + 1, n - 1)] - grid.height[z * n + Math.max(x - 1, 0)]) / (dx * cell);
258
+ const gz = (grid.height[Math.min(z + 1, n - 1) * n + x] - grid.height[Math.max(z - 1, 0) * n + x]) / (dz * cell);
259
+ return Math.atan(Math.hypot(gx, gz)) * (180 / Math.PI);
260
+ }
261
+ function falloff(distance, radius, softness = 0.6) {
262
+ const d = distance / radius;
263
+ return d >= 1 ? 0 : 1 - smoothstep(1 - clamp(softness, 1e-5, 1), 1, d);
264
+ }
265
+ function splinePoints(points, step = 3, smooth = true) {
266
+ const out = [];
267
+ for (let k = 0; k < points.length - 1; k += 1) {
268
+ const a = points[Math.max(0, k - 1)];
269
+ const b = points[k];
270
+ const c = points[k + 1];
271
+ const d = points[Math.min(points.length - 1, k + 2)];
272
+ const count2 = Math.max(
273
+ 1,
274
+ Math.min(512, Math.ceil(Math.hypot(c[0] - b[0], c[2] - b[2]) / step))
275
+ );
276
+ for (let j = 0; j < count2; j += 1) {
277
+ const t = j / count2;
278
+ const t2 = t * t;
279
+ const t3 = t2 * t;
280
+ const cat = (dim) => 0.5 * (2 * b[dim] + (-a[dim] + c[dim]) * t + (2 * a[dim] - 5 * b[dim] + 4 * c[dim] - d[dim]) * t2 + (-a[dim] + 3 * b[dim] - 3 * c[dim] + d[dim]) * t3);
281
+ out.push([
282
+ smooth ? cat(0) : lerp(b[0], c[0], t),
283
+ lerp(b[1], c[1], t),
284
+ smooth ? cat(2) : lerp(b[2], c[2], t)
285
+ ]);
286
+ }
287
+ }
288
+ const last = points[points.length - 1];
289
+ out.push([last[0], last[1], last[2]]);
290
+ return out;
291
+ }
292
+
293
+ // src/core/erosion.ts
294
+ function thermal(height, n, size, { iterations = 20, talus = 32, rate = 0.22 } = {}, observations) {
295
+ if (!Number.isInteger(n) || n < 2)
296
+ throw RangeError("Thermal erosion requires grid resolution n >= 2");
297
+ if (!Number.isInteger(iterations) || iterations < 0 || iterations > 200)
298
+ throw RangeError("Thermal erosion iterations must be between 0 and 200");
299
+ const h = height.slice();
300
+ const delta = new Float64Array(h.length);
301
+ const limit = Math.tan(talus * Math.PI / 180) * (size / (n - 1));
302
+ for (let k = 0; k < iterations; k += 1) {
303
+ delta.fill(0);
304
+ for (let z = 0; z < n; z += 1) {
305
+ for (let x = 0; x < n; x += 1) {
306
+ const i = z * n + x;
307
+ const here = h[i];
308
+ let best = -1;
309
+ let diff = limit;
310
+ if (x > 0 && here - h[i - 1] > diff) {
311
+ diff = here - h[i - 1];
312
+ best = i - 1;
313
+ }
314
+ if (x < n - 1 && here - h[i + 1] > diff) {
315
+ diff = here - h[i + 1];
316
+ best = i + 1;
317
+ }
318
+ if (z > 0 && here - h[i - n] > diff) {
319
+ diff = here - h[i - n];
320
+ best = i - n;
321
+ }
322
+ if (z < n - 1 && here - h[i + n] > diff) {
323
+ diff = here - h[i + n];
324
+ best = i + n;
325
+ }
326
+ if (best >= 0) {
327
+ const transfer = (diff - limit) * rate;
328
+ delta[i] = delta[i] - transfer;
329
+ delta[best] = delta[best] + transfer;
330
+ if (observations)
331
+ observations.talus[best] = observations.talus[best] + transfer;
332
+ }
333
+ }
334
+ }
335
+ for (let i = 0; i < h.length; i += 1) h[i] = h[i] + delta[i];
336
+ }
337
+ return h;
338
+ }
339
+ var brushes = /* @__PURE__ */ new Map();
340
+ function brush(radius) {
341
+ let cells = brushes.get(radius);
342
+ if (!cells) {
343
+ const dx = [];
344
+ const dz = [];
345
+ const raw = [];
346
+ let total = 0;
347
+ for (let z = -radius; z <= radius; z += 1) {
348
+ for (let x = -radius; x <= radius; x += 1) {
349
+ const d = Math.hypot(x, z);
350
+ if (d > radius) continue;
351
+ const weight2 = 1 - d / (radius + 1);
352
+ dx.push(x);
353
+ dz.push(z);
354
+ raw.push(weight2);
355
+ total += weight2;
356
+ }
357
+ }
358
+ const weight = Float64Array.from(raw, (w) => w / total);
359
+ let full = 0;
360
+ for (let k = 0; k < weight.length; k += 1) full += weight[k];
361
+ cells = { dx: Int32Array.from(dx), dz: Int32Array.from(dz), full, radius, weight };
362
+ brushes.set(radius, cells);
363
+ }
364
+ return cells;
365
+ }
366
+ var MAX_AUTOMATIC_DROPLETS = 1025 * 1025;
367
+ var MAX_EXPLICIT_DROPLETS = 2e5;
368
+ function hydraulic(height, n, size, options = {}, observations) {
369
+ const {
370
+ droplets: requestedDroplets,
371
+ // A droplet has to be able to cross the world, so its step budget scales with the grid: a
372
+ // fixed 40 barely leaves a 257 world while a 65 world would walk off it in a few steps.
373
+ maxSteps = Math.round(Math.min(64, Math.max(24, n / 4))),
374
+ inertia = 0.2,
375
+ capacity = 4,
376
+ // Each step takes a small bite of the sediment the droplet can carry. A big bite carves
377
+ // fewer, deeper dimples that stand proud of their neighbours as spikes; many shallow bites
378
+ // over the same lines incise the same drainage with a smooth surface.
379
+ erosion = 0.03,
380
+ deposition = 0.3,
381
+ evaporation = 0.025,
382
+ seed = 1,
383
+ brushRadius = 3
384
+ } = options;
385
+ if (!Number.isInteger(n) || n < 2)
386
+ throw RangeError("Hydraulic erosion requires grid resolution n >= 2");
387
+ const droplets = requestedDroplets === void 0 ? Math.min(n * n, MAX_AUTOMATIC_DROPLETS) : requestedDroplets;
388
+ if (!Number.isSafeInteger(droplets) || droplets < 0)
389
+ throw RangeError("Hydraulic erosion droplets must be a non-negative integer");
390
+ if (requestedDroplets !== void 0 && droplets > MAX_EXPLICIT_DROPLETS)
391
+ throw RangeError(`Hydraulic erosion droplets must not exceed ${String(MAX_EXPLICIT_DROPLETS)}`);
392
+ if (!Number.isInteger(maxSteps) || maxSteps < 1 || maxSteps > 128)
393
+ throw RangeError("Hydraulic erosion maxSteps must be between 1 and 128");
394
+ const h = Float64Array.from(height);
395
+ const rnd = random(seed);
396
+ const cell = size / (n - 1);
397
+ const minSlope = 5e-3 * cell;
398
+ const oneMinusInertia = 1 - inertia;
399
+ const oneMinusEvaporation = 1 - evaporation;
400
+ const brushCells = brush(brushRadius);
401
+ const brushDx = brushCells.dx;
402
+ const brushDz = brushCells.dz;
403
+ const brushWeight = brushCells.weight;
404
+ const brushCount = brushDx.length;
405
+ const brushFull = brushCells.full;
406
+ const brushEdge = brushCells.radius;
407
+ const brushOffset = new Int32Array(brushCount);
408
+ for (let k = 0; k < brushCount; k += 1)
409
+ brushOffset[k] = brushDz[k] * n + brushDx[k];
410
+ const obsFlow = observations?.flow;
411
+ const obsSediment = observations?.sediment;
412
+ const obsDeposition = observations?.deposition;
413
+ const spread = (x, z, amount, floor = Number.NEGATIVE_INFINITY) => {
414
+ if (amount === 0) return 0;
415
+ const interior = x >= brushEdge && x < n - brushEdge && z >= brushEdge && z < n - brushEdge;
416
+ if (interior) {
417
+ const total2 = brushFull;
418
+ if (total2 <= 0) return 0;
419
+ const base = z * n + x;
420
+ if (amount < 0) {
421
+ let moved = 0;
422
+ for (let k = 0; k < brushCount; k += 1) {
423
+ const i = base + brushOffset[k];
424
+ const share2 = amount * brushWeight[k] / total2;
425
+ const avail = h[i] - floor;
426
+ const change = avail <= 0 ? -0 : -share2 < avail ? share2 : -avail;
427
+ h[i] = h[i] + change;
428
+ moved += change;
429
+ }
430
+ return moved;
431
+ }
432
+ if (obsDeposition !== void 0) {
433
+ for (let k = 0; k < brushCount; k += 1) {
434
+ const i = base + brushOffset[k];
435
+ const share2 = amount * brushWeight[k] / total2;
436
+ h[i] = h[i] + share2;
437
+ obsDeposition[i] = obsDeposition[i] + share2;
438
+ }
439
+ } else {
440
+ for (let k = 0; k < brushCount; k += 1) {
441
+ const i = base + brushOffset[k];
442
+ const share2 = amount * brushWeight[k] / total2;
443
+ h[i] = h[i] + share2;
444
+ }
445
+ }
446
+ return amount;
447
+ }
448
+ let total = 0;
449
+ for (let k = 0; k < brushCount; k += 1) {
450
+ const ix = x + brushDx[k];
451
+ const iz = z + brushDz[k];
452
+ if (ix >= 0 && ix < n && iz >= 0 && iz < n) total += brushWeight[k];
453
+ }
454
+ if (total <= 0) return 0;
455
+ if (amount < 0) {
456
+ let moved = 0;
457
+ for (let k = 0; k < brushCount; k += 1) {
458
+ const ix = x + brushDx[k];
459
+ const iz = z + brushDz[k];
460
+ if (ix < 0 || ix >= n || iz < 0 || iz >= n) continue;
461
+ const i = iz * n + ix;
462
+ const share2 = amount * brushWeight[k] / total;
463
+ const avail = h[i] - floor;
464
+ const change = avail <= 0 ? -0 : -share2 < avail ? share2 : -avail;
465
+ h[i] = h[i] + change;
466
+ moved += change;
467
+ }
468
+ return moved;
469
+ }
470
+ if (obsDeposition !== void 0) {
471
+ for (let k = 0; k < brushCount; k += 1) {
472
+ const ix = x + brushDx[k];
473
+ const iz = z + brushDz[k];
474
+ if (ix < 0 || ix >= n || iz < 0 || iz >= n) continue;
475
+ const i = iz * n + ix;
476
+ const share2 = amount * brushWeight[k] / total;
477
+ h[i] = h[i] + share2;
478
+ obsDeposition[i] = obsDeposition[i] + share2;
479
+ }
480
+ } else {
481
+ for (let k = 0; k < brushCount; k += 1) {
482
+ const ix = x + brushDx[k];
483
+ const iz = z + brushDz[k];
484
+ if (ix < 0 || ix >= n || iz < 0 || iz >= n) continue;
485
+ const i = iz * n + ix;
486
+ const share2 = amount * brushWeight[k] / total;
487
+ h[i] = h[i] + share2;
488
+ }
489
+ }
490
+ return amount;
491
+ };
492
+ const probeOld = { value: 0, dx: 0, dz: 0, ix: 0, iz: 0 };
493
+ const probeNext = { value: 0, dx: 0, dz: 0, ix: 0, iz: 0 };
494
+ const get = (x, z, out) => {
495
+ const ix = Math.min(n - 2, Math.floor(x));
496
+ const iz = Math.min(n - 2, Math.floor(z));
497
+ const tx = x - ix;
498
+ const tz = z - iz;
499
+ const i = iz * n + ix;
500
+ const h00 = h[i];
501
+ const h10 = h[i + 1];
502
+ const h01 = h[i + n];
503
+ const h11 = h[i + n + 1];
504
+ const g10 = h10 - h00;
505
+ const g01 = h01 - h00;
506
+ const v0 = h00 + g10 * tx;
507
+ const v1 = h01 + (h11 - h01) * tx;
508
+ out.value = v0 + (v1 - v0) * tz;
509
+ out.dx = (g10 + (h11 - h01 - g10) * tz) / cell;
510
+ out.dz = (g01 + (h11 - h10 - g01) * tx) / cell;
511
+ out.ix = ix;
512
+ out.iz = iz;
513
+ return out;
514
+ };
515
+ for (let k = 0; k < droplets; k += 1) {
516
+ let x = rnd() * (n - 1 - 1e-3);
517
+ let z = rnd() * (n - 1 - 1e-3);
518
+ let dx = 0;
519
+ let dz = 0;
520
+ let water2 = 1;
521
+ let speed = 1;
522
+ let sediment = 0;
523
+ for (let step = 0; step < maxSteps; step += 1) {
524
+ const old = get(x, z, probeOld);
525
+ if (obsFlow !== void 0 && obsSediment !== void 0) {
526
+ const tx = x - old.ix;
527
+ const tz = z - old.iz;
528
+ const i = old.iz * n + old.ix;
529
+ const w00 = (1 - tx) * (1 - tz);
530
+ const w10 = tx * (1 - tz);
531
+ const w01 = (1 - tx) * tz;
532
+ const w11 = tx * tz;
533
+ obsFlow[i] = obsFlow[i] + water2 * w00;
534
+ obsSediment[i] = obsSediment[i] + sediment * w00;
535
+ obsFlow[i + 1] = obsFlow[i + 1] + water2 * w10;
536
+ obsSediment[i + 1] = obsSediment[i + 1] + sediment * w10;
537
+ obsFlow[i + n] = obsFlow[i + n] + water2 * w01;
538
+ obsSediment[i + n] = obsSediment[i + n] + sediment * w01;
539
+ obsFlow[i + n + 1] = obsFlow[i + n + 1] + water2 * w11;
540
+ obsSediment[i + n + 1] = obsSediment[i + n + 1] + sediment * w11;
541
+ }
542
+ dx = dx * inertia - old.dx * oneMinusInertia;
543
+ dz = dz * inertia - old.dz * oneMinusInertia;
544
+ const largest = Math.max(Math.abs(dx), Math.abs(dz));
545
+ const scaledX = Math.abs(dx) / largest;
546
+ const scaledZ = Math.abs(dz) / largest;
547
+ let length = largest === 0 || largest === Number.POSITIVE_INFINITY ? largest : Math.sqrt(scaledX * scaledX + scaledZ * scaledZ) * largest;
548
+ if (length < 1e-9) {
549
+ const angle = rnd() * Math.PI * 2;
550
+ dx = Math.cos(angle);
551
+ dz = Math.sin(angle);
552
+ length = 1;
553
+ }
554
+ dx /= length;
555
+ dz /= length;
556
+ const nx = x + dx;
557
+ const nz = z + dz;
558
+ if (nx < 0 || nx >= n - 1 || nz < 0 || nz >= n - 1) {
559
+ sediment = 0;
560
+ break;
561
+ }
562
+ const next = get(nx, nz, probeNext);
563
+ const dh = next.value - old.value;
564
+ const slope = -dh;
565
+ const cap = (slope > minSlope ? slope : minSlope) * speed * water2 * capacity;
566
+ if (dh > 0 || sediment > cap) {
567
+ const amount = dh > 0 ? dh < sediment ? dh : sediment : (sediment - cap) * deposition;
568
+ spread(old.ix, old.iz, amount);
569
+ sediment -= amount;
570
+ } else {
571
+ const bite = (cap - sediment) * erosion;
572
+ const amount = bite < slope ? bite : slope;
573
+ sediment -= spread(old.ix, old.iz, -amount, next.value);
574
+ }
575
+ const sq = speed * speed - dh * 3;
576
+ speed = Math.sqrt(sq > 0.01 ? sq : 0.01);
577
+ water2 *= oneMinusEvaporation;
578
+ x = nx;
579
+ z = nz;
580
+ if (water2 < 0.02) break;
581
+ }
582
+ if (sediment > 0 && water2 < 0.02) {
583
+ const end = get(clamp(x, 0, n - 1.001), clamp(z, 0, n - 1.001), probeOld);
584
+ spread(end.ix, end.iz, sediment);
585
+ }
586
+ }
587
+ return Float32Array.from(h);
588
+ }
589
+
590
+ // src/core/fluvial.ts
591
+ var DX = Int8Array.of(-1, 0, 1, -1, 1, -1, 0, 1);
592
+ var DZ = Int8Array.of(-1, -1, -1, 0, 0, 1, 1, 1);
593
+ var DIST = Float64Array.from(DX, (dx, k) => Math.hypot(dx, DZ[k]));
594
+ var FILL_SLOPE = Math.tan(0.06 * Math.PI / 180);
595
+ var EPSILON = 1e-3;
596
+ function fillDepressions(h, n, epsilon = EPSILON) {
597
+ const total = n * n;
598
+ const keys = new Float64Array(total);
599
+ const cells = new Int32Array(total);
600
+ const closed2 = new Uint8Array(total);
601
+ let size = 0;
602
+ const push = (key, cell) => {
603
+ let k = size++;
604
+ while (k > 0) {
605
+ const parent = k - 1 >> 1;
606
+ if (keys[parent] <= key) break;
607
+ keys[k] = keys[parent];
608
+ cells[k] = cells[parent];
609
+ k = parent;
610
+ }
611
+ keys[k] = key;
612
+ cells[k] = cell;
613
+ };
614
+ const pop = () => {
615
+ const top = cells[0];
616
+ size -= 1;
617
+ const key = keys[size];
618
+ const cell = cells[size];
619
+ let k = 0;
620
+ for (; ; ) {
621
+ let child = 2 * k + 1;
622
+ if (child >= size) break;
623
+ if (child + 1 < size && keys[child + 1] < keys[child]) child += 1;
624
+ if (keys[child] >= key) break;
625
+ keys[k] = keys[child];
626
+ cells[k] = cells[child];
627
+ k = child;
628
+ }
629
+ keys[k] = key;
630
+ cells[k] = cell;
631
+ return top;
632
+ };
633
+ for (let z = 0; z < n; z += 1) {
634
+ for (let x = 0; x < n; x += 1) {
635
+ if (x > 0 && x < n - 1 && z > 0 && z < n - 1) continue;
636
+ const i = z * n + x;
637
+ closed2[i] = 1;
638
+ push(h[i], i);
639
+ }
640
+ }
641
+ while (size > 0) {
642
+ const c = pop();
643
+ const cx = c % n;
644
+ const cz = (c - cx) / n;
645
+ const level = h[c];
646
+ for (let k = 0; k < 8; k += 1) {
647
+ const x = cx + DX[k];
648
+ const z = cz + DZ[k];
649
+ if (x < 0 || z < 0 || x >= n || z >= n) continue;
650
+ const j = z * n + x;
651
+ if (closed2[j]) continue;
652
+ closed2[j] = 1;
653
+ if (h[j] <= level) h[j] = level + epsilon;
654
+ push(h[j], j);
655
+ }
656
+ }
657
+ }
658
+ function createFlow(n) {
659
+ const total = n * n;
660
+ return {
661
+ receiver: new Int32Array(total),
662
+ order: new Int32Array(total),
663
+ cells: new Float64Array(total)
664
+ };
665
+ }
666
+ function routeFlow(h, n, flow) {
667
+ const { receiver, order, cells } = flow;
668
+ const total = n * n;
669
+ const head = new Int32Array(total).fill(-1);
670
+ const next = new Int32Array(total);
671
+ let roots = 0;
672
+ for (let z = 0; z < n; z += 1) {
673
+ for (let x = 0; x < n; x += 1) {
674
+ const i = z * n + x;
675
+ let best = -1;
676
+ if (x > 0 && x < n - 1 && z > 0 && z < n - 1) {
677
+ const here = h[i];
678
+ let bestSlope = 0;
679
+ for (let k = 0; k < 8; k += 1) {
680
+ const j = i + DZ[k] * n + DX[k];
681
+ const slope = (here - h[j]) / DIST[k];
682
+ if (slope > bestSlope) {
683
+ bestSlope = slope;
684
+ best = j;
685
+ }
686
+ }
687
+ }
688
+ receiver[i] = best;
689
+ if (best < 0) order[roots++] = i;
690
+ else {
691
+ next[i] = head[best];
692
+ head[best] = i;
693
+ }
694
+ }
695
+ }
696
+ for (let k = 0; k < total; k += 1) {
697
+ const i = order[k];
698
+ for (let d = head[i]; d >= 0; d = next[d]) order[roots++] = d;
699
+ }
700
+ cells.fill(1);
701
+ for (let k = total - 1; k >= 0; k -= 1) {
702
+ const i = order[k];
703
+ const r = receiver[i];
704
+ if (r >= 0) cells[r] = cells[r] + cells[i];
705
+ }
706
+ }
707
+ function fluvial(height, n, size, {
708
+ iterations = 40,
709
+ uplift = 1e-3,
710
+ erodibility = 5e-6,
711
+ timeStep = 2e4,
712
+ concavity = 0.45,
713
+ talus = 35,
714
+ relief
715
+ } = {}) {
716
+ const total = n * n;
717
+ const spacing = size / (n - 1);
718
+ const h = Float64Array.from(height);
719
+ const band2 = Math.min(4, n - 1);
720
+ for (let a = 0; a < n; a += 1)
721
+ for (let d = 1; d <= band2; d += 1) {
722
+ h[a] = Math.min(h[a], h[d * n + a]);
723
+ h[(n - 1) * n + a] = Math.min(h[(n - 1) * n + a], h[(n - 1 - d) * n + a]);
724
+ h[a * n] = Math.min(h[a * n], h[a * n + d]);
725
+ h[a * n + n - 1] = Math.min(h[a * n + n - 1], h[a * n + n - 1 - d]);
726
+ }
727
+ fillDepressions(h, n, FILL_SLOPE * spacing);
728
+ let low = Number.POSITIVE_INFINITY;
729
+ let high = Number.NEGATIVE_INFINITY;
730
+ for (let i = 0; i < total; i += 1) {
731
+ low = Math.min(low, h[i]);
732
+ high = Math.max(high, h[i]);
733
+ }
734
+ const range2 = high - low || 1;
735
+ const rise = Float64Array.from(h, (v) => uplift * timeStep * (v - low) / range2);
736
+ const flow = createFlow(n);
737
+ const kdt = erodibility * timeStep;
738
+ const maxRise = Math.tan(talus * Math.PI / 180) * spacing;
739
+ const power = Float64Array.from(
740
+ { length: total + 1 },
741
+ (_, c) => (c * spacing * spacing) ** concavity
742
+ );
743
+ for (let step = 0; step < iterations; step += 1) {
744
+ routeFlow(h, n, flow);
745
+ const { order, receiver, cells } = flow;
746
+ for (let k = 0; k < total; k += 1) {
747
+ const i = order[k];
748
+ const r = receiver[i];
749
+ if (r < 0) continue;
750
+ const delta = Math.abs(r - i);
751
+ const run = delta === 1 || delta === n ? 1 : Math.SQRT2;
752
+ const factor = kdt * power[cells[i]] / (spacing * run);
753
+ const below = h[r];
754
+ const solved = (h[i] + rise[i] + factor * below) / (1 + factor);
755
+ h[i] = Math.max(Math.min(solved, below + maxRise * run), below + EPSILON);
756
+ }
757
+ }
758
+ for (let a = 0; a < n; a += 1) {
759
+ h[a] = h[n + a];
760
+ h[(n - 1) * n + a] = h[(n - 2) * n + a];
761
+ }
762
+ for (let a = 0; a < n; a += 1) {
763
+ h[a * n] = h[a * n + 1];
764
+ h[a * n + n - 1] = h[a * n + n - 2];
765
+ }
766
+ if (relief !== void 0) {
767
+ let lo = Number.POSITIVE_INFINITY;
768
+ let hi = Number.NEGATIVE_INFINITY;
769
+ for (const v of h) {
770
+ lo = Math.min(lo, v);
771
+ hi = Math.max(hi, v);
772
+ }
773
+ const gain = relief / (hi - lo || 1);
774
+ for (let i = 0; i < total; i += 1) h[i] = lo + (h[i] - lo) * gain;
775
+ }
776
+ return Float32Array.from(h);
777
+ }
778
+
779
+ // src/core/gully.ts
780
+ var STEP_SECONDS = 0.1;
781
+ var FLUX_KEEP = 0.99;
782
+ var DISSOLVE = 0.3;
783
+ var DEPOSIT = 0.02;
784
+ var EVAPORATE = 0.05;
785
+ var DEPTH_REF = 0.01;
786
+ var DEPTH_MAX = 0.3;
787
+ var MIN_TILT = 0.05;
788
+ var GRAVITY = 9.81;
789
+ var MAX_ITERATIONS = 200;
790
+ function gully(height, n, size, { iterations = 200, capacity = 0.05, rain = 5e-4 } = {}) {
791
+ if (!Number.isInteger(n) || n < 2)
792
+ throw new RangeError("Gully erosion requires grid resolution n >= 2");
793
+ if (!Number.isInteger(iterations) || iterations < 0 || iterations > MAX_ITERATIONS)
794
+ throw new RangeError(`Gully erosion iterations must be between 0 and ${MAX_ITERATIONS}`);
795
+ if (!Number.isFinite(capacity) || capacity < 0 || capacity > 1e6)
796
+ throw new RangeError("Gully erosion capacity must be between 0 and 1000000");
797
+ if (!Number.isFinite(rain) || rain < 0 || rain > 1)
798
+ throw new RangeError("Gully erosion rain must be between 0 and 1 metres per step");
799
+ const total = n * n;
800
+ let h = Float64Array.from(height);
801
+ let hTmp = new Float64Array(total);
802
+ const water2 = new Float64Array(total);
803
+ const waterBefore = new Float64Array(total);
804
+ const speed = new Float64Array(total);
805
+ const sediment = new Float64Array(total);
806
+ const sedTmp = new Float64Array(total);
807
+ const fluxL = new Float64Array(total);
808
+ const fluxR = new Float64Array(total);
809
+ const fluxT = new Float64Array(total);
810
+ const fluxB = new Float64Array(total);
811
+ const cell = size / (n - 1);
812
+ const cellArea = cell * cell;
813
+ const gain = STEP_SECONDS * GRAVITY * cell;
814
+ const evaporateKeep = Math.max(1 - EVAPORATE * STEP_SECONDS, 0);
815
+ const share2 = (flow, depth) => depth > 0 ? flow * STEP_SECONDS / (depth * cellArea) : 0;
816
+ for (let step = 0; step < iterations; step += 1) {
817
+ for (let z = 0; z < n; z += 1) {
818
+ for (let x = 0; x < n; x += 1) {
819
+ const i = z * n + x;
820
+ const depth = water2[i] + rain;
821
+ const surface = h[i] + depth;
822
+ const ground = h[i];
823
+ const left = x > 0 ? h[i - 1] + water2[i - 1] + rain : ground;
824
+ const right = x < n - 1 ? h[i + 1] + water2[i + 1] + rain : ground;
825
+ const top = z > 0 ? h[i - n] + water2[i - n] + rain : ground;
826
+ const bottom = z < n - 1 ? h[i + n] + water2[i + n] + rain : ground;
827
+ let l = fluxL[i] * FLUX_KEEP + gain * (surface - left);
828
+ let r = fluxR[i] * FLUX_KEEP + gain * (surface - right);
829
+ let t = fluxT[i] * FLUX_KEEP + gain * (surface - top);
830
+ let b = fluxB[i] * FLUX_KEEP + gain * (surface - bottom);
831
+ if (l < 0) l = 0;
832
+ if (r < 0) r = 0;
833
+ if (t < 0) t = 0;
834
+ if (b < 0) b = 0;
835
+ const sum = l + r + t + b;
836
+ if (sum > 0) {
837
+ const keep = Math.min(1, depth * cellArea / (sum * STEP_SECONDS));
838
+ l *= keep;
839
+ r *= keep;
840
+ t *= keep;
841
+ b *= keep;
842
+ }
843
+ fluxL[i] = l;
844
+ fluxR[i] = r;
845
+ fluxT[i] = t;
846
+ fluxB[i] = b;
847
+ }
848
+ }
849
+ for (let z = 0; z < n; z += 1) {
850
+ for (let x = 0; x < n; x += 1) {
851
+ const i = z * n + x;
852
+ const inL = x > 0 ? fluxR[i - 1] : 0;
853
+ const inR = x < n - 1 ? fluxL[i + 1] : 0;
854
+ const inT = z > 0 ? fluxB[i - n] : 0;
855
+ const inB = z < n - 1 ? fluxT[i + n] : 0;
856
+ const before = water2[i] + rain;
857
+ const after = Math.max(
858
+ 0,
859
+ before + STEP_SECONDS * (inL + inR + inT + inB - fluxL[i] - fluxR[i] - fluxT[i] - fluxB[i]) / cellArea
860
+ );
861
+ const depth = 0.5 * (before + after);
862
+ const acrossX = inL - fluxL[i] + fluxR[i] - inR;
863
+ const acrossZ = inT - fluxT[i] + fluxB[i] - inB;
864
+ speed[i] = depth > 1e-4 ? Math.sqrt(acrossX * acrossX + acrossZ * acrossZ) * 0.5 / (cell * depth) : 0;
865
+ water2[i] = after;
866
+ waterBefore[i] = before;
867
+ }
868
+ }
869
+ for (let z = 0; z < n; z += 1) {
870
+ for (let x = 0; x < n; x += 1) {
871
+ const i = z * n + x;
872
+ const gx = (h[z * n + Math.min(x + 1, n - 1)] - h[z * n + Math.max(x - 1, 0)]) / (2 * cell);
873
+ const gy = (h[Math.min(z + 1, n - 1) * n + x] - h[Math.max(z - 1, 0) * n + x]) / (2 * cell);
874
+ const squared = gx * gx + gy * gy;
875
+ const sine = Math.max(Math.sqrt(squared / (1 + squared)), MIN_TILT);
876
+ const depth = water2[i];
877
+ const transport = capacity * sine * speed[i] * Math.min(depth / DEPTH_REF, 1) * Math.max(1 - depth / DEPTH_MAX, 0);
878
+ let surface = h[i];
879
+ let load = sediment[i];
880
+ if (transport > load) {
881
+ const cut = DISSOLVE * (transport - load);
882
+ surface -= cut;
883
+ load += cut;
884
+ } else {
885
+ const drop = DEPOSIT * (load - transport);
886
+ surface += drop;
887
+ load -= drop;
888
+ }
889
+ hTmp[i] = surface;
890
+ sedTmp[i] = load;
891
+ }
892
+ }
893
+ const passed = h;
894
+ h = hTmp;
895
+ hTmp = passed;
896
+ for (let z = 0; z < n; z += 1) {
897
+ for (let x = 0; x < n; x += 1) {
898
+ const i = z * n + x;
899
+ let load = sedTmp[i] * (1 - share2(
900
+ fluxL[i] + fluxR[i] + fluxT[i] + fluxB[i],
901
+ waterBefore[i]
902
+ ));
903
+ if (x > 0)
904
+ load += sedTmp[i - 1] * share2(fluxR[i - 1], waterBefore[i - 1]);
905
+ if (x < n - 1)
906
+ load += sedTmp[i + 1] * share2(fluxL[i + 1], waterBefore[i + 1]);
907
+ if (z > 0)
908
+ load += sedTmp[i - n] * share2(fluxB[i - n], waterBefore[i - n]);
909
+ if (z < n - 1)
910
+ load += sedTmp[i + n] * share2(fluxT[i + n], waterBefore[i + n]);
911
+ sediment[i] = load;
912
+ water2[i] = water2[i] * evaporateKeep;
913
+ }
914
+ }
915
+ }
916
+ return Float32Array.from(h, (surface, i) => surface + sediment[i]);
917
+ }
918
+
919
+ // src/core/masks.ts
920
+ var MATERIAL_IDS = Object.freeze([
921
+ "grass",
922
+ "dirt",
923
+ "rock",
924
+ "snow",
925
+ "sand",
926
+ "mud",
927
+ "road",
928
+ "moss"
929
+ ]);
930
+ var range = (v, min, max, fade = 0) => fade > 0 ? smoothstep(min - fade, min, v) * (1 - smoothstep(max, max + fade, v)) : Number(v >= min && v <= max);
931
+ function compileMask(mask, s) {
932
+ if (!mask || mask.type === "all") return () => 1;
933
+ switch (mask.type) {
934
+ case "none":
935
+ return () => 0;
936
+ case "circle": {
937
+ const centre = mask.at;
938
+ return (i, x, z) => falloff(
939
+ Math.hypot(x - centre[0], z - centre[1]),
940
+ mask.radius,
941
+ mask.falloff ?? 0.6
942
+ );
943
+ }
944
+ case "rectangle": {
945
+ const centre = mask.at;
946
+ const rad = (mask.rotation ?? 0) * Math.PI / 180;
947
+ const c = Math.cos(rad);
948
+ const sn = Math.sin(rad);
949
+ const size = Array.isArray(mask.size) ? mask.size : [mask.size, mask.size];
950
+ return (i, x, z) => {
951
+ const dx = x - centre[0];
952
+ const dz = z - centre[1];
953
+ return falloff(
954
+ Math.max(
955
+ Math.abs(dx * c + dz * sn) / (size[0] / 2),
956
+ Math.abs(-dx * sn + dz * c) / (size[1] / 2)
957
+ ),
958
+ 1,
959
+ mask.falloff ?? 0.2
960
+ );
961
+ };
962
+ }
963
+ case "height":
964
+ return (i) => range(s.height[i], mask.min ?? -1e9, mask.max ?? 1e9, mask.fade);
965
+ case "slope":
966
+ return (i) => range(slopeAtIndex(s, i), mask.min ?? 0, mask.max ?? 90, mask.fade);
967
+ case "noise":
968
+ return (i, x, z) => smoothstep(
969
+ (mask.threshold ?? 0.5) - (mask.fade ?? 0.15),
970
+ (mask.threshold ?? 0.5) + (mask.fade ?? 0.15),
971
+ noise2(x / mask.scale, z / mask.scale, mask.seed ?? s.seed) * 0.5 + 0.5
972
+ );
973
+ case "biome": {
974
+ const field = s.biomes[mask.name];
975
+ return (i) => field?.[i] ?? 0;
976
+ }
977
+ case "material": {
978
+ const channel = MATERIAL_IDS.indexOf(mask.name);
979
+ if (channel < 0) throw Error(`Unknown material: ${String(mask.name)}`);
980
+ return (i) => s.splat[i * 8 + channel];
981
+ }
982
+ case "not": {
983
+ const inner = compileMask(mask.mask, s);
984
+ return (i, x, z) => 1 - inner(i, x, z);
985
+ }
986
+ case "and": {
987
+ const inner = (mask.masks ?? []).map((entry2) => compileMask(entry2, s));
988
+ return (i, x, z) => inner.reduce((value, sample) => value * sample(i, x, z), 1);
989
+ }
990
+ case "or": {
991
+ const inner = (mask.masks ?? []).map((entry2) => compileMask(entry2, s));
992
+ return (i, x, z) => 1 - inner.reduce((value, sample) => value * (1 - sample(i, x, z)), 1);
993
+ }
994
+ default:
995
+ throw Error(`Unknown mask: ${String(mask.type)}`);
996
+ }
997
+ }
998
+ function rasterMask(mask, s) {
999
+ if (!mask || mask.type === "all") return null;
1000
+ const out = new Float32Array(s.height.length);
1001
+ const sample = compileMask(mask, s);
1002
+ for (let z = 0; z < s.resolution; z += 1) {
1003
+ for (let x = 0; x < s.resolution; x += 1) {
1004
+ const i = z * s.resolution + x;
1005
+ out[i] = clamp(sample(i, world(s, x), world(s, z)));
1006
+ }
1007
+ }
1008
+ return out;
1009
+ }
1010
+ function paintWeights(s, i, channel, weight) {
1011
+ const w = clamp(weight);
1012
+ const base = i * 8;
1013
+ for (let c = 0; c < 8; c += 1)
1014
+ s.splat[base + c] = s.splat[base + c] * (1 - w) + (c === channel ? w : 0);
1015
+ }
1016
+
1017
+ // src/core/scree.ts
1018
+ var NEIGHBOURS = [
1019
+ [-1, -1],
1020
+ [0, -1],
1021
+ [1, -1],
1022
+ [-1, 0],
1023
+ [1, 0],
1024
+ [-1, 1],
1025
+ [0, 1],
1026
+ [1, 1]
1027
+ ];
1028
+ var DISTANCE = Float64Array.from(NEIGHBOURS, ([dx, dz]) => Math.hypot(dx, dz));
1029
+ var MAX_ITERATIONS2 = 200;
1030
+ function scree(height, n, size, { iterations = 200, talus = 35, rate = 0.05 } = {}) {
1031
+ if (!Number.isInteger(n) || n < 2)
1032
+ throw new RangeError("Scree slide requires grid resolution n >= 2");
1033
+ if (!Number.isInteger(iterations) || iterations < 0 || iterations > MAX_ITERATIONS2)
1034
+ throw new RangeError(`Scree slide iterations must be between 0 and ${MAX_ITERATIONS2}`);
1035
+ if (!Number.isFinite(talus) || talus < 0 || talus > 89.9)
1036
+ throw new RangeError("Scree slide talus must be between 0 and 89.9 degrees");
1037
+ if (!Number.isFinite(rate) || rate < 0 || rate > 1)
1038
+ throw new RangeError("Scree slide rate must be between 0 and 1");
1039
+ const cell = size / (n - 1);
1040
+ const limit = Float64Array.from(DISTANCE, (d) => Math.tan(talus * Math.PI / 180) * cell * d);
1041
+ let source = Float64Array.from(height);
1042
+ let target = new Float64Array(source.length);
1043
+ for (let k = 0; k < iterations; k += 1) {
1044
+ for (let z = 0; z < n; z += 1) {
1045
+ for (let x = 0; x < n; x += 1) {
1046
+ const i = z * n + x;
1047
+ const here = source[i];
1048
+ let received = 0;
1049
+ for (let d = 0; d < 8; d += 1) {
1050
+ const nx = x + NEIGHBOURS[d][0];
1051
+ const nz = z + NEIGHBOURS[d][1];
1052
+ if (nx < 0 || nz < 0 || nx >= n || nz >= n) continue;
1053
+ const other = source[nz * n + nx];
1054
+ const gap = limit[d];
1055
+ if (other - here > gap) received += other - here - gap;
1056
+ else if (here - other > gap) received -= here - other - gap;
1057
+ }
1058
+ target[i] = here + rate * received;
1059
+ }
1060
+ }
1061
+ const swap = source;
1062
+ source = target;
1063
+ target = swap;
1064
+ }
1065
+ return Float32Array.from(source);
1066
+ }
1067
+
1068
+ // src/core/operations.ts
1069
+ var OPERATION_TYPES = Object.freeze([
1070
+ "noise",
1071
+ "sculpt",
1072
+ "smooth",
1073
+ "flatten",
1074
+ "ramp",
1075
+ "stamp",
1076
+ "erode",
1077
+ "terrace",
1078
+ "materials",
1079
+ "paint",
1080
+ "biome",
1081
+ "scatter",
1082
+ "clear",
1083
+ "road",
1084
+ "river",
1085
+ "water",
1086
+ "heightmap",
1087
+ "paste"
1088
+ ]);
1089
+ function createState(config, resolution = config.resolution) {
1090
+ const height = new Float32Array(resolution * resolution);
1091
+ const splat = new Float32Array(height.length * 8);
1092
+ for (let i = 0; i < height.length; i += 1) splat[i * 8] = 1;
1093
+ return {
1094
+ size: config.size,
1095
+ resolution,
1096
+ seed: config.seed,
1097
+ height,
1098
+ splat,
1099
+ biomes: {},
1100
+ scatterRules: [],
1101
+ waterRules: [],
1102
+ rivers: [],
1103
+ instances: [],
1104
+ waters: [],
1105
+ diagnostics: []
1106
+ };
1107
+ }
1108
+ function brushCenters(p, seed) {
1109
+ const source = p.points ?? (p.at ? [p.at] : null);
1110
+ if (!source) return null;
1111
+ const radius = p.radius ?? 30;
1112
+ const first = source[0];
1113
+ if (!first) return null;
1114
+ const out = [[first[0], first[1]]];
1115
+ const step = Math.max(0.1, radius * 2 * (p.spacing ?? 0.15));
1116
+ for (let k = 1; k < source.length; k += 1) {
1117
+ const a = source[k - 1];
1118
+ const b = source[k];
1119
+ const count2 = Math.max(1, Math.ceil(Math.hypot(b[0] - a[0], b[1] - a[1]) / step));
1120
+ for (let j = 1; j <= count2; j += 1)
1121
+ out.push([lerp(a[0], b[0], j / count2), lerp(a[1], b[1], j / count2)]);
1122
+ }
1123
+ if (p.jitter) {
1124
+ const rnd = random(seed);
1125
+ for (const centre of out) {
1126
+ const angle = rnd() * Math.PI * 2;
1127
+ const offset = Math.sqrt(rnd()) * p.jitter * radius;
1128
+ centre[0] += Math.cos(angle) * offset;
1129
+ centre[1] += Math.sin(angle) * offset;
1130
+ }
1131
+ }
1132
+ return out;
1133
+ }
1134
+ function brushWeights(s, p, mask, seed) {
1135
+ const centers = brushCenters(p, seed);
1136
+ if (!centers) return mask ?? new Float32Array(s.height.length).fill(1);
1137
+ const n = s.resolution;
1138
+ const r = p.radius ?? 30;
1139
+ const cell = s.size / (n - 1);
1140
+ const weights = new Float32Array(n * n);
1141
+ const angle = (p.rotation ?? 0) * Math.PI / 180;
1142
+ const cos = Math.cos(angle);
1143
+ const sin = Math.sin(angle);
1144
+ const bound = r * (p.shape === "square" ? Math.SQRT2 : 1);
1145
+ for (const [cx, cz] of centers) {
1146
+ const x0 = clamp(Math.floor((cx - bound + s.size / 2) / cell), 0, n - 1);
1147
+ const x1 = clamp(Math.ceil((cx + bound + s.size / 2) / cell), 0, n - 1);
1148
+ const z0 = clamp(Math.floor((cz - bound + s.size / 2) / cell), 0, n - 1);
1149
+ const z1 = clamp(Math.ceil((cz + bound + s.size / 2) / cell), 0, n - 1);
1150
+ for (let z = z0; z <= z1; z += 1) {
1151
+ for (let x = x0; x <= x1; x += 1) {
1152
+ const dx = world(s, x) - cx;
1153
+ const dz = world(s, z) - cz;
1154
+ const distance = p.shape === "square" ? Math.max(Math.abs(dx * cos + dz * sin), Math.abs(-dx * sin + dz * cos)) : Math.hypot(dx, dz);
1155
+ const i = z * n + x;
1156
+ weights[i] = Math.max(
1157
+ weights[i],
1158
+ falloff(distance, r, p.falloff ?? 0.6) * (mask?.[i] ?? 1)
1159
+ );
1160
+ }
1161
+ }
1162
+ }
1163
+ return weights;
1164
+ }
1165
+ function followsTerrain(source, followTerrain) {
1166
+ return followTerrain ?? source.some((point) => !Number.isFinite(point[1]));
1167
+ }
1168
+ function gradeToGround(s, points, p) {
1169
+ const at = (k) => points[k];
1170
+ const run = (k) => {
1171
+ const a = at(k - 1);
1172
+ const b = at(k);
1173
+ return Math.hypot(b[0] - a[0], b[2] - a[2]);
1174
+ };
1175
+ const bed = points.map(([x, , z]) => sampleHeight(s, x, z));
1176
+ let spacing = 0;
1177
+ for (let k = 1; k < points.length && spacing === 0; k += 1) spacing = run(k);
1178
+ spacing ||= 3;
1179
+ const window = Math.max(1, Math.round(Math.max(8, p.width ?? 12) / spacing));
1180
+ const profile = bed.slice();
1181
+ for (let pass = 0; pass < 2; pass += 1) {
1182
+ const next = profile.slice();
1183
+ for (let k = 0; k < profile.length; k += 1) {
1184
+ let sum = 0;
1185
+ let count2 = 0;
1186
+ for (let j = Math.max(0, k - window); j <= Math.min(profile.length - 1, k + window); j += 1) {
1187
+ sum += profile[j];
1188
+ count2 += 1;
1189
+ }
1190
+ next[k] = sum / count2;
1191
+ }
1192
+ for (let k = 0; k < profile.length; k += 1) profile[k] = next[k];
1193
+ }
1194
+ const maxCut = p.maxCut ?? 2.5;
1195
+ const maxFill = p.maxFill ?? 1.5;
1196
+ const grade2 = p.maxGrade ?? 0.12;
1197
+ const limit = (k) => grade2 * Math.max(0.5, run(k));
1198
+ for (let round = 0; round < 16; round += 1) {
1199
+ let moved = 0;
1200
+ for (let k = 1; k < profile.length; k += 1) {
1201
+ const y = clamp(
1202
+ profile[k],
1203
+ profile[k - 1] - limit(k),
1204
+ profile[k - 1] + limit(k)
1205
+ );
1206
+ moved += Math.abs(y - profile[k]);
1207
+ profile[k] = y;
1208
+ }
1209
+ for (let k = profile.length - 2; k >= 0; k -= 1) {
1210
+ const y = clamp(
1211
+ profile[k],
1212
+ profile[k + 1] - limit(k + 1),
1213
+ profile[k + 1] + limit(k + 1)
1214
+ );
1215
+ moved += Math.abs(y - profile[k]);
1216
+ profile[k] = y;
1217
+ }
1218
+ if (moved < 1e-4) break;
1219
+ }
1220
+ for (let k = 0; k < profile.length; k += 1)
1221
+ profile[k] = clamp(
1222
+ profile[k],
1223
+ bed[k] - maxCut,
1224
+ bed[k] + maxFill
1225
+ );
1226
+ for (let k = 0; k < points.length; k += 1) at(k)[1] = profile[k];
1227
+ }
1228
+ function applySpline(s, layer2, mask) {
1229
+ const p = layer2.params;
1230
+ const river = layer2.type === "river";
1231
+ const ramp = layer2.type === "ramp";
1232
+ const seed = p.seed ?? s.seed;
1233
+ const raw = ramp ? [p.from, p.to] : p.points ?? [];
1234
+ const follows = followsTerrain(raw, p.followTerrain);
1235
+ const source = raw.map(
1236
+ ([x, y, z]) => [x, Number.isFinite(y) ? y : 0, z]
1237
+ );
1238
+ const points = splinePoints(
1239
+ source,
1240
+ Math.max(1, (p.width ?? 12) * 0.22),
1241
+ !ramp && p.smooth !== false
1242
+ );
1243
+ if (follows) gradeToGround(s, points, p);
1244
+ const half = (p.width ?? 12) / 2;
1245
+ const shoulder = p.shoulder ?? half;
1246
+ const extent = half + shoulder;
1247
+ const depth = p.depth ?? 4;
1248
+ const alpha = layer2.opacity ?? 1;
1249
+ const n = s.resolution;
1250
+ const cell = s.size / (n - 1);
1251
+ const dist = new Float32Array(n * n).fill(Number.POSITIVE_INFINITY);
1252
+ const target = new Float32Array(n * n);
1253
+ const bed = new Float32Array(n * n);
1254
+ const floor = river ? 1.5 * depth : 0;
1255
+ let reach = extent;
1256
+ const raster = () => {
1257
+ dist.fill(Number.POSITIVE_INFINITY);
1258
+ for (let k = 1; k < points.length; k += 1) {
1259
+ const a = points[k - 1];
1260
+ const b = points[k];
1261
+ const dx = b[0] - a[0];
1262
+ const dz = b[2] - a[2];
1263
+ const den = dx * dx + dz * dz;
1264
+ if (den < 1e-12) continue;
1265
+ const xmin = clamp(Math.floor((Math.min(a[0], b[0]) - reach + s.size / 2) / cell), 0, n - 1);
1266
+ const xmax = clamp(Math.ceil((Math.max(a[0], b[0]) + reach + s.size / 2) / cell), 0, n - 1);
1267
+ const zmin = clamp(Math.floor((Math.min(a[2], b[2]) - reach + s.size / 2) / cell), 0, n - 1);
1268
+ const zmax = clamp(Math.ceil((Math.max(a[2], b[2]) + reach + s.size / 2) / cell), 0, n - 1);
1269
+ for (let z = zmin; z <= zmax; z += 1) {
1270
+ for (let x = xmin; x <= xmax; x += 1) {
1271
+ const wx = world(s, x);
1272
+ const wz = world(s, z);
1273
+ const t = clamp(((wx - a[0]) * dx + (wz - a[2]) * dz) / den);
1274
+ const d = Math.hypot(wx - a[0] - t * dx, wz - a[2] - t * dz);
1275
+ const i = z * n + x;
1276
+ if (d < dist[i]) {
1277
+ dist[i] = d;
1278
+ target[i] = lerp(a[1], b[1], t);
1279
+ bed[i] = s.height[i];
1280
+ }
1281
+ }
1282
+ }
1283
+ }
1284
+ };
1285
+ raster();
1286
+ let worst = 0;
1287
+ for (let i = 0; i < dist.length; i += 1)
1288
+ if (dist[i] <= extent)
1289
+ worst = Math.max(worst, Math.abs(target[i] - bed[i]));
1290
+ if (floor + 1.5 * worst > 0.05) {
1291
+ reach = extent + floor + 1.5 * worst;
1292
+ raster();
1293
+ }
1294
+ const material = MATERIAL_IDS.indexOf(p.material ?? (river ? "mud" : "road"));
1295
+ for (let i = 0; i < s.height.length; i += 1) {
1296
+ const d = dist[i];
1297
+ if (d > reach) continue;
1298
+ const pre = bed[i];
1299
+ const edge = Math.min(reach, extent + floor + 1.5 * Math.abs(target[i] - pre));
1300
+ const blend = 1 - smoothstep(half, edge, d);
1301
+ const w = blend * blend * (mask?.[i] ?? 1) * alpha;
1302
+ let y = target[i];
1303
+ if (river) {
1304
+ const bowl = 1 - 0.35 * clamp(d / half) ** 2;
1305
+ const bars = 1 + 0.22 * noise2(world(s, i % n) / (half * 8), world(s, Math.floor(i / n)) / (half * 8), seed + 7);
1306
+ y = Math.min(pre, y - depth * bowl * bars * blend);
1307
+ }
1308
+ s.height[i] = lerp(pre, y, w);
1309
+ if (material >= 0) paintWeights(s, i, material, w * (river ? 0.85 : 1));
1310
+ }
1311
+ if (river && p.water !== false)
1312
+ s.rivers.push({
1313
+ id: layer2.id,
1314
+ points,
1315
+ width: (p.width ?? 12) * (p.waterWidth ?? 0.76),
1316
+ color: p.color,
1317
+ opacity: alpha
1318
+ });
1319
+ }
1320
+ function applyOperation(s, layer2) {
1321
+ const { type, params: p } = layer2;
1322
+ const opacity = layer2.opacity ?? 1;
1323
+ if (layer2.enabled === false || opacity <= 0) return;
1324
+ const mask = rasterMask(layer2.mask, s);
1325
+ const weight = (i) => (mask?.[i] ?? 1) * opacity;
1326
+ const n = s.resolution;
1327
+ const seed = p.seed ?? s.seed;
1328
+ switch (type) {
1329
+ case "noise": {
1330
+ const amplitude = p.amplitude ?? 35;
1331
+ const scale = p.scale ?? 100;
1332
+ const warp = p.warp ?? 20;
1333
+ for (let z = 0; z < n; z += 1) {
1334
+ for (let x = 0; x < n; x += 1) {
1335
+ const i = z * n + x;
1336
+ const wx = world(s, x);
1337
+ const wz = world(s, z);
1338
+ const ox = noise2(wx / (scale * 1.7) + 17, wz / (scale * 1.7) - 19, seed + 29) * warp;
1339
+ const oz = noise2(wx / (scale * 1.7) - 27, wz / (scale * 1.7) + 12, seed + 31) * warp;
1340
+ let value = (p.base ?? 0) + fbm((wx + ox) / scale, (wz + oz) / scale, {
1341
+ seed,
1342
+ octaves: p.octaves,
1343
+ persistence: p.persistence,
1344
+ lacunarity: p.lacunarity,
1345
+ mode: p.mode
1346
+ }) * amplitude;
1347
+ if (p.island) {
1348
+ const r = Math.hypot(wx / (s.size * 0.59), wz / (s.size * 0.59));
1349
+ value = value * (1 - smoothstep(0.45, 1, r)) - (p.coastDepth ?? 15) * smoothstep(0.6, 1, r);
1350
+ }
1351
+ s.height[i] = p.blend === "replace" ? lerp(s.height[i], value, weight(i)) : s.height[i] + value * weight(i);
1352
+ }
1353
+ }
1354
+ break;
1355
+ }
1356
+ case "sculpt":
1357
+ case "flatten":
1358
+ case "smooth":
1359
+ case "paint": {
1360
+ const weights = brushWeights(s, p, mask, seed);
1361
+ const w = (i) => (weights?.[i] ?? 1) * opacity;
1362
+ if (type === "sculpt")
1363
+ for (let i = 0; i < s.height.length; i += 1)
1364
+ s.height[i] = s.height[i] + (p.strength ?? 5) * w(i);
1365
+ if (type === "flatten") {
1366
+ const level = "height" in p ? p.height : void 0;
1367
+ if (typeof level !== "number" || !Number.isFinite(level)) {
1368
+ const covered = brushWeights(s, p, mask, seed);
1369
+ let sum = 0;
1370
+ let total = 0;
1371
+ for (let i = 0; i < s.height.length; i += 1) {
1372
+ const share2 = covered[i] * opacity;
1373
+ sum += s.height[i] * share2;
1374
+ total += share2;
1375
+ }
1376
+ const target = total > 0 ? sum / total : 0;
1377
+ let delta = 0;
1378
+ for (let i = 0; i < s.height.length; i += 1)
1379
+ if (covered[i] > 0)
1380
+ delta = Math.max(delta, Math.abs(s.height[i] - target));
1381
+ const graded = brushWeights(
1382
+ s,
1383
+ { ...p, radius: (p.radius ?? 30) + 1.5 * delta },
1384
+ mask,
1385
+ seed
1386
+ );
1387
+ for (let i = 0; i < s.height.length; i += 1)
1388
+ s.height[i] = lerp(
1389
+ s.height[i],
1390
+ target,
1391
+ graded[i] * opacity * clamp(p.strength ?? 1)
1392
+ );
1393
+ } else
1394
+ for (let i = 0; i < s.height.length; i += 1)
1395
+ s.height[i] = lerp(s.height[i], level, w(i) * clamp(p.strength ?? 1));
1396
+ }
1397
+ if (type === "paint") {
1398
+ const channel = MATERIAL_IDS.indexOf(("material" in p ? p.material : void 0) ?? "dirt");
1399
+ for (let i = 0; i < s.height.length; i += 1)
1400
+ paintWeights(s, i, channel, w(i) * clamp(p.strength ?? 1));
1401
+ }
1402
+ if (type === "smooth")
1403
+ for (let k = 0; k < (("iterations" in p ? p.iterations : void 0) ?? 3); k += 1) {
1404
+ const old = s.height.slice();
1405
+ for (let z = 0; z < n; z += 1) {
1406
+ for (let x = 0; x < n; x += 1) {
1407
+ const i = z * n + x;
1408
+ if (w(i) === 0) continue;
1409
+ let total = 0;
1410
+ let count2 = 0;
1411
+ for (let dz = -1; dz <= 1; dz += 1) {
1412
+ for (let dx = -1; dx <= 1; dx += 1) {
1413
+ const xx = x + dx;
1414
+ const zz = z + dz;
1415
+ if (xx >= 0 && xx < n && zz >= 0 && zz < n) {
1416
+ total += old[zz * n + xx];
1417
+ count2 += 1;
1418
+ }
1419
+ }
1420
+ }
1421
+ s.height[i] = lerp(old[i], total / count2, w(i) * clamp(p.strength ?? 0.65));
1422
+ }
1423
+ }
1424
+ }
1425
+ break;
1426
+ }
1427
+ case "stamp":
1428
+ case "paste": {
1429
+ const at = p.at ?? [0, 0];
1430
+ const radius = p.radius ?? (p.size ? typeof p.size === "number" ? p.size / 2 : p.size.map((v) => v / 2) : 60);
1431
+ const extents = Array.isArray(radius) ? [radius[0] / 1, radius[1] / 1] : [radius / 1, radius / 1];
1432
+ const rot = (p.rotation ?? 0) * Math.PI / 180;
1433
+ const c = Math.cos(rot);
1434
+ const sn = Math.sin(rot);
1435
+ const shape = ("shape" in p ? p.shape : void 0) ?? "mountain";
1436
+ for (let z = 0; z < n; z += 1) {
1437
+ for (let x = 0; x < n; x += 1) {
1438
+ const i = z * n + x;
1439
+ const dx = world(s, x) - at[0];
1440
+ const dz = world(s, z) - at[1];
1441
+ const u = (dx * c + dz * sn) / extents[0] * (p.mirrorX ? -1 : 1);
1442
+ const v = (-dx * sn + dz * c) / extents[1] * (p.mirrorZ ? -1 : 1);
1443
+ const d = Math.hypot(u, v);
1444
+ let profile;
1445
+ let w = 1;
1446
+ if (p.data) {
1447
+ if (Math.abs(u) > 1 || Math.abs(v) > 1) continue;
1448
+ const source = p.data;
1449
+ profile = sampleGrid(
1450
+ source.values,
1451
+ source.width,
1452
+ source.height,
1453
+ u * 0.5 + 0.5,
1454
+ v * 0.5 + 0.5
1455
+ );
1456
+ w = falloff(Math.max(Math.abs(u), Math.abs(v)), 1, p.falloff ?? 0.12);
1457
+ } else {
1458
+ if (d >= 1) continue;
1459
+ const rough = 1 + (("roughness" in p ? p.roughness : void 0) ?? 0.13) * fbm(u * 5, v * 5, { seed, octaves: 3 });
1460
+ if (shape === "crater")
1461
+ profile = (Math.exp(-(((d - 0.67) / 0.14) ** 2)) * 0.48 - Math.exp(-((d / 0.49) ** 4)) * 0.6) * (1 - smoothstep(0.85, 1, d));
1462
+ else if (shape === "ridge")
1463
+ profile = Math.max(0, 1 - Math.abs(v)) ** 1.7 * (1 - smoothstep(0.35, 1, Math.abs(u))) * rough;
1464
+ else if (shape === "mesa") profile = (1 - smoothstep(0.5, 1, d)) * rough;
1465
+ else if (shape === "valley") profile = -(1 - smoothstep(0, 1, d)) * rough;
1466
+ else if (shape === "dune") profile = Math.max(0, 1 - d) ** 1.2 * (1 + 0.25 * u) * rough;
1467
+ else profile = Math.max(0, 1 - d) ** 1.65 * rough;
1468
+ profile *= ("amplitude" in p ? p.amplitude : void 0) ?? 45;
1469
+ w = falloff(d, 1, p.falloff ?? 0);
1470
+ }
1471
+ const alpha = weight(i) * w;
1472
+ const blend = p.blend ?? (type === "paste" ? "replace" : "add");
1473
+ const height = profile * (p.scale ?? 1) + (p.offset ?? 0);
1474
+ const value = blend === "replace" ? height : blend === "max" ? Math.max(s.height[i], height) : blend === "min" ? Math.min(s.height[i], height) : s.height[i] + height;
1475
+ s.height[i] = lerp(s.height[i], value, alpha);
1476
+ }
1477
+ }
1478
+ break;
1479
+ }
1480
+ case "erode": {
1481
+ const observations = {
1482
+ flow: new Float32Array(s.height.length),
1483
+ sediment: new Float32Array(s.height.length),
1484
+ deposition: new Float32Array(s.height.length),
1485
+ talus: new Float32Array(s.height.length)
1486
+ };
1487
+ s.erosion ??= structuredClone(observations);
1488
+ const eroded = p.method === "fluvial" ? fluvial(s.height, n, s.size, p) : p.method === "hydraulic" ? hydraulic(
1489
+ s.height,
1490
+ n,
1491
+ s.size,
1492
+ {
1493
+ seed,
1494
+ droplets: p.droplets,
1495
+ maxSteps: p.maxSteps,
1496
+ inertia: p.inertia,
1497
+ capacity: p.capacity,
1498
+ erosion: p.erosion,
1499
+ deposition: p.deposition,
1500
+ evaporation: p.evaporation
1501
+ },
1502
+ observations
1503
+ ) : p.method === "gully" ? gully(s.height, n, s.size, p) : p.method === "scree" ? scree(s.height, n, s.size, p) : thermal(s.height, n, s.size, p, observations);
1504
+ let influence = mask;
1505
+ if (p.at || p.points) influence = brushWeights(s, p, mask, seed);
1506
+ for (let i = 0; i < s.height.length; i += 1) {
1507
+ const alpha = (influence?.[i] ?? 1) * opacity * (p.strength ?? 1);
1508
+ s.height[i] = lerp(s.height[i], eroded[i], alpha);
1509
+ for (const key of ["flow", "sediment", "deposition", "talus"])
1510
+ s.erosion[key][i] = s.erosion[key][i] + observations[key][i] * alpha;
1511
+ }
1512
+ break;
1513
+ }
1514
+ case "terrace": {
1515
+ const step = p.step ?? 8;
1516
+ const softness = p.softness ?? 0.18;
1517
+ for (let i = 0; i < s.height.length; i += 1) {
1518
+ const v = (s.height[i] - (p.offset ?? 0)) / step;
1519
+ const base = Math.floor(v);
1520
+ const f = v - base;
1521
+ const target = (base + smoothstep(0.5 - softness * 0.5, 0.5 + softness * 0.5, f)) * step + (p.offset ?? 0);
1522
+ s.height[i] = lerp(s.height[i], target, weight(i) * (p.strength ?? 1));
1523
+ }
1524
+ break;
1525
+ }
1526
+ case "materials": {
1527
+ if (p.reset !== false)
1528
+ for (let i = 0; i < s.height.length; i += 1)
1529
+ paintWeights(s, i, MATERIAL_IDS.indexOf(p.base ?? "grass"), weight(i));
1530
+ for (const rule of p.rules ?? []) {
1531
+ const ruleMask = rasterMask(rule.mask, s);
1532
+ const channel = MATERIAL_IDS.indexOf(rule.material);
1533
+ for (let i = 0; i < s.height.length; i += 1)
1534
+ paintWeights(s, i, channel, (ruleMask?.[i] ?? 1) * weight(i) * (rule.strength ?? 1));
1535
+ }
1536
+ break;
1537
+ }
1538
+ case "biome": {
1539
+ const name = p.name ?? "forest";
1540
+ s.biomes[name] ??= new Float32Array(s.height.length);
1541
+ const values = s.biomes[name];
1542
+ const weights = brushWeights(s, p, mask, seed);
1543
+ for (let i = 0; i < values.length; i += 1)
1544
+ values[i] = lerp(
1545
+ values[i],
1546
+ p.value ?? 1,
1547
+ (weights?.[i] ?? 1) * opacity * (p.strength ?? 1)
1548
+ );
1549
+ break;
1550
+ }
1551
+ case "scatter":
1552
+ s.scatterRules.push({ id: layer2.id, ...p, mask: layer2.mask, opacity, clear: [] });
1553
+ break;
1554
+ case "clear": {
1555
+ if (p.target === "scatter" || p.target === "all") {
1556
+ for (const rule of s.scatterRules)
1557
+ if (!p.asset || rule.asset === p.asset)
1558
+ rule.clear.push({ mask: layer2.mask ?? { type: "all" }, opacity });
1559
+ }
1560
+ if (p.target === "biome" || p.target === "all")
1561
+ for (const [name, values] of Object.entries(s.biomes)) {
1562
+ if (p.name && p.name !== name) continue;
1563
+ for (let i = 0; i < values.length; i += 1)
1564
+ values[i] = values[i] * (1 - weight(i));
1565
+ }
1566
+ if (p.target === "paint" || p.target === "all")
1567
+ for (let i = 0; i < s.height.length; i += 1) paintWeights(s, i, 0, weight(i));
1568
+ break;
1569
+ }
1570
+ case "road":
1571
+ case "river":
1572
+ case "ramp":
1573
+ applySpline(s, layer2, mask);
1574
+ break;
1575
+ case "water":
1576
+ s.waterRules.push({ id: layer2.id, ...p, mask: layer2.mask, opacity });
1577
+ break;
1578
+ case "heightmap": {
1579
+ if (p.at !== void 0 || p.size !== void 0 || p.rotation !== void 0 || p.falloff !== void 0) {
1580
+ applyOperation(s, {
1581
+ ...layer2,
1582
+ type: "paste",
1583
+ params: { ...p, size: p.size ?? s.size, falloff: p.falloff ?? 0 }
1584
+ });
1585
+ break;
1586
+ }
1587
+ const data = p.data;
1588
+ for (let z = 0; z < n; z += 1) {
1589
+ for (let x = 0; x < n; x += 1) {
1590
+ const i = z * n + x;
1591
+ const value = sampleGrid(data.values, data.width, data.height, x / (n - 1), z / (n - 1)) * (p.scale ?? 1) + (p.offset ?? 0);
1592
+ s.height[i] = p.blend === "add" ? s.height[i] + value * weight(i) : lerp(s.height[i], value, weight(i));
1593
+ }
1594
+ }
1595
+ break;
1596
+ }
1597
+ default:
1598
+ throw Error(`Unsupported operation: ${String(layer2.type)}`);
1599
+ }
1600
+ }
1601
+ function finalizeState(s) {
1602
+ const n = s.resolution;
1603
+ const cell = s.size / (n - 1);
1604
+ s.waters = [];
1605
+ s.instances = [];
1606
+ for (const water2 of s.waterRules) {
1607
+ const mask = new Uint8Array(n * n);
1608
+ const queue = new Int32Array(n * n);
1609
+ const allowed = compileMask(water2.mask, s);
1610
+ const level = water2.level ?? 0;
1611
+ const at = water2.at ?? [0, 0];
1612
+ const radius = water2.radius ?? s.size;
1613
+ let front = 0;
1614
+ let back = 0;
1615
+ const eligible = (i) => {
1616
+ const x = world(s, i % n);
1617
+ const z = world(s, Math.floor(i / n));
1618
+ return s.height[i] < level && Math.hypot(x - at[0], z - at[1]) <= radius && allowed(i, x, z) > 0.05;
1619
+ };
1620
+ const push = (i) => {
1621
+ if (i >= 0 && i < n * n && !mask[i] && eligible(i)) {
1622
+ mask[i] = 1;
1623
+ queue[back] = i;
1624
+ back += 1;
1625
+ }
1626
+ };
1627
+ if (water2.kind === "ocean") {
1628
+ for (let k = 0; k < n; k += 1) {
1629
+ push(k);
1630
+ push((n - 1) * n + k);
1631
+ push(k * n);
1632
+ push(k * n + n - 1);
1633
+ }
1634
+ } else {
1635
+ const x = clamp(Math.round((at[0] + s.size / 2) / cell), 0, n - 1);
1636
+ const z = clamp(Math.round((at[1] + s.size / 2) / cell), 0, n - 1);
1637
+ push(z * n + x);
1638
+ }
1639
+ while (front < back) {
1640
+ const i = queue[front];
1641
+ front += 1;
1642
+ const x = i % n;
1643
+ const z = Math.floor(i / n);
1644
+ if (x > 0) push(i - 1);
1645
+ if (x < n - 1) push(i + 1);
1646
+ if (z > 0) push(i - n);
1647
+ if (z < n - 1) push(i + n);
1648
+ }
1649
+ s.waters.push({ ...water2, level, mask });
1650
+ if (!back)
1651
+ s.diagnostics.push(
1652
+ `Water '${water2.id}' has no flooded cells; its seed may be above the water level.`
1653
+ );
1654
+ }
1655
+ const wet = (i, x, z, h) => {
1656
+ if (s.waters.some((water2) => water2.mask[i])) return true;
1657
+ if (s.waters.some((water2) => water2.kind === "ocean" && h < water2.level + 0.35)) return true;
1658
+ for (const river of s.rivers) {
1659
+ const half = river.width / 2;
1660
+ for (let k = 1; k < river.points.length; k += 1) {
1661
+ const a = river.points[k - 1];
1662
+ const b = river.points[k];
1663
+ if (x < Math.min(a[0], b[0]) - half || x > Math.max(a[0], b[0]) + half || z < Math.min(a[2], b[2]) - half || z > Math.max(a[2], b[2]) + half)
1664
+ continue;
1665
+ const dx = b[0] - a[0];
1666
+ const dz = b[2] - a[2];
1667
+ const t = clamp(((x - a[0]) * dx + (z - a[2]) * dz) / (dx * dx + dz * dz || 1));
1668
+ if (Math.hypot(x - a[0] - t * dx, z - a[2] - t * dz) < half && h <= lerp(a[1], b[1], t) + 0.2)
1669
+ return true;
1670
+ }
1671
+ }
1672
+ return false;
1673
+ };
1674
+ for (const rule of s.scatterRules) {
1675
+ const count2 = Math.round((rule.count ?? 300) * (rule.opacity ?? 1));
1676
+ const seed = (rule.seed ?? s.seed ^ hashString(rule.id)) >>> 0;
1677
+ const rnd = random(seed);
1678
+ const accept = compileMask(rule.mask, s);
1679
+ const clears = rule.clear.map((entry2) => ({
1680
+ fn: compileMask(entry2.mask, s),
1681
+ opacity: entry2.opacity
1682
+ }));
1683
+ const distance = rule.minDistance ?? 4;
1684
+ const gridSize = Math.max(distance, 0.1);
1685
+ const buckets = /* @__PURE__ */ new Map();
1686
+ const accepted = [];
1687
+ const maxAttempts = count2 * 40;
1688
+ const scale = rule.scale ?? [0.8, 1.3];
1689
+ for (let attempt = 0; attempt < maxAttempts && accepted.length < count2; attempt += 1) {
1690
+ const x = (rnd() - 0.5) * s.size;
1691
+ const z = (rnd() - 0.5) * s.size;
1692
+ const acceptance = rnd();
1693
+ const scaleRandom = rnd();
1694
+ const yaw = rnd() * Math.PI * 2;
1695
+ const ix = clamp(Math.round((x / s.size + 0.5) * (n - 1)), 0, n - 1);
1696
+ const iz = clamp(Math.round((z / s.size + 0.5) * (n - 1)), 0, n - 1);
1697
+ const i = iz * n + ix;
1698
+ let w = accept(i, x, z);
1699
+ for (const clear of clears) w *= 1 - clear.fn(i, x, z) * clear.opacity;
1700
+ if (acceptance > w) continue;
1701
+ const h = sampleHeight(s, x, z);
1702
+ if (rule.avoidWater !== false && wet(i, x, z, h)) continue;
1703
+ if (h < (rule.minHeight ?? -1e9) || h > (rule.maxHeight ?? 1e9)) continue;
1704
+ const g = gradientAt(s, x, z);
1705
+ const slope = Math.atan(Math.hypot(g[0], g[1])) * (180 / Math.PI);
1706
+ if (slope < (rule.minSlope ?? 0) || slope > (rule.maxSlope ?? 90)) continue;
1707
+ const gx = Math.floor(x / gridSize);
1708
+ const gz = Math.floor(z / gridSize);
1709
+ let blocked = false;
1710
+ if (distance > 0)
1711
+ for (let dz = -1; dz <= 1 && !blocked; dz += 1) {
1712
+ for (let dx = -1; dx <= 1 && !blocked; dx += 1) {
1713
+ for (const j of buckets.get(`${gx + dx},${gz + dz}`) ?? []) {
1714
+ const other = accepted[j];
1715
+ if (Math.hypot(other.position[0] - x, other.position[2] - z) < distance) {
1716
+ blocked = true;
1717
+ break;
1718
+ }
1719
+ }
1720
+ }
1721
+ }
1722
+ if (blocked) continue;
1723
+ const index = accepted.length;
1724
+ const itemScale = Array.isArray(scale) ? lerp(scale[0], scale[1], scaleRandom) : scale;
1725
+ const normal = [-g[0], 1, -g[1]];
1726
+ const length = Math.hypot(normal[0], normal[1], normal[2]);
1727
+ accepted.push({
1728
+ id: `${rule.id}:candidate:${seed}:${attempt}`,
1729
+ layer: rule.id,
1730
+ asset: rule.asset,
1731
+ position: [x, h + (rule.offsetY ?? 0), z],
1732
+ rotation: yaw,
1733
+ scale: itemScale,
1734
+ normal: [normal[0] / length, normal[1] / length, normal[2] / length],
1735
+ alignToNormal: rule.alignToNormal ?? false
1736
+ });
1737
+ const key = `${gx},${gz}`;
1738
+ const bucket = buckets.get(key) ?? [];
1739
+ bucket.push(index);
1740
+ buckets.set(key, bucket);
1741
+ }
1742
+ for (const instance of accepted) s.instances.push(instance);
1743
+ if (accepted.length < count2)
1744
+ s.diagnostics.push(
1745
+ `Scatter '${rule.id}': placed ${accepted.length}/${count2}; masks or spacing exhausted the attempt budget.`
1746
+ );
1747
+ }
1748
+ return s;
1749
+ }
1750
+
1751
+ // src/core/validation.ts
1752
+ var RESOLUTIONS = Object.freeze([17, 33, 65, 129, 257, 513, 1025]);
1753
+ var brush2 = [
1754
+ "at",
1755
+ "points",
1756
+ "radius",
1757
+ "strength",
1758
+ "falloff",
1759
+ "shape",
1760
+ "rotation",
1761
+ "spacing",
1762
+ "jitter"
1763
+ ];
1764
+ var grade = ["followTerrain", "maxGrade", "maxCut", "maxFill"];
1765
+ var PARAMS = Object.freeze({
1766
+ noise: [
1767
+ "amplitude",
1768
+ "scale",
1769
+ "octaves",
1770
+ "persistence",
1771
+ "lacunarity",
1772
+ "mode",
1773
+ "warp",
1774
+ "base",
1775
+ "blend",
1776
+ "island",
1777
+ "coastDepth"
1778
+ ],
1779
+ sculpt: brush2,
1780
+ smooth: [...brush2, "iterations"],
1781
+ flatten: [...brush2, "height"],
1782
+ paint: [...brush2, "material"],
1783
+ stamp: [
1784
+ "at",
1785
+ "radius",
1786
+ "size",
1787
+ "amplitude",
1788
+ "shape",
1789
+ "rotation",
1790
+ "mirrorX",
1791
+ "mirrorZ",
1792
+ "blend",
1793
+ "roughness",
1794
+ "scale",
1795
+ "offset",
1796
+ "data",
1797
+ "falloff"
1798
+ ],
1799
+ paste: [
1800
+ "at",
1801
+ "size",
1802
+ "radius",
1803
+ "rotation",
1804
+ "mirrorX",
1805
+ "mirrorZ",
1806
+ "blend",
1807
+ "offset",
1808
+ "scale",
1809
+ "data",
1810
+ "falloff"
1811
+ ],
1812
+ erode: [
1813
+ ...brush2,
1814
+ "method",
1815
+ "iterations",
1816
+ "talus",
1817
+ "uplift",
1818
+ "erodibility",
1819
+ "timeStep",
1820
+ "relief",
1821
+ "rate",
1822
+ "droplets",
1823
+ "maxSteps",
1824
+ "inertia",
1825
+ "capacity",
1826
+ "erosion",
1827
+ "deposition",
1828
+ "evaporation",
1829
+ "rain"
1830
+ ],
1831
+ terrace: ["step", "softness", "strength", "offset"],
1832
+ materials: ["base", "rules", "reset"],
1833
+ biome: [...brush2, "name", "value"],
1834
+ scatter: [
1835
+ "asset",
1836
+ "count",
1837
+ "minDistance",
1838
+ "scale",
1839
+ "minHeight",
1840
+ "maxHeight",
1841
+ "minSlope",
1842
+ "maxSlope",
1843
+ "avoidWater",
1844
+ "offsetY",
1845
+ "alignToNormal"
1846
+ ],
1847
+ clear: ["target", "asset", "name"],
1848
+ road: ["points", "width", "shoulder", "material", "smooth", ...grade],
1849
+ river: [
1850
+ "points",
1851
+ "width",
1852
+ "shoulder",
1853
+ "depth",
1854
+ "material",
1855
+ "smooth",
1856
+ "water",
1857
+ "waterWidth",
1858
+ "color",
1859
+ "enforceDownhill",
1860
+ ...grade
1861
+ ],
1862
+ ramp: ["from", "to", "width", "shoulder", "material", ...grade],
1863
+ water: ["kind", "at", "radius", "level", "color"],
1864
+ heightmap: ["data", "scale", "offset", "blend", "at", "size", "rotation", "falloff"]
1865
+ });
1866
+ function fail(message) {
1867
+ throw new TypeError(message);
1868
+ }
1869
+ function finiteTree(value, path = "value", depth = 0) {
1870
+ if (depth > 32) fail(`${path}: nesting is too deep`);
1871
+ if (typeof value === "number") {
1872
+ if (!Number.isFinite(value)) fail(`${path} must be finite`);
1873
+ return;
1874
+ }
1875
+ if (value === void 0 || typeof value === "function" || typeof value === "bigint" || typeof value === "symbol")
1876
+ fail(`${path} is not JSON-serializable`);
1877
+ if (value && typeof value === "object") {
1878
+ if (ArrayBuffer.isView(value)) fail(`${path}: use a plain array in recipes`);
1879
+ for (const key of Object.keys(value)) {
1880
+ if (key === "__proto__" || key === "prototype" || key === "constructor")
1881
+ fail(`${path}: unsafe object key`);
1882
+ const entry2 = value[key];
1883
+ if (typeof entry2 === "number") {
1884
+ if (depth + 1 > 32) fail(`${path}.${key}: nesting is too deep`);
1885
+ if (!Number.isFinite(entry2)) fail(`${path}.${key} must be finite`);
1886
+ continue;
1887
+ }
1888
+ finiteTree(entry2, `${path}.${key}`, depth + 1);
1889
+ }
1890
+ }
1891
+ }
1892
+ var num = (v, name, min = -1e9, max = 1e9, integer = false) => {
1893
+ if (typeof v !== "number" || !Number.isFinite(v) || v < min || v > max || integer && !Number.isInteger(v))
1894
+ fail(`${name} must be ${integer ? "an integer" : "finite"} between ${min} and ${max}`);
1895
+ };
1896
+ var vec = (v, name, n) => {
1897
+ if (!Array.isArray(v) || v.length !== n) fail(`${name} must contain ${n} numbers`);
1898
+ for (const x of v) num(x, name);
1899
+ };
1900
+ var identifier = (v, name) => {
1901
+ if (typeof v !== "string" || v.length === 0 || v.length > 100 || ["__proto__", "prototype", "constructor"].includes(v))
1902
+ fail(`${name} must be a nonempty safe string, at most 100 characters`);
1903
+ };
1904
+ var enumeration = (v, name, choices) => {
1905
+ if (!choices.includes(v)) fail(`${name}: expected ${choices.join(", ")}`);
1906
+ };
1907
+ function validateConfig(config) {
1908
+ num(config.size, "size", 1, 1e5);
1909
+ if (!RESOLUTIONS.includes(config.resolution))
1910
+ fail(`resolution must be one of ${RESOLUTIONS.join(", ")}`);
1911
+ num(config.seed, "seed", 0, 4294967295, true);
1912
+ }
1913
+ function validateMask(m, depth = 0) {
1914
+ if (!m || typeof m !== "object" || depth > 20) fail("Invalid mask");
1915
+ enumeration(m.type, "mask.type", [
1916
+ "all",
1917
+ "none",
1918
+ "circle",
1919
+ "rectangle",
1920
+ "height",
1921
+ "slope",
1922
+ "noise",
1923
+ "biome",
1924
+ "material",
1925
+ "and",
1926
+ "or",
1927
+ "not"
1928
+ ]);
1929
+ const allowed = {
1930
+ all: [],
1931
+ none: [],
1932
+ circle: ["at", "radius", "falloff"],
1933
+ rectangle: ["at", "size", "rotation", "falloff"],
1934
+ height: ["min", "max", "fade"],
1935
+ slope: ["min", "max", "fade"],
1936
+ noise: ["scale", "threshold", "seed", "fade"],
1937
+ biome: ["name"],
1938
+ material: ["name"],
1939
+ and: ["masks"],
1940
+ or: ["masks"],
1941
+ not: ["mask"]
1942
+ };
1943
+ for (const key of Object.keys(m))
1944
+ if (key !== "type" && !allowed[m.type].includes(key)) fail(`Unknown mask field '${key}'`);
1945
+ if (m.rotation !== void 0) num(m.rotation, "mask.rotation");
1946
+ if (m.seed !== void 0) num(m.seed, "mask.seed", 0, 4294967295, true);
1947
+ if (m.type === "circle") {
1948
+ vec(m.at, "mask.at", 2);
1949
+ num(m.radius, "mask.radius", 1e-3, 1e6);
1950
+ }
1951
+ if (m.type === "rectangle") {
1952
+ vec(m.at, "mask.at", 2);
1953
+ const size = m.size;
1954
+ if (Array.isArray(size)) {
1955
+ vec(size, "mask.size", 2);
1956
+ for (const value of size) num(value, "mask.size", 1e-3, 1e6);
1957
+ } else num(size, "mask.size", 1e-3, 1e6);
1958
+ }
1959
+ if (["height", "slope"].includes(m.type)) {
1960
+ if (m.min !== void 0) num(m.min, "mask.min");
1961
+ if (m.max !== void 0) num(m.max, "mask.max");
1962
+ if ((m.min ?? -1e9) > (m.max ?? 1e9)) fail("mask.min must not exceed mask.max");
1963
+ if (m.fade !== void 0) num(m.fade, "mask.fade", 0, 1e6);
1964
+ }
1965
+ if (m.type === "noise") {
1966
+ num(m.scale, "mask.scale", 1e-3, 1e6);
1967
+ if (m.threshold !== void 0) num(m.threshold, "mask.threshold", 0, 1);
1968
+ if (m.fade !== void 0) num(m.fade, "mask.fade", 1e-6, 1);
1969
+ }
1970
+ if (m.type === "biome") identifier(m.name, "mask.name");
1971
+ if (m.type === "material") enumeration(m.name, "mask.material", MATERIAL_IDS);
1972
+ if (m.type === "not") validateMask(m.mask, depth + 1);
1973
+ if (["and", "or"].includes(m.type)) {
1974
+ if (!Array.isArray(m.masks) || m.masks.length > 32)
1975
+ fail("mask.masks must be an array of at most 32 masks");
1976
+ for (const entry2 of m.masks) validateMask(entry2, depth + 1);
1977
+ }
1978
+ if (m.falloff !== void 0) num(m.falloff, "mask.falloff", 0, 1);
1979
+ }
1980
+ function splinePoint(v, name, follows) {
1981
+ if (!Array.isArray(v) || v.length !== 3) fail(`${name} must contain 3 numbers`);
1982
+ num(v[0], name);
1983
+ num(v[2], name);
1984
+ const y = v[1];
1985
+ if (y === null || y === void 0) {
1986
+ if (follows) return;
1987
+ fail(`${name} must contain 3 numbers`);
1988
+ }
1989
+ if (typeof y !== "number") fail(`${name} must contain 3 numbers`);
1990
+ if (!Number.isFinite(y) && !follows) fail(`${name} elevation must be finite`);
1991
+ }
1992
+ function layerFollowsTerrain(layer2) {
1993
+ if (!layer2 || typeof layer2 !== "object" || !["road", "river", "ramp"].includes(layer2.type))
1994
+ return false;
1995
+ const params = layer2.params ?? {};
1996
+ const source = layer2.type === "ramp" ? [params.from, params.to] : params.points;
1997
+ if (!Array.isArray(source)) return false;
1998
+ return followsTerrain(source, params.followTerrain);
1999
+ }
2000
+ function omittedElevations(layer2, follows) {
2001
+ if (!follows) return layer2;
2002
+ const params = layer2.params ?? {};
2003
+ const zero = (p) => Array.isArray(p) && p.length === 3 ? [p[0], 0, p[2]] : p;
2004
+ const points = params.points;
2005
+ const fixes = {
2006
+ ...Array.isArray(points) ? { points: points.map(zero) } : {},
2007
+ ...Array.isArray(params.from) ? { from: zero(params.from) } : {},
2008
+ ...Array.isArray(params.to) ? { to: zero(params.to) } : {}
2009
+ };
2010
+ return Object.keys(fixes).length ? { ...layer2, params: { ...params, ...fixes } } : layer2;
2011
+ }
2012
+ function validateLayer(layer2) {
2013
+ const follows = layerFollowsTerrain(layer2);
2014
+ finiteTree(omittedElevations(layer2, follows), "layer");
2015
+ if (!layer2 || typeof layer2 !== "object") fail("layer must be an object");
2016
+ for (const k of Object.keys(layer2))
2017
+ if (!["id", "name", "type", "params", "enabled", "opacity", "mask"].includes(k))
2018
+ fail(`Unknown layer field '${k}'`);
2019
+ identifier(layer2.id, "layer.id");
2020
+ enumeration(layer2.type, "operation", OPERATION_TYPES);
2021
+ if (layer2.name !== void 0) identifier(layer2.name, "layer.name");
2022
+ if (layer2.enabled !== void 0 && typeof layer2.enabled !== "boolean")
2023
+ fail("enabled must be boolean");
2024
+ if (layer2.opacity !== void 0) num(layer2.opacity, "opacity", 0, 1);
2025
+ if (layer2.mask) validateMask(layer2.mask);
2026
+ const params = layer2.params ?? {};
2027
+ if (!params || Array.isArray(params) || typeof params !== "object")
2028
+ fail("params must be an object");
2029
+ for (const k of Object.keys(params))
2030
+ if (!PARAMS[layer2.type].includes(k) && k !== "seed")
2031
+ fail(`Unknown ${layer2.type} parameter '${k}'`);
2032
+ for (const key of [
2033
+ "island",
2034
+ "mirrorX",
2035
+ "mirrorZ",
2036
+ "reset",
2037
+ "avoidWater",
2038
+ "alignToNormal",
2039
+ "smooth",
2040
+ "water",
2041
+ "enforceDownhill",
2042
+ "followTerrain"
2043
+ ])
2044
+ if (params[key] !== void 0 && typeof params[key] !== "boolean")
2045
+ fail(`${key} must be boolean`);
2046
+ if (params.seed !== void 0) num(params.seed, "seed", 0, 4294967295, true);
2047
+ if (params.at !== void 0) vec(params.at, "at", 2);
2048
+ if (params.from !== void 0) splinePoint(params.from, "from", follows);
2049
+ if (params.to !== void 0) splinePoint(params.to, "to", follows);
2050
+ const points = params.points;
2051
+ const isSpline = ["road", "river"].includes(layer2.type);
2052
+ if (points) {
2053
+ if (!Array.isArray(points) || !points.length || points.length > 8192)
2054
+ fail("points must have 1..8192 entries");
2055
+ const dimensions = isSpline ? 3 : 2;
2056
+ for (const point of points)
2057
+ if (isSpline) splinePoint(point, "point", follows);
2058
+ else vec(point, "point", dimensions);
2059
+ }
2060
+ if (Array.isArray(points) && !isSpline) {
2061
+ const stroke = points;
2062
+ const spacing = Math.max(
2063
+ 0.1,
2064
+ (params.radius ?? 30) * 2 * (params.spacing ?? 0.15)
2065
+ );
2066
+ let samples = 1;
2067
+ for (let k = 1; k < stroke.length; k += 1) {
2068
+ const next = stroke[k];
2069
+ const previous = stroke[k - 1];
2070
+ samples += Math.max(
2071
+ 1,
2072
+ Math.ceil(
2073
+ Math.hypot(
2074
+ next[0] - previous[0],
2075
+ next[1] - previous[1]
2076
+ ) / spacing
2077
+ )
2078
+ );
2079
+ }
2080
+ if (samples > 65536)
2081
+ fail(
2082
+ "Brush interpolation exceeds 65536 samples; increase radius/spacing or shorten the stroke"
2083
+ );
2084
+ }
2085
+ if (isSpline && (!Array.isArray(points) || points.length < 2))
2086
+ fail(`${layer2.type} requires at least two [x,y,z] points`);
2087
+ if (layer2.type === "ramp" && (!params.from || !params.to)) fail("ramp requires from and to");
2088
+ for (const key of ["radius", "size"]) {
2089
+ const value = params[key];
2090
+ if (value === void 0) continue;
2091
+ if (Array.isArray(value)) {
2092
+ vec(value, key, 2);
2093
+ for (const entry2 of value) num(entry2, key, 1e-3, 1e6);
2094
+ } else num(value, key, 1e-3, 1e6);
2095
+ }
2096
+ if (Array.isArray(params.radius) && !["stamp", "paste"].includes(layer2.type))
2097
+ fail("Brush radius must be one number");
2098
+ for (const key of [
2099
+ "amplitude",
2100
+ "height",
2101
+ "base",
2102
+ "offset",
2103
+ "offsetY",
2104
+ "minHeight",
2105
+ "maxHeight",
2106
+ "level",
2107
+ "rotation"
2108
+ ])
2109
+ if (params[key] !== void 0 && !(key === "base" && layer2.type === "materials")) {
2110
+ if (params[key] !== null || key !== "height") num(params[key], key);
2111
+ }
2112
+ for (const key of ["width", "step"])
2113
+ if (params[key] !== void 0) num(params[key], key, 1e-3, 1e6);
2114
+ for (const key of [
2115
+ "warp",
2116
+ "shoulder",
2117
+ "roughness",
2118
+ "coastDepth",
2119
+ "minDistance",
2120
+ "depth",
2121
+ "capacity",
2122
+ "maxCut",
2123
+ "maxFill"
2124
+ ])
2125
+ if (params[key] !== void 0) num(params[key], key, 0, 1e6);
2126
+ for (const key of [
2127
+ "falloff",
2128
+ "jitter",
2129
+ "softness",
2130
+ "inertia",
2131
+ "erosion",
2132
+ "deposition",
2133
+ "evaporation",
2134
+ "rate",
2135
+ "value",
2136
+ "waterWidth",
2137
+ "maxGrade",
2138
+ "rain"
2139
+ ])
2140
+ if (params[key] !== void 0) num(params[key], key, 0, 1);
2141
+ if (params.spacing !== void 0) num(params.spacing, "spacing", 0.01, 2);
2142
+ if (params.strength !== void 0)
2143
+ num(
2144
+ params.strength,
2145
+ "strength",
2146
+ layer2.type === "sculpt" ? -1e4 : 0,
2147
+ layer2.type === "sculpt" ? 1e4 : 1
2148
+ );
2149
+ if (params.scale !== void 0) {
2150
+ const scale = params.scale;
2151
+ if (layer2.type === "scatter") {
2152
+ if (Array.isArray(scale)) {
2153
+ vec(scale, "scale", 2);
2154
+ if (scale[0] > scale[1]) fail("scale range is inverted");
2155
+ for (const entry2 of scale) num(entry2, "scale", 1e-3, 1e4);
2156
+ } else num(scale, "scale", 1e-3, 1e4);
2157
+ } else num(scale, "scale", 1e-3, 1e6);
2158
+ }
2159
+ for (const [key, max] of [
2160
+ ["octaves", 10],
2161
+ ["iterations", 200],
2162
+ ["droplets", 2e5],
2163
+ ["maxSteps", 128],
2164
+ ["count", 2e4]
2165
+ ])
2166
+ if (params[key] !== void 0) num(params[key], key, key === "count" ? 0 : 1, max, true);
2167
+ if (params.persistence !== void 0) num(params.persistence, "persistence", 0.01, 1);
2168
+ if (params.lacunarity !== void 0) num(params.lacunarity, "lacunarity", 1, 4);
2169
+ for (const [key, min, max] of [
2170
+ ["uplift", 1e-9, 1],
2171
+ ["erodibility", 1e-9, 1],
2172
+ ["timeStep", 1, 1e7],
2173
+ ["relief", 1, 1e5]
2174
+ ])
2175
+ if (params[key] !== void 0) num(params[key], key, min, max);
2176
+ for (const key of ["minSlope", "maxSlope", "talus"])
2177
+ if (params[key] !== void 0) num(params[key], key, 0, key === "talus" ? 89.9 : 90);
2178
+ if (params.minHeight !== void 0 && params.maxHeight !== void 0 && params.minHeight > params.maxHeight)
2179
+ fail("height range is inverted");
2180
+ if (params.minSlope !== void 0 && params.maxSlope !== void 0 && params.minSlope > params.maxSlope)
2181
+ fail("slope range is inverted");
2182
+ if (params.material !== void 0) enumeration(params.material, "material", MATERIAL_IDS);
2183
+ if (layer2.type === "materials") {
2184
+ if (params.base !== void 0) enumeration(params.base, "base", MATERIAL_IDS);
2185
+ const rules = params.rules;
2186
+ if (!Array.isArray(rules) || rules.length > 64) fail("materials requires a rules array");
2187
+ for (const rule of rules) {
2188
+ enumeration(rule.material, "rule.material", MATERIAL_IDS);
2189
+ if (rule.mask) validateMask(rule.mask);
2190
+ if (rule.strength !== void 0) num(rule.strength, "rule.strength", 0, 1);
2191
+ }
2192
+ }
2193
+ if (params.method !== void 0)
2194
+ enumeration(params.method, "method", ["thermal", "hydraulic", "fluvial", "gully", "scree"]);
2195
+ if (params.mode !== void 0) enumeration(params.mode, "mode", ["fbm", "ridged", "billow"]);
2196
+ if (params.shape !== void 0)
2197
+ enumeration(
2198
+ params.shape,
2199
+ "shape",
2200
+ ["stamp"].includes(layer2.type) ? ["mountain", "crater", "ridge", "valley", "mesa", "dune"] : ["circle", "square"]
2201
+ );
2202
+ if (params.blend !== void 0)
2203
+ enumeration(
2204
+ params.blend,
2205
+ "blend",
2206
+ ["noise", "heightmap"].includes(layer2.type) ? ["add", "replace"] : ["add", "replace", "min", "max"]
2207
+ );
2208
+ if (layer2.type === "clear")
2209
+ enumeration(params.target, "clear.target", ["scatter", "paint", "biome", "all"]);
2210
+ if (layer2.type === "water") enumeration(params.kind ?? "lake", "water.kind", ["lake", "ocean"]);
2211
+ if (layer2.type === "river" && params.enforceDownhill && Array.isArray(points)) {
2212
+ const river = points;
2213
+ for (let i = 1; i < river.length; i += 1) {
2214
+ const next = river[i];
2215
+ const previous = river[i - 1];
2216
+ if (next[1] > previous[1])
2217
+ fail("River control-point elevations must be non-increasing");
2218
+ }
2219
+ }
2220
+ if (params.name !== void 0) identifier(params.name, "name");
2221
+ if (params.asset !== void 0) identifier(params.asset, "asset");
2222
+ if (layer2.type === "scatter" && typeof params.asset !== "string")
2223
+ fail(
2224
+ 'scatter requires an asset identifier; a document saved before `asset` was mandatory defaulted it to "pine", so add "asset": "pine" (or the asset it should place) to this layer'
2225
+ );
2226
+ if (["heightmap", "paste"].includes(layer2.type) && !params.data)
2227
+ fail(`${layer2.type} requires heightmap data`);
2228
+ const data = params.data;
2229
+ if (data) {
2230
+ num(data.width, "data.width", 2, 4097, true);
2231
+ num(data.height, "data.height", 2, 4097, true);
2232
+ if (!Array.isArray(data.values) || data.values.length !== data.width * data.height)
2233
+ fail("heightmap dimensions do not match values");
2234
+ for (const value of data.values)
2235
+ if (typeof value !== "number" || !Number.isFinite(value))
2236
+ fail("data.values must contain only finite numbers");
2237
+ }
2238
+ }
2239
+ function validateDocument(doc) {
2240
+ finiteTree(
2241
+ Array.isArray(doc.layers) ? {
2242
+ ...doc,
2243
+ layers: doc.layers.map((layer2) => omittedElevations(layer2, layerFollowsTerrain(layer2)))
2244
+ } : doc,
2245
+ "recipe"
2246
+ );
2247
+ if (doc.version !== 1) fail("Unsupported recipe version; expected 1");
2248
+ validateConfig(doc.config);
2249
+ if (!Array.isArray(doc.layers) || doc.layers.length > 512)
2250
+ fail("layers must be an array of at most 512 layers");
2251
+ const ids = /* @__PURE__ */ new Set();
2252
+ for (const layer2 of doc.layers) {
2253
+ validateLayer(layer2);
2254
+ if (ids.has(layer2.id)) fail(`Duplicate layer ID: ${layer2.id}`);
2255
+ ids.add(layer2.id);
2256
+ }
2257
+ }
2258
+
2259
+ // src/core/terrain.ts
2260
+ var TerrainEvaluator = class {
2261
+ cache = /* @__PURE__ */ new Map();
2262
+ bytes = 0;
2263
+ limit;
2264
+ constructor({ cacheMB = 48 } = {}) {
2265
+ if (!Number.isFinite(cacheMB) || cacheMB < 0)
2266
+ throw new RangeError("cacheMB must be finite and nonnegative");
2267
+ this.limit = cacheMB * 1024 * 1024;
2268
+ }
2269
+ clear() {
2270
+ this.cache.clear();
2271
+ this.bytes = 0;
2272
+ }
2273
+ evaluate(doc, { resolution = doc.config.resolution, signal, onProgress } = {}) {
2274
+ validateDocument(doc);
2275
+ validateConfig({ ...doc.config, resolution });
2276
+ const keys = [];
2277
+ let key = this.limit > 0 ? JSON.stringify({ ...doc.config, resolution }) : "";
2278
+ for (const layer2 of this.limit > 0 ? doc.layers : []) {
2279
+ key += `|${JSON.stringify(layer2)}`;
2280
+ keys.push(key);
2281
+ }
2282
+ let state;
2283
+ let start = 0;
2284
+ for (let i = keys.length - 1; i >= 0; i--) {
2285
+ const k = keys[i];
2286
+ const hit = this.cache.get(k);
2287
+ if (hit) {
2288
+ state = structuredClone(hit.state);
2289
+ start = i + 1;
2290
+ this.cache.delete(k);
2291
+ this.cache.set(k, hit);
2292
+ break;
2293
+ }
2294
+ }
2295
+ state ??= createState(doc.config, resolution);
2296
+ for (let i = start; i < doc.layers.length; i++) {
2297
+ signal?.throwIfAborted();
2298
+ const layer2 = doc.layers[i];
2299
+ applyOperation(state, layer2);
2300
+ onProgress?.({ index: i, total: doc.layers.length, id: layer2.id });
2301
+ const bytes = state.height.byteLength + state.splat.byteLength + Object.values(state.erosion ?? {}).reduce((n, a) => n + a.byteLength, 0) + Object.values(state.biomes).reduce((n, a) => n + a.byteLength, 0);
2302
+ if (bytes <= this.limit) {
2303
+ while (this.bytes + bytes > this.limit && this.cache.size) {
2304
+ const first = this.cache.entries().next().value;
2305
+ if (!first) break;
2306
+ this.bytes -= first[1].bytes;
2307
+ this.cache.delete(first[0]);
2308
+ }
2309
+ this.cache.set(keys[i], { state: structuredClone(state), bytes });
2310
+ this.bytes += bytes;
2311
+ }
2312
+ }
2313
+ signal?.throwIfAborted();
2314
+ if (!state.height.every(Number.isFinite))
2315
+ throw new Error("A terrain operation produced a non-finite height");
2316
+ return finalizeState(state);
2317
+ }
2318
+ };
2319
+ var Terrain = class _Terrain {
2320
+ _doc;
2321
+ _undo = [];
2322
+ _redo = [];
2323
+ _listeners = /* @__PURE__ */ new Set();
2324
+ _historyLimit;
2325
+ _transactionDepth = 0;
2326
+ _evaluator = new TerrainEvaluator();
2327
+ constructor({
2328
+ size = 512,
2329
+ resolution = 257,
2330
+ seed = 73,
2331
+ historyLimit = 60
2332
+ } = {}) {
2333
+ const config = { size, resolution, seed };
2334
+ validateConfig(config);
2335
+ if (!Number.isInteger(historyLimit) || historyLimit < 0)
2336
+ throw new RangeError("historyLimit must be a nonnegative integer");
2337
+ this._doc = { version: 1, config, layers: [] };
2338
+ this._historyLimit = historyLimit;
2339
+ }
2340
+ static fromJSON(json) {
2341
+ const doc = typeof json === "string" ? JSON.parse(json) : structuredClone(json);
2342
+ validateDocument(doc);
2343
+ const terrain = new _Terrain(doc.config);
2344
+ terrain._doc = doc;
2345
+ return terrain;
2346
+ }
2347
+ get layers() {
2348
+ return structuredClone(this._doc.layers);
2349
+ }
2350
+ get config() {
2351
+ return structuredClone(this._doc.config);
2352
+ }
2353
+ get canUndo() {
2354
+ return this._undo.length > 0;
2355
+ }
2356
+ get canRedo() {
2357
+ return this._redo.length > 0;
2358
+ }
2359
+ toJSON() {
2360
+ return structuredClone(this._doc);
2361
+ }
2362
+ subscribe(fn) {
2363
+ this._listeners.add(fn);
2364
+ return () => this._listeners.delete(fn);
2365
+ }
2366
+ _emit() {
2367
+ for (const fn of this._listeners) {
2368
+ try {
2369
+ fn(this);
2370
+ } catch (error) {
2371
+ console.error("Terrain subscriber failed:", error);
2372
+ }
2373
+ }
2374
+ }
2375
+ _change(fn) {
2376
+ const before = structuredClone(this._doc);
2377
+ try {
2378
+ fn();
2379
+ validateDocument(this._doc);
2380
+ } catch (error) {
2381
+ this._doc = before;
2382
+ throw error;
2383
+ }
2384
+ if (!this._transactionDepth) {
2385
+ this._undo.push(before);
2386
+ if (this._undo.length > this._historyLimit) this._undo.shift();
2387
+ this._redo = [];
2388
+ this._emit();
2389
+ }
2390
+ return this;
2391
+ }
2392
+ _id(type) {
2393
+ let i = 1;
2394
+ while (this._doc.layers.some((layer2) => layer2.id === `${type}-${i}`)) i++;
2395
+ return `${type}-${i}`;
2396
+ }
2397
+ add(layer2) {
2398
+ const next = { enabled: true, opacity: 1, ...structuredClone(layer2) };
2399
+ next.id ??= this._id(next.type);
2400
+ validateLayer(next);
2401
+ return this._change(() => {
2402
+ const i = this._doc.layers.findIndex((layer3) => layer3.id === next.id);
2403
+ if (i < 0) this._doc.layers.push(next);
2404
+ else this._doc.layers[i] = next;
2405
+ });
2406
+ }
2407
+ _operation(type, options) {
2408
+ const { id, label, enabled, opacity, mask, ...params } = options;
2409
+ if ("data" in params && params.data && typeof params.data === "object" && "values" in params.data && ArrayBuffer.isView(params.data.values)) {
2410
+ const data = params.data;
2411
+ Object.assign(params, { data: { ...data, values: Array.from(data.values) } });
2412
+ }
2413
+ const layer2 = { id: id ?? this._id(type), type, params };
2414
+ const optional = Object.fromEntries(
2415
+ Object.entries({ name: label, enabled, opacity, mask }).filter(
2416
+ ([, value]) => value !== void 0
2417
+ )
2418
+ );
2419
+ return this.add(Object.assign(layer2, optional));
2420
+ }
2421
+ layer(id) {
2422
+ const layer2 = this._doc.layers.find((layer3) => layer3.id === id);
2423
+ if (!layer2) throw new Error(`Unknown layer '${id}'`);
2424
+ return structuredClone(layer2);
2425
+ }
2426
+ update(id, patch) {
2427
+ const old = this.layer(id);
2428
+ const next = {
2429
+ ...old,
2430
+ ...structuredClone(patch),
2431
+ id,
2432
+ params: { ...old.params, ...structuredClone(patch.params ?? {}) }
2433
+ };
2434
+ const { mask: _mask, ...unmasked } = next;
2435
+ return this.add(patch.mask === null ? unmasked : next);
2436
+ }
2437
+ toggle(id, enabled = this.layer(id).enabled === false) {
2438
+ return this.update(id, { enabled });
2439
+ }
2440
+ move(id, index) {
2441
+ if (!Number.isInteger(index) || index < 0 || index >= this._doc.layers.length)
2442
+ throw new RangeError("Layer index out of bounds");
2443
+ return this._change(() => {
2444
+ const i = this._doc.layers.findIndex((layer3) => layer3.id === id);
2445
+ if (i < 0) throw new Error(`Unknown layer '${id}'`);
2446
+ const layer2 = this._doc.layers.splice(i, 1)[0];
2447
+ this._doc.layers.splice(index, 0, layer2);
2448
+ });
2449
+ }
2450
+ remove(id) {
2451
+ this.layer(id);
2452
+ return this._change(() => {
2453
+ this._doc.layers = this._doc.layers.filter((layer2) => layer2.id !== id);
2454
+ });
2455
+ }
2456
+ setConfig(patch) {
2457
+ const config = { ...this._doc.config, ...patch };
2458
+ validateConfig(config);
2459
+ return this._change(() => {
2460
+ this._doc.config = config;
2461
+ });
2462
+ }
2463
+ loadJSON(json) {
2464
+ const next = _Terrain.fromJSON(json).toJSON();
2465
+ return this._change(() => {
2466
+ this._doc = next;
2467
+ });
2468
+ }
2469
+ transaction(fn) {
2470
+ if (fn.constructor.name === "AsyncFunction")
2471
+ throw new TypeError("Transactions must be synchronous");
2472
+ const before = structuredClone(this._doc);
2473
+ const undo = this._undo.slice();
2474
+ const redo = this._redo.slice();
2475
+ this._transactionDepth++;
2476
+ try {
2477
+ const result = fn(this);
2478
+ if (result && (typeof result === "object" || typeof result === "function") && "then" in result && typeof result.then === "function")
2479
+ throw new TypeError("Transactions must be synchronous");
2480
+ validateDocument(this._doc);
2481
+ this._transactionDepth--;
2482
+ if (!this._transactionDepth) {
2483
+ this._undo.push(before);
2484
+ if (this._undo.length > this._historyLimit) this._undo.shift();
2485
+ this._redo = [];
2486
+ this._emit();
2487
+ }
2488
+ return this;
2489
+ } catch (error) {
2490
+ this._transactionDepth--;
2491
+ this._doc = before;
2492
+ this._undo = undo;
2493
+ this._redo = redo;
2494
+ throw error;
2495
+ }
2496
+ }
2497
+ applyPatch(commands) {
2498
+ return this.transaction(() => {
2499
+ for (const command of commands) {
2500
+ switch (command.op) {
2501
+ case "upsert":
2502
+ this.add(command.layer);
2503
+ break;
2504
+ case "update":
2505
+ this.update(command.id, command.patch);
2506
+ break;
2507
+ case "remove":
2508
+ this.remove(command.id);
2509
+ break;
2510
+ case "move":
2511
+ this.move(command.id, command.index);
2512
+ break;
2513
+ case "toggle":
2514
+ this.toggle(command.id, command.enabled);
2515
+ break;
2516
+ default:
2517
+ throw new Error("Unknown patch command");
2518
+ }
2519
+ }
2520
+ });
2521
+ }
2522
+ undo() {
2523
+ const prior = this._undo.pop();
2524
+ if (prior) {
2525
+ this._redo.push(structuredClone(this._doc));
2526
+ this._doc = prior;
2527
+ this._emit();
2528
+ }
2529
+ return this;
2530
+ }
2531
+ redo() {
2532
+ const next = this._redo.pop();
2533
+ if (next) {
2534
+ this._undo.push(structuredClone(this._doc));
2535
+ this._doc = next;
2536
+ this._emit();
2537
+ }
2538
+ return this;
2539
+ }
2540
+ evaluate(options) {
2541
+ return this._evaluator.evaluate(this._doc, options);
2542
+ }
2543
+ clearCache() {
2544
+ this._evaluator.clear();
2545
+ }
2546
+ copyRegion({ at = [0, 0], size = 64, resolution = 33 } = {}) {
2547
+ if (!RESOLUTIONS.includes(resolution)) throw new RangeError("Unsupported copy resolution");
2548
+ if (!(size > 0 && Number.isFinite(size))) throw new RangeError("Copy size must be positive");
2549
+ const state = this.evaluate();
2550
+ const values = [];
2551
+ for (let z = 0; z < resolution; z++)
2552
+ for (let x = 0; x < resolution; x++)
2553
+ values.push(
2554
+ sampleHeight(
2555
+ state,
2556
+ at[0] + (x / (resolution - 1) - 0.5) * size,
2557
+ at[1] + (z / (resolution - 1) - 0.5) * size
2558
+ )
2559
+ );
2560
+ return { width: resolution, height: resolution, values };
2561
+ }
2562
+ inspect(options) {
2563
+ const state = this.evaluate(options);
2564
+ let min = Number.POSITIVE_INFINITY;
2565
+ let max = Number.NEGATIVE_INFINITY;
2566
+ for (const height of state.height) {
2567
+ min = Math.min(min, height);
2568
+ max = Math.max(max, height);
2569
+ }
2570
+ return {
2571
+ size: state.size,
2572
+ resolution: state.resolution,
2573
+ layers: this._doc.layers.length,
2574
+ vertices: state.height.length,
2575
+ triangles: 2 * (state.resolution - 1) ** 2,
2576
+ minHeight: min,
2577
+ maxHeight: max,
2578
+ instances: state.instances.length,
2579
+ diagnostics: state.diagnostics
2580
+ };
2581
+ }
2582
+ noise(options = {}) {
2583
+ return this._operation("noise", options);
2584
+ }
2585
+ sculpt(options = {}) {
2586
+ return this._operation("sculpt", options);
2587
+ }
2588
+ smooth(options = {}) {
2589
+ return this._operation("smooth", options);
2590
+ }
2591
+ flatten(options = {}) {
2592
+ return this._operation("flatten", options);
2593
+ }
2594
+ ramp(options) {
2595
+ return this._operation("ramp", options);
2596
+ }
2597
+ stamp(options = {}) {
2598
+ return this._operation("stamp", options);
2599
+ }
2600
+ erode(options = {}) {
2601
+ return this._operation("erode", options);
2602
+ }
2603
+ terrace(options = {}) {
2604
+ return this._operation("terrace", options);
2605
+ }
2606
+ materials(options) {
2607
+ return this._operation("materials", options);
2608
+ }
2609
+ paint(options = {}) {
2610
+ return this._operation("paint", options);
2611
+ }
2612
+ biome(options = {}) {
2613
+ return this._operation("biome", options);
2614
+ }
2615
+ scatter(options) {
2616
+ return this._operation("scatter", options);
2617
+ }
2618
+ clear(options) {
2619
+ return this._operation("clear", options);
2620
+ }
2621
+ road(options) {
2622
+ return this._operation("road", options);
2623
+ }
2624
+ river(options) {
2625
+ return this._operation("river", options);
2626
+ }
2627
+ water(options = {}) {
2628
+ return this._operation("water", options);
2629
+ }
2630
+ heightmap(options) {
2631
+ return this._operation("heightmap", options);
2632
+ }
2633
+ paste(options) {
2634
+ return this._operation("paste", options);
2635
+ }
2636
+ };
2637
+
2638
+ // src/core/presets.ts
2639
+ var LANDFORMS = {
2640
+ alpine: {
2641
+ summary: "Glacier-cut granite peaks: steep headwalls, sharp ar\xEAtes, dendritic gullies.",
2642
+ reliefRatio: 0.25,
2643
+ reference: "Longs Peak, Rocky Mountain National Park, Colorado (USGS 3DEP, DEM crop `alpine`)",
2644
+ target: { slopeP50: 27.3, slopeP90: 42.5, hypsometricIntegral: 0.452, curvatureKurtosis: 89.3 }
2645
+ },
2646
+ temperateMountains: {
2647
+ summary: "Forested mountain backdrop: rounded massifs cut by branching valleys.",
2648
+ reliefRatio: 0.17,
2649
+ reference: "Sprague Lake / Glacier Creek, Rocky Mountain National Park (DEM crop `forest`)",
2650
+ target: { slopeP50: 14.7, slopeP90: 28.1, hypsometricIntegral: 0.398, curvatureKurtosis: 13.7 }
2651
+ },
2652
+ rollingHills: {
2653
+ summary: "Low dendritic hills with convex ridges and gentle slopes.",
2654
+ reliefRatio: 0.03,
2655
+ reference: "Driftless Area, Wisconsin: fluvially dissected flat-lying bedrock, local relief up to about 115 m (WGNHS county reports); no DEM crop in the repo, so no measured target"
2656
+ },
2657
+ desertMesa: {
2658
+ summary: "Caprock mesas and buttes over a stepped, cliff-and-bench canyon landscape.",
2659
+ reliefRatio: 0.055,
2660
+ reference: "Valley of the Gods, Utah (DEM crop `desert`)",
2661
+ target: { slopeP50: 3.7, slopeP90: 16.9, hypsometricIntegral: 0.276, curvatureKurtosis: 203.9 }
2662
+ },
2663
+ coastalCliffs: {
2664
+ summary: "Island massif with steep rocky shore and drowned gullies.",
2665
+ reliefRatio: 0.075,
2666
+ reference: "Sand Beach / Great Head, Acadia National Park, Maine (DEM crop `coastal`)",
2667
+ target: { slopeP50: 1.6, slopeP90: 19.4, hypsometricIntegral: 0.11, curvatureKurtosis: 34.7 }
2668
+ },
2669
+ tundra: {
2670
+ summary: "Broad rounded uplands above the tree line with shallow glacial valleys.",
2671
+ reliefRatio: 0.15,
2672
+ reference: "Trail Ridge, Rocky Mountain National Park (DEM crop `tundra`)",
2673
+ target: { slopeP50: 17.1, slopeP90: 27.9, hypsometricIntegral: 0.473, curvatureKurtosis: 16.7 }
2674
+ },
2675
+ volcanic: {
2676
+ summary: "Stratovolcano cone with a summit crater and radial gullies.",
2677
+ reliefRatio: 0.18,
2678
+ reference: "Mayon Volcano, Philippines: summit 2469 m, slope about 1:2.5 above 500 m easing to 1:7.8 and 1:19.9 (JICA hazard report); no DEM crop in the repo, so no measured target"
2679
+ }
2680
+ };
2681
+
2682
+ // src/core/biome.ts
2683
+ var SPEC_FIELDS = [
2684
+ "look",
2685
+ "bake",
2686
+ "landform",
2687
+ "sizeMeters",
2688
+ "seed",
2689
+ "stream",
2690
+ "cover",
2691
+ "foliage",
2692
+ "grass",
2693
+ "layers",
2694
+ "water",
2695
+ "spawn",
2696
+ "species",
2697
+ "aliases"
2698
+ ];
2699
+ var COVER_FIELDS = [
2700
+ "ground",
2701
+ "seed",
2702
+ "attempts",
2703
+ "stoneRadius",
2704
+ "clearings",
2705
+ "understorey"
2706
+ ];
2707
+ var UNDERSTOREY_FIELDS = [
2708
+ "attempts",
2709
+ "litter",
2710
+ "fern",
2711
+ "bush",
2712
+ "flower",
2713
+ "deadfall",
2714
+ "shade",
2715
+ "shadeRadius"
2716
+ ];
2717
+ var COVER_GROUNDS = ["wood", "crag", "mesa", "mats"];
2718
+ var STREAMS = ["ordered", "seeded"];
2719
+ var DRIFT_FIELDS = ["field", "frequency", "offset", "amplitude", "band"];
2720
+ var DRIFT_FIELDS_NAMES = ["stand", "mats"];
2721
+ var FOLIAGE_FIELDS = [
2722
+ "species",
2723
+ "density",
2724
+ "slope",
2725
+ "height",
2726
+ "spacing",
2727
+ "collision",
2728
+ "stands",
2729
+ "grassThreshold",
2730
+ "standThreshold",
2731
+ "far"
2732
+ ];
2733
+ var FAR_FIELDS = [
2734
+ "cell",
2735
+ "spacing",
2736
+ "spacingAt",
2737
+ "slope",
2738
+ "meadowSlope",
2739
+ "reach",
2740
+ "treelineJitter",
2741
+ "stand",
2742
+ "seed",
2743
+ "impostor"
2744
+ ];
2745
+ var GRASS_FIELDS = [
2746
+ "species",
2747
+ "density",
2748
+ "slope",
2749
+ "height",
2750
+ "spacing",
2751
+ "slopeFalloff",
2752
+ "heightFalloff",
2753
+ "mats",
2754
+ "waterMargin",
2755
+ "beach",
2756
+ "detailSpacing",
2757
+ "drift",
2758
+ "bladeScale",
2759
+ "bladeJitter",
2760
+ "scrubChance",
2761
+ "scrubScale",
2762
+ "scrubJitter",
2763
+ "scrubBush",
2764
+ "shoreGround",
2765
+ "cobbledBed"
2766
+ ];
2767
+ var BAKE_FIELDS = ["file", "key"];
2768
+ var LAYER_FIELDS = ["layer", "from", "to", "shedFrom", "shedTo"];
2769
+ var LAYER_REQUIRED = ["layer", "from", "to"];
2770
+ var WATER_FIELDS = ["kind", "width", "radius", "depth", "level"];
2771
+ var WATER_REQUIRED = ["kind"];
2772
+ var SPAWN_FIELDS = ["at", "cameraOffset", "focus"];
2773
+ var LANDFORM_KINDS = Object.keys(LANDFORMS);
2774
+ var COLLISION_CLASSES = ["none", "trunk", "hull"];
2775
+ var WATER_KINDS = ["river", "lake", "ocean"];
2776
+ function fail2(biome, field, problem) {
2777
+ throw new TypeError(`${biome}: biome field '${field}' ${problem}.`);
2778
+ }
2779
+ function closed(value, biome, field, fields, required = fields) {
2780
+ const at = (name) => field === "" ? name : `${field}.${name}`;
2781
+ if (typeof value !== "object" || value === null || Array.isArray(value))
2782
+ fail2(biome, field || "<file>", "must be an object");
2783
+ const record = value;
2784
+ for (const key of Object.keys(record))
2785
+ if (!fields.includes(key)) fail2(biome, at(key), "is not a field a biome has");
2786
+ for (const key of required) if (!(key in record)) fail2(biome, at(key), "is missing");
2787
+ return record;
2788
+ }
2789
+ function count(value, biome, field, min = 0) {
2790
+ if (typeof value !== "number" || !Number.isFinite(value))
2791
+ fail2(biome, field, "must be a finite number");
2792
+ if (value < min) fail2(biome, field, `must be at least ${min}`);
2793
+ return value;
2794
+ }
2795
+ function positive(value, biome, field) {
2796
+ const number = count(value, biome, field);
2797
+ if (number === 0) fail2(biome, field, "must be greater than 0");
2798
+ return number;
2799
+ }
2800
+ function whole(value, biome, field, min = 0) {
2801
+ if (typeof value !== "number" || !Number.isSafeInteger(value))
2802
+ fail2(biome, field, "must be a whole number");
2803
+ if (value < min) fail2(biome, field, `must be at least ${min}`);
2804
+ return value;
2805
+ }
2806
+ function share(value, biome, field) {
2807
+ const number = count(value, biome, field);
2808
+ if (number > 1) fail2(biome, field, "must be at most 1");
2809
+ return number;
2810
+ }
2811
+ function flag(value, biome, field) {
2812
+ if (typeof value !== "boolean") fail2(biome, field, "must be true or false");
2813
+ return value;
2814
+ }
2815
+ function text(value, biome, field) {
2816
+ if (typeof value !== "string" || value.trim() === "")
2817
+ fail2(biome, field, "must be a non-empty string");
2818
+ return value;
2819
+ }
2820
+ function oneOf(value, biome, field, options) {
2821
+ if (typeof value !== "string" || !options.includes(value))
2822
+ fail2(biome, field, `must be one of ${options.join(", ")}`);
2823
+ return value;
2824
+ }
2825
+ function intervalOf(value, biome, field, size, min = 0, max = Number.POSITIVE_INFINITY) {
2826
+ if (!Array.isArray(value) || value.length !== size)
2827
+ fail2(biome, field, `must be an array of ${size} numbers`);
2828
+ const numbers = value.map((entry2, index) => count(entry2, biome, `${field}[${index}]`, min));
2829
+ if (numbers[0] > numbers[1])
2830
+ fail2(biome, field, "must ascend");
2831
+ for (const [index, entry2] of numbers.entries())
2832
+ if (entry2 > max) fail2(biome, `${field}[${index}]`, `must be at most ${max}`);
2833
+ return numbers;
2834
+ }
2835
+ function band(value, biome, field) {
2836
+ if (!Array.isArray(value) || value.length !== 2)
2837
+ fail2(biome, field, "must be an array of 2 numbers");
2838
+ const [threshold = 0, span = 0] = value.map(
2839
+ (entry2, index) => share(entry2, biome, `${field}[${index}]`)
2840
+ );
2841
+ if (span === 0) fail2(biome, `${field}[1]`, "must be greater than 0");
2842
+ return [threshold, span];
2843
+ }
2844
+ function pair(value, biome, field, min = 0, max = Number.POSITIVE_INFINITY) {
2845
+ const [first = 0, second = 0] = intervalOf(value, biome, field, 2, min, max);
2846
+ return [first, second];
2847
+ }
2848
+ function pointOf(value, biome, field, size) {
2849
+ if (!Array.isArray(value) || value.length !== size)
2850
+ fail2(biome, field, `must be an array of ${size} numbers`);
2851
+ return value.map((entry2, index) => {
2852
+ if (typeof entry2 !== "number" || !Number.isFinite(entry2))
2853
+ fail2(biome, `${field}[${index}]`, "must be a finite number");
2854
+ return entry2 ?? 0;
2855
+ });
2856
+ }
2857
+ function point2(value, biome, field) {
2858
+ const [x = 0, z = 0] = pointOf(value, biome, field, 2);
2859
+ return [x, z];
2860
+ }
2861
+ function point3(value, biome, field) {
2862
+ const [x = 0, y = 0, z = 0] = pointOf(value, biome, field, 3);
2863
+ return [x, y, z];
2864
+ }
2865
+ function far(value, biome, field) {
2866
+ if (value === null) return null;
2867
+ const far2 = closed(value, biome, field, FAR_FIELDS);
2868
+ return {
2869
+ cell: positive(far2.cell, biome, `${field}.cell`),
2870
+ spacing: pair(far2.spacing, biome, `${field}.spacing`),
2871
+ spacingAt: pair(far2.spacingAt, biome, `${field}.spacingAt`),
2872
+ slope: pair(far2.slope, biome, `${field}.slope`, 0, 90),
2873
+ meadowSlope: pair(far2.meadowSlope, biome, `${field}.meadowSlope`, 0, 90),
2874
+ reach: positive(far2.reach, biome, `${field}.reach`),
2875
+ treelineJitter: count(far2.treelineJitter, biome, `${field}.treelineJitter`),
2876
+ stand: pair(far2.stand, biome, `${field}.stand`, 0, 1),
2877
+ seed: whole(far2.seed, biome, `${field}.seed`),
2878
+ impostor: count(far2.impostor, biome, `${field}.impostor`)
2879
+ };
2880
+ }
2881
+ function frequencies(value, biome, field) {
2882
+ const [x = 0, z = 0] = pointOf(value, biome, field, 2);
2883
+ if (x <= 0 || z <= 0) fail2(biome, field, "must be two positive frequencies");
2884
+ return [x, z];
2885
+ }
2886
+ function driftRow(value, biome, field) {
2887
+ const row = closed(value, biome, field, DRIFT_FIELDS);
2888
+ return {
2889
+ field: oneOf(row.field, biome, `${field}.field`, DRIFT_FIELDS_NAMES),
2890
+ frequency: frequencies(row.frequency, biome, `${field}.frequency`),
2891
+ offset: share(row.offset, biome, `${field}.offset`),
2892
+ amplitude: share(row.amplitude, biome, `${field}.amplitude`),
2893
+ band: band(row.band, biome, `${field}.band`)
2894
+ };
2895
+ }
2896
+ function clearing(value, biome, field) {
2897
+ if (!Array.isArray(value) || value.length !== 3)
2898
+ fail2(biome, field, "must be an array of 3 numbers");
2899
+ const [x = 0, z = 0, radius = 0] = pointOf(value, biome, field, 3);
2900
+ if (radius <= 0) fail2(biome, `${field}[2]`, "must be greater than 0");
2901
+ return [x, z, radius];
2902
+ }
2903
+ function understorey(value, biome) {
2904
+ const row = closed(value, biome, "cover.understorey", UNDERSTOREY_FIELDS);
2905
+ return {
2906
+ attempts: whole(row.attempts, biome, "cover.understorey.attempts"),
2907
+ litter: count(row.litter, biome, "cover.understorey.litter"),
2908
+ fern: count(row.fern, biome, "cover.understorey.fern"),
2909
+ bush: count(row.bush, biome, "cover.understorey.bush"),
2910
+ flower: count(row.flower, biome, "cover.understorey.flower"),
2911
+ deadfall: count(row.deadfall, biome, "cover.understorey.deadfall"),
2912
+ shade: share(row.shade, biome, "cover.understorey.shade"),
2913
+ shadeRadius: count(row.shadeRadius, biome, "cover.understorey.shadeRadius")
2914
+ };
2915
+ }
2916
+ function cover(value, biome) {
2917
+ const row = closed(value, biome, "cover", COVER_FIELDS);
2918
+ const clearings = row.clearings;
2919
+ if (!Array.isArray(clearings)) fail2(biome, "cover.clearings", "must be an array");
2920
+ return {
2921
+ ground: oneOf(row.ground, biome, "cover.ground", COVER_GROUNDS),
2922
+ seed: whole(row.seed, biome, "cover.seed"),
2923
+ attempts: whole(row.attempts, biome, "cover.attempts", 1),
2924
+ stoneRadius: positive(row.stoneRadius, biome, "cover.stoneRadius"),
2925
+ clearings: clearings.map((entry2, index) => clearing(entry2, biome, `cover.clearings[${index}]`)),
2926
+ understorey: understorey(row.understorey, biome)
2927
+ };
2928
+ }
2929
+ function foliage(value, biome, field) {
2930
+ const row = closed(value, biome, field, FOLIAGE_FIELDS);
2931
+ const height = row.height === null ? null : pair(row.height, biome, `${field}.height`);
2932
+ return {
2933
+ species: text(row.species, biome, `${field}.species`),
2934
+ density: count(row.density, biome, `${field}.density`),
2935
+ slope: pair(row.slope, biome, `${field}.slope`, 0, 90),
2936
+ height,
2937
+ spacing: pair(row.spacing, biome, `${field}.spacing`),
2938
+ collision: oneOf(row.collision, biome, `${field}.collision`, COLLISION_CLASSES),
2939
+ stands: flag(row.stands, biome, `${field}.stands`),
2940
+ grassThreshold: share(row.grassThreshold, biome, `${field}.grassThreshold`),
2941
+ standThreshold: share(row.standThreshold, biome, `${field}.standThreshold`),
2942
+ far: far(row.far, biome, `${field}.far`)
2943
+ };
2944
+ }
2945
+ function grass(value, biome, field) {
2946
+ const row = closed(value, biome, field, GRASS_FIELDS);
2947
+ const density = count(row.density, biome, `${field}.density`);
2948
+ if (density > 1) fail2(biome, `${field}.density`, "must be at most 1");
2949
+ return {
2950
+ species: text(row.species, biome, `${field}.species`),
2951
+ density,
2952
+ slope: pair(row.slope, biome, `${field}.slope`, 0, 90),
2953
+ height: row.height === null ? null : pair(row.height, biome, `${field}.height`),
2954
+ spacing: positive(row.spacing, biome, `${field}.spacing`),
2955
+ slopeFalloff: count(row.slopeFalloff, biome, `${field}.slopeFalloff`),
2956
+ heightFalloff: count(row.heightFalloff, biome, `${field}.heightFalloff`),
2957
+ mats: row.mats === null ? null : band(row.mats, biome, `${field}.mats`),
2958
+ waterMargin: count(row.waterMargin, biome, `${field}.waterMargin`),
2959
+ beach: row.beach === null ? null : pair(row.beach, biome, `${field}.beach`),
2960
+ detailSpacing: positive(row.detailSpacing, biome, `${field}.detailSpacing`),
2961
+ drift: driftRow(row.drift, biome, `${field}.drift`),
2962
+ bladeScale: count(row.bladeScale, biome, `${field}.bladeScale`),
2963
+ bladeJitter: count(row.bladeJitter, biome, `${field}.bladeJitter`),
2964
+ scrubChance: share(row.scrubChance, biome, `${field}.scrubChance`),
2965
+ scrubScale: count(row.scrubScale, biome, `${field}.scrubScale`),
2966
+ scrubJitter: count(row.scrubJitter, biome, `${field}.scrubJitter`),
2967
+ scrubBush: flag(row.scrubBush, biome, `${field}.scrubBush`),
2968
+ shoreGround: flag(row.shoreGround, biome, `${field}.shoreGround`),
2969
+ cobbledBed: flag(row.cobbledBed, biome, `${field}.cobbledBed`)
2970
+ };
2971
+ }
2972
+ function layer(value, biome, field) {
2973
+ const row = closed(value, biome, field, LAYER_FIELDS, LAYER_REQUIRED);
2974
+ const from = count(row.from, biome, `${field}.from`);
2975
+ const to = count(row.to, biome, `${field}.to`);
2976
+ if (from >= to) fail2(biome, field, "must end above where it starts");
2977
+ const shedFrom = row.shedFrom === void 0 ? void 0 : count(row.shedFrom, biome, `${field}.shedFrom`, 0);
2978
+ const shedTo = row.shedTo === void 0 ? void 0 : count(row.shedTo, biome, `${field}.shedTo`, 0);
2979
+ for (const [key, entry2] of [
2980
+ ["shedFrom", shedFrom],
2981
+ ["shedTo", shedTo]
2982
+ ])
2983
+ if (entry2 !== void 0 && entry2 > 1) fail2(biome, `${field}.${key}`, "must be at most 1");
2984
+ if (shedFrom !== void 0 && shedTo !== void 0 && shedFrom >= shedTo)
2985
+ fail2(biome, field, "must shed from a gentler slope than it sheds to");
2986
+ return {
2987
+ layer: text(row.layer, biome, `${field}.layer`),
2988
+ from,
2989
+ to,
2990
+ shedFrom,
2991
+ shedTo
2992
+ };
2993
+ }
2994
+ function water(value, biome, field) {
2995
+ const row = closed(value, biome, field, WATER_FIELDS, WATER_REQUIRED);
2996
+ const kind = oneOf(row.kind, biome, `${field}.kind`, WATER_KINDS);
2997
+ const width = row.width === void 0 ? void 0 : positive(row.width, biome, `${field}.width`);
2998
+ const radius = row.radius === void 0 ? void 0 : positive(row.radius, biome, `${field}.radius`);
2999
+ const depth = row.depth === void 0 ? void 0 : positive(row.depth, biome, `${field}.depth`);
3000
+ const level = row.level === void 0 ? void 0 : count(row.level, biome, `${field}.level`);
3001
+ if (kind === "river" && width === void 0) fail2(biome, `${field}.width`, "is missing");
3002
+ if (kind === "lake" && radius === void 0) fail2(biome, `${field}.radius`, "is missing");
3003
+ if (kind === "ocean" && level === void 0) fail2(biome, `${field}.level`, "is missing");
3004
+ return { kind, width, radius, depth, level };
3005
+ }
3006
+ function bake(value, biome) {
3007
+ const row = closed(value, biome, "bake", BAKE_FIELDS);
3008
+ return {
3009
+ file: text(row.file, biome, "bake.file"),
3010
+ key: row.key === null ? null : text(row.key, biome, "bake.key")
3011
+ };
3012
+ }
3013
+ function spawn2(value, biome) {
3014
+ const row = closed(value, biome, "spawn", SPAWN_FIELDS);
3015
+ return {
3016
+ at: point2(row.at, biome, "spawn.at"),
3017
+ cameraOffset: point3(row.cameraOffset, biome, "spawn.cameraOffset"),
3018
+ focus: point2(row.focus, biome, "spawn.focus")
3019
+ };
3020
+ }
3021
+ function species(value, biome) {
3022
+ if (!Array.isArray(value) || value.length === 0)
3023
+ fail2(biome, "species", "must be a non-empty array of asset ids");
3024
+ const names = value.map((name, index) => text(name, biome, `species[${index}]`));
3025
+ for (const [index, name] of names.entries())
3026
+ if (names.indexOf(name) !== index) fail2(biome, `species[${index}]`, `repeats '${name}'`);
3027
+ return names;
3028
+ }
3029
+ function validateBiome(spec, name) {
3030
+ if (typeof name !== "string" || name.trim() === "")
3031
+ throw new TypeError("validateBiome needs the biome's name");
3032
+ const biome = name;
3033
+ const root = closed(spec, biome, "", SPEC_FIELDS);
3034
+ const aliases = root.aliases;
3035
+ if (!Array.isArray(aliases) || aliases.length === 0)
3036
+ fail2(biome, "aliases", "must be a non-empty array of words");
3037
+ const rows = (value, field, one) => {
3038
+ if (!Array.isArray(value)) fail2(biome, field, "must be an array");
3039
+ return value.map((entry2, index) => one(entry2, `${field}[${index}]`));
3040
+ };
3041
+ return {
3042
+ look: text(root.look, biome, "look"),
3043
+ bake: bake(root.bake, biome),
3044
+ landform: oneOf(root.landform, biome, "landform", LANDFORM_KINDS),
3045
+ sizeMeters: positive(root.sizeMeters, biome, "sizeMeters"),
3046
+ seed: whole(root.seed, biome, "seed"),
3047
+ stream: oneOf(root.stream, biome, "stream", STREAMS),
3048
+ cover: cover(root.cover, biome),
3049
+ foliage: rows(root.foliage, "foliage", (entry2, at) => foliage(entry2, biome, at)),
3050
+ grass: rows(root.grass, "grass", (entry2, at) => grass(entry2, biome, at)),
3051
+ layers: rows(root.layers, "layers", (entry2, at) => layer(entry2, biome, at)),
3052
+ water: rows(root.water, "water", (entry2, at) => water(entry2, biome, at)),
3053
+ spawn: spawn2(root.spawn, biome),
3054
+ species: species(root.species, biome),
3055
+ aliases: aliases.map(
3056
+ (word, index) => text(word, biome, `aliases[${index}]`).toLowerCase()
3057
+ )
3058
+ };
3059
+ }
3060
+
3061
+ // src/core/request-words.ts
3062
+ var LANDFORM_WORD_ROWS = [
3063
+ // First: a volcano is the more specific shape, so "a volcanic island" is a volcano in the sea.
3064
+ ["volcanic", ["volcano", "volcanoes", "volcanic"]],
3065
+ ["alpine", ["alpine", "alps", "mountain", "mountains", "peaks"]],
3066
+ ["temperateMountains", ["foothills", "valley", "valleys"]],
3067
+ ["rollingHills", ["hill", "hills", "rolling"]],
3068
+ ["desertMesa", ["butte", "buttes", "canyon", "canyons", "mesa", "mesas"]],
3069
+ [
3070
+ "coastalCliffs",
3071
+ ["cliff", "cliffs", "coast", "coastal", "fjord", "fjords", "island", "islands"]
3072
+ ],
3073
+ ["tundra", ["arctic", "tundra"]]
3074
+ ];
3075
+ var WATER_WORD_ROWS = [
3076
+ [{ kind: "river", width: 5.32 }, ["creek", "creeks", "river", "rivers", "stream", "streams"]],
3077
+ [{ kind: "lake", radius: 105 }, ["lake", "lakes", "pond", "ponds"]],
3078
+ [
3079
+ { kind: "ocean", level: 1.5 },
3080
+ ["fjord", "fjords", "island", "islands", "ocean", "oceans", "sea", "seas"]
3081
+ ]
3082
+ ];
3083
+ var LANDFORM_BIOME = {
3084
+ alpine: "alpine",
3085
+ temperateMountains: "forest",
3086
+ rollingHills: "forest",
3087
+ desertMesa: "desert",
3088
+ coastalCliffs: "coastal",
3089
+ tundra: "tundra",
3090
+ volcanic: "alpine"
3091
+ };
3092
+ var DEFAULT_BIOME = "forest";
3093
+ var FEATURE_WORD_ROWS = [
3094
+ ["canyon", ["canyon", "canyons", "gorge", "gorges", "ravine", "ravines"]],
3095
+ ["fjord", ["fjord", "fjords", "inlet", "inlets"]]
3096
+ ];
3097
+ var SIZE_WORD_ROWS = [
3098
+ [2, ["big", "huge", "large"]],
3099
+ [0.5, ["small", "tiny"]]
3100
+ ];
3101
+ var BIOME_OWN = {
3102
+ alpine: { landform: "alpine", sizeMeters: 512, water: [] },
3103
+ coastal: { landform: "coastalCliffs", sizeMeters: 512, water: [{ kind: "ocean", level: 1.5 }] },
3104
+ desert: { landform: "desertMesa", sizeMeters: 512, water: [] },
3105
+ forest: {
3106
+ landform: "temperateMountains",
3107
+ sizeMeters: 512,
3108
+ water: [
3109
+ { kind: "river", width: 5.32 },
3110
+ { kind: "lake", radius: 105 }
3111
+ ]
3112
+ },
3113
+ tundra: {
3114
+ landform: "tundra",
3115
+ sizeMeters: 512,
3116
+ water: [
3117
+ { kind: "river", width: 5.32 },
3118
+ { kind: "river", width: 3.04 },
3119
+ { kind: "lake", radius: 34 },
3120
+ { kind: "lake", radius: 46 }
3121
+ ]
3122
+ }
3123
+ };
3124
+ var REQUEST_STOP_WORDS = /* @__PURE__ */ new Set([
3125
+ "a",
3126
+ "an",
3127
+ "and",
3128
+ "create",
3129
+ "for",
3130
+ "game",
3131
+ "in",
3132
+ "like",
3133
+ "make",
3134
+ "me",
3135
+ "of",
3136
+ "on",
3137
+ "some",
3138
+ "terrain",
3139
+ "the",
3140
+ "with",
3141
+ "world"
3142
+ ]);
3143
+ var BACKDROP_WORDS = [
3144
+ "under",
3145
+ "below",
3146
+ "beneath",
3147
+ "behind",
3148
+ "among",
3149
+ "beside"
3150
+ ];
3151
+ var REQUEST_KNOWN_WORDS = /* @__PURE__ */ new Set([
3152
+ ...[
3153
+ ...BIOME_WORD_ROWS,
3154
+ ...LANDFORM_WORD_ROWS,
3155
+ ...WATER_WORD_ROWS,
3156
+ ...SIZE_WORD_ROWS,
3157
+ ...FEATURE_WORD_ROWS
3158
+ ].flatMap(([, names]) => names),
3159
+ ...BACKDROP_WORDS
3160
+ ]);
3161
+
3162
+ // src/core/surveys.ts
3163
+ var TILES = "AWS Terrain Tiles (github.com/tilezen/joerd, Mapzen terrain tiles).";
3164
+ var USGS_3DEP = "United States 3DEP (formerly NED) terrain data courtesy of the U.S. Geological Survey.";
3165
+ var SRTM = "SRTM data courtesy of the U.S. Geological Survey.";
3166
+ var MASSIFS = {
3167
+ temperateMountains: [
3168
+ {
3169
+ name: "Longs Peak and Mount Meeker, Rocky Mountain National Park, Colorado",
3170
+ lat: 40.2549,
3171
+ lon: -105.6101,
3172
+ extentMeters: 4400,
3173
+ zoom: 12,
3174
+ attribution: `${USGS_3DEP} ${TILES}`
3175
+ }
3176
+ ],
3177
+ alpine: [
3178
+ {
3179
+ name: "Grand Teton and the Cathedral Group, Wyoming",
3180
+ lat: 43.7455,
3181
+ lon: -110.8024,
3182
+ extentMeters: 3600,
3183
+ zoom: 12,
3184
+ attribution: `${USGS_3DEP} ${TILES}`
3185
+ },
3186
+ {
3187
+ name: "Maroon Bells, Elk Mountains, Colorado",
3188
+ lat: 39.0708,
3189
+ lon: -106.989,
3190
+ extentMeters: 3600,
3191
+ zoom: 12,
3192
+ attribution: `${USGS_3DEP} ${TILES}`
3193
+ }
3194
+ ]
3195
+ };
3196
+ var LOCATION_EXTENT_METERS = 6e3;
3197
+ var LOCATION_ZOOM = 12;
3198
+ var finite = (value, axis) => {
3199
+ if (!Number.isFinite(value))
3200
+ throw new TypeError(`ground.location.${axis} must be a finite number.`);
3201
+ return value;
3202
+ };
3203
+ function locationSurvey(lat, lon) {
3204
+ const latitude = finite(lat, "lat");
3205
+ const longitude = finite(lon, "lon");
3206
+ if (Math.abs(latitude) > 90)
3207
+ throw new RangeError("ground.location.lat must be between -90 and 90.");
3208
+ if (Math.abs(longitude) > 180)
3209
+ throw new RangeError("ground.location.lon must be between -180 and 180.");
3210
+ return {
3211
+ name: `${latitude}, ${longitude}`,
3212
+ lat: latitude,
3213
+ lon: longitude,
3214
+ extentMeters: LOCATION_EXTENT_METERS,
3215
+ zoom: LOCATION_ZOOM,
3216
+ attribution: `${SRTM} ${TILES}`
3217
+ };
3218
+ }
3219
+
3220
+ // src/mcp/tools.ts
3221
+ var PATCH_OPS = ["upsert", "update", "remove", "move", "toggle"];
3222
+ var GROUND_SCHEMA = {
3223
+ description: 'Where the ground comes from. "procedural" keeps the landform preset\'s own noise; { heightmap } names a 16-bit grayscale PNG or a square .r16 file (min and max in metres, needed when the file carries no range); { location } cuts a survey at that latitude and longitude. Omitted, a landform preset is grounded on the real survey its kind names, and the result reports it as `ground` with its attribution.',
3224
+ anyOf: [
3225
+ { type: "string", enum: ["procedural"] },
3226
+ {
3227
+ type: "object",
3228
+ properties: {
3229
+ heightmap: {
3230
+ type: "string",
3231
+ description: "Path to a .png or .r16 height file, relative to the project."
3232
+ },
3233
+ min: { type: "number", description: "Lowest elevation in the file, metres." },
3234
+ max: { type: "number", description: "Highest elevation in the file, metres." }
3235
+ },
3236
+ required: ["heightmap"],
3237
+ additionalProperties: false
3238
+ },
3239
+ {
3240
+ type: "object",
3241
+ properties: {
3242
+ location: {
3243
+ type: "object",
3244
+ properties: { lat: { type: "number" }, lon: { type: "number" } },
3245
+ required: ["lat", "lon"],
3246
+ additionalProperties: false
3247
+ }
3248
+ },
3249
+ required: ["location"],
3250
+ additionalProperties: false
3251
+ }
3252
+ ]
3253
+ };
3254
+ var TERRAIN_TOOLS = [
3255
+ {
3256
+ name: "terrain_generate",
3257
+ description: "Choose from a request, an explicit kit or a biome and cook one editable starter terrain kit (forest, coastal, alpine, desert or tundra) into a world.glb; `biome` names a starter or one of its alias words, or carries an inline IBiomeSpec whose own landform, size and seed build the ground; `landform` swaps the ground for one of the seven shape presets (alpine, temperateMountains, rollingHills, desertMesa, coastalCliffs, tundra, volcanic) and keeps the kit's surface and assets; `water` replaces the water bodies the biome declares and changes the cooked world: an ocean row floods to its level, a river or lake row re-shapes the recipe's own river or lake in order (width or radius), a recipe layer with no row is removed, and a river or lake row with no layer to take it fails. A `request`'s words also decide the landform (mountains, hills, mesa, cliffs, volcano), the water (river, lake, island, ocean), the features carved into any ground (canyon, gorge, ravine: a steep cut across it; fjord, inlet: a sea inlet into the land) and the size (huge, small: the biome's own size scaled); an explicit `landform`, `water` or `sizeMeters` wins over a word. A landform preset's ground is a real survey of the place its kind names, fetched from the AWS terrain tiles, resampled onto the recipe's grid, cooked with the attribution its source requires, and reported as `ground`; the preset's erosion and grain still run on top of it. `ground` replaces that choice: \"procedural\" cooks the preset's own noise, { heightmap } reads a 16-bit grayscale PNG or a square .r16 grid, { location } cuts a survey at a latitude and longitude. An alpine or temperateMountains world on a survey also writes ring.json, its survey continued to ten times the world's size with one real whole mountain from that range past the square, reported as `backdrop`; `backdrop: \"none\"` cooks none. The result's `decided` names each choice with the word behind it or `argument`, and `unused` lists the request words that named nothing. A request that names only a starter (no shape, water, feature, size, seed or ground of its own) is that starter as shipped, judged and measured, reported as `source: \"catalog:<kit>\"`; anything else is `\"cooked\"`. The reply's `seed` is the seed the world was cooked with: pass another `seed` for a variation of the same request. A request repeated in the same project is copied from its cook cache (`node_modules/.cache/threenative-terrain`) and reported as `cache: \"hit\"`. Returns the kit as recipe, the biome it bakes, the water bodies the cooked world floods, measured from the evaluated state as `water.json` records them, its band rows resolved against the cooked heights (`bands`), the world.glb, recipe.json and world.json paths, triangles, instances and draws measured from the produced GLB's default scene, and a ctx.assets.model load snippet. triangles counts every instance of the LOD0 default scene in full, before distance LOD and culling, instances sums the EXT_mesh_gpu_instancing instances, and draws counts primitives across instanced and non-instanced meshes, an instanced primitive counting once.",
3258
+ inputSchema: {
3259
+ type: "object",
3260
+ properties: {
3261
+ kit: { type: "string", enum: [...TERRAIN_KITS] },
3262
+ biome: {
3263
+ description: "A starter biome's name or alias word (forest, woods, beach, ...), or an inline IBiomeSpec object; a spec cooks with `kit`'s surface and assets, forest's when kit is absent.",
3264
+ anyOf: [{ type: "string", minLength: 1 }, { type: "object" }]
3265
+ },
3266
+ landform: { type: "string", enum: Object.keys(LANDFORMS) },
3267
+ request: {
3268
+ type: "string",
3269
+ minLength: 1,
3270
+ description: "What the world should be, in any words: a biome, a landform (mountains, hills, canyon, volcano, fjord, ...), water (river, lake, sea, ...) and a size (huge, small); an explicit argument wins over a word. A request with no biome word takes the biome its sea or shape suits, else the forest; `decided` names the word behind each choice and `unused` the words that named nothing. A real place's name is not geocoded: pass its latitude and longitude as `ground: { location }` to cook that place's survey."
3271
+ },
3272
+ sizeMeters: { type: "number", exclusiveMinimum: 0 },
3273
+ seed: { type: "integer" },
3274
+ water: {
3275
+ type: "array",
3276
+ items: { type: "object" },
3277
+ description: "IBiomeWaterBody rows that replace the biome's declared water: river (width), lake (radius), ocean (level)."
3278
+ },
3279
+ ground: GROUND_SCHEMA,
3280
+ backdrop: {
3281
+ type: "string",
3282
+ enum: ["none"],
3283
+ description: `"none" cooks no far ring. Omitted, an alpine or temperateMountains world on a survey gets ring.json: its survey continued to ten times the world's size, with one real whole mountain (a seeded pick, pose and height) standing past the playable square.`
3284
+ },
3285
+ out: {
3286
+ type: "string",
3287
+ description: "Relative directory under the project's assets.source that must not exist yet; the default is assets.source/worlds/<kit>."
3288
+ }
3289
+ },
3290
+ anyOf: [{ required: ["request"] }, { required: ["kit"] }, { required: ["biome"] }],
3291
+ additionalProperties: false
3292
+ }
3293
+ },
3294
+ {
3295
+ name: "terrain_biome_new",
3296
+ description: "Make a new biome from a shipped one and cook it: copies the base biome's biome.data.json into <assets.source>/biomes/<name>/, applies the overrides, validates the file with validateBiome, then cooks it with the base kit's surface and assets and the biome's own landform preset. One call writes only under <assets.source>/biomes/<name>/, its cooked world included. Its ground comes from the biome's landform, the real survey that kind names unless `ground` names another source. Returns the same cook result as terrain_generate plus the biome file path and the biome's resolved `bands`. No code changes anywhere: the biome is data.",
3297
+ inputSchema: {
3298
+ type: "object",
3299
+ properties: {
3300
+ from: { type: "string", enum: [...TERRAIN_KITS] },
3301
+ name: {
3302
+ type: "string",
3303
+ pattern: "^[a-z][a-z0-9-]{0,31}$",
3304
+ description: "The new biome's folder and look name; lowercase, no spaces."
3305
+ },
3306
+ overrides: {
3307
+ type: "object",
3308
+ description: "IBiomeSpec fields to change on the base file (landform, foliage, grass, layers, water, spawn, species, aliases, bake). An unknown field fails."
3309
+ },
3310
+ ground: GROUND_SCHEMA,
3311
+ out: {
3312
+ type: "string",
3313
+ description: "Relative directory under the project's assets.source that must not exist yet; the default is assets.source/biomes/<name>/world."
3314
+ }
3315
+ },
3316
+ required: ["from", "name"],
3317
+ additionalProperties: false
3318
+ }
3319
+ },
3320
+ {
3321
+ name: "terrain_patch",
3322
+ description: "Apply editor commands (upsert, update, remove, move, toggle) to a terrain recipe and return the edited recipe.",
3323
+ inputSchema: {
3324
+ type: "object",
3325
+ properties: {
3326
+ recipe: { type: "object" },
3327
+ commands: { type: "array", items: { type: "object" } }
3328
+ },
3329
+ required: ["recipe", "commands"],
3330
+ additionalProperties: false
3331
+ }
3332
+ }
3333
+ ];
3334
+ function isRecord(value) {
3335
+ return typeof value === "object" && value !== null && !Array.isArray(value);
3336
+ }
3337
+ function closedRecord(input, tool, fields) {
3338
+ if (!isRecord(input)) throw new TypeError(`${tool}: arguments must be an object.`);
3339
+ for (const key of Object.keys(input)) {
3340
+ if (!fields.includes(key)) throw new TypeError(`${tool}: unknown field '${key}'.`);
3341
+ }
3342
+ return input;
3343
+ }
3344
+ function relativeDirectory(out) {
3345
+ if (typeof out !== "string" || out.trim() === "" || isAbsolute(out) || out.split(/[\\/]/).includes("..")) {
3346
+ throw new TypeError("terrain_generate: out must be a relative directory inside the project.");
3347
+ }
3348
+ return out;
3349
+ }
3350
+ var GENERATE_FIELDS = [
3351
+ "request",
3352
+ "kit",
3353
+ "biome",
3354
+ "landform",
3355
+ "sizeMeters",
3356
+ "seed",
3357
+ "water",
3358
+ "ground",
3359
+ "backdrop",
3360
+ "out"
3361
+ ];
3362
+ var BIOME_NEW_FIELDS = ["from", "name", "overrides", "ground", "out"];
3363
+ var LANDFORM_KINDS2 = Object.keys(LANDFORMS);
3364
+ function parseBiomeArgument(biome) {
3365
+ if (biome === void 0) return {};
3366
+ if (typeof biome === "string") {
3367
+ const word = biome.trim().toLowerCase();
3368
+ const kit = BIOME_WORD_ROWS.find(([, names]) => names.includes(word))?.[0];
3369
+ if (kit === void 0) {
3370
+ throw new TypeError(
3371
+ `terrain_generate: biome '${biome}' matches no biome. Try one of: ${biomeWordList()}.`
3372
+ );
3373
+ }
3374
+ return { kit };
3375
+ }
3376
+ if (isRecord(biome)) {
3377
+ const look = biome.look;
3378
+ return { spec: validateBiome(biome, typeof look === "string" ? look : "biome") };
3379
+ }
3380
+ throw new TypeError(
3381
+ "terrain_generate: biome must be a starter name, an alias word or a biome spec object."
3382
+ );
3383
+ }
3384
+ function parseLandform(value) {
3385
+ if (value === void 0) return void 0;
3386
+ if (!LANDFORM_KINDS2.includes(value))
3387
+ throw new TypeError(`terrain_generate: landform must be one of ${LANDFORM_KINDS2.join(", ")}.`);
3388
+ return value;
3389
+ }
3390
+ function parseSize(value) {
3391
+ if (value === void 0) return void 0;
3392
+ if (typeof value !== "number" || !Number.isFinite(value) || value <= 0)
3393
+ throw new TypeError("terrain_generate: sizeMeters must be a positive finite number.");
3394
+ return value;
3395
+ }
3396
+ function parseWater(water2) {
3397
+ if (water2 === void 0) return void 0;
3398
+ if (!Array.isArray(water2) || water2.some((body) => !isRecord(body))) {
3399
+ throw new TypeError("terrain_generate: water must be an array of water body objects.");
3400
+ }
3401
+ return water2;
3402
+ }
3403
+ function parseGround(value, tool) {
3404
+ if (value === void 0) return void 0;
3405
+ if (value === "procedural") return "procedural";
3406
+ const forms = `${tool}: ground must be "procedural", { heightmap } or { location }.`;
3407
+ if (!isRecord(value)) throw new TypeError(forms);
3408
+ for (const key of Object.keys(value)) {
3409
+ if (!["heightmap", "location", "min", "max"].includes(key)) {
3410
+ throw new TypeError(`${tool}: ground field '${key}' is not a ground source.`);
3411
+ }
3412
+ }
3413
+ const { heightmap, location, min, max } = value;
3414
+ if (heightmap !== void 0) {
3415
+ if (typeof heightmap !== "string" || !/\.(png|r16)$/iu.test(heightmap)) {
3416
+ throw new TypeError(`${tool}: ground.heightmap must name a .png or .r16 file.`);
3417
+ }
3418
+ if (min === void 0 !== (max === void 0)) {
3419
+ throw new TypeError(`${tool}: ground.heightmap needs min and max together, in metres.`);
3420
+ }
3421
+ if (min !== void 0 && max !== void 0) {
3422
+ if (typeof min !== "number" || typeof max !== "number" || !Number.isFinite(min) || !Number.isFinite(max))
3423
+ throw new TypeError(`${tool}: ground.heightmap min and max must be finite metres.`);
3424
+ if (max <= min) throw new TypeError(`${tool}: ground.heightmap max must exceed min.`);
3425
+ return { heightmap, min, max };
3426
+ }
3427
+ return { heightmap };
3428
+ }
3429
+ if (location !== void 0) {
3430
+ if (!isRecord(location) || Object.keys(location).some((key) => !["lat", "lon"].includes(key))) {
3431
+ throw new TypeError(`${tool}: ground.location must be { lat, lon }.`);
3432
+ }
3433
+ const { lat, lon } = location;
3434
+ if (typeof lat !== "number" || typeof lon !== "number") {
3435
+ throw new TypeError(`${tool}: ground.location lat and lon must be numbers.`);
3436
+ }
3437
+ locationSurvey(lat, lon);
3438
+ return { location: { lat, lon } };
3439
+ }
3440
+ throw new TypeError(forms);
3441
+ }
3442
+ function backdropWordAt(words, word) {
3443
+ const at = words.indexOf(word);
3444
+ const before = words[at - 1] === "the" ? words[at - 2] : words[at - 1];
3445
+ return before !== void 0 && BACKDROP_WORDS.includes(before);
3446
+ }
3447
+ function rowHit(rows, words) {
3448
+ for (const [row, names] of rows) {
3449
+ const word = words.find((candidate) => names.includes(candidate));
3450
+ if (word !== void 0) return { row, word };
3451
+ }
3452
+ return void 0;
3453
+ }
3454
+ function declaredWater(rows, row) {
3455
+ return rows.some(
3456
+ (own) => own.kind === row.kind && own.width === row.width && own.radius === row.radius && own.level === row.level
3457
+ );
3458
+ }
3459
+ function parseGenerateRequest(input) {
3460
+ const args = closedRecord(input, "terrain_generate", GENERATE_FIELDS);
3461
+ const { request, sizeMeters, seed, out } = args;
3462
+ if (request !== void 0 && (typeof request !== "string" || request.trim() === "")) {
3463
+ throw new TypeError("terrain_generate: request must be a non-empty string.");
3464
+ }
3465
+ if (request === void 0 && args.kit === void 0 && args.biome === void 0) {
3466
+ throw new TypeError("terrain_generate: give a request, a kit or a biome.");
3467
+ }
3468
+ const words = typeof request === "string" ? request.toLowerCase().split(/[^a-z]+/u) : [];
3469
+ const { kit: biomeKit, spec } = parseBiomeArgument(args.biome);
3470
+ const biomeWord = rowHit(BIOME_WORD_ROWS, words);
3471
+ const arguedKit = args.kit ?? biomeKit;
3472
+ let inferred;
3473
+ if (arguedKit === void 0 && spec === void 0 && biomeWord === void 0) {
3474
+ const sea = rowHit(
3475
+ WATER_WORD_ROWS.filter(([row]) => row.kind === "ocean"),
3476
+ words
3477
+ );
3478
+ const shape = rowHit(LANDFORM_WORD_ROWS, words);
3479
+ if (sea !== void 0) inferred = { kit: "coastal", word: sea.word };
3480
+ else if (shape !== void 0 && !backdropWordAt(words, shape.word))
3481
+ inferred = { kit: LANDFORM_BIOME[shape.row], word: shape.word };
3482
+ }
3483
+ const kit = arguedKit ?? // A spec carries no appearance, so it cooks with the forest starter's surface and assets.
3484
+ (spec === void 0 ? biomeWord?.row ?? inferred?.kit ?? DEFAULT_BIOME : "forest");
3485
+ if (typeof kit !== "string" || !TERRAIN_KITS.includes(kit)) {
3486
+ throw new TypeError(
3487
+ `terrain_generate: kit must be one of ${TERRAIN_KITS.join(", ")}. Words a request may use: ${biomeWordList()}.`
3488
+ );
3489
+ }
3490
+ const parsed = { kit };
3491
+ if (spec !== void 0) parsed.spec = spec;
3492
+ const own = BIOME_OWN[kit];
3493
+ const landformArgument = parseLandform(args.landform);
3494
+ const landformWord = rowHit(LANDFORM_WORD_ROWS, words);
3495
+ let landform;
3496
+ if (landformArgument !== void 0) {
3497
+ parsed.landform = landformArgument;
3498
+ landform = { value: landformArgument, source: "argument" };
3499
+ } else if (spec !== void 0) {
3500
+ landform = { value: spec.landform, source: "argument" };
3501
+ } else if (landformWord === void 0) {
3502
+ landform = { value: null, source: "default" };
3503
+ } else if (backdropWordAt(words, landformWord.word)) {
3504
+ parsed.landform = own.landform;
3505
+ parsed.backdropRange = landformWord.row;
3506
+ landform = { value: own.landform, source: "default" };
3507
+ } else {
3508
+ landform = { value: landformWord.row, source: { word: landformWord.word } };
3509
+ if (landformWord.row !== own.landform) parsed.landform = landformWord.row;
3510
+ }
3511
+ const waterWord = rowHit(WATER_WORD_ROWS, words);
3512
+ const waterArgument = parseWater(args.water);
3513
+ let water2;
3514
+ if (waterArgument !== void 0) {
3515
+ parsed.water = waterArgument;
3516
+ water2 = { value: waterArgument, source: "argument" };
3517
+ } else if (spec !== void 0) {
3518
+ water2 = { value: spec.water, source: "argument" };
3519
+ } else if (waterWord === void 0) {
3520
+ water2 = { value: null, source: "default" };
3521
+ } else {
3522
+ const bodies = WATER_WORD_ROWS.filter(([, names]) => words.some((w) => names.includes(w))).map(
3523
+ ([row]) => row
3524
+ );
3525
+ if (parsed.landform === void 0 && bodies.every((row) => declaredWater(own.water, row))) {
3526
+ water2 = { value: own.water, source: { word: waterWord.word } };
3527
+ } else {
3528
+ parsed.water = bodies;
3529
+ water2 = { value: parsed.water, source: { word: waterWord.word } };
3530
+ }
3531
+ }
3532
+ const sizeArgument = parseSize(sizeMeters);
3533
+ const sizeWord = rowHit(SIZE_WORD_ROWS, words);
3534
+ let size;
3535
+ if (sizeArgument !== void 0) {
3536
+ parsed.sizeMeters = sizeArgument;
3537
+ size = { value: sizeArgument, source: "argument" };
3538
+ } else if (spec !== void 0) {
3539
+ size = { value: spec.sizeMeters, source: "argument" };
3540
+ } else if (sizeWord === void 0) {
3541
+ size = { value: null, source: "default" };
3542
+ } else {
3543
+ parsed.sizeMeters = Math.round(own.sizeMeters * sizeWord.row);
3544
+ size = { value: parsed.sizeMeters, source: { word: sizeWord.word } };
3545
+ }
3546
+ const featureHits = FEATURE_WORD_ROWS.flatMap(([feature, names]) => {
3547
+ const word = words.find((w) => names.includes(w));
3548
+ return word === void 0 ? [] : [{ feature, word }];
3549
+ });
3550
+ let features = { value: [], source: "default" };
3551
+ if (featureHits.length > 0) {
3552
+ parsed.features = featureHits.map((hit) => hit.feature);
3553
+ features = {
3554
+ value: parsed.features,
3555
+ source: { word: featureHits[0].word }
3556
+ };
3557
+ }
3558
+ const groundArgument = parseGround(args.ground, "terrain_generate");
3559
+ const presetKind = parsed.landform ?? (spec === void 0 ? void 0 : spec.landform);
3560
+ let ground;
3561
+ if (groundArgument !== void 0) {
3562
+ parsed.ground = groundArgument;
3563
+ ground = { value: groundArgument, source: "argument" };
3564
+ } else {
3565
+ ground = { value: presetKind === void 0 ? "starter" : "survey", source: "default" };
3566
+ }
3567
+ let backdrop;
3568
+ if (args.backdrop !== void 0) {
3569
+ if (args.backdrop !== "none")
3570
+ throw new TypeError('terrain_generate: backdrop must be "none" when given.');
3571
+ parsed.backdrop = "none";
3572
+ backdrop = { value: "none", source: "argument" };
3573
+ } else {
3574
+ const surveyed = ground.value === "survey" || typeof ground.value === "object" && "location" in ground.value;
3575
+ const range2 = parsed.backdropRange ?? presetKind;
3576
+ const mountain = range2 !== void 0 && MASSIFS[range2] !== void 0;
3577
+ backdrop = { value: surveyed && mountain ? "massif" : "none", source: "default" };
3578
+ }
3579
+ if (seed !== void 0) {
3580
+ if (typeof seed !== "number" || !Number.isSafeInteger(seed)) {
3581
+ throw new TypeError("terrain_generate: seed must be a safe integer.");
3582
+ }
3583
+ parsed.seed = seed;
3584
+ }
3585
+ if (out !== void 0) parsed.out = relativeDirectory(out);
3586
+ let biomeSource = "default";
3587
+ if (arguedKit !== void 0) biomeSource = "argument";
3588
+ else if (biomeWord !== void 0) biomeSource = { word: biomeWord.word };
3589
+ else if (inferred !== void 0) biomeSource = { word: inferred.word };
3590
+ return {
3591
+ input: parsed,
3592
+ decided: {
3593
+ biome: { value: kit, source: biomeSource },
3594
+ landform,
3595
+ water: water2,
3596
+ sizeMeters: size,
3597
+ features,
3598
+ ground,
3599
+ backdrop
3600
+ },
3601
+ // What is left is what the tool could not act on: a retry names a word, not a guess.
3602
+ unused: [...new Set(words)].filter(
3603
+ (word) => word.length >= 3 && !REQUEST_STOP_WORDS.has(word) && !REQUEST_KNOWN_WORDS.has(word)
3604
+ )
3605
+ };
3606
+ }
3607
+ function parseBiomeNewInput(input) {
3608
+ const args = closedRecord(input, "terrain_biome_new", BIOME_NEW_FIELDS);
3609
+ const from = args.from;
3610
+ if (typeof from !== "string" || !TERRAIN_KITS.includes(from))
3611
+ throw new TypeError(`terrain_biome_new: from must be one of ${TERRAIN_KITS.join(", ")}.`);
3612
+ const name = args.name;
3613
+ if (typeof name !== "string" || !/^[a-z][a-z0-9-]{0,31}$/u.test(name))
3614
+ throw new TypeError(
3615
+ "terrain_biome_new: name must be lowercase letters, digits and dashes, starting with a letter."
3616
+ );
3617
+ if (TERRAIN_KITS.includes(name))
3618
+ throw new TypeError(`terrain_biome_new: '${name}' is a shipped biome; choose a new name.`);
3619
+ const overrides = args.overrides;
3620
+ if (overrides !== void 0 && !isRecord(overrides))
3621
+ throw new TypeError("terrain_biome_new: overrides must be an object.");
3622
+ const parsed = { from, name };
3623
+ if (overrides !== void 0) parsed.overrides = { ...overrides };
3624
+ const ground = parseGround(args.ground, "terrain_biome_new");
3625
+ if (ground !== void 0) parsed.ground = ground;
3626
+ if (args.out !== void 0) parsed.out = relativeDirectory(args.out);
3627
+ return parsed;
3628
+ }
3629
+ function newBiomeSpec(base, name, overrides = {}) {
3630
+ return validateBiome(
3631
+ {
3632
+ ...base,
3633
+ ...overrides,
3634
+ aliases: overrides.aliases ?? [name],
3635
+ look: overrides.look ?? name
3636
+ },
3637
+ name
3638
+ );
3639
+ }
3640
+ async function resolveOutput(root, out, assetSource) {
3641
+ const realRoot = await realpath(root);
3642
+ let existing = resolve(realRoot, out);
3643
+ const tail = [];
3644
+ for (; ; ) {
3645
+ try {
3646
+ existing = await realpath(existing);
3647
+ break;
3648
+ } catch (error) {
3649
+ if (error.code !== "ENOENT") throw error;
3650
+ if (await lstat(existing).then(
3651
+ () => true,
3652
+ () => false
3653
+ )) {
3654
+ throw new Error(`terrain_generate: out '${out}' passes through a dangling symlink.`);
3655
+ }
3656
+ tail.unshift(basename(existing));
3657
+ existing = dirname(existing);
3658
+ }
3659
+ }
3660
+ const real = join(existing, ...tail);
3661
+ const inside = relative(realRoot, real);
3662
+ if (inside === "" || inside === ".." || inside.startsWith(`..${sep}`) || isAbsolute(inside)) {
3663
+ throw new Error(`terrain_generate: out '${out}' resolves outside the project.`);
3664
+ }
3665
+ if (assetSource !== void 0) {
3666
+ const under = relative(assetSource, real);
3667
+ if (under === "" || under === ".." || under.startsWith(`..${sep}`) || isAbsolute(under))
3668
+ throw new Error(
3669
+ `terrain_generate: out '${out}' must be under assets.source ('${relative(realRoot, assetSource)}') so the build lists the world in its manifest.`
3670
+ );
3671
+ }
3672
+ await assertOutputFree(real);
3673
+ return real;
3674
+ }
3675
+ async function assertOutputFree(dir) {
3676
+ const entries = await readdir(dir).catch((error) => {
3677
+ if (error.code === "ENOENT") return void 0;
3678
+ throw error;
3679
+ });
3680
+ if (entries !== void 0) {
3681
+ throw new Error(`terrain_generate: out '${dir}' already exists; choose a new directory.`);
3682
+ }
3683
+ }
3684
+ function isTerrainDocument(input) {
3685
+ Terrain.fromJSON(JSON.stringify(input));
3686
+ return true;
3687
+ }
3688
+ function isLayer(input) {
3689
+ isTerrainDocument({ version: 1, config: new Terrain().config, layers: [input] });
3690
+ return true;
3691
+ }
3692
+ function isLayerPatch(patch) {
3693
+ if (patch.mask !== void 0 && patch.mask !== null) {
3694
+ isLayer({ id: "validation", type: "noise", params: {}, mask: patch.mask });
3695
+ }
3696
+ return (patch.type === void 0 || OPERATION_TYPES.some((type) => type === patch.type)) && (patch.name === void 0 || typeof patch.name === "string") && (patch.enabled === void 0 || typeof patch.enabled === "boolean") && (patch.opacity === void 0 || typeof patch.opacity === "number" && Number.isFinite(patch.opacity)) && (patch.params === void 0 || isRecord(patch.params));
3697
+ }
3698
+ function parseCommand(command, index) {
3699
+ if (!isRecord(command) || !PATCH_OPS.includes(command.op)) {
3700
+ throw new TypeError(
3701
+ `terrain_patch: command ${index} op must be one of ${PATCH_OPS.join(", ")}.`
3702
+ );
3703
+ }
3704
+ if (command.op === "upsert") {
3705
+ if (!isRecord(command.layer)) {
3706
+ throw new TypeError(`terrain_patch: command ${index} needs a layer object.`);
3707
+ }
3708
+ if (!isLayer(command.layer)) ;
3709
+ return { ...command, op: "upsert", layer: command.layer };
3710
+ }
3711
+ if (typeof command.id !== "string") {
3712
+ throw new TypeError(`terrain_patch: command ${index} needs a layer id.`);
3713
+ }
3714
+ const id = command.id;
3715
+ switch (command.op) {
3716
+ case "update": {
3717
+ if (!isRecord(command.patch) || !isLayerPatch(command.patch)) {
3718
+ throw new TypeError(`terrain_patch: command ${index} needs a valid patch object.`);
3719
+ }
3720
+ return { ...command, op: "update", id, patch: command.patch };
3721
+ }
3722
+ case "move":
3723
+ if (typeof command.index !== "number" || !Number.isInteger(command.index)) {
3724
+ throw new TypeError(`terrain_patch: command ${index} needs an integer index.`);
3725
+ }
3726
+ return { ...command, op: "move", id, index: command.index };
3727
+ case "toggle":
3728
+ if (command.enabled !== void 0 && typeof command.enabled !== "boolean") {
3729
+ throw new TypeError(`terrain_patch: command ${index} enabled must be a boolean.`);
3730
+ }
3731
+ return { ...command, op: "toggle", id };
3732
+ case "remove":
3733
+ return { ...command, op: "remove", id };
3734
+ default:
3735
+ throw new TypeError(`terrain_patch: command ${index} has an unknown op.`);
3736
+ }
3737
+ }
3738
+ function parsePatchInput(input) {
3739
+ const args = closedRecord(input, "terrain_patch", ["recipe", "commands"]);
3740
+ if (!isRecord(args.recipe)) {
3741
+ throw new TypeError("terrain_patch: recipe must be a terrain document object.");
3742
+ }
3743
+ if (!Array.isArray(args.commands)) {
3744
+ throw new TypeError("terrain_patch: commands must be an array.");
3745
+ }
3746
+ if (!isTerrainDocument(args.recipe)) ;
3747
+ const commands = args.commands.map(parseCommand);
3748
+ patchRecipe(args.recipe, commands);
3749
+ return { recipe: args.recipe, commands };
3750
+ }
3751
+ function patchRecipe(recipe, commands) {
3752
+ return Terrain.fromJSON(recipe).applyPatch(commands).toJSON();
3753
+ }
3754
+ async function resolveAssetSource(projectRoot) {
3755
+ const configFile = join(projectRoot, "threenative.config.ts");
3756
+ const exists = await lstat(configFile).then(
3757
+ () => true,
3758
+ (error) => {
3759
+ if (error.code === "ENOENT") return false;
3760
+ throw error;
3761
+ }
3762
+ );
3763
+ let source = "assets";
3764
+ if (exists) {
3765
+ const { loadConfigFromFile } = await import('vite');
3766
+ const loaded = await loadConfigFromFile(
3767
+ { command: "build", mode: "production" },
3768
+ configFile,
3769
+ projectRoot
3770
+ );
3771
+ const assets = loaded?.config?.assets;
3772
+ if (assets !== void 0) {
3773
+ if (!isRecord(assets)) throw new TypeError("terrain_generate: assets must be an object.");
3774
+ source = assets.source === void 0 ? "assets" : assets.source;
3775
+ }
3776
+ }
3777
+ if (typeof source !== "string" || source.trim() === "") {
3778
+ throw new TypeError("terrain_generate: assets.source must be a non-empty path.");
3779
+ }
3780
+ const configuredRoot = resolve(projectRoot, source);
3781
+ const sourceRoot = await realpath(configuredRoot).catch((error) => {
3782
+ if (error.code === "ENOENT") return configuredRoot;
3783
+ throw error;
3784
+ });
3785
+ const inside = relative(projectRoot, sourceRoot);
3786
+ if (inside === "" || inside === ".." || inside.startsWith(`..${sep}`) || isAbsolute(inside)) {
3787
+ throw new TypeError("terrain_generate: assets.source must be inside the project.");
3788
+ }
3789
+ return sourceRoot;
3790
+ }
3791
+
3792
+ // src/mcp/server.ts
3793
+ var SERVER_NAME = "threenative-terrain";
3794
+ var SERVER_VERSION = "0.1.2";
3795
+ var COOK_TIMEOUT_MS = 6e4;
3796
+ var COOK_CHILD = fileURLToPath(new URL("./cook-child.js", import.meta.url));
3797
+ function reply(id, result) {
3798
+ return JSON.stringify({ id, jsonrpc: "2.0", result });
3799
+ }
3800
+ function fail3(id, code, message) {
3801
+ return JSON.stringify({ id, jsonrpc: "2.0", error: { code, message } });
3802
+ }
3803
+ function toolResult(text2, isError = false) {
3804
+ return { content: [{ type: "text", text: text2 }], isError };
3805
+ }
3806
+ async function cookInChild(request, out) {
3807
+ const child = await runIsolated({
3808
+ command: process.execPath,
3809
+ // Inherits the parent's loader flags, so the same TypeScript runtime starts the child.
3810
+ args: [...childExecArgv(process.execArgv), COOK_CHILD, JSON.stringify(request)],
3811
+ timeoutMs: COOK_TIMEOUT_MS
3812
+ }).catch(async (error) => {
3813
+ if (error instanceof IsolatedKillError) await rm(out, { recursive: true, force: true });
3814
+ throw error;
3815
+ });
3816
+ return child.stdout.trim().split("\n").at(-1) ?? "";
3817
+ }
3818
+ var CACHED_OUT = "@@TN_TERRAIN_OUT@@";
3819
+ var CACHED_URL = "@@TN_TERRAIN_URL@@";
3820
+ async function cookCached(request, out) {
3821
+ const { out: _out, projectRoot, ...inputs } = request;
3822
+ const starter = new URL(`../../starter/${request.kit}/`, import.meta.url);
3823
+ const starterFiles = await readdir(starter).catch(() => []);
3824
+ const stamps = await Promise.all(
3825
+ [COOK_CHILD, ...starterFiles.map((f) => fileURLToPath(new URL(f, starter)))].map(
3826
+ async (file) => `${file}:${(await stat(file)).mtimeMs}`
3827
+ )
3828
+ );
3829
+ const key = createHash("sha256").update(JSON.stringify({ inputs, version: SERVER_VERSION, stamps })).digest("hex").slice(0, 32);
3830
+ const dir = join(projectRoot, "node_modules", ".cache", "threenative-terrain", key);
3831
+ const shown = relative(realpathSync(projectRoot), out).split(sep).join("/");
3832
+ const url = relative(request.assetSource, out).split(sep).join("/");
3833
+ const stored = await readFile(join(dir, "reply.json"), "utf8").catch(() => void 0);
3834
+ if (stored !== void 0) {
3835
+ await cp(join(dir, "world"), out, { recursive: true });
3836
+ return {
3837
+ text: stored.replaceAll(CACHED_OUT, shown).replaceAll(CACHED_URL, url),
3838
+ cache: "hit"
3839
+ };
3840
+ }
3841
+ const text2 = await cookInChild(request, out);
3842
+ const staging = `${dir}.${String(process.pid)}`;
3843
+ try {
3844
+ await cp(out, join(staging, "world"), { recursive: true });
3845
+ await writeFile(
3846
+ join(staging, "reply.json"),
3847
+ text2.replaceAll(shown, CACHED_OUT).replaceAll(url, CACHED_URL)
3848
+ );
3849
+ await rename(staging, dir);
3850
+ } catch (error) {
3851
+ await rm(staging, { recursive: true, force: true });
3852
+ console.error(`terrain: cook cache not written: ${error.message}`);
3853
+ }
3854
+ return { text: text2, cache: "miss" };
3855
+ }
3856
+ async function callTool(name, args) {
3857
+ try {
3858
+ if (name === "terrain_generate") {
3859
+ const { input, decided, unused } = parseGenerateRequest(args);
3860
+ const projectRoot = process.cwd();
3861
+ const assetSource = await resolveAssetSource(projectRoot);
3862
+ const out = await resolveOutput(
3863
+ projectRoot,
3864
+ input.out ?? relative(projectRoot, join(assetSource, "worlds", input.kit)),
3865
+ assetSource
3866
+ );
3867
+ const { text: text2, cache } = await cookCached({ ...input, out, projectRoot, assetSource }, out);
3868
+ const { kit, out: _out, ...own } = input;
3869
+ const source = Object.keys(own).length === 0 ? `catalog:${kit}` : "cooked";
3870
+ return toolResult(
3871
+ JSON.stringify({ ...JSON.parse(text2), source, cache, decided, unused })
3872
+ );
3873
+ }
3874
+ if (name === "terrain_biome_new") {
3875
+ const input = parseBiomeNewInput(args);
3876
+ const projectRoot = process.cwd();
3877
+ const assetSource = await resolveAssetSource(projectRoot);
3878
+ const base = JSON.parse(
3879
+ await readFile(
3880
+ new URL(`../../starter/${input.from}/biome.data.json`, import.meta.url),
3881
+ "utf8"
3882
+ )
3883
+ );
3884
+ const spec = newBiomeSpec(base, input.name, input.overrides);
3885
+ const biomeDir = await resolveOutput(
3886
+ projectRoot,
3887
+ relative(projectRoot, join(assetSource, "biomes", input.name)),
3888
+ assetSource
3889
+ );
3890
+ const out = await resolveOutput(
3891
+ projectRoot,
3892
+ input.out ?? relative(projectRoot, join(assetSource, "biomes", input.name, "world")),
3893
+ assetSource
3894
+ );
3895
+ await mkdir(biomeDir, { recursive: true });
3896
+ const biomeJson = join(biomeDir, "biome.data.json");
3897
+ await writeFile(biomeJson, `${JSON.stringify(spec, null, 2)}
3898
+ `);
3899
+ let text2;
3900
+ try {
3901
+ text2 = await cookInChild(
3902
+ {
3903
+ assetSource,
3904
+ biome: input.name,
3905
+ kit: input.from,
3906
+ out,
3907
+ projectRoot,
3908
+ spec,
3909
+ ground: input.ground
3910
+ },
3911
+ out
3912
+ );
3913
+ } catch (error) {
3914
+ await rm(biomeDir, { recursive: true, force: true });
3915
+ throw error;
3916
+ }
3917
+ const shown = relative(projectRoot, biomeJson).split(sep).join("/");
3918
+ return toolResult(JSON.stringify({ ...JSON.parse(text2), biomeJson: shown }));
3919
+ }
3920
+ if (name === "terrain_patch") {
3921
+ const { recipe, commands } = parsePatchInput(args);
3922
+ return toolResult(JSON.stringify(patchRecipe(recipe, commands)));
3923
+ }
3924
+ throw new TypeError(`Unknown tool '${name}'.`);
3925
+ } catch (error) {
3926
+ const message = error instanceof Error ? error.message : String(error);
3927
+ return toolResult(message.match(/^\w*Error: .*$/m)?.[0] ?? message, true);
3928
+ }
3929
+ }
3930
+ async function handleLine(line) {
3931
+ let request;
3932
+ try {
3933
+ request = JSON.parse(line);
3934
+ } catch {
3935
+ return fail3(null, -32700, "Parse error.");
3936
+ }
3937
+ const { id, method, params } = request;
3938
+ if (method === void 0) return fail3(id ?? null, -32600, "Invalid request: no method.");
3939
+ if (id === void 0) return void 0;
3940
+ if (method === "initialize") {
3941
+ return reply(id, {
3942
+ protocolVersion: typeof params?.protocolVersion === "string" ? params.protocolVersion : "2025-06-18",
3943
+ capabilities: { tools: {} },
3944
+ serverInfo: { name: SERVER_NAME, version: SERVER_VERSION }
3945
+ });
3946
+ }
3947
+ if (method === "tools/list") return reply(id, { tools: TERRAIN_TOOLS });
3948
+ if (method === "tools/call") {
3949
+ const name = params?.name;
3950
+ if (typeof name !== "string") return fail3(id, -32602, "tools/call needs a tool name.");
3951
+ return reply(id, await callTool(name, params?.arguments ?? {}));
3952
+ }
3953
+ return fail3(id, -32601, `Method not found: ${method}.`);
3954
+ }
3955
+ function runServer() {
3956
+ const lines = createInterface({ input: process.stdin, crlfDelay: Number.POSITIVE_INFINITY });
3957
+ lines.on("line", (line) => {
3958
+ if (line.trim() === "") return;
3959
+ handleLine(line).then((response) => {
3960
+ if (response !== void 0) process.stdout.write(`${response}
3961
+ `);
3962
+ });
3963
+ });
3964
+ }
3965
+ var entry = process.argv[1];
3966
+ if (entry !== void 0 && realpathSync(resolve(entry)) === realpathSync(fileURLToPath(import.meta.url))) {
3967
+ runServer();
3968
+ }
3969
+
3970
+ export { handleLine, runServer };