@threenative/terrain 0.1.7 → 0.1.8

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 (127) hide show
  1. package/AGENT_GUIDE.md +19 -4
  2. package/dist/editor/index.d.ts +160 -5
  3. package/dist/editor/index.js +3783 -1406
  4. package/dist/editor/server.d.ts +2 -2
  5. package/dist/editor/server.js +555 -121
  6. package/dist/editor/worker.d.ts +33 -1
  7. package/dist/editor/worker.js +444 -110
  8. package/dist/export.d.ts +11 -9
  9. package/dist/export.js +22 -34
  10. package/dist/index.d.ts +727 -73
  11. package/dist/index.js +2434 -553
  12. package/dist/kit.d.ts +56 -0
  13. package/dist/kit.js +2524 -0
  14. package/dist/mcp/cook-child.d.ts +2 -0
  15. package/dist/mcp/cook-child.js +3705 -0
  16. package/dist/mcp/server.d.ts +7 -0
  17. package/dist/mcp/server.js +3279 -0
  18. package/dist/{server-ByM2hmYJ.d.ts → server-C8Ydr_IM.d.ts} +3 -2
  19. package/dist/starter.d.ts +143 -0
  20. package/dist/starter.js +1030 -0
  21. package/dist/{terrain-gPnkCU6S.d.ts → terrain-B3DkduPw.d.ts} +3 -2
  22. package/dist/three.d.ts +1 -1
  23. package/dist/{types-Ant8-Axc.d.ts → types-CPYAc9vo.d.ts} +13 -4
  24. package/dist/world-package-B7KGYIou.d.ts +94 -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 +114 -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 +77 -1
  33. package/starter/coastal/bake.mjs +4 -116
  34. package/starter/coastal/biome.data.json +135 -0
  35. package/starter/coastal/heightmap.r16 +0 -0
  36. package/starter/coastal/recipe.json +3 -66051
  37. package/starter/coastal/sea.ts +49 -16
  38. package/starter/coastal/world.ts +53 -318
  39. package/starter/desert/README.md +77 -1
  40. package/starter/desert/bake.mjs +4 -116
  41. package/starter/desert/biome.data.json +114 -0
  42. package/starter/desert/heightmap.r16 +0 -0
  43. package/starter/desert/recipe.json +3 -66051
  44. package/starter/desert/world.ts +45 -293
  45. package/starter/forest/README.md +84 -4
  46. package/starter/forest/assets.json +32 -0
  47. package/starter/forest/bake.mjs +6 -116
  48. package/starter/forest/biome.data.json +150 -0
  49. package/starter/forest/heightmap.r16 +0 -0
  50. package/starter/forest/recipe.json +192 -4428
  51. package/starter/forest/sky.ts +11 -0
  52. package/starter/forest/water.ts +30 -20
  53. package/starter/forest/world.ts +86 -322
  54. package/starter/tundra/README.md +77 -1
  55. package/starter/tundra/bake.mjs +4 -116
  56. package/starter/tundra/biome.data.json +131 -0
  57. package/starter/tundra/heightmap.r16 +0 -0
  58. package/starter/tundra/recipe.json +18 -66066
  59. package/starter/tundra/world.ts +65 -319
  60. package/starter-assets.json +6 -0
  61. package/{starter-assets/credits.json → starter-credits.json} +12 -105
  62. package/starter-assets/bark_brown_02/bark_brown_02_diff_1k.jpg +0 -0
  63. package/starter-assets/bark_brown_02/bark_brown_02_nor_gl_1k.jpg +0 -0
  64. package/starter-assets/bark_brown_02/bark_brown_02_rough_1k.jpg +0 -0
  65. package/starter-assets/boulder_01/boulder-mid.glb +0 -0
  66. package/starter-assets/boulder_01/boulder-near.glb +0 -0
  67. package/starter-assets/cliff_side/cliff_side_ao_1k.jpg +0 -0
  68. package/starter-assets/cliff_side/cliff_side_diff_1k.jpg +0 -0
  69. package/starter-assets/cliff_side/cliff_side_nor_gl_1k.jpg +0 -0
  70. package/starter-assets/cliff_side/cliff_side_rough_1k.jpg +0 -0
  71. package/starter-assets/fern_02/fern_02_alpha_512.png +0 -0
  72. package/starter-assets/fern_02/fern_02_diff_512.jpg +0 -0
  73. package/starter-assets/fern_02/fern_02_nor_gl_512.jpg +0 -0
  74. package/starter-assets/fir_tree_01/fir-b-lod1.glb +0 -0
  75. package/starter-assets/fir_tree_01/fir-b-lod2.glb +0 -0
  76. package/starter-assets/fir_tree_01/fir-c-lod1.glb +0 -0
  77. package/starter-assets/fir_tree_01/fir-c-lod2.glb +0 -0
  78. package/starter-assets/fir_tree_01/fir_tree_01_twig_arm_1k.jpg +0 -0
  79. package/starter-assets/fir_tree_01/fir_tree_01_twig_diff_1k.jpg +0 -0
  80. package/starter-assets/fir_tree_01/fir_tree_01_twig_nor_gl_1k.jpg +0 -0
  81. package/starter-assets/forest_ground_04/forest_ground_04_ao_1k.jpg +0 -0
  82. package/starter-assets/forest_ground_04/forest_ground_04_diff_1k.jpg +0 -0
  83. package/starter-assets/forest_ground_04/forest_ground_04_nor_gl_1k.jpg +0 -0
  84. package/starter-assets/forest_ground_04/forest_ground_04_rough_1k.jpg +0 -0
  85. package/starter-assets/forest_leaves_02/forest_leaves_02_arm_512.jpg +0 -0
  86. package/starter-assets/forest_leaves_02/forest_leaves_02_diff_512.jpg +0 -0
  87. package/starter-assets/forest_leaves_02/forest_leaves_02_nor_gl_512.jpg +0 -0
  88. package/starter-assets/grass_medium_02/grass_medium_02_alpha_512.png +0 -0
  89. package/starter-assets/grass_medium_02/grass_medium_02_diff_512.jpg +0 -0
  90. package/starter-assets/grass_medium_02/grass_medium_02_nor_gl_512.jpg +0 -0
  91. package/starter-assets/hdri/kloofendal_48d_partly_cloudy_1k.hdr +0 -0
  92. package/starter-assets/leafy_grass/leafy_grass_ao_1k.jpg +0 -0
  93. package/starter-assets/leafy_grass/leafy_grass_diff_1k.jpg +0 -0
  94. package/starter-assets/leafy_grass/leafy_grass_nor_gl_1k.jpg +0 -0
  95. package/starter-assets/leafy_grass/leafy_grass_rough_1k.jpg +0 -0
  96. package/starter-assets/lichen_rock/lichen_rock_arm_512.jpg +0 -0
  97. package/starter-assets/lichen_rock/lichen_rock_diff_512.jpg +0 -0
  98. package/starter-assets/lichen_rock/lichen_rock_nor_gl_512.jpg +0 -0
  99. package/starter-assets/mossy_rock/mossy_rock_ao_1k.jpg +0 -0
  100. package/starter-assets/mossy_rock/mossy_rock_diff_1k.jpg +0 -0
  101. package/starter-assets/mossy_rock/mossy_rock_nor_gl_1k.jpg +0 -0
  102. package/starter-assets/mossy_rock/mossy_rock_rough_1k.jpg +0 -0
  103. package/starter-assets/needle-atlas.png +0 -0
  104. package/starter-assets/needle-surface.png +0 -0
  105. package/starter-assets/river_small_rocks/river_small_rocks_arm_512.jpg +0 -0
  106. package/starter-assets/river_small_rocks/river_small_rocks_diff_512.jpg +0 -0
  107. package/starter-assets/river_small_rocks/river_small_rocks_nor_gl_512.jpg +0 -0
  108. package/starter-assets/rock_boulder_dry/rock_boulder_dry_arm_512.jpg +0 -0
  109. package/starter-assets/rock_boulder_dry/rock_boulder_dry_diff_512.jpg +0 -0
  110. package/starter-assets/rock_boulder_dry/rock_boulder_dry_nor_gl_512.jpg +0 -0
  111. package/starter-assets/rocks/boulder-mid.glb +0 -0
  112. package/starter-assets/rocks/boulder-near.glb +0 -0
  113. package/starter-assets/rocks/boulder-prep.json +0 -37
  114. package/starter-assets/rocks/rock01-mid.glb +0 -0
  115. package/starter-assets/rocks/rock01-near.glb +0 -0
  116. package/starter-assets/rocks/rock01-prep.json +0 -37
  117. package/starter-assets/rocks/rock04-mid.glb +0 -0
  118. package/starter-assets/rocks/rock04-near.glb +0 -0
  119. package/starter-assets/rocks/rock04-prep.json +0 -37
  120. package/starter-assets/sand_01/sand_01_ao_1k.jpg +0 -0
  121. package/starter-assets/sand_01/sand_01_diff_1k.jpg +0 -0
  122. package/starter-assets/sand_01/sand_01_nor_gl_1k.jpg +0 -0
  123. package/starter-assets/sand_01/sand_01_rough_1k.jpg +0 -0
  124. package/starter-assets/snow_02/snow_02_ao_1k.jpg +0 -0
  125. package/starter-assets/snow_02/snow_02_diff_1k.jpg +0 -0
  126. package/starter-assets/snow_02/snow_02_nor_gl_1k.jpg +0 -0
  127. package/starter-assets/snow_02/snow_02_rough_1k.jpg +0 -0
package/dist/index.js CHANGED
@@ -1,3 +1,8 @@
1
+ import { Heightfield } from '@threenative/core/world';
2
+ import { createRandom } from '@threenative/core';
3
+ import { ImprovedNoise } from 'three/addons/math/ImprovedNoise.js';
4
+ import { MathUtils } from 'three';
5
+
1
6
  // src/core/math.ts
2
7
  var clamp = (x, a = 0, b = 1) => Math.max(a, Math.min(b, x));
3
8
  var lerp = (a, b, t) => a + (b - a) * t;
@@ -6,9 +11,9 @@ var smoothstep = (a, b, x) => {
6
11
  const t = clamp((x - a) / (b - a));
7
12
  return t * t * (3 - 2 * t);
8
13
  };
9
- var hashString = (text) => {
14
+ var hashString = (text2) => {
10
15
  let h = 2166136261;
11
- for (const c of text) h = Math.imul(h ^ c.charCodeAt(0), 16777619);
16
+ for (const c of text2) h = Math.imul(h ^ c.charCodeAt(0), 16777619);
12
17
  return h >>> 0;
13
18
  };
14
19
  function random(seed) {
@@ -121,10 +126,10 @@ function slopeAtIndex(grid, i) {
121
126
  const gz = (grid.height[Math.min(z + 1, n - 1) * n + x] - grid.height[Math.max(z - 1, 0) * n + x]) / (dz * cell);
122
127
  return Math.atan(Math.hypot(gx, gz)) * (180 / Math.PI);
123
128
  }
124
- function slopeQuantile(grid, quantile) {
125
- if (!(quantile >= 0 && quantile <= 1))
129
+ function slopeQuantile(grid, quantile2) {
130
+ if (!(quantile2 >= 0 && quantile2 <= 1))
126
131
  throw new Error(
127
- `TN_TERRAIN_SLOPE_QUANTILE_INVALID: quantile must be in [0, 1], received ${String(quantile)}.`
132
+ `TN_TERRAIN_SLOPE_QUANTILE_INVALID: quantile must be in [0, 1], received ${String(quantile2)}.`
128
133
  );
129
134
  const n = grid.resolution;
130
135
  const slopes = [];
@@ -132,7 +137,7 @@ function slopeQuantile(grid, quantile) {
132
137
  for (let x = 1; x < n - 1; x++) slopes.push(slopeAtIndex(grid, z * n + x));
133
138
  if (slopes.length === 0) return 0;
134
139
  slopes.sort((a, b) => a - b);
135
- return slopes[Math.min(slopes.length - 1, Math.floor(slopes.length * quantile))];
140
+ return slopes[Math.min(slopes.length - 1, Math.floor(slopes.length * quantile2))];
136
141
  }
137
142
  function falloff(distance, radius, softness = 0.6) {
138
143
  const d = distance / radius;
@@ -145,12 +150,12 @@ function splinePoints(points, step = 3, smooth = true) {
145
150
  const b = points[k];
146
151
  const c = points[k + 1];
147
152
  const d = points[Math.min(points.length - 1, k + 2)];
148
- const count = Math.max(
153
+ const count2 = Math.max(
149
154
  1,
150
155
  Math.min(512, Math.ceil(Math.hypot(c[0] - b[0], c[2] - b[2]) / step))
151
156
  );
152
- for (let j = 0; j < count; j += 1) {
153
- const t = j / count;
157
+ for (let j = 0; j < count2; j += 1) {
158
+ const t = j / count2;
154
159
  const t2 = t * t;
155
160
  const t3 = t2 * t;
156
161
  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);
@@ -168,6 +173,10 @@ function splinePoints(points, step = 3, smooth = true) {
168
173
 
169
174
  // src/core/erosion.ts
170
175
  function thermal(height, n, size, { iterations = 20, talus = 32, rate = 0.22 } = {}, observations) {
176
+ if (!Number.isInteger(n) || n < 2)
177
+ throw RangeError("Thermal erosion requires grid resolution n >= 2");
178
+ if (!Number.isInteger(iterations) || iterations < 0 || iterations > 200)
179
+ throw RangeError("Thermal erosion iterations must be between 0 and 200");
171
180
  const h = height.slice();
172
181
  const delta = new Float64Array(h.length);
173
182
  const limit = Math.tan(talus * Math.PI / 180) * (size / (n - 1));
@@ -176,18 +185,24 @@ function thermal(height, n, size, { iterations = 20, talus = 32, rate = 0.22 } =
176
185
  for (let z = 0; z < n; z += 1) {
177
186
  for (let x = 0; x < n; x += 1) {
178
187
  const i = z * n + x;
188
+ const here = h[i];
179
189
  let best = -1;
180
190
  let diff = limit;
181
- for (const j of [
182
- x > 0 ? i - 1 : -1,
183
- x < n - 1 ? i + 1 : -1,
184
- z > 0 ? i - n : -1,
185
- z < n - 1 ? i + n : -1
186
- ]) {
187
- if (j >= 0 && h[i] - h[j] > diff) {
188
- diff = h[i] - h[j];
189
- best = j;
190
- }
191
+ if (x > 0 && here - h[i - 1] > diff) {
192
+ diff = here - h[i - 1];
193
+ best = i - 1;
194
+ }
195
+ if (x < n - 1 && here - h[i + 1] > diff) {
196
+ diff = here - h[i + 1];
197
+ best = i + 1;
198
+ }
199
+ if (z > 0 && here - h[i - n] > diff) {
200
+ diff = here - h[i - n];
201
+ best = i - n;
202
+ }
203
+ if (z < n - 1 && here - h[i + n] > diff) {
204
+ diff = here - h[i + n];
205
+ best = i + n;
191
206
  }
192
207
  if (best >= 0) {
193
208
  const transfer = (diff - limit) * rate;
@@ -206,119 +221,211 @@ var brushes = /* @__PURE__ */ new Map();
206
221
  function brush(radius) {
207
222
  let cells = brushes.get(radius);
208
223
  if (!cells) {
209
- cells = [];
224
+ const dx = [];
225
+ const dz = [];
226
+ const raw = [];
210
227
  let total = 0;
211
- for (let dz = -radius; dz <= radius; dz += 1) {
212
- for (let dx = -radius; dx <= radius; dx += 1) {
213
- const d = Math.hypot(dx, dz);
228
+ for (let z = -radius; z <= radius; z += 1) {
229
+ for (let x = -radius; x <= radius; x += 1) {
230
+ const d = Math.hypot(x, z);
214
231
  if (d > radius) continue;
215
- const weight = 1 - d / (radius + 1);
216
- cells.push({ dx, dz, weight });
217
- total += weight;
232
+ const weight2 = 1 - d / (radius + 1);
233
+ dx.push(x);
234
+ dz.push(z);
235
+ raw.push(weight2);
236
+ total += weight2;
218
237
  }
219
238
  }
220
- for (const c of cells) c.weight /= total;
239
+ const weight = Float64Array.from(raw, (w) => w / total);
240
+ let full = 0;
241
+ for (let k = 0; k < weight.length; k += 1) full += weight[k];
242
+ cells = { dx: Int32Array.from(dx), dz: Int32Array.from(dz), full, radius, weight };
221
243
  brushes.set(radius, cells);
222
244
  }
223
245
  return cells;
224
246
  }
225
- function hydraulic(height, n, size, {
226
- // Roughly one droplet per cell. Incision saturates near here: more droplets keep cutting the
227
- // same drainage lines over, which deepens nothing and spends the bake time.
228
- droplets = n * n,
229
- // A droplet has to be able to cross the world, so its step budget scales with the grid: a
230
- // fixed 40 barely leaves a 257 world while a 65 world would walk off it in a few steps.
231
- maxSteps = Math.round(Math.min(64, Math.max(24, n / 4))),
232
- inertia = 0.2,
233
- capacity = 4,
234
- // Each step takes a small bite of the sediment the droplet can carry. A big bite carves
235
- // fewer, deeper dimples that stand proud of their neighbours as spikes; many shallow bites
236
- // over the same lines incise the same drainage with a smooth surface.
237
- erosion = 0.03,
238
- deposition = 0.3,
239
- evaporation = 0.025,
240
- seed = 1,
241
- brushRadius = 3
242
- } = {}, observations) {
247
+ var MAX_AUTOMATIC_DROPLETS = 1025 * 1025;
248
+ var MAX_EXPLICIT_DROPLETS = 2e5;
249
+ function hydraulic(height, n, size, options = {}, observations) {
250
+ const {
251
+ droplets: requestedDroplets,
252
+ // A droplet has to be able to cross the world, so its step budget scales with the grid: a
253
+ // fixed 40 barely leaves a 257 world while a 65 world would walk off it in a few steps.
254
+ maxSteps = Math.round(Math.min(64, Math.max(24, n / 4))),
255
+ inertia = 0.2,
256
+ capacity = 4,
257
+ // Each step takes a small bite of the sediment the droplet can carry. A big bite carves
258
+ // fewer, deeper dimples that stand proud of their neighbours as spikes; many shallow bites
259
+ // over the same lines incise the same drainage with a smooth surface.
260
+ erosion = 0.03,
261
+ deposition = 0.3,
262
+ evaporation = 0.025,
263
+ seed = 1,
264
+ brushRadius = 3
265
+ } = options;
266
+ if (!Number.isInteger(n) || n < 2)
267
+ throw RangeError("Hydraulic erosion requires grid resolution n >= 2");
268
+ const droplets = requestedDroplets === void 0 ? Math.min(n * n, MAX_AUTOMATIC_DROPLETS) : requestedDroplets;
269
+ if (!Number.isSafeInteger(droplets) || droplets < 0)
270
+ throw RangeError("Hydraulic erosion droplets must be a non-negative integer");
271
+ if (requestedDroplets !== void 0 && droplets > MAX_EXPLICIT_DROPLETS)
272
+ throw RangeError(`Hydraulic erosion droplets must not exceed ${String(MAX_EXPLICIT_DROPLETS)}`);
273
+ if (!Number.isInteger(maxSteps) || maxSteps < 1 || maxSteps > 128)
274
+ throw RangeError("Hydraulic erosion maxSteps must be between 1 and 128");
243
275
  const h = Float64Array.from(height);
244
276
  const rnd = random(seed);
245
277
  const cell = size / (n - 1);
246
- const cells = brush(brushRadius);
278
+ const minSlope = 5e-3 * cell;
279
+ const oneMinusInertia = 1 - inertia;
280
+ const oneMinusEvaporation = 1 - evaporation;
281
+ const brushCells = brush(brushRadius);
282
+ const brushDx = brushCells.dx;
283
+ const brushDz = brushCells.dz;
284
+ const brushWeight = brushCells.weight;
285
+ const brushCount = brushDx.length;
286
+ const brushFull = brushCells.full;
287
+ const brushEdge = brushCells.radius;
288
+ const brushOffset = new Int32Array(brushCount);
289
+ for (let k = 0; k < brushCount; k += 1)
290
+ brushOffset[k] = brushDz[k] * n + brushDx[k];
291
+ const obsFlow = observations?.flow;
292
+ const obsSediment = observations?.sediment;
293
+ const obsDeposition = observations?.deposition;
247
294
  const spread = (x, z, amount, floor = Number.NEGATIVE_INFINITY) => {
295
+ if (amount === 0) return 0;
296
+ const interior = x >= brushEdge && x < n - brushEdge && z >= brushEdge && z < n - brushEdge;
297
+ if (interior) {
298
+ const total2 = brushFull;
299
+ if (total2 <= 0) return 0;
300
+ const base = z * n + x;
301
+ if (amount < 0) {
302
+ let moved = 0;
303
+ for (let k = 0; k < brushCount; k += 1) {
304
+ const i = base + brushOffset[k];
305
+ const share2 = amount * brushWeight[k] / total2;
306
+ const avail = h[i] - floor;
307
+ const change = avail <= 0 ? -0 : -share2 < avail ? share2 : -avail;
308
+ h[i] = h[i] + change;
309
+ moved += change;
310
+ }
311
+ return moved;
312
+ }
313
+ if (obsDeposition !== void 0) {
314
+ for (let k = 0; k < brushCount; k += 1) {
315
+ const i = base + brushOffset[k];
316
+ const share2 = amount * brushWeight[k] / total2;
317
+ h[i] = h[i] + share2;
318
+ obsDeposition[i] = obsDeposition[i] + share2;
319
+ }
320
+ } else {
321
+ for (let k = 0; k < brushCount; k += 1) {
322
+ const i = base + brushOffset[k];
323
+ const share2 = amount * brushWeight[k] / total2;
324
+ h[i] = h[i] + share2;
325
+ }
326
+ }
327
+ return amount;
328
+ }
248
329
  let total = 0;
249
- for (const c of cells) {
250
- const ix = x + c.dx;
251
- const iz = z + c.dz;
252
- if (ix >= 0 && ix < n && iz >= 0 && iz < n) total += c.weight;
330
+ for (let k = 0; k < brushCount; k += 1) {
331
+ const ix = x + brushDx[k];
332
+ const iz = z + brushDz[k];
333
+ if (ix >= 0 && ix < n && iz >= 0 && iz < n) total += brushWeight[k];
253
334
  }
254
335
  if (total <= 0) return 0;
255
- let moved = 0;
256
- for (const c of cells) {
257
- const ix = x + c.dx;
258
- const iz = z + c.dz;
259
- if (ix < 0 || ix >= n || iz < 0 || iz >= n) continue;
260
- const i = iz * n + ix;
261
- const share = amount * c.weight / total;
262
- const change = amount < 0 ? -Math.min(-share, Math.max(0, h[i] - floor)) : share;
263
- h[i] = h[i] + change;
264
- moved += change;
265
- if (observations && amount > 0)
266
- observations.deposition[i] = observations.deposition[i] + amount * c.weight / total;
267
- }
268
- return moved;
336
+ if (amount < 0) {
337
+ let moved = 0;
338
+ for (let k = 0; k < brushCount; k += 1) {
339
+ const ix = x + brushDx[k];
340
+ const iz = z + brushDz[k];
341
+ if (ix < 0 || ix >= n || iz < 0 || iz >= n) continue;
342
+ const i = iz * n + ix;
343
+ const share2 = amount * brushWeight[k] / total;
344
+ const avail = h[i] - floor;
345
+ const change = avail <= 0 ? -0 : -share2 < avail ? share2 : -avail;
346
+ h[i] = h[i] + change;
347
+ moved += change;
348
+ }
349
+ return moved;
350
+ }
351
+ if (obsDeposition !== void 0) {
352
+ for (let k = 0; k < brushCount; k += 1) {
353
+ const ix = x + brushDx[k];
354
+ const iz = z + brushDz[k];
355
+ if (ix < 0 || ix >= n || iz < 0 || iz >= n) continue;
356
+ const i = iz * n + ix;
357
+ const share2 = amount * brushWeight[k] / total;
358
+ h[i] = h[i] + share2;
359
+ obsDeposition[i] = obsDeposition[i] + share2;
360
+ }
361
+ } else {
362
+ for (let k = 0; k < brushCount; k += 1) {
363
+ const ix = x + brushDx[k];
364
+ const iz = z + brushDz[k];
365
+ if (ix < 0 || ix >= n || iz < 0 || iz >= n) continue;
366
+ const i = iz * n + ix;
367
+ const share2 = amount * brushWeight[k] / total;
368
+ h[i] = h[i] + share2;
369
+ }
370
+ }
371
+ return amount;
269
372
  };
270
- const get = (x, z) => {
373
+ const probeOld = { value: 0, dx: 0, dz: 0, ix: 0, iz: 0 };
374
+ const probeNext = { value: 0, dx: 0, dz: 0, ix: 0, iz: 0 };
375
+ const get = (x, z, out) => {
271
376
  const ix = Math.min(n - 2, Math.floor(x));
272
377
  const iz = Math.min(n - 2, Math.floor(z));
273
378
  const tx = x - ix;
274
379
  const tz = z - iz;
275
380
  const i = iz * n + ix;
276
- return {
277
- value: lerp(
278
- lerp(h[i], h[i + 1], tx),
279
- lerp(h[i + n], h[i + n + 1], tx),
280
- tz
281
- ),
282
- dx: lerp(
283
- h[i + 1] - h[i],
284
- h[i + n + 1] - h[i + n],
285
- tz
286
- ) / cell,
287
- dz: lerp(
288
- h[i + n] - h[i],
289
- h[i + n + 1] - h[i + 1],
290
- tx
291
- ) / cell,
292
- ix,
293
- iz
294
- };
381
+ const h00 = h[i];
382
+ const h10 = h[i + 1];
383
+ const h01 = h[i + n];
384
+ const h11 = h[i + n + 1];
385
+ const g10 = h10 - h00;
386
+ const g01 = h01 - h00;
387
+ const v0 = h00 + g10 * tx;
388
+ const v1 = h01 + (h11 - h01) * tx;
389
+ out.value = v0 + (v1 - v0) * tz;
390
+ out.dx = (g10 + (h11 - h01 - g10) * tz) / cell;
391
+ out.dz = (g01 + (h11 - h10 - g01) * tx) / cell;
392
+ out.ix = ix;
393
+ out.iz = iz;
394
+ return out;
295
395
  };
296
396
  for (let k = 0; k < droplets; k += 1) {
297
397
  let x = rnd() * (n - 1 - 1e-3);
298
398
  let z = rnd() * (n - 1 - 1e-3);
299
399
  let dx = 0;
300
400
  let dz = 0;
301
- let water = 1;
401
+ let water2 = 1;
302
402
  let speed = 1;
303
403
  let sediment = 0;
304
404
  for (let step = 0; step < maxSteps; step += 1) {
305
- const old = get(x, z);
306
- if (observations) {
405
+ const old = get(x, z, probeOld);
406
+ if (obsFlow !== void 0 && obsSediment !== void 0) {
307
407
  const tx = x - old.ix;
308
408
  const tz = z - old.iz;
309
409
  const i = old.iz * n + old.ix;
310
- for (let oz = 0; oz < 2; oz++) {
311
- for (let ox = 0; ox < 2; ox++) {
312
- const index = i + oz * n + ox;
313
- const weight = (ox ? tx : 1 - tx) * (oz ? tz : 1 - tz);
314
- observations.flow[index] = observations.flow[index] + water * weight;
315
- observations.sediment[index] = observations.sediment[index] + sediment * weight;
316
- }
317
- }
410
+ const w00 = (1 - tx) * (1 - tz);
411
+ const w10 = tx * (1 - tz);
412
+ const w01 = (1 - tx) * tz;
413
+ const w11 = tx * tz;
414
+ obsFlow[i] = obsFlow[i] + water2 * w00;
415
+ obsSediment[i] = obsSediment[i] + sediment * w00;
416
+ obsFlow[i + 1] = obsFlow[i + 1] + water2 * w10;
417
+ obsSediment[i + 1] = obsSediment[i + 1] + sediment * w10;
418
+ obsFlow[i + n] = obsFlow[i + n] + water2 * w01;
419
+ obsSediment[i + n] = obsSediment[i + n] + sediment * w01;
420
+ obsFlow[i + n + 1] = obsFlow[i + n + 1] + water2 * w11;
421
+ obsSediment[i + n + 1] = obsSediment[i + n + 1] + sediment * w11;
318
422
  }
319
- dx = dx * inertia - old.dx * (1 - inertia);
320
- dz = dz * inertia - old.dz * (1 - inertia);
321
- let length = Math.hypot(dx, dz);
423
+ dx = dx * inertia - old.dx * oneMinusInertia;
424
+ dz = dz * inertia - old.dz * oneMinusInertia;
425
+ const largest = Math.max(Math.abs(dx), Math.abs(dz));
426
+ const scaledX = Math.abs(dx) / largest;
427
+ const scaledZ = Math.abs(dz) / largest;
428
+ let length = largest === 0 || largest === Number.POSITIVE_INFINITY ? largest : Math.sqrt(scaledX * scaledX + scaledZ * scaledZ) * largest;
322
429
  if (length < 1e-9) {
323
430
  const angle = rnd() * Math.PI * 2;
324
431
  dx = Math.cos(angle);
@@ -333,31 +440,223 @@ function hydraulic(height, n, size, {
333
440
  sediment = 0;
334
441
  break;
335
442
  }
336
- const next = get(nx, nz);
443
+ const next = get(nx, nz, probeNext);
337
444
  const dh = next.value - old.value;
338
- const cap = Math.max(-dh, 5e-3 * cell) * speed * water * capacity;
445
+ const slope = -dh;
446
+ const cap = (slope > minSlope ? slope : minSlope) * speed * water2 * capacity;
339
447
  if (dh > 0 || sediment > cap) {
340
- const amount = dh > 0 ? Math.min(dh, sediment) : (sediment - cap) * deposition;
448
+ const amount = dh > 0 ? dh < sediment ? dh : sediment : (sediment - cap) * deposition;
341
449
  spread(old.ix, old.iz, amount);
342
450
  sediment -= amount;
343
451
  } else {
344
- const amount = Math.max(0, Math.min((cap - sediment) * erosion, -dh));
452
+ const bite = (cap - sediment) * erosion;
453
+ const amount = bite < slope ? bite : slope;
345
454
  sediment -= spread(old.ix, old.iz, -amount, next.value);
346
455
  }
347
- speed = Math.sqrt(Math.max(0.01, speed * speed - dh * 3));
348
- water *= 1 - evaporation;
456
+ const sq = speed * speed - dh * 3;
457
+ speed = Math.sqrt(sq > 0.01 ? sq : 0.01);
458
+ water2 *= oneMinusEvaporation;
349
459
  x = nx;
350
460
  z = nz;
351
- if (water < 0.02) break;
461
+ if (water2 < 0.02) break;
352
462
  }
353
- if (sediment > 0 && water < 0.02) {
354
- const end = get(clamp(x, 0, n - 1.001), clamp(z, 0, n - 1.001));
463
+ if (sediment > 0 && water2 < 0.02) {
464
+ const end = get(clamp(x, 0, n - 1.001), clamp(z, 0, n - 1.001), probeOld);
355
465
  spread(end.ix, end.iz, sediment);
356
466
  }
357
467
  }
358
468
  return Float32Array.from(h);
359
469
  }
360
470
 
471
+ // src/core/fluvial.ts
472
+ var DX = Int8Array.of(-1, 0, 1, -1, 1, -1, 0, 1);
473
+ var DZ = Int8Array.of(-1, -1, -1, 0, 0, 1, 1, 1);
474
+ var DIST = Float64Array.from(DX, (dx, k) => Math.hypot(dx, DZ[k]));
475
+ var FILL_SLOPE = Math.tan(0.06 * Math.PI / 180);
476
+ var EPSILON = 1e-3;
477
+ function fillDepressions(h, n, epsilon = EPSILON) {
478
+ const total = n * n;
479
+ const keys = new Float64Array(total);
480
+ const cells = new Int32Array(total);
481
+ const closed2 = new Uint8Array(total);
482
+ let size = 0;
483
+ const push = (key, cell) => {
484
+ let k = size++;
485
+ while (k > 0) {
486
+ const parent = k - 1 >> 1;
487
+ if (keys[parent] <= key) break;
488
+ keys[k] = keys[parent];
489
+ cells[k] = cells[parent];
490
+ k = parent;
491
+ }
492
+ keys[k] = key;
493
+ cells[k] = cell;
494
+ };
495
+ const pop = () => {
496
+ const top = cells[0];
497
+ size -= 1;
498
+ const key = keys[size];
499
+ const cell = cells[size];
500
+ let k = 0;
501
+ for (; ; ) {
502
+ let child = 2 * k + 1;
503
+ if (child >= size) break;
504
+ if (child + 1 < size && keys[child + 1] < keys[child]) child += 1;
505
+ if (keys[child] >= key) break;
506
+ keys[k] = keys[child];
507
+ cells[k] = cells[child];
508
+ k = child;
509
+ }
510
+ keys[k] = key;
511
+ cells[k] = cell;
512
+ return top;
513
+ };
514
+ for (let z = 0; z < n; z += 1) {
515
+ for (let x = 0; x < n; x += 1) {
516
+ if (x > 0 && x < n - 1 && z > 0 && z < n - 1) continue;
517
+ const i = z * n + x;
518
+ closed2[i] = 1;
519
+ push(h[i], i);
520
+ }
521
+ }
522
+ while (size > 0) {
523
+ const c = pop();
524
+ const cx = c % n;
525
+ const cz = (c - cx) / n;
526
+ const level = h[c];
527
+ for (let k = 0; k < 8; k += 1) {
528
+ const x = cx + DX[k];
529
+ const z = cz + DZ[k];
530
+ if (x < 0 || z < 0 || x >= n || z >= n) continue;
531
+ const j = z * n + x;
532
+ if (closed2[j]) continue;
533
+ closed2[j] = 1;
534
+ if (h[j] <= level) h[j] = level + epsilon;
535
+ push(h[j], j);
536
+ }
537
+ }
538
+ }
539
+ function createFlow(n) {
540
+ const total = n * n;
541
+ return {
542
+ receiver: new Int32Array(total),
543
+ order: new Int32Array(total),
544
+ cells: new Float64Array(total)
545
+ };
546
+ }
547
+ function routeFlow(h, n, flow) {
548
+ const { receiver, order, cells } = flow;
549
+ const total = n * n;
550
+ const head = new Int32Array(total).fill(-1);
551
+ const next = new Int32Array(total);
552
+ let roots = 0;
553
+ for (let z = 0; z < n; z += 1) {
554
+ for (let x = 0; x < n; x += 1) {
555
+ const i = z * n + x;
556
+ let best = -1;
557
+ if (x > 0 && x < n - 1 && z > 0 && z < n - 1) {
558
+ const here = h[i];
559
+ let bestSlope = 0;
560
+ for (let k = 0; k < 8; k += 1) {
561
+ const j = i + DZ[k] * n + DX[k];
562
+ const slope = (here - h[j]) / DIST[k];
563
+ if (slope > bestSlope) {
564
+ bestSlope = slope;
565
+ best = j;
566
+ }
567
+ }
568
+ }
569
+ receiver[i] = best;
570
+ if (best < 0) order[roots++] = i;
571
+ else {
572
+ next[i] = head[best];
573
+ head[best] = i;
574
+ }
575
+ }
576
+ }
577
+ for (let k = 0; k < total; k += 1) {
578
+ const i = order[k];
579
+ for (let d = head[i]; d >= 0; d = next[d]) order[roots++] = d;
580
+ }
581
+ cells.fill(1);
582
+ for (let k = total - 1; k >= 0; k -= 1) {
583
+ const i = order[k];
584
+ const r = receiver[i];
585
+ if (r >= 0) cells[r] = cells[r] + cells[i];
586
+ }
587
+ }
588
+ function fluvial(height, n, size, {
589
+ iterations = 40,
590
+ uplift = 1e-3,
591
+ erodibility = 5e-6,
592
+ timeStep = 2e4,
593
+ concavity = 0.45,
594
+ talus = 35,
595
+ relief
596
+ } = {}) {
597
+ const total = n * n;
598
+ const spacing = size / (n - 1);
599
+ const h = Float64Array.from(height);
600
+ const band2 = Math.min(4, n - 1);
601
+ for (let a = 0; a < n; a += 1)
602
+ for (let d = 1; d <= band2; d += 1) {
603
+ h[a] = Math.min(h[a], h[d * n + a]);
604
+ h[(n - 1) * n + a] = Math.min(h[(n - 1) * n + a], h[(n - 1 - d) * n + a]);
605
+ h[a * n] = Math.min(h[a * n], h[a * n + d]);
606
+ h[a * n + n - 1] = Math.min(h[a * n + n - 1], h[a * n + n - 1 - d]);
607
+ }
608
+ fillDepressions(h, n, FILL_SLOPE * spacing);
609
+ let low = Number.POSITIVE_INFINITY;
610
+ let high = Number.NEGATIVE_INFINITY;
611
+ for (let i = 0; i < total; i += 1) {
612
+ low = Math.min(low, h[i]);
613
+ high = Math.max(high, h[i]);
614
+ }
615
+ const range2 = high - low || 1;
616
+ const rise = Float64Array.from(h, (v) => uplift * timeStep * (v - low) / range2);
617
+ const flow = createFlow(n);
618
+ const kdt = erodibility * timeStep;
619
+ const maxRise = Math.tan(talus * Math.PI / 180) * spacing;
620
+ const power = Float64Array.from(
621
+ { length: total + 1 },
622
+ (_, c) => (c * spacing * spacing) ** concavity
623
+ );
624
+ for (let step = 0; step < iterations; step += 1) {
625
+ routeFlow(h, n, flow);
626
+ const { order, receiver, cells } = flow;
627
+ for (let k = 0; k < total; k += 1) {
628
+ const i = order[k];
629
+ const r = receiver[i];
630
+ if (r < 0) continue;
631
+ const delta = Math.abs(r - i);
632
+ const run = delta === 1 || delta === n ? 1 : Math.SQRT2;
633
+ const factor = kdt * power[cells[i]] / (spacing * run);
634
+ const below = h[r];
635
+ const solved = (h[i] + rise[i] + factor * below) / (1 + factor);
636
+ h[i] = Math.max(Math.min(solved, below + maxRise * run), below + EPSILON);
637
+ }
638
+ }
639
+ for (let a = 0; a < n; a += 1) {
640
+ h[a] = h[n + a];
641
+ h[(n - 1) * n + a] = h[(n - 2) * n + a];
642
+ }
643
+ for (let a = 0; a < n; a += 1) {
644
+ h[a * n] = h[a * n + 1];
645
+ h[a * n + n - 1] = h[a * n + n - 2];
646
+ }
647
+ if (relief !== void 0) {
648
+ let lo = Number.POSITIVE_INFINITY;
649
+ let hi = Number.NEGATIVE_INFINITY;
650
+ for (const v of h) {
651
+ lo = Math.min(lo, v);
652
+ hi = Math.max(hi, v);
653
+ }
654
+ const gain = relief / (hi - lo || 1);
655
+ for (let i = 0; i < total; i += 1) h[i] = lo + (h[i] - lo) * gain;
656
+ }
657
+ return Float32Array.from(h);
658
+ }
659
+
361
660
  // src/core/masks.ts
362
661
  var MATERIAL_IDS = Object.freeze([
363
662
  "grass",
@@ -532,9 +831,9 @@ function brushCenters(p, seed) {
532
831
  for (let k = 1; k < source.length; k += 1) {
533
832
  const a = source[k - 1];
534
833
  const b = source[k];
535
- const count = Math.max(1, Math.ceil(Math.hypot(b[0] - a[0], b[1] - a[1]) / step));
536
- for (let j = 1; j <= count; j += 1)
537
- out.push([lerp(a[0], b[0], j / count), lerp(a[1], b[1], j / count)]);
834
+ const count2 = Math.max(1, Math.ceil(Math.hypot(b[0] - a[0], b[1] - a[1]) / step));
835
+ for (let j = 1; j <= count2; j += 1)
836
+ out.push([lerp(a[0], b[0], j / count2), lerp(a[1], b[1], j / count2)]);
538
837
  }
539
838
  if (p.jitter) {
540
839
  const rnd = random(seed);
@@ -598,12 +897,12 @@ function gradeToGround(s, points, p) {
598
897
  const next = profile.slice();
599
898
  for (let k = 0; k < profile.length; k += 1) {
600
899
  let sum = 0;
601
- let count = 0;
900
+ let count2 = 0;
602
901
  for (let j = Math.max(0, k - window); j <= Math.min(profile.length - 1, k + window); j += 1) {
603
902
  sum += profile[j];
604
- count += 1;
903
+ count2 += 1;
605
904
  }
606
- next[k] = sum / count;
905
+ next[k] = sum / count2;
607
906
  }
608
907
  for (let k = 0; k < profile.length; k += 1) profile[k] = next[k];
609
908
  }
@@ -641,10 +940,10 @@ function gradeToGround(s, points, p) {
641
940
  );
642
941
  for (let k = 0; k < points.length; k += 1) at(k)[1] = profile[k];
643
942
  }
644
- function applySpline(s, layer, mask) {
645
- const p = layer.params;
646
- const river = layer.type === "river";
647
- const ramp = layer.type === "ramp";
943
+ function applySpline(s, layer2, mask) {
944
+ const p = layer2.params;
945
+ const river = layer2.type === "river";
946
+ const ramp = layer2.type === "ramp";
648
947
  const seed = p.seed ?? s.seed;
649
948
  const raw = ramp ? [p.from, p.to] : p.points ?? [];
650
949
  const follows = followsTerrain(raw, p.followTerrain);
@@ -661,7 +960,7 @@ function applySpline(s, layer, mask) {
661
960
  const shoulder = p.shoulder ?? half;
662
961
  const extent = half + shoulder;
663
962
  const depth = p.depth ?? 4;
664
- const alpha = layer.opacity ?? 1;
963
+ const alpha = layer2.opacity ?? 1;
665
964
  const n = s.resolution;
666
965
  const cell = s.size / (n - 1);
667
966
  const dist = new Float32Array(n * n).fill(Number.POSITIVE_INFINITY);
@@ -726,18 +1025,18 @@ function applySpline(s, layer, mask) {
726
1025
  }
727
1026
  if (river && p.water !== false)
728
1027
  s.rivers.push({
729
- id: layer.id,
1028
+ id: layer2.id,
730
1029
  points,
731
1030
  width: (p.width ?? 12) * (p.waterWidth ?? 0.76),
732
1031
  color: p.color,
733
1032
  opacity: alpha
734
1033
  });
735
1034
  }
736
- function applyOperation(s, layer) {
737
- const { type, params: p } = layer;
738
- const opacity = layer.opacity ?? 1;
739
- if (layer.enabled === false || opacity <= 0) return;
740
- const mask = rasterMask(layer.mask, s);
1035
+ function applyOperation(s, layer2) {
1036
+ const { type, params: p } = layer2;
1037
+ const opacity = layer2.opacity ?? 1;
1038
+ if (layer2.enabled === false || opacity <= 0) return;
1039
+ const mask = rasterMask(layer2.mask, s);
741
1040
  const weight = (i) => (mask?.[i] ?? 1) * opacity;
742
1041
  const n = s.resolution;
743
1042
  const seed = p.seed ?? s.seed;
@@ -785,9 +1084,9 @@ function applyOperation(s, layer) {
785
1084
  let sum = 0;
786
1085
  let total = 0;
787
1086
  for (let i = 0; i < s.height.length; i += 1) {
788
- const share = covered[i] * opacity;
789
- sum += s.height[i] * share;
790
- total += share;
1087
+ const share2 = covered[i] * opacity;
1088
+ sum += s.height[i] * share2;
1089
+ total += share2;
791
1090
  }
792
1091
  const target = total > 0 ? sum / total : 0;
793
1092
  let delta = 0;
@@ -823,18 +1122,18 @@ function applyOperation(s, layer) {
823
1122
  const i = z * n + x;
824
1123
  if (w(i) === 0) continue;
825
1124
  let total = 0;
826
- let count = 0;
1125
+ let count2 = 0;
827
1126
  for (let dz = -1; dz <= 1; dz += 1) {
828
1127
  for (let dx = -1; dx <= 1; dx += 1) {
829
1128
  const xx = x + dx;
830
1129
  const zz = z + dz;
831
1130
  if (xx >= 0 && xx < n && zz >= 0 && zz < n) {
832
1131
  total += old[zz * n + xx];
833
- count += 1;
1132
+ count2 += 1;
834
1133
  }
835
1134
  }
836
1135
  }
837
- s.height[i] = lerp(old[i], total / count, w(i) * clamp(p.strength ?? 0.65));
1136
+ s.height[i] = lerp(old[i], total / count2, w(i) * clamp(p.strength ?? 0.65));
838
1137
  }
839
1138
  }
840
1139
  }
@@ -901,7 +1200,7 @@ function applyOperation(s, layer) {
901
1200
  talus: new Float32Array(s.height.length)
902
1201
  };
903
1202
  s.erosion ??= structuredClone(observations);
904
- const eroded = p.method === "hydraulic" ? hydraulic(
1203
+ const eroded = p.method === "fluvial" ? fluvial(s.height, n, s.size, p) : p.method === "hydraulic" ? hydraulic(
905
1204
  s.height,
906
1205
  n,
907
1206
  s.size,
@@ -965,13 +1264,13 @@ function applyOperation(s, layer) {
965
1264
  break;
966
1265
  }
967
1266
  case "scatter":
968
- s.scatterRules.push({ id: layer.id, ...p, mask: layer.mask, opacity, clear: [] });
1267
+ s.scatterRules.push({ id: layer2.id, ...p, mask: layer2.mask, opacity, clear: [] });
969
1268
  break;
970
1269
  case "clear": {
971
1270
  if (p.target === "scatter" || p.target === "all") {
972
1271
  for (const rule of s.scatterRules)
973
1272
  if (!p.asset || rule.asset === p.asset)
974
- rule.clear.push({ mask: layer.mask ?? { type: "all" }, opacity });
1273
+ rule.clear.push({ mask: layer2.mask ?? { type: "all" }, opacity });
975
1274
  }
976
1275
  if (p.target === "biome" || p.target === "all")
977
1276
  for (const [name, values] of Object.entries(s.biomes)) {
@@ -986,15 +1285,15 @@ function applyOperation(s, layer) {
986
1285
  case "road":
987
1286
  case "river":
988
1287
  case "ramp":
989
- applySpline(s, layer, mask);
1288
+ applySpline(s, layer2, mask);
990
1289
  break;
991
1290
  case "water":
992
- s.waterRules.push({ id: layer.id, ...p, mask: layer.mask, opacity });
1291
+ s.waterRules.push({ id: layer2.id, ...p, mask: layer2.mask, opacity });
993
1292
  break;
994
1293
  case "heightmap": {
995
1294
  if (p.at !== void 0 || p.size !== void 0 || p.rotation !== void 0 || p.falloff !== void 0) {
996
1295
  applyOperation(s, {
997
- ...layer,
1296
+ ...layer2,
998
1297
  type: "paste",
999
1298
  params: { ...p, size: p.size ?? s.size, falloff: p.falloff ?? 0 }
1000
1299
  });
@@ -1011,7 +1310,7 @@ function applyOperation(s, layer) {
1011
1310
  break;
1012
1311
  }
1013
1312
  default:
1014
- throw Error(`Unsupported operation: ${String(layer.type)}`);
1313
+ throw Error(`Unsupported operation: ${String(layer2.type)}`);
1015
1314
  }
1016
1315
  }
1017
1316
  function finalizeState(s) {
@@ -1019,13 +1318,13 @@ function finalizeState(s) {
1019
1318
  const cell = s.size / (n - 1);
1020
1319
  s.waters = [];
1021
1320
  s.instances = [];
1022
- for (const water of s.waterRules) {
1321
+ for (const water2 of s.waterRules) {
1023
1322
  const mask = new Uint8Array(n * n);
1024
1323
  const queue = new Int32Array(n * n);
1025
- const allowed = compileMask(water.mask, s);
1026
- const level = water.level ?? 0;
1027
- const at = water.at ?? [0, 0];
1028
- const radius = water.radius ?? s.size;
1324
+ const allowed = compileMask(water2.mask, s);
1325
+ const level = water2.level ?? 0;
1326
+ const at = water2.at ?? [0, 0];
1327
+ const radius = water2.radius ?? s.size;
1029
1328
  let front = 0;
1030
1329
  let back = 0;
1031
1330
  const eligible = (i) => {
@@ -1040,7 +1339,7 @@ function finalizeState(s) {
1040
1339
  back += 1;
1041
1340
  }
1042
1341
  };
1043
- if (water.kind === "ocean") {
1342
+ if (water2.kind === "ocean") {
1044
1343
  for (let k = 0; k < n; k += 1) {
1045
1344
  push(k);
1046
1345
  push((n - 1) * n + k);
@@ -1062,14 +1361,14 @@ function finalizeState(s) {
1062
1361
  if (z > 0) push(i - n);
1063
1362
  if (z < n - 1) push(i + n);
1064
1363
  }
1065
- s.waters.push({ ...water, level, mask });
1364
+ s.waters.push({ ...water2, level, mask });
1066
1365
  if (!back)
1067
1366
  s.diagnostics.push(
1068
- `Water '${water.id}' has no flooded cells; its seed may be above the water level.`
1367
+ `Water '${water2.id}' has no flooded cells; its seed may be above the water level.`
1069
1368
  );
1070
1369
  }
1071
1370
  const wet = (i, x, z, h) => {
1072
- if (s.waters.some((water) => water.mask[i])) return true;
1371
+ if (s.waters.some((water2) => water2.mask[i])) return true;
1073
1372
  for (const river of s.rivers) {
1074
1373
  const half = river.width / 2;
1075
1374
  for (let k = 1; k < river.points.length; k += 1) {
@@ -1087,7 +1386,7 @@ function finalizeState(s) {
1087
1386
  return false;
1088
1387
  };
1089
1388
  for (const rule of s.scatterRules) {
1090
- const count = Math.round((rule.count ?? 300) * (rule.opacity ?? 1));
1389
+ const count2 = Math.round((rule.count ?? 300) * (rule.opacity ?? 1));
1091
1390
  const seed = (rule.seed ?? s.seed ^ hashString(rule.id)) >>> 0;
1092
1391
  const rnd = random(seed);
1093
1392
  const accept = compileMask(rule.mask, s);
@@ -1099,9 +1398,9 @@ function finalizeState(s) {
1099
1398
  const gridSize = Math.max(distance, 0.1);
1100
1399
  const buckets = /* @__PURE__ */ new Map();
1101
1400
  const accepted = [];
1102
- const maxAttempts = count * 40;
1401
+ const maxAttempts = count2 * 40;
1103
1402
  const scale = rule.scale ?? [0.8, 1.3];
1104
- for (let attempt = 0; attempt < maxAttempts && accepted.length < count; attempt += 1) {
1403
+ for (let attempt = 0; attempt < maxAttempts && accepted.length < count2; attempt += 1) {
1105
1404
  const x = (rnd() - 0.5) * s.size;
1106
1405
  const z = (rnd() - 0.5) * s.size;
1107
1406
  const acceptance = rnd();
@@ -1142,7 +1441,7 @@ function finalizeState(s) {
1142
1441
  accepted.push({
1143
1442
  id: `${rule.id}:candidate:${seed}:${attempt}`,
1144
1443
  layer: rule.id,
1145
- asset: rule.asset ?? "pine",
1444
+ asset: rule.asset,
1146
1445
  position: [x, h + (rule.offsetY ?? 0), z],
1147
1446
  rotation: yaw,
1148
1447
  scale: itemScale,
@@ -1154,10 +1453,10 @@ function finalizeState(s) {
1154
1453
  bucket.push(index);
1155
1454
  buckets.set(key, bucket);
1156
1455
  }
1157
- s.instances.push(...accepted);
1158
- if (accepted.length < count)
1456
+ for (const instance of accepted) s.instances.push(instance);
1457
+ if (accepted.length < count2)
1159
1458
  s.diagnostics.push(
1160
- `Scatter '${rule.id}': placed ${accepted.length}/${count}; masks or spacing exhausted the attempt budget.`
1459
+ `Scatter '${rule.id}': placed ${accepted.length}/${count2}; masks or spacing exhausted the attempt budget.`
1161
1460
  );
1162
1461
  }
1163
1462
  return s;
@@ -1229,6 +1528,10 @@ var PARAMS = Object.freeze({
1229
1528
  "method",
1230
1529
  "iterations",
1231
1530
  "talus",
1531
+ "uplift",
1532
+ "erodibility",
1533
+ "timeStep",
1534
+ "relief",
1232
1535
  "rate",
1233
1536
  "droplets",
1234
1537
  "maxSteps",
@@ -1278,14 +1581,23 @@ function fail(message) {
1278
1581
  }
1279
1582
  function finiteTree(value, path = "value", depth = 0) {
1280
1583
  if (depth > 32) fail(`${path}: nesting is too deep`);
1281
- if (typeof value === "number" && !Number.isFinite(value)) fail(`${path} must be finite`);
1584
+ if (typeof value === "number") {
1585
+ if (!Number.isFinite(value)) fail(`${path} must be finite`);
1586
+ return;
1587
+ }
1282
1588
  if (value === void 0 || typeof value === "function" || typeof value === "bigint" || typeof value === "symbol")
1283
1589
  fail(`${path} is not JSON-serializable`);
1284
1590
  if (value && typeof value === "object") {
1285
1591
  if (ArrayBuffer.isView(value)) fail(`${path}: use a plain array in recipes`);
1286
- for (const [key, entry] of Object.entries(value)) {
1287
- if (["__proto__", "prototype", "constructor"].includes(key))
1592
+ for (const key of Object.keys(value)) {
1593
+ if (key === "__proto__" || key === "prototype" || key === "constructor")
1288
1594
  fail(`${path}: unsafe object key`);
1595
+ const entry = value[key];
1596
+ if (typeof entry === "number") {
1597
+ if (depth + 1 > 32) fail(`${path}.${key}: nesting is too deep`);
1598
+ if (!Number.isFinite(entry)) fail(`${path}.${key} must be finite`);
1599
+ continue;
1600
+ }
1289
1601
  finiteTree(entry, `${path}.${key}`, depth + 1);
1290
1602
  }
1291
1603
  }
@@ -1390,17 +1702,17 @@ function splinePoint(v, name, follows) {
1390
1702
  if (typeof y !== "number") fail(`${name} must contain 3 numbers`);
1391
1703
  if (!Number.isFinite(y) && !follows) fail(`${name} elevation must be finite`);
1392
1704
  }
1393
- function layerFollowsTerrain(layer) {
1394
- if (!layer || typeof layer !== "object" || !["road", "river", "ramp"].includes(layer.type))
1705
+ function layerFollowsTerrain(layer2) {
1706
+ if (!layer2 || typeof layer2 !== "object" || !["road", "river", "ramp"].includes(layer2.type))
1395
1707
  return false;
1396
- const params = layer.params ?? {};
1397
- const source = layer.type === "ramp" ? [params.from, params.to] : params.points;
1708
+ const params = layer2.params ?? {};
1709
+ const source = layer2.type === "ramp" ? [params.from, params.to] : params.points;
1398
1710
  if (!Array.isArray(source)) return false;
1399
1711
  return followsTerrain(source, params.followTerrain);
1400
1712
  }
1401
- function omittedElevations(layer, follows) {
1402
- if (!follows) return layer;
1403
- const params = layer.params ?? {};
1713
+ function omittedElevations(layer2, follows) {
1714
+ if (!follows) return layer2;
1715
+ const params = layer2.params ?? {};
1404
1716
  const zero = (p) => Array.isArray(p) && p.length === 3 ? [p[0], 0, p[2]] : p;
1405
1717
  const points = params.points;
1406
1718
  const fixes = {
@@ -1408,28 +1720,28 @@ function omittedElevations(layer, follows) {
1408
1720
  ...Array.isArray(params.from) ? { from: zero(params.from) } : {},
1409
1721
  ...Array.isArray(params.to) ? { to: zero(params.to) } : {}
1410
1722
  };
1411
- return Object.keys(fixes).length ? { ...layer, params: { ...params, ...fixes } } : layer;
1723
+ return Object.keys(fixes).length ? { ...layer2, params: { ...params, ...fixes } } : layer2;
1412
1724
  }
1413
- function validateLayer(layer) {
1414
- const follows = layerFollowsTerrain(layer);
1415
- finiteTree(omittedElevations(layer, follows), "layer");
1416
- if (!layer || typeof layer !== "object") fail("layer must be an object");
1417
- for (const k of Object.keys(layer))
1725
+ function validateLayer(layer2) {
1726
+ const follows = layerFollowsTerrain(layer2);
1727
+ finiteTree(omittedElevations(layer2, follows), "layer");
1728
+ if (!layer2 || typeof layer2 !== "object") fail("layer must be an object");
1729
+ for (const k of Object.keys(layer2))
1418
1730
  if (!["id", "name", "type", "params", "enabled", "opacity", "mask"].includes(k))
1419
1731
  fail(`Unknown layer field '${k}'`);
1420
- identifier(layer.id, "layer.id");
1421
- enumeration(layer.type, "operation", OPERATION_TYPES);
1422
- if (layer.name !== void 0) identifier(layer.name, "layer.name");
1423
- if (layer.enabled !== void 0 && typeof layer.enabled !== "boolean")
1732
+ identifier(layer2.id, "layer.id");
1733
+ enumeration(layer2.type, "operation", OPERATION_TYPES);
1734
+ if (layer2.name !== void 0) identifier(layer2.name, "layer.name");
1735
+ if (layer2.enabled !== void 0 && typeof layer2.enabled !== "boolean")
1424
1736
  fail("enabled must be boolean");
1425
- if (layer.opacity !== void 0) num(layer.opacity, "opacity", 0, 1);
1426
- if (layer.mask) validateMask(layer.mask);
1427
- const params = layer.params ?? {};
1737
+ if (layer2.opacity !== void 0) num(layer2.opacity, "opacity", 0, 1);
1738
+ if (layer2.mask) validateMask(layer2.mask);
1739
+ const params = layer2.params ?? {};
1428
1740
  if (!params || Array.isArray(params) || typeof params !== "object")
1429
1741
  fail("params must be an object");
1430
1742
  for (const k of Object.keys(params))
1431
- if (!PARAMS[layer.type].includes(k) && k !== "seed")
1432
- fail(`Unknown ${layer.type} parameter '${k}'`);
1743
+ if (!PARAMS[layer2.type].includes(k) && k !== "seed")
1744
+ fail(`Unknown ${layer2.type} parameter '${k}'`);
1433
1745
  for (const key of [
1434
1746
  "island",
1435
1747
  "mirrorX",
@@ -1449,7 +1761,7 @@ function validateLayer(layer) {
1449
1761
  if (params.from !== void 0) splinePoint(params.from, "from", follows);
1450
1762
  if (params.to !== void 0) splinePoint(params.to, "to", follows);
1451
1763
  const points = params.points;
1452
- const isSpline = ["road", "river"].includes(layer.type);
1764
+ const isSpline = ["road", "river"].includes(layer2.type);
1453
1765
  if (points) {
1454
1766
  if (!Array.isArray(points) || !points.length || points.length > 8192)
1455
1767
  fail("points must have 1..8192 entries");
@@ -1484,8 +1796,8 @@ function validateLayer(layer) {
1484
1796
  );
1485
1797
  }
1486
1798
  if (isSpline && (!Array.isArray(points) || points.length < 2))
1487
- fail(`${layer.type} requires at least two [x,y,z] points`);
1488
- if (layer.type === "ramp" && (!params.from || !params.to)) fail("ramp requires from and to");
1799
+ fail(`${layer2.type} requires at least two [x,y,z] points`);
1800
+ if (layer2.type === "ramp" && (!params.from || !params.to)) fail("ramp requires from and to");
1489
1801
  for (const key of ["radius", "size"]) {
1490
1802
  const value = params[key];
1491
1803
  if (value === void 0) continue;
@@ -1494,7 +1806,7 @@ function validateLayer(layer) {
1494
1806
  for (const entry of value) num(entry, key, 1e-3, 1e6);
1495
1807
  } else num(value, key, 1e-3, 1e6);
1496
1808
  }
1497
- if (Array.isArray(params.radius) && !["stamp", "paste"].includes(layer.type))
1809
+ if (Array.isArray(params.radius) && !["stamp", "paste"].includes(layer2.type))
1498
1810
  fail("Brush radius must be one number");
1499
1811
  for (const key of [
1500
1812
  "amplitude",
@@ -1507,7 +1819,7 @@ function validateLayer(layer) {
1507
1819
  "level",
1508
1820
  "rotation"
1509
1821
  ])
1510
- if (params[key] !== void 0 && !(key === "base" && layer.type === "materials")) {
1822
+ if (params[key] !== void 0 && !(key === "base" && layer2.type === "materials")) {
1511
1823
  if (params[key] !== null || key !== "height") num(params[key], key);
1512
1824
  }
1513
1825
  for (const key of ["width", "step"])
@@ -1543,12 +1855,12 @@ function validateLayer(layer) {
1543
1855
  num(
1544
1856
  params.strength,
1545
1857
  "strength",
1546
- layer.type === "sculpt" ? -1e4 : 0,
1547
- layer.type === "sculpt" ? 1e4 : 1
1858
+ layer2.type === "sculpt" ? -1e4 : 0,
1859
+ layer2.type === "sculpt" ? 1e4 : 1
1548
1860
  );
1549
1861
  if (params.scale !== void 0) {
1550
1862
  const scale = params.scale;
1551
- if (layer.type === "scatter") {
1863
+ if (layer2.type === "scatter") {
1552
1864
  if (Array.isArray(scale)) {
1553
1865
  vec(scale, "scale", 2);
1554
1866
  if (scale[0] > scale[1]) fail("scale range is inverted");
@@ -1566,6 +1878,13 @@ function validateLayer(layer) {
1566
1878
  if (params[key] !== void 0) num(params[key], key, key === "count" ? 0 : 1, max, true);
1567
1879
  if (params.persistence !== void 0) num(params.persistence, "persistence", 0.01, 1);
1568
1880
  if (params.lacunarity !== void 0) num(params.lacunarity, "lacunarity", 1, 4);
1881
+ for (const [key, min, max] of [
1882
+ ["uplift", 1e-9, 1],
1883
+ ["erodibility", 1e-9, 1],
1884
+ ["timeStep", 1, 1e7],
1885
+ ["relief", 1, 1e5]
1886
+ ])
1887
+ if (params[key] !== void 0) num(params[key], key, min, max);
1569
1888
  for (const key of ["minSlope", "maxSlope", "talus"])
1570
1889
  if (params[key] !== void 0) num(params[key], key, 0, key === "talus" ? 89.9 : 90);
1571
1890
  if (params.minHeight !== void 0 && params.maxHeight !== void 0 && params.minHeight > params.maxHeight)
@@ -1573,7 +1892,7 @@ function validateLayer(layer) {
1573
1892
  if (params.minSlope !== void 0 && params.maxSlope !== void 0 && params.minSlope > params.maxSlope)
1574
1893
  fail("slope range is inverted");
1575
1894
  if (params.material !== void 0) enumeration(params.material, "material", MATERIAL_IDS);
1576
- if (layer.type === "materials") {
1895
+ if (layer2.type === "materials") {
1577
1896
  if (params.base !== void 0) enumeration(params.base, "base", MATERIAL_IDS);
1578
1897
  const rules = params.rules;
1579
1898
  if (!Array.isArray(rules) || rules.length > 64) fail("materials requires a rules array");
@@ -1583,24 +1902,25 @@ function validateLayer(layer) {
1583
1902
  if (rule.strength !== void 0) num(rule.strength, "rule.strength", 0, 1);
1584
1903
  }
1585
1904
  }
1586
- if (params.method !== void 0) enumeration(params.method, "method", ["thermal", "hydraulic"]);
1905
+ if (params.method !== void 0)
1906
+ enumeration(params.method, "method", ["thermal", "hydraulic", "fluvial"]);
1587
1907
  if (params.mode !== void 0) enumeration(params.mode, "mode", ["fbm", "ridged", "billow"]);
1588
1908
  if (params.shape !== void 0)
1589
1909
  enumeration(
1590
1910
  params.shape,
1591
1911
  "shape",
1592
- ["stamp"].includes(layer.type) ? ["mountain", "crater", "ridge", "valley", "mesa", "dune"] : ["circle", "square"]
1912
+ ["stamp"].includes(layer2.type) ? ["mountain", "crater", "ridge", "valley", "mesa", "dune"] : ["circle", "square"]
1593
1913
  );
1594
1914
  if (params.blend !== void 0)
1595
1915
  enumeration(
1596
1916
  params.blend,
1597
1917
  "blend",
1598
- ["noise", "heightmap"].includes(layer.type) ? ["add", "replace"] : ["add", "replace", "min", "max"]
1918
+ ["noise", "heightmap"].includes(layer2.type) ? ["add", "replace"] : ["add", "replace", "min", "max"]
1599
1919
  );
1600
- if (layer.type === "clear")
1920
+ if (layer2.type === "clear")
1601
1921
  enumeration(params.target, "clear.target", ["scatter", "paint", "biome", "all"]);
1602
- if (layer.type === "water") enumeration(params.kind ?? "lake", "water.kind", ["lake", "ocean"]);
1603
- if (layer.type === "river" && params.enforceDownhill && Array.isArray(points)) {
1922
+ if (layer2.type === "water") enumeration(params.kind ?? "lake", "water.kind", ["lake", "ocean"]);
1923
+ if (layer2.type === "river" && params.enforceDownhill && Array.isArray(points)) {
1604
1924
  const river = points;
1605
1925
  for (let i = 1; i < river.length; i += 1) {
1606
1926
  const next = river[i];
@@ -1611,8 +1931,12 @@ function validateLayer(layer) {
1611
1931
  }
1612
1932
  if (params.name !== void 0) identifier(params.name, "name");
1613
1933
  if (params.asset !== void 0) identifier(params.asset, "asset");
1614
- if (["heightmap", "paste"].includes(layer.type) && !params.data)
1615
- fail(`${layer.type} requires heightmap data`);
1934
+ if (layer2.type === "scatter" && typeof params.asset !== "string")
1935
+ fail(
1936
+ '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'
1937
+ );
1938
+ if (["heightmap", "paste"].includes(layer2.type) && !params.data)
1939
+ fail(`${layer2.type} requires heightmap data`);
1616
1940
  const data = params.data;
1617
1941
  if (data) {
1618
1942
  num(data.width, "data.width", 2, 4097, true);
@@ -1628,7 +1952,7 @@ function validateDocument(doc) {
1628
1952
  finiteTree(
1629
1953
  Array.isArray(doc.layers) ? {
1630
1954
  ...doc,
1631
- layers: doc.layers.map((layer) => omittedElevations(layer, layerFollowsTerrain(layer)))
1955
+ layers: doc.layers.map((layer2) => omittedElevations(layer2, layerFollowsTerrain(layer2)))
1632
1956
  } : doc,
1633
1957
  "recipe"
1634
1958
  );
@@ -1637,10 +1961,10 @@ function validateDocument(doc) {
1637
1961
  if (!Array.isArray(doc.layers) || doc.layers.length > 512)
1638
1962
  fail("layers must be an array of at most 512 layers");
1639
1963
  const ids = /* @__PURE__ */ new Set();
1640
- for (const layer of doc.layers) {
1641
- validateLayer(layer);
1642
- if (ids.has(layer.id)) fail(`Duplicate layer ID: ${layer.id}`);
1643
- ids.add(layer.id);
1964
+ for (const layer2 of doc.layers) {
1965
+ validateLayer(layer2);
1966
+ if (ids.has(layer2.id)) fail(`Duplicate layer ID: ${layer2.id}`);
1967
+ ids.add(layer2.id);
1644
1968
  }
1645
1969
  }
1646
1970
 
@@ -1662,9 +1986,9 @@ var TerrainEvaluator = class {
1662
1986
  validateDocument(doc);
1663
1987
  validateConfig({ ...doc.config, resolution });
1664
1988
  const keys = [];
1665
- let key = JSON.stringify({ ...doc.config, resolution });
1666
- for (const layer of doc.layers) {
1667
- key += `|${JSON.stringify(layer)}`;
1989
+ let key = this.limit > 0 ? JSON.stringify({ ...doc.config, resolution }) : "";
1990
+ for (const layer2 of this.limit > 0 ? doc.layers : []) {
1991
+ key += `|${JSON.stringify(layer2)}`;
1668
1992
  keys.push(key);
1669
1993
  }
1670
1994
  let state;
@@ -1683,9 +2007,9 @@ var TerrainEvaluator = class {
1683
2007
  state ??= createState(doc.config, resolution);
1684
2008
  for (let i = start; i < doc.layers.length; i++) {
1685
2009
  signal?.throwIfAborted();
1686
- const layer = doc.layers[i];
1687
- applyOperation(state, layer);
1688
- onProgress?.({ index: i, total: doc.layers.length, id: layer.id });
2010
+ const layer2 = doc.layers[i];
2011
+ applyOperation(state, layer2);
2012
+ onProgress?.({ index: i, total: doc.layers.length, id: layer2.id });
1689
2013
  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);
1690
2014
  if (bytes <= this.limit) {
1691
2015
  while (this.bytes + bytes > this.limit && this.cache.size) {
@@ -1779,15 +2103,15 @@ var Terrain = class _Terrain {
1779
2103
  }
1780
2104
  _id(type) {
1781
2105
  let i = 1;
1782
- while (this._doc.layers.some((layer) => layer.id === `${type}-${i}`)) i++;
2106
+ while (this._doc.layers.some((layer2) => layer2.id === `${type}-${i}`)) i++;
1783
2107
  return `${type}-${i}`;
1784
2108
  }
1785
- add(layer) {
1786
- const next = { enabled: true, opacity: 1, ...structuredClone(layer) };
2109
+ add(layer2) {
2110
+ const next = { enabled: true, opacity: 1, ...structuredClone(layer2) };
1787
2111
  next.id ??= this._id(next.type);
1788
2112
  validateLayer(next);
1789
2113
  return this._change(() => {
1790
- const i = this._doc.layers.findIndex((layer2) => layer2.id === next.id);
2114
+ const i = this._doc.layers.findIndex((layer3) => layer3.id === next.id);
1791
2115
  if (i < 0) this._doc.layers.push(next);
1792
2116
  else this._doc.layers[i] = next;
1793
2117
  });
@@ -1798,18 +2122,18 @@ var Terrain = class _Terrain {
1798
2122
  const data = params.data;
1799
2123
  Object.assign(params, { data: { ...data, values: Array.from(data.values) } });
1800
2124
  }
1801
- const layer = { id: id ?? this._id(type), type, params };
2125
+ const layer2 = { id: id ?? this._id(type), type, params };
1802
2126
  const optional = Object.fromEntries(
1803
2127
  Object.entries({ name: label, enabled, opacity, mask }).filter(
1804
2128
  ([, value]) => value !== void 0
1805
2129
  )
1806
2130
  );
1807
- return this.add(Object.assign(layer, optional));
2131
+ return this.add(Object.assign(layer2, optional));
1808
2132
  }
1809
2133
  layer(id) {
1810
- const layer = this._doc.layers.find((layer2) => layer2.id === id);
1811
- if (!layer) throw new Error(`Unknown layer '${id}'`);
1812
- return structuredClone(layer);
2134
+ const layer2 = this._doc.layers.find((layer3) => layer3.id === id);
2135
+ if (!layer2) throw new Error(`Unknown layer '${id}'`);
2136
+ return structuredClone(layer2);
1813
2137
  }
1814
2138
  update(id, patch) {
1815
2139
  const old = this.layer(id);
@@ -1829,16 +2153,16 @@ var Terrain = class _Terrain {
1829
2153
  if (!Number.isInteger(index) || index < 0 || index >= this._doc.layers.length)
1830
2154
  throw new RangeError("Layer index out of bounds");
1831
2155
  return this._change(() => {
1832
- const i = this._doc.layers.findIndex((layer2) => layer2.id === id);
2156
+ const i = this._doc.layers.findIndex((layer3) => layer3.id === id);
1833
2157
  if (i < 0) throw new Error(`Unknown layer '${id}'`);
1834
- const layer = this._doc.layers.splice(i, 1)[0];
1835
- this._doc.layers.splice(index, 0, layer);
2158
+ const layer2 = this._doc.layers.splice(i, 1)[0];
2159
+ this._doc.layers.splice(index, 0, layer2);
1836
2160
  });
1837
2161
  }
1838
2162
  remove(id) {
1839
2163
  this.layer(id);
1840
2164
  return this._change(() => {
1841
- this._doc.layers = this._doc.layers.filter((layer) => layer.id !== id);
2165
+ this._doc.layers = this._doc.layers.filter((layer2) => layer2.id !== id);
1842
2166
  });
1843
2167
  }
1844
2168
  setConfig(patch) {
@@ -2000,7 +2324,7 @@ var Terrain = class _Terrain {
2000
2324
  biome(options = {}) {
2001
2325
  return this._operation("biome", options);
2002
2326
  }
2003
- scatter(options = {}) {
2327
+ scatter(options) {
2004
2328
  return this._operation("scatter", options);
2005
2329
  }
2006
2330
  clear(options) {
@@ -2023,157 +2347,1797 @@ var Terrain = class _Terrain {
2023
2347
  }
2024
2348
  };
2025
2349
 
2026
- // src/core/bake.ts
2027
- var toLinear = (color) => color <= 0.04045 ? color / 12.92 : ((color + 0.055) / 1.055) ** 2.4;
2028
- function bakeMesh(state, {
2029
- step = 1,
2030
- x = 0,
2031
- z = 0,
2032
- cells = state.resolution - 1,
2033
- skirtDepth = 0,
2034
- palette
2035
- } = {}) {
2036
- if (!Number.isFinite(skirtDepth) || skirtDepth < 0)
2037
- throw new RangeError("skirtDepth must be finite and nonnegative");
2038
- const n = state.resolution;
2039
- if (!Number.isInteger(n) || n < 2 || !Number.isFinite(state.size) || state.size <= 0)
2040
- throw new RangeError("Invalid heightfield extent");
2041
- if (!Number.isInteger(step) || step < 1 || (step & step - 1) !== 0 || cells % step !== 0)
2042
- throw new RangeError("step must be a power of two dividing chunk cells");
2043
- if (![x, z, cells].every(Number.isInteger) || x < 0 || z < 0 || cells < 1 || x + cells >= n || z + cells >= n)
2044
- throw new RangeError("Chunk outside heightfield");
2045
- if (state.height.length !== n * n || !state.height.every(Number.isFinite))
2046
- throw new RangeError("Invalid heightfield samples");
2047
- if (palette && (palette.length !== 8 || Array.from(palette).some(
2048
- (rgb) => !Array.isArray(rgb) || rgb.length !== 3 || Array.from(rgb).some((value) => !Number.isFinite(value) || value < 0 || value > 1)
2049
- )))
2050
- throw new RangeError("palette requires eight finite sRGB triples in 0..1");
2051
- if (palette && (state.splat.length !== n * n * 8 || !state.splat.every(Number.isFinite)))
2052
- throw new RangeError("Invalid splat samples");
2053
- const side = cells / step + 1;
2054
- const base = side * side;
2055
- const ring = [];
2056
- if (skirtDepth > 0) {
2057
- for (let k2 = 0; k2 < side - 1; k2++) ring.push(k2);
2058
- for (let k2 = 0; k2 < side - 1; k2++) ring.push(k2 * side + side - 1);
2059
- for (let k2 = side - 1; k2 > 0; k2--) ring.push((side - 1) * side + k2);
2060
- for (let k2 = side - 1; k2 > 0; k2--) ring.push(k2 * side);
2350
+ // src/core/presets.ts
2351
+ var LANDFORMS = {
2352
+ alpine: {
2353
+ summary: "Glacier-cut granite peaks: steep headwalls, sharp ar\xEAtes, dendritic gullies.",
2354
+ reliefRatio: 0.25,
2355
+ reference: "Longs Peak, Rocky Mountain National Park, Colorado (USGS 3DEP, DEM crop `alpine`)",
2356
+ target: { slopeP50: 27.3, slopeP90: 42.5, hypsometricIntegral: 0.452, curvatureKurtosis: 89.3 }
2357
+ },
2358
+ temperateMountains: {
2359
+ summary: "Forested mountain backdrop: rounded massifs cut by branching valleys.",
2360
+ reliefRatio: 0.17,
2361
+ reference: "Sprague Lake / Glacier Creek, Rocky Mountain National Park (DEM crop `forest`)",
2362
+ target: { slopeP50: 14.7, slopeP90: 28.1, hypsometricIntegral: 0.398, curvatureKurtosis: 13.7 }
2363
+ },
2364
+ rollingHills: {
2365
+ summary: "Low dendritic hills with convex ridges and gentle slopes.",
2366
+ reliefRatio: 0.03,
2367
+ 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"
2368
+ },
2369
+ desertMesa: {
2370
+ summary: "Caprock mesas and buttes over a stepped, cliff-and-bench canyon landscape.",
2371
+ reliefRatio: 0.055,
2372
+ reference: "Valley of the Gods, Utah (DEM crop `desert`)",
2373
+ target: { slopeP50: 3.7, slopeP90: 16.9, hypsometricIntegral: 0.276, curvatureKurtosis: 203.9 }
2374
+ },
2375
+ coastalCliffs: {
2376
+ summary: "Island massif with steep rocky shore and drowned gullies.",
2377
+ reliefRatio: 0.075,
2378
+ reference: "Sand Beach / Great Head, Acadia National Park, Maine (DEM crop `coastal`)",
2379
+ target: { slopeP50: 1.6, slopeP90: 19.4, hypsometricIntegral: 0.11, curvatureKurtosis: 34.7 }
2380
+ },
2381
+ tundra: {
2382
+ summary: "Broad rounded uplands above the tree line with shallow glacial valleys.",
2383
+ reliefRatio: 0.15,
2384
+ reference: "Trail Ridge, Rocky Mountain National Park (DEM crop `tundra`)",
2385
+ target: { slopeP50: 17.1, slopeP90: 27.9, hypsometricIntegral: 0.473, curvatureKurtosis: 16.7 }
2386
+ },
2387
+ volcanic: {
2388
+ summary: "Stratovolcano cone with a summit crater and radial gullies.",
2389
+ reliefRatio: 0.18,
2390
+ 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"
2061
2391
  }
2062
- const count = base + ring.length;
2063
- const positions = new Float32Array(count * 3);
2064
- const normals = new Float32Array(count * 3);
2065
- const uvs = new Float32Array(count * 2);
2066
- const indices = new Uint32Array((side - 1) ** 2 * 6 + ring.length * 6);
2067
- const colors = palette ? new Float32Array(count * 3) : void 0;
2068
- const cell = state.size / (n - 1);
2069
- for (let zz = 0; zz < side; zz++)
2070
- for (let xx = 0; xx < side; xx++) {
2071
- const gx = x + xx * step;
2072
- const gz = z + zz * step;
2073
- const i = gz * n + gx;
2074
- const j = zz * side + xx;
2075
- const dx = (state.height[gz * n + Math.min(n - 1, gx + 1)] - state.height[gz * n + Math.max(0, gx - 1)]) / ((gx > 0 && gx < n - 1 ? 2 : 1) * cell);
2076
- const dz = (state.height[Math.min(n - 1, gz + 1) * n + gx] - state.height[Math.max(0, gz - 1) * n + gx]) / ((gz > 0 && gz < n - 1 ? 2 : 1) * cell);
2077
- const length = Math.hypot(dx, 1, dz);
2078
- positions.set([world(state, gx), state.height[i], world(state, gz)], j * 3);
2079
- normals.set([-dx / length, 1 / length, -dz / length], j * 3);
2080
- if (colors && palette)
2081
- for (let k2 = 0; k2 < 3; k2++) {
2082
- let color = 0;
2083
- for (let c = 0; c < 8; c++)
2084
- color += toLinear(palette[c]?.[k2]) * state.splat[i * 8 + c];
2085
- colors[j * 3 + k2] = color;
2392
+ };
2393
+ function landform(kind, options = {}) {
2394
+ const info = LANDFORMS[kind];
2395
+ if (!info) throw new TypeError(`Unknown landform kind: ${String(kind)}`);
2396
+ const { size = 5e3, resolution = 513, seed = 73 } = options;
2397
+ const s = size;
2398
+ const relief = options.relief ?? info.reliefRatio * s;
2399
+ const t = new Terrain({ size, resolution, seed });
2400
+ const uplift = (u) => u * (s / 5e3);
2401
+ const valleys = (u, talus, iterations) => ({
2402
+ id: "valleys",
2403
+ method: "fluvial",
2404
+ iterations,
2405
+ uplift: uplift(u),
2406
+ erodibility: 1e-5,
2407
+ talus,
2408
+ // Rescales the eroded surface, so the finished relief follows the request at any seed.
2409
+ relief
2410
+ });
2411
+ switch (kind) {
2412
+ case "alpine":
2413
+ t.noise({
2414
+ id: "massif",
2415
+ amplitude: relief * 3.01,
2416
+ scale: s * 0.535,
2417
+ octaves: 4,
2418
+ mode: "ridged",
2419
+ warp: s * 0.0706
2420
+ }).stamp({
2421
+ id: "peak",
2422
+ shape: "mountain",
2423
+ at: [0, 0],
2424
+ radius: s * 0.42,
2425
+ amplitude: relief * 7.83,
2426
+ roughness: 0.5
2427
+ }).erode(valleys(15e-5, 60.5, 49)).erode({ id: "talus", method: "thermal", iterations: 13, talus: 26.8 }).smooth({ id: "grain", iterations: 3 });
2428
+ break;
2429
+ case "temperateMountains":
2430
+ t.noise({
2431
+ id: "massif",
2432
+ amplitude: relief * 2.18,
2433
+ scale: s * 0.988,
2434
+ octaves: 4,
2435
+ mode: "fbm",
2436
+ warp: s * 0.0716
2437
+ }).stamp({
2438
+ id: "peak",
2439
+ shape: "mountain",
2440
+ at: [0, 0],
2441
+ radius: s * 0.42,
2442
+ amplitude: relief * 4.5,
2443
+ roughness: 0.5
2444
+ }).erode(valleys(413e-7, 30.2, 43)).smooth({ id: "grain", iterations: 3 });
2445
+ break;
2446
+ case "rollingHills":
2447
+ t.noise({
2448
+ id: "hills",
2449
+ amplitude: relief * 1.6,
2450
+ scale: s * 0.25,
2451
+ octaves: 4,
2452
+ mode: "fbm",
2453
+ warp: s * 0.05
2454
+ }).erode(valleys(1e-5, 12, 40)).smooth({ id: "grain", iterations: 2 });
2455
+ break;
2456
+ case "desertMesa":
2457
+ t.noise({
2458
+ id: "plateau",
2459
+ amplitude: relief * 1.75,
2460
+ scale: s * 0.447,
2461
+ octaves: 3,
2462
+ mode: "fbm",
2463
+ warp: s * 0.12
2464
+ }).erode(valleys(837e-6, 33.4, 28)).terrace({ id: "caprock", step: relief / 6, softness: 0.15, strength: 0.688 }).erode({ id: "talus", method: "thermal", iterations: 16, talus: 25 }).smooth({ id: "grain", iterations: 1 });
2465
+ break;
2466
+ case "coastalCliffs":
2467
+ t.noise({
2468
+ id: "island",
2469
+ amplitude: relief * 1.11,
2470
+ scale: s * 0.962,
2471
+ octaves: 6,
2472
+ mode: "ridged",
2473
+ warp: s * 0.0456,
2474
+ island: true,
2475
+ coastDepth: relief * 0.111
2476
+ }).erode(valleys(775e-7, 64.8, 55)).erode({ id: "talus", method: "thermal", iterations: 8, talus: 32.7 }).smooth({ id: "grain", iterations: 3 });
2477
+ break;
2478
+ case "tundra":
2479
+ t.noise({
2480
+ id: "uplands",
2481
+ amplitude: relief * 3.59,
2482
+ scale: s * 0.837,
2483
+ octaves: 4,
2484
+ mode: "fbm",
2485
+ warp: s * 0.097
2486
+ }).stamp({
2487
+ id: "ridge",
2488
+ shape: "mountain",
2489
+ at: [0, 0],
2490
+ radius: s * 0.42,
2491
+ amplitude: relief * 3.95,
2492
+ roughness: 0.5
2493
+ }).erode(valleys(869e-7, 30.1, 30)).erode({ id: "talus", method: "thermal", iterations: 8, talus: 26.2 });
2494
+ break;
2495
+ case "volcanic":
2496
+ t.noise({ id: "rubble", amplitude: relief * 0.04, scale: s * 0.1, octaves: 4, mode: "fbm" }).stamp({
2497
+ id: "cone",
2498
+ shape: "mountain",
2499
+ at: [0, 0],
2500
+ radius: s * 0.45,
2501
+ amplitude: relief,
2502
+ roughness: 0.15
2503
+ }).stamp({
2504
+ id: "crater",
2505
+ shape: "crater",
2506
+ at: [0, 0],
2507
+ radius: s * 0.07,
2508
+ amplitude: relief * 0.08,
2509
+ blend: "add"
2510
+ }).erode(valleys(3e-4, 38, 15)).erode({ id: "talus", method: "thermal", iterations: 8, talus: 36 }).smooth({ id: "grain", iterations: 1 });
2511
+ break;
2512
+ }
2513
+ return t;
2514
+ }
2515
+ function landformBackdrop(kind, options = {}) {
2516
+ const { size = 5e3, resolution = 513, seed = 73, centerHeight = 0 } = options;
2517
+ const wide = 2 * (resolution - 1) + 1;
2518
+ if (!RESOLUTIONS.includes(wide))
2519
+ throw new RangeError(`Backdrop resolution ${resolution} needs a ${wide}-sample source`);
2520
+ const relief = options.relief ?? LANDFORMS[kind].reliefRatio * size;
2521
+ const source = landform(kind, {
2522
+ size: 2 * size,
2523
+ resolution: wide,
2524
+ seed,
2525
+ relief: relief * 1.4
2526
+ }).evaluate();
2527
+ const h = source.height;
2528
+ const half = (resolution - 1) / 2;
2529
+ const stride = 8;
2530
+ let best = Number.POSITIVE_INFINITY;
2531
+ let bx = half;
2532
+ let bz = half;
2533
+ for (let cz = half; cz <= wide - 1 - half; cz += stride)
2534
+ for (let cx = half; cx <= wide - 1 - half; cx += stride) {
2535
+ let lo = Number.POSITIVE_INFINITY;
2536
+ let hi = Number.NEGATIVE_INFINITY;
2537
+ for (let z = cz - half; z <= cz + half; z += 2 * stride)
2538
+ for (let x = cx - half; x <= cx + half; x += 2 * stride) {
2539
+ const v = h[z * wide + x];
2540
+ lo = Math.min(lo, v);
2541
+ hi = Math.max(hi, v);
2086
2542
  }
2087
- uvs.set([gx / (n - 1), 1 - gz / (n - 1)], j * 2);
2543
+ const centre2 = h[cz * wide + cx];
2544
+ const rough = Math.abs(h[cz * wide + cx + 8] - centre2) + Math.abs(h[(cz + 8) * wide + cx] - centre2);
2545
+ const score = (centre2 - lo) / (hi - lo || 1) + rough / (hi - lo || 1);
2546
+ if (score < best) {
2547
+ best = score;
2548
+ bx = cx;
2549
+ bz = cz;
2550
+ }
2088
2551
  }
2089
- let k = 0;
2090
- for (let zz = 0; zz < side - 1; zz++)
2091
- for (let xx = 0; xx < side - 1; xx++) {
2092
- const a = zz * side + xx;
2093
- const b = a + 1;
2094
- const c = a + side;
2095
- const d = c + 1;
2096
- indices.set([a, c, b, b, c, d], k);
2097
- k += 6;
2552
+ const heights = new Float32Array(resolution * resolution);
2553
+ let low = Number.POSITIVE_INFINITY;
2554
+ let high = Number.NEGATIVE_INFINITY;
2555
+ for (let z = 0; z < resolution; z += 1)
2556
+ for (let x = 0; x < resolution; x += 1) {
2557
+ const v = h[(bz - half + z) * wide + bx - half + x];
2558
+ heights[z * resolution + x] = v;
2559
+ low = Math.min(low, v);
2560
+ high = Math.max(high, v);
2098
2561
  }
2099
- for (let j = 0; j < ring.length; j++) {
2100
- const top = ring[j];
2101
- const bottom = base + j;
2102
- positions.set(positions.subarray(top * 3, top * 3 + 3), bottom * 3);
2103
- positions[bottom * 3 + 1] = positions[bottom * 3 + 1] - skirtDepth;
2104
- normals.set(normals.subarray(top * 3, top * 3 + 3), bottom * 3);
2105
- colors?.set(colors.subarray(top * 3, top * 3 + 3), bottom * 3);
2106
- uvs.set(uvs.subarray(top * 2, top * 2 + 2), bottom * 2);
2107
- const next = (j + 1) % ring.length;
2108
- indices.set([top, ring[next], bottom, ring[next], base + next, bottom], k);
2109
- k += 6;
2110
- }
2562
+ const gain = relief / (high - low || 1);
2563
+ const centre = heights[half * resolution + half];
2564
+ for (let i = 0; i < heights.length; i += 1)
2565
+ heights[i] = centerHeight + (heights[i] - centre) * gain;
2566
+ return { size, resolution, heights };
2567
+ }
2568
+
2569
+ // src/core/biome.ts
2570
+ var SPEC_FIELDS = [
2571
+ "look",
2572
+ "bake",
2573
+ "landform",
2574
+ "sizeMeters",
2575
+ "seed",
2576
+ "stream",
2577
+ "cover",
2578
+ "foliage",
2579
+ "grass",
2580
+ "layers",
2581
+ "water",
2582
+ "spawn",
2583
+ "species",
2584
+ "aliases"
2585
+ ];
2586
+ var COVER_FIELDS = ["ground", "seed", "attempts", "stoneRadius", "clearings"];
2587
+ var COVER_GROUNDS = ["wood", "crag", "mesa", "mats"];
2588
+ var STREAMS = ["ordered", "seeded"];
2589
+ var DRIFT_FIELDS = ["field", "frequency", "offset", "amplitude", "band"];
2590
+ var DRIFT_FIELDS_NAMES = ["stand", "mats"];
2591
+ var FOLIAGE_FIELDS = [
2592
+ "species",
2593
+ "density",
2594
+ "slope",
2595
+ "height",
2596
+ "spacing",
2597
+ "collision",
2598
+ "stands",
2599
+ "grassThreshold",
2600
+ "standThreshold",
2601
+ "far"
2602
+ ];
2603
+ var FAR_FIELDS = [
2604
+ "cell",
2605
+ "spacing",
2606
+ "spacingAt",
2607
+ "slope",
2608
+ "meadowSlope",
2609
+ "reach",
2610
+ "treelineJitter",
2611
+ "stand",
2612
+ "seed",
2613
+ "impostor"
2614
+ ];
2615
+ var GRASS_FIELDS = [
2616
+ "species",
2617
+ "density",
2618
+ "slope",
2619
+ "height",
2620
+ "spacing",
2621
+ "slopeFalloff",
2622
+ "heightFalloff",
2623
+ "mats",
2624
+ "waterMargin",
2625
+ "beach",
2626
+ "detailSpacing",
2627
+ "drift",
2628
+ "bladeScale",
2629
+ "bladeJitter",
2630
+ "scrubChance",
2631
+ "scrubScale",
2632
+ "scrubJitter",
2633
+ "scrubBush",
2634
+ "shoreGround",
2635
+ "cobbledBed"
2636
+ ];
2637
+ var BAKE_FIELDS = ["file", "key"];
2638
+ var LAYER_FIELDS = ["layer", "from", "to", "shedFrom", "shedTo"];
2639
+ var LAYER_REQUIRED = ["layer", "from", "to"];
2640
+ var WATER_FIELDS = ["kind", "width", "radius", "depth", "level"];
2641
+ var WATER_REQUIRED = ["kind"];
2642
+ var SPAWN_FIELDS = ["at", "cameraOffset", "focus"];
2643
+ var LANDFORM_KINDS = Object.keys(LANDFORMS);
2644
+ var COLLISION_CLASSES = ["none", "trunk", "hull"];
2645
+ var WATER_KINDS = ["river", "lake", "ocean"];
2646
+ function fail2(biome, field, problem) {
2647
+ throw new TypeError(`${biome}: biome field '${field}' ${problem}.`);
2648
+ }
2649
+ function closed(value, biome, field, fields, required = fields) {
2650
+ const at = (name) => field === "" ? name : `${field}.${name}`;
2651
+ if (typeof value !== "object" || value === null || Array.isArray(value))
2652
+ fail2(biome, field || "<file>", "must be an object");
2653
+ const record = value;
2654
+ for (const key of Object.keys(record))
2655
+ if (!fields.includes(key)) fail2(biome, at(key), "is not a field a biome has");
2656
+ for (const key of required) if (!(key in record)) fail2(biome, at(key), "is missing");
2657
+ return record;
2658
+ }
2659
+ function count(value, biome, field, min = 0) {
2660
+ if (typeof value !== "number" || !Number.isFinite(value))
2661
+ fail2(biome, field, "must be a finite number");
2662
+ if (value < min) fail2(biome, field, `must be at least ${min}`);
2663
+ return value;
2664
+ }
2665
+ function positive(value, biome, field) {
2666
+ const number = count(value, biome, field);
2667
+ if (number === 0) fail2(biome, field, "must be greater than 0");
2668
+ return number;
2669
+ }
2670
+ function whole(value, biome, field, min = 0) {
2671
+ if (typeof value !== "number" || !Number.isSafeInteger(value))
2672
+ fail2(biome, field, "must be a whole number");
2673
+ if (value < min) fail2(biome, field, `must be at least ${min}`);
2674
+ return value;
2675
+ }
2676
+ function share(value, biome, field) {
2677
+ const number = count(value, biome, field);
2678
+ if (number > 1) fail2(biome, field, "must be at most 1");
2679
+ return number;
2680
+ }
2681
+ function flag(value, biome, field) {
2682
+ if (typeof value !== "boolean") fail2(biome, field, "must be true or false");
2683
+ return value;
2684
+ }
2685
+ function text(value, biome, field) {
2686
+ if (typeof value !== "string" || value.trim() === "")
2687
+ fail2(biome, field, "must be a non-empty string");
2688
+ return value;
2689
+ }
2690
+ function oneOf(value, biome, field, options) {
2691
+ if (typeof value !== "string" || !options.includes(value))
2692
+ fail2(biome, field, `must be one of ${options.join(", ")}`);
2693
+ return value;
2694
+ }
2695
+ function intervalOf(value, biome, field, size, min = 0, max = Number.POSITIVE_INFINITY) {
2696
+ if (!Array.isArray(value) || value.length !== size)
2697
+ fail2(biome, field, `must be an array of ${size} numbers`);
2698
+ const numbers = value.map((entry, index) => count(entry, biome, `${field}[${index}]`, min));
2699
+ if (numbers[0] > numbers[1])
2700
+ fail2(biome, field, "must ascend");
2701
+ for (const [index, entry] of numbers.entries())
2702
+ if (entry > max) fail2(biome, `${field}[${index}]`, `must be at most ${max}`);
2703
+ return numbers;
2704
+ }
2705
+ function band(value, biome, field) {
2706
+ if (!Array.isArray(value) || value.length !== 2)
2707
+ fail2(biome, field, "must be an array of 2 numbers");
2708
+ const [threshold = 0, span = 0] = value.map(
2709
+ (entry, index) => share(entry, biome, `${field}[${index}]`)
2710
+ );
2711
+ if (span === 0) fail2(biome, `${field}[1]`, "must be greater than 0");
2712
+ return [threshold, span];
2713
+ }
2714
+ function pair(value, biome, field, min = 0, max = Number.POSITIVE_INFINITY) {
2715
+ const [first = 0, second = 0] = intervalOf(value, biome, field, 2, min, max);
2716
+ return [first, second];
2717
+ }
2718
+ function pointOf(value, biome, field, size) {
2719
+ if (!Array.isArray(value) || value.length !== size)
2720
+ fail2(biome, field, `must be an array of ${size} numbers`);
2721
+ return value.map((entry, index) => {
2722
+ if (typeof entry !== "number" || !Number.isFinite(entry))
2723
+ fail2(biome, `${field}[${index}]`, "must be a finite number");
2724
+ return entry ?? 0;
2725
+ });
2726
+ }
2727
+ function point2(value, biome, field) {
2728
+ const [x = 0, z = 0] = pointOf(value, biome, field, 2);
2729
+ return [x, z];
2730
+ }
2731
+ function point3(value, biome, field) {
2732
+ const [x = 0, y = 0, z = 0] = pointOf(value, biome, field, 3);
2733
+ return [x, y, z];
2734
+ }
2735
+ function far(value, biome, field) {
2736
+ if (value === null) return null;
2737
+ const far2 = closed(value, biome, field, FAR_FIELDS);
2111
2738
  return {
2112
- name: `terrain_${x}_${z}_step${step}`,
2113
- positions,
2114
- normals,
2115
- colors,
2116
- uvs,
2117
- indices,
2118
- side,
2119
- topVertexCount: base,
2120
- bounds: { x, z, cells, step },
2121
- skirtDepth
2739
+ cell: positive(far2.cell, biome, `${field}.cell`),
2740
+ spacing: pair(far2.spacing, biome, `${field}.spacing`),
2741
+ spacingAt: pair(far2.spacingAt, biome, `${field}.spacingAt`),
2742
+ slope: pair(far2.slope, biome, `${field}.slope`, 0, 90),
2743
+ meadowSlope: pair(far2.meadowSlope, biome, `${field}.meadowSlope`, 0, 90),
2744
+ reach: positive(far2.reach, biome, `${field}.reach`),
2745
+ treelineJitter: count(far2.treelineJitter, biome, `${field}.treelineJitter`),
2746
+ stand: pair(far2.stand, biome, `${field}.stand`, 0, 1),
2747
+ seed: whole(far2.seed, biome, `${field}.seed`),
2748
+ impostor: count(far2.impostor, biome, `${field}.impostor`)
2122
2749
  };
2123
2750
  }
2124
- function bakeTerrain(state, {
2125
- chunkCells = Math.min(64, state.resolution - 1),
2126
- lodSteps = [1, 2, 4],
2127
- skirtDepth = 6,
2128
- palette
2129
- } = {}) {
2130
- if (!Number.isInteger(chunkCells) || chunkCells < 1 || (state.resolution - 1) % chunkCells !== 0)
2131
- throw new RangeError("chunkCells must divide resolution - 1");
2132
- if (!lodSteps.length) throw new RangeError("lodSteps must not be empty");
2133
- const lods = lodSteps.map((step) => {
2134
- const chunks = [];
2135
- for (let z = 0; z < state.resolution - 1; z += chunkCells)
2136
- for (let x = 0; x < state.resolution - 1; x += chunkCells)
2137
- chunks.push(bakeMesh(state, { x, z, cells: chunkCells, step, skirtDepth, palette }));
2138
- return { step, chunks };
2139
- });
2751
+ function frequencies(value, biome, field) {
2752
+ const [x = 0, z = 0] = pointOf(value, biome, field, 2);
2753
+ if (x <= 0 || z <= 0) fail2(biome, field, "must be two positive frequencies");
2754
+ return [x, z];
2755
+ }
2756
+ function driftRow(value, biome, field) {
2757
+ const row = closed(value, biome, field, DRIFT_FIELDS);
2140
2758
  return {
2141
- version: 1,
2142
- size: state.size,
2143
- resolution: state.resolution,
2144
- lods,
2145
- collision: {
2146
- type: "heightfield",
2147
- size: state.size,
2148
- resolution: state.resolution,
2149
- cellSize: state.size / (state.resolution - 1),
2150
- origin: [-state.size / 2, 0, -state.size / 2],
2151
- heights: state.height.slice()
2152
- },
2153
- instances: structuredClone(state.instances),
2154
- materialChannels: [...MATERIAL_IDS]
2759
+ field: oneOf(row.field, biome, `${field}.field`, DRIFT_FIELDS_NAMES),
2760
+ frequency: frequencies(row.frequency, biome, `${field}.frequency`),
2761
+ offset: share(row.offset, biome, `${field}.offset`),
2762
+ amplitude: share(row.amplitude, biome, `${field}.amplitude`),
2763
+ band: band(row.band, biome, `${field}.band`)
2155
2764
  };
2156
2765
  }
2157
- function validateBakedMesh(mesh) {
2158
- if (![mesh.positions, mesh.normals, mesh.uvs, ...mesh.colors ? [mesh.colors] : []].every(
2159
- (array) => array instanceof Float32Array
2160
- ) || !(mesh.indices instanceof Uint32Array))
2161
- throw new TypeError("Baked mesh requires Float32 attributes and Uint32 indices");
2162
- const count = mesh.positions.length / 3;
2163
- if (!count || !Number.isInteger(count) || mesh.normals.length !== count * 3 || mesh.uvs.length !== count * 2 || mesh.colors && mesh.colors.length !== count * 3 || !mesh.indices.length || mesh.indices.length % 3)
2164
- throw new RangeError("Baked mesh attribute counts do not agree");
2165
- for (const array of [
2166
- mesh.positions,
2167
- mesh.normals,
2168
- mesh.uvs,
2169
- ...mesh.colors ? [mesh.colors] : []
2766
+ function clearing(value, biome, field) {
2767
+ if (!Array.isArray(value) || value.length !== 3)
2768
+ fail2(biome, field, "must be an array of 3 numbers");
2769
+ const [x = 0, z = 0, radius = 0] = pointOf(value, biome, field, 3);
2770
+ if (radius <= 0) fail2(biome, `${field}[2]`, "must be greater than 0");
2771
+ return [x, z, radius];
2772
+ }
2773
+ function cover(value, biome) {
2774
+ const row = closed(value, biome, "cover", COVER_FIELDS);
2775
+ const clearings = row.clearings;
2776
+ if (!Array.isArray(clearings)) fail2(biome, "cover.clearings", "must be an array");
2777
+ return {
2778
+ ground: oneOf(row.ground, biome, "cover.ground", COVER_GROUNDS),
2779
+ seed: whole(row.seed, biome, "cover.seed"),
2780
+ attempts: whole(row.attempts, biome, "cover.attempts", 1),
2781
+ stoneRadius: positive(row.stoneRadius, biome, "cover.stoneRadius"),
2782
+ clearings: clearings.map((entry, index) => clearing(entry, biome, `cover.clearings[${index}]`))
2783
+ };
2784
+ }
2785
+ function foliage(value, biome, field) {
2786
+ const row = closed(value, biome, field, FOLIAGE_FIELDS);
2787
+ const height = row.height === null ? null : pair(row.height, biome, `${field}.height`);
2788
+ return {
2789
+ species: text(row.species, biome, `${field}.species`),
2790
+ density: count(row.density, biome, `${field}.density`),
2791
+ slope: pair(row.slope, biome, `${field}.slope`, 0, 90),
2792
+ height,
2793
+ spacing: pair(row.spacing, biome, `${field}.spacing`),
2794
+ collision: oneOf(row.collision, biome, `${field}.collision`, COLLISION_CLASSES),
2795
+ stands: flag(row.stands, biome, `${field}.stands`),
2796
+ grassThreshold: share(row.grassThreshold, biome, `${field}.grassThreshold`),
2797
+ standThreshold: share(row.standThreshold, biome, `${field}.standThreshold`),
2798
+ far: far(row.far, biome, `${field}.far`)
2799
+ };
2800
+ }
2801
+ function grass(value, biome, field) {
2802
+ const row = closed(value, biome, field, GRASS_FIELDS);
2803
+ const density = count(row.density, biome, `${field}.density`);
2804
+ if (density > 1) fail2(biome, `${field}.density`, "must be at most 1");
2805
+ return {
2806
+ species: text(row.species, biome, `${field}.species`),
2807
+ density,
2808
+ slope: pair(row.slope, biome, `${field}.slope`, 0, 90),
2809
+ height: row.height === null ? null : pair(row.height, biome, `${field}.height`),
2810
+ spacing: positive(row.spacing, biome, `${field}.spacing`),
2811
+ slopeFalloff: count(row.slopeFalloff, biome, `${field}.slopeFalloff`),
2812
+ heightFalloff: count(row.heightFalloff, biome, `${field}.heightFalloff`),
2813
+ mats: row.mats === null ? null : band(row.mats, biome, `${field}.mats`),
2814
+ waterMargin: count(row.waterMargin, biome, `${field}.waterMargin`),
2815
+ beach: row.beach === null ? null : pair(row.beach, biome, `${field}.beach`),
2816
+ detailSpacing: positive(row.detailSpacing, biome, `${field}.detailSpacing`),
2817
+ drift: driftRow(row.drift, biome, `${field}.drift`),
2818
+ bladeScale: count(row.bladeScale, biome, `${field}.bladeScale`),
2819
+ bladeJitter: count(row.bladeJitter, biome, `${field}.bladeJitter`),
2820
+ scrubChance: share(row.scrubChance, biome, `${field}.scrubChance`),
2821
+ scrubScale: count(row.scrubScale, biome, `${field}.scrubScale`),
2822
+ scrubJitter: count(row.scrubJitter, biome, `${field}.scrubJitter`),
2823
+ scrubBush: flag(row.scrubBush, biome, `${field}.scrubBush`),
2824
+ shoreGround: flag(row.shoreGround, biome, `${field}.shoreGround`),
2825
+ cobbledBed: flag(row.cobbledBed, biome, `${field}.cobbledBed`)
2826
+ };
2827
+ }
2828
+ function layer(value, biome, field) {
2829
+ const row = closed(value, biome, field, LAYER_FIELDS, LAYER_REQUIRED);
2830
+ const from = count(row.from, biome, `${field}.from`);
2831
+ const to = count(row.to, biome, `${field}.to`);
2832
+ if (from >= to) fail2(biome, field, "must end above where it starts");
2833
+ const shedFrom = row.shedFrom === void 0 ? void 0 : count(row.shedFrom, biome, `${field}.shedFrom`, 0);
2834
+ const shedTo = row.shedTo === void 0 ? void 0 : count(row.shedTo, biome, `${field}.shedTo`, 0);
2835
+ for (const [key, entry] of [
2836
+ ["shedFrom", shedFrom],
2837
+ ["shedTo", shedTo]
2170
2838
  ])
2171
- if (!array.every(Number.isFinite)) throw new RangeError("Baked mesh attributes must be finite");
2172
- if (mesh.indices.some((index) => index >= count))
2173
- throw new RangeError("Baked mesh index outside vertex range");
2839
+ if (entry !== void 0 && entry > 1) fail2(biome, `${field}.${key}`, "must be at most 1");
2840
+ if (shedFrom !== void 0 && shedTo !== void 0 && shedFrom >= shedTo)
2841
+ fail2(biome, field, "must shed from a gentler slope than it sheds to");
2842
+ return {
2843
+ layer: text(row.layer, biome, `${field}.layer`),
2844
+ from,
2845
+ to,
2846
+ shedFrom,
2847
+ shedTo
2848
+ };
2174
2849
  }
2175
-
2176
- // src/core/placements.ts
2850
+ function water(value, biome, field) {
2851
+ const row = closed(value, biome, field, WATER_FIELDS, WATER_REQUIRED);
2852
+ const kind = oneOf(row.kind, biome, `${field}.kind`, WATER_KINDS);
2853
+ const width = row.width === void 0 ? void 0 : positive(row.width, biome, `${field}.width`);
2854
+ const radius = row.radius === void 0 ? void 0 : positive(row.radius, biome, `${field}.radius`);
2855
+ const depth = row.depth === void 0 ? void 0 : positive(row.depth, biome, `${field}.depth`);
2856
+ const level = row.level === void 0 ? void 0 : count(row.level, biome, `${field}.level`);
2857
+ if (kind === "river" && width === void 0) fail2(biome, `${field}.width`, "is missing");
2858
+ if (kind === "lake" && radius === void 0) fail2(biome, `${field}.radius`, "is missing");
2859
+ if (kind === "ocean" && level === void 0) fail2(biome, `${field}.level`, "is missing");
2860
+ return { kind, width, radius, depth, level };
2861
+ }
2862
+ function bake(value, biome) {
2863
+ const row = closed(value, biome, "bake", BAKE_FIELDS);
2864
+ return {
2865
+ file: text(row.file, biome, "bake.file"),
2866
+ key: row.key === null ? null : text(row.key, biome, "bake.key")
2867
+ };
2868
+ }
2869
+ function spawn(value, biome) {
2870
+ const row = closed(value, biome, "spawn", SPAWN_FIELDS);
2871
+ return {
2872
+ at: point2(row.at, biome, "spawn.at"),
2873
+ cameraOffset: point3(row.cameraOffset, biome, "spawn.cameraOffset"),
2874
+ focus: point2(row.focus, biome, "spawn.focus")
2875
+ };
2876
+ }
2877
+ function species(value, biome) {
2878
+ if (!Array.isArray(value) || value.length === 0)
2879
+ fail2(biome, "species", "must be a non-empty array of asset ids");
2880
+ const names = value.map((name, index) => text(name, biome, `species[${index}]`));
2881
+ for (const [index, name] of names.entries())
2882
+ if (names.indexOf(name) !== index) fail2(biome, `species[${index}]`, `repeats '${name}'`);
2883
+ return names;
2884
+ }
2885
+ function validateBiome(spec, name) {
2886
+ if (typeof name !== "string" || name.trim() === "")
2887
+ throw new TypeError("validateBiome needs the biome's name");
2888
+ const biome = name;
2889
+ const root = closed(spec, biome, "", SPEC_FIELDS);
2890
+ const aliases = root.aliases;
2891
+ if (!Array.isArray(aliases) || aliases.length === 0)
2892
+ fail2(biome, "aliases", "must be a non-empty array of words");
2893
+ const rows = (value, field, one) => {
2894
+ if (!Array.isArray(value)) fail2(biome, field, "must be an array");
2895
+ return value.map((entry, index) => one(entry, `${field}[${index}]`));
2896
+ };
2897
+ return {
2898
+ look: text(root.look, biome, "look"),
2899
+ bake: bake(root.bake, biome),
2900
+ landform: oneOf(root.landform, biome, "landform", LANDFORM_KINDS),
2901
+ sizeMeters: positive(root.sizeMeters, biome, "sizeMeters"),
2902
+ seed: whole(root.seed, biome, "seed"),
2903
+ stream: oneOf(root.stream, biome, "stream", STREAMS),
2904
+ cover: cover(root.cover, biome),
2905
+ foliage: rows(root.foliage, "foliage", (entry, at) => foliage(entry, biome, at)),
2906
+ grass: rows(root.grass, "grass", (entry, at) => grass(entry, biome, at)),
2907
+ layers: rows(root.layers, "layers", (entry, at) => layer(entry, biome, at)),
2908
+ water: rows(root.water, "water", (entry, at) => water(entry, biome, at)),
2909
+ spawn: spawn(root.spawn, biome),
2910
+ species: species(root.species, biome),
2911
+ aliases: aliases.map(
2912
+ (word, index) => text(word, biome, `aliases[${index}]`).toLowerCase()
2913
+ )
2914
+ };
2915
+ }
2916
+
2917
+ // src/core/bands.ts
2918
+ function measureBands(layers, heights) {
2919
+ if (heights.length === 0) throw new RangeError("Terrain elevation samples are empty");
2920
+ let min = Number.POSITIVE_INFINITY;
2921
+ let max = Number.NEGATIVE_INFINITY;
2922
+ for (let index = 0; index < heights.length; index += 1) {
2923
+ const height = heights[index];
2924
+ if (!Number.isFinite(height)) throw new RangeError("Terrain elevation sample is nonfinite");
2925
+ min = Math.min(min, height);
2926
+ max = Math.max(max, height);
2927
+ }
2928
+ const span = max - min;
2929
+ if (!Number.isFinite(span)) throw new RangeError("Terrain elevation range is nonfinite");
2930
+ const resolve = (fraction) => {
2931
+ const height = min + fraction * span;
2932
+ if (!Number.isFinite(height)) throw new RangeError("Terrain elevation band is nonfinite");
2933
+ return height;
2934
+ };
2935
+ let snowBand = null;
2936
+ let snowShed = null;
2937
+ const bands = {};
2938
+ for (const layer2 of layers) {
2939
+ const band2 = [resolve(layer2.from), resolve(layer2.to)];
2940
+ if (layer2.layer === "snow") {
2941
+ snowBand = band2;
2942
+ if (layer2.shedFrom !== void 0 && layer2.shedTo !== void 0)
2943
+ snowShed = [layer2.shedFrom, layer2.shedTo];
2944
+ } else {
2945
+ bands[layer2.layer] = band2;
2946
+ }
2947
+ }
2948
+ return { bands, elevationRange: [min, max], snowBand, snowShed };
2949
+ }
2950
+ var noise = new ImprovedNoise();
2951
+ function clamp01(value) {
2952
+ return Math.min(1, Math.max(0, value));
2953
+ }
2954
+ function fieldWeight(field, x, z) {
2955
+ let sum = field.base;
2956
+ for (const octave of field.octaves)
2957
+ sum += octave.gain * noise.noise(x * octave.frequency, octave.offset, z * octave.frequency);
2958
+ return clamp01(sum);
2959
+ }
2960
+ var STAND_FIELD = {
2961
+ base: 0.5,
2962
+ octaves: [
2963
+ { gain: 0.3, frequency: 75e-4, offset: 3.1 },
2964
+ { gain: 0.2, frequency: 0.026, offset: 8.7 }
2965
+ ]
2966
+ };
2967
+ var MATS_FIELD = {
2968
+ base: 0.52,
2969
+ octaves: [
2970
+ { gain: 0.85, frequency: 0.043, offset: 11 },
2971
+ { gain: 0.15, frequency: 0.11, offset: 19 }
2972
+ ]
2973
+ };
2974
+
2975
+ // src/core/water.ts
2976
+ var EMPTY = [];
2977
+ function createSegmentIndex(segments, cellSize) {
2978
+ if (!(cellSize > 0) || !Number.isFinite(cellSize))
2979
+ throw new Error(
2980
+ `TN_TERRAIN_WATER_CELL_INVALID: cellSize must be a positive finite number, received ${String(cellSize)}.`
2981
+ );
2982
+ const cells = /* @__PURE__ */ new Map();
2983
+ for (const segment of segments) {
2984
+ const { a, b, reach } = segment;
2985
+ if (!(reach >= 0) || !Number.isFinite(reach))
2986
+ throw new Error(
2987
+ `TN_TERRAIN_WATER_REACH_INVALID: reach must be a non-negative finite number, received ${String(reach)}.`
2988
+ );
2989
+ const fromX = Math.floor((Math.min(a[0], b[0]) - reach) / cellSize);
2990
+ const toX = Math.floor((Math.max(a[0], b[0]) + reach) / cellSize);
2991
+ const fromZ = Math.floor((Math.min(a[1], b[1]) - reach) / cellSize);
2992
+ const toZ = Math.floor((Math.max(a[1], b[1]) + reach) / cellSize);
2993
+ for (let cx = fromX; cx <= toX; cx++)
2994
+ for (let cz = fromZ; cz <= toZ; cz++) {
2995
+ const key = `${cx}:${cz}`;
2996
+ const list = cells.get(key);
2997
+ if (list) list.push(segment.data);
2998
+ else cells.set(key, [segment.data]);
2999
+ }
3000
+ }
3001
+ return {
3002
+ nearby: (x, z) => cells.get(`${Math.floor(x / cellSize)}:${Math.floor(z / cellSize)}`) ?? EMPTY
3003
+ };
3004
+ }
3005
+
3006
+ // src/core/scatter-ordered.ts
3007
+ function orderedScatterRules(spec) {
3008
+ const tree = spec.foliage[0];
3009
+ const grass2 = spec.grass[0];
3010
+ if (tree === void 0 || grass2 === void 0)
3011
+ throw new RangeError(`${spec.look}: an ordered biome needs one tree and one ground cover`);
3012
+ if (spec.cover === null)
3013
+ throw new RangeError(`${spec.look}: an ordered biome needs its cover block`);
3014
+ if (tree.species !== "spruce" && tree.species !== "sapling")
3015
+ throw new RangeError(`${spec.look}: no ordered rule for the tree '${tree.species}'`);
3016
+ const { cover: cover2 } = spec;
3017
+ const drift = grass2.drift;
3018
+ if (drift === null) throw new RangeError(`${spec.look}: an ordered biome needs its cover drift`);
3019
+ return {
3020
+ ground: cover2.ground,
3021
+ seed: cover2.seed,
3022
+ attempts: cover2.attempts,
3023
+ drift: {
3024
+ field: drift.field === "mats" ? MATS_FIELD : STAND_FIELD,
3025
+ frequency: drift.frequency,
3026
+ amplitude: drift.amplitude,
3027
+ offset: drift.offset,
3028
+ band: drift.band
3029
+ },
3030
+ bladeScale: grass2.bladeScale,
3031
+ bladeJitter: grass2.bladeJitter,
3032
+ scrubChance: grass2.scrubChance,
3033
+ scrubScale: grass2.scrubScale,
3034
+ scrubJitter: grass2.scrubJitter,
3035
+ scrubBush: grass2.scrubBush,
3036
+ shoreGround: grass2.shoreGround,
3037
+ cobbledBed: grass2.cobbledBed,
3038
+ stoneRadius: cover2.stoneRadius,
3039
+ treeAsset: tree.species,
3040
+ treeCount: tree.density,
3041
+ treeSpacing: tree.spacing,
3042
+ treeStands: tree.stands,
3043
+ treeSlopeLimit: tree.slope[1],
3044
+ treeHeightCeiling: tree.height === null ? null : tree.height[1],
3045
+ treeGrassThreshold: tree.grassThreshold,
3046
+ treeStandThreshold: tree.standThreshold,
3047
+ grassCell: grass2.spacing,
3048
+ grassDensity: grass2.density,
3049
+ grassSlopeLimit: grass2.slope[1],
3050
+ grassSlopeFalloff: grass2.slopeFalloff,
3051
+ grassWaterMargin: grass2.waterMargin,
3052
+ grassBeach: grass2.beach,
3053
+ grassHeight: grass2.height === null ? null : [grass2.height[1], grass2.heightFalloff],
3054
+ grassMats: grass2.mats,
3055
+ grassDetailSpacing: grass2.detailSpacing
3056
+ };
3057
+ }
3058
+ var tundraCover = (x, z) => fieldWeight(MATS_FIELD, x, z);
3059
+ function grassWeight(data, x, z) {
3060
+ const rules = data.rules;
3061
+ const height = clampedHeight(data, x, z);
3062
+ if (rules.grassBeach && data.waterLevel !== null)
3063
+ return clamp012((height - data.waterLevel - rules.grassBeach[0]) / rules.grassBeach[1]) * clamp012((rules.grassSlopeLimit - slopeDegrees(data, x, z)) / rules.grassSlopeFalloff);
3064
+ if (data.waterLevel !== null && height < data.waterLevel + rules.grassWaterMargin) return 0;
3065
+ const slope = slopeDegrees(data, x, z);
3066
+ if (rules.grassDensity === 0) return 0;
3067
+ const meadow = clamp012((rules.grassSlopeLimit - slope) / rules.grassSlopeFalloff);
3068
+ const fade = rules.grassHeight === null ? 1 : clamp012((rules.grassHeight[0] - height) / rules.grassHeight[1]);
3069
+ const mats = rules.grassMats === null ? 1 : clamp012((forestWeight(x * 9.8, z * 8.7) - rules.grassMats[0]) / rules.grassMats[1]);
3070
+ return meadow * rules.grassDensity * fade * mats;
3071
+ }
3072
+ function depositAtIndex(data, vertex) {
3073
+ const sediment = data.erosion?.sediment[vertex] ?? 0;
3074
+ const hydraulic2 = (data.erosion?.deposition[vertex] ?? 0) / (1 + Math.sqrt(sediment));
3075
+ return Math.min(1, hydraulic2 * 0.25 + (data.erosion?.talus[vertex] ?? 0) * 0.3);
3076
+ }
3077
+ function clamp012(value) {
3078
+ return Math.min(1, Math.max(0, value));
3079
+ }
3080
+ function clampedHeight(data, x, z) {
3081
+ const limit = data.size / 2 - 1e-3;
3082
+ return data.field.heightAt(
3083
+ Math.min(limit, Math.max(-limit, x)),
3084
+ Math.min(limit, Math.max(-limit, z))
3085
+ );
3086
+ }
3087
+ function slopeDegrees(data, x, z) {
3088
+ const step = data.size / (data.resolution - 1);
3089
+ const dx = clampedHeight(data, x + step, z) - clampedHeight(data, x - step, z);
3090
+ const dz = clampedHeight(data, x, z + step) - clampedHeight(data, x, z - step);
3091
+ return Math.atan(Math.hypot(dx, dz) / (2 * step)) * 180 / Math.PI;
3092
+ }
3093
+ function forestWeight(x, z) {
3094
+ return fieldWeight(STAND_FIELD, x, z);
3095
+ }
3096
+ var fieldNoise = new ImprovedNoise();
3097
+ var sample01 = (x, y, z) => clamp012(fieldNoise.noise(x, y, z) * 0.5 + 0.5);
3098
+ function coverDriftWeight(drift, x, z) {
3099
+ const [frequencyX, frequencyZ] = drift.frequency;
3100
+ const [threshold, span] = drift.band;
3101
+ const weight = fieldWeight(drift.field, x * frequencyX, z * frequencyZ);
3102
+ return drift.offset + drift.amplitude * clamp012((weight - threshold) / span);
3103
+ }
3104
+ var GRASS_FULL = 22;
3105
+ var GRASS_THIN = 62;
3106
+ function scatterProps(data, focus, clearings = []) {
3107
+ const { spec, rules } = data;
3108
+ const temperate = rules.ground === "wood";
3109
+ const desert = rules.ground === "mesa";
3110
+ const tundra = rules.ground === "mats";
3111
+ const alpine = rules.ground === "crag";
3112
+ const treeLimit = rules.treeCount;
3113
+ const placements = [];
3114
+ const counts = Object.fromEntries(
3115
+ [
3116
+ "boulder",
3117
+ "bush",
3118
+ "fern",
3119
+ "grass",
3120
+ "litter",
3121
+ "poppy",
3122
+ "sapling",
3123
+ "scrub",
3124
+ "spruce",
3125
+ "riverrock",
3126
+ "scree",
3127
+ "cliff",
3128
+ "mountain",
3129
+ "volcanic",
3130
+ "reveal"
3131
+ ].map((name) => [name, 0])
3132
+ );
3133
+ const random2 = createRandom(rules.seed);
3134
+ const half = data.size / 2;
3135
+ const inside = (x, z) => Math.abs(x) < half - 3 && Math.abs(z) < half - 3;
3136
+ const riverIndex = createSegmentIndex(
3137
+ spec.water.some((body) => body.kind === "river") ? (data.rivers ?? []).flatMap(
3138
+ (river) => river.points.flatMap((b, index) => {
3139
+ const a = river.points[index - 1];
3140
+ return a ? [
3141
+ {
3142
+ a: [a[0] ?? 0, a[2] ?? 0],
3143
+ b: [b[0] ?? 0, b[2] ?? 0],
3144
+ reach: river.width * 2.5,
3145
+ data: { a, b, reach: river.width * 2.5 }
3146
+ }
3147
+ ] : [];
3148
+ })
3149
+ ) : [],
3150
+ 32
3151
+ );
3152
+ const nearRiver = (x, z) => riverIndex.nearby(x, z).some(({ a, b, reach }) => {
3153
+ const dx = (b[0] ?? 0) - (a[0] ?? 0);
3154
+ const dz = (b[2] ?? 0) - (a[2] ?? 0);
3155
+ const t = clamp012(
3156
+ ((x - (a[0] ?? 0)) * dx + (z - (a[2] ?? 0)) * dz) / (dx * dx + dz * dz || 1)
3157
+ );
3158
+ const distance = Math.hypot(x - (a[0] ?? 0) - t * dx, z - (a[2] ?? 0) - t * dz);
3159
+ const level = (a[1] ?? 0) + t * ((b[1] ?? 0) - (a[1] ?? 0));
3160
+ return distance < reach && clampedHeight(data, x, z) < level + 0.35;
3161
+ });
3162
+ const wet = (x, z) => data.waterLevel !== null && clampedHeight(data, x, z) < data.waterLevel + 0.35 || tundra && nearRiver(x, z) || (data.lakes ?? []).some(
3163
+ (lake) => Math.hypot(x - (lake.at[0] ?? 0), z - (lake.at[1] ?? 0)) < lake.radius && clampedHeight(data, x, z) < lake.level + 0.35
3164
+ );
3165
+ const depositsAt = (x, z) => {
3166
+ const column = Math.max(
3167
+ 0,
3168
+ Math.min(data.resolution - 1, Math.round((x / data.size + 0.5) * (data.resolution - 1)))
3169
+ );
3170
+ const row = Math.max(
3171
+ 0,
3172
+ Math.min(data.resolution - 1, Math.round((z / data.size + 0.5) * (data.resolution - 1)))
3173
+ );
3174
+ return depositAtIndex(data, row * data.resolution + column);
3175
+ };
3176
+ const put = (asset, x, z, scale, suffix = "") => {
3177
+ if (!inside(x, z) || asset !== "riverrock" && asset !== "pebble" && wet(x, z)) return;
3178
+ if (data.erosion && asset === "scree" && depositsAt(x, z) < 0.08) {
3179
+ const slope = slopeDegrees(data, x, z);
3180
+ if (!(alpine || desert) || slope < 18 || slope > 38) return;
3181
+ }
3182
+ if (asset === "cliff") {
3183
+ const reach = 18 * Math.SQRT1_2 * scale;
3184
+ if (data.waterLevel !== null || [-reach, 0, reach].some(
3185
+ (dx) => [-reach, 0, reach].some(
3186
+ (dz) => grassWeight(data, x + dx, z + dz) > 0.05 || slopeDegrees(data, x + dx, z + dz) < 43
3187
+ )
3188
+ ))
3189
+ return;
3190
+ }
3191
+ if (alpine && asset === "mountain" && (Math.abs(x) > half - 48 || Math.abs(z) > half - 48))
3192
+ return;
3193
+ if (desert && ["boulder", "scree", "volcanic", "reveal"].includes(asset)) {
3194
+ const height = clampedHeight(data, x, z);
3195
+ const slope = slopeDegrees(data, x, z);
3196
+ const neighbours = [
3197
+ [-18, 0],
3198
+ [18, 0],
3199
+ [0, -18],
3200
+ [0, 18]
3201
+ ].map(([dx, dz]) => clampedHeight(data, x + (dx ?? 0), z + (dz ?? 0)));
3202
+ const foot = slope < 35 && Math.max(...neighbours) > height + 8;
3203
+ const rim = slope < 24 && Math.min(...neighbours) < height - 8;
3204
+ if (!foot && !rim) return;
3205
+ }
3206
+ const index = counts[asset] ?? 0;
3207
+ const crag = asset === "mountain" || asset === "volcanic" || asset === "reveal";
3208
+ const bedded = temperate && ["boulder", "riverrock", "scree", "pebble"].includes(asset);
3209
+ const normal = crag || bedded ? data.field.normalAt(x, z) : void 0;
3210
+ if (crag && normal) {
3211
+ normal.y += 0.65;
3212
+ normal.normalize();
3213
+ }
3214
+ placements.push({
3215
+ asset,
3216
+ id: `temperate-${asset}:${index}${suffix}`,
3217
+ layer: `temperate-${asset}`,
3218
+ alignToNormal: crag || bedded || temperate && (asset === "spruce" || asset === "sapling"),
3219
+ normal: (crag || bedded) && normal ? normal.toArray() : temperate && (asset === "spruce" || asset === "sapling") ? [Math.sin(x * 1.17 + z) * 0.045, 1, Math.cos(z * 1.31 - x) * 0.045] : [0, 1, 0],
3220
+ position: [x, clampedHeight(data, x, z), z],
3221
+ rotation: crag && normal ? Math.atan2(normal.x, normal.z) + (random2() - 0.5) * 0.6 : random2() * Math.PI * 2,
3222
+ scale
3223
+ });
3224
+ counts[asset] = index + 1;
3225
+ };
3226
+ const nearEye = (x, z) => clearings.some(([cx, cz, radius]) => Math.hypot(x - cx, z - cz) < radius * 1.6);
3227
+ const cells = /* @__PURE__ */ new Map();
3228
+ const CELL = 7;
3229
+ const crowded = (x, z, reach) => {
3230
+ const cx = Math.floor(x / CELL);
3231
+ const cz = Math.floor(z / CELL);
3232
+ for (let dz = -1; dz <= 1; dz++)
3233
+ for (let dx = -1; dx <= 1; dx++)
3234
+ for (const [tx, tz, tr] of cells.get(`${cx + dx},${cz + dz}`) ?? [])
3235
+ if (Math.hypot(tx - x, tz - z) < Math.max(reach, tr)) return true;
3236
+ return false;
3237
+ };
3238
+ const treeAsset = rules.treeAsset;
3239
+ const hollow = (x, z) => {
3240
+ const here = clampedHeight(data, x, z);
3241
+ const around = [-26, -13, 13, 26].map(
3242
+ (d) => (clampedHeight(data, x + d, z) + clampedHeight(data, x, z + d)) / 2
3243
+ );
3244
+ return clamp012(((Math.max(...around) - here) / 3.5 + 0.15) * 0.5);
3245
+ };
3246
+ for (let tries = 0; (counts[treeAsset] ?? 0) < treeLimit && tries < rules.attempts; tries++) {
3247
+ const x = (random2() - 0.5) * data.size;
3248
+ const z = (random2() - 0.5) * data.size;
3249
+ if (!inside(x, z) || wet(x, z) || nearEye(x, z) || slopeDegrees(data, x, z) > rules.treeSlopeLimit || data.waterLevel !== null && clampedHeight(data, x, z) < data.waterLevel + rules.grassWaterMargin || rules.treeHeightCeiling !== null && clampedHeight(data, x, z) > rules.treeHeightCeiling || grassWeight(data, x, z) < rules.treeGrassThreshold || forestWeight(x, z) < rules.treeStandThreshold)
3250
+ continue;
3251
+ const stand = forestWeight(x, z);
3252
+ const reach = rules.treeStands ? rules.treeSpacing[1] - rules.treeSpacing[0] * clamp012((stand - 0.28) / 0.5) : rules.treeSpacing[0];
3253
+ if (crowded(x, z, reach)) continue;
3254
+ const key = `${Math.floor(x / CELL)},${Math.floor(z / CELL)}`;
3255
+ const bucket = cells.get(key) ?? [];
3256
+ bucket.push([x, z, reach]);
3257
+ cells.set(key, bucket);
3258
+ const age = sample01(x * 0.021, 7, z * 0.021);
3259
+ put(
3260
+ treeAsset,
3261
+ x,
3262
+ z,
3263
+ temperate ? 0.42 + 1.18 * age ** 1.6 + random2() * 0.16 : (tundra ? 0.25 : 0.55) + random2() * 0.35
3264
+ );
3265
+ const edge = stand < 0.57;
3266
+ for (let i = 0; i < (tundra ? 0 : edge ? 2 : 1); i++) {
3267
+ const angle = random2() * Math.PI * 2;
3268
+ const reachOut = 2 + random2() * 4;
3269
+ const sx = x + Math.cos(angle) * reachOut;
3270
+ const sz = z + Math.sin(angle) * reachOut;
3271
+ if (!nearEye(sx, sz) && grassWeight(data, sx, sz) > 0.25)
3272
+ put("sapling", sx, sz, 0.55 + random2() * 0.9);
3273
+ }
3274
+ if (temperate)
3275
+ for (let i = 0; i < 2; i++)
3276
+ put("fern", x + (random2() - 0.5) * 7, z + (random2() - 0.5) * 7, 0.6 + random2() * 0.75);
3277
+ }
3278
+ if (temperate) {
3279
+ for (let i = 0; i < 14e3; i++) {
3280
+ const x = (random2() - 0.5) * data.size;
3281
+ const z = (random2() - 0.5) * data.size;
3282
+ if (!inside(x, z) || wet(x, z) || nearEye(x, z)) continue;
3283
+ if (slopeDegrees(data, x, z) > 30) continue;
3284
+ const stand = forestWeight(x, z);
3285
+ const damp = hollow(x, z);
3286
+ const open = grassWeight(data, x, z);
3287
+ if (open < 0.28) continue;
3288
+ if (stand > 0.44 && random2() < (stand - 0.4) * 1.9 + damp * 0.25)
3289
+ put("litter", x, z, 0.65 + random2() * 1.1);
3290
+ if (stand > 0.4 && damp > 0.25 && random2() < damp * 0.55)
3291
+ put("fern", x, z, 0.7 + random2() * 0.8);
3292
+ if (stand < 0.66 && random2() < 0.05 + damp * 0.16 + (stand < 0.5 ? 0.06 : 0))
3293
+ put("bush", x, z, 0.5 + random2() * 1.1);
3294
+ if (stand < 0.58 && damp > 0.18 && random2() < 0.02 + damp * 0.05)
3295
+ put("poppy", x, z, 0.75 + random2() * 0.6);
3296
+ }
3297
+ }
3298
+ if (tundra || desert) {
3299
+ for (let i = 0; i < (tundra ? 1100 : 900); i++) {
3300
+ const cx = (random2() - 0.5) * data.size;
3301
+ const cz = (random2() - 0.5) * data.size;
3302
+ if (!inside(cx, cz)) continue;
3303
+ const bias = tundra ? clamp012((tundraCover(cx, cz) - 0.42) / 0.3) : clamp012((hollow(cx, cz) - 0.1) * 1.5);
3304
+ if (random2() > 0.3 + bias * 0.65) continue;
3305
+ const radius = tundra ? 1.2 + random2() * 3 : 1.8 + random2() * 4.5;
3306
+ const tufts = tundra ? 8 + Math.floor(random2() * 14) : 5 + Math.floor(random2() * 9);
3307
+ for (let k = 0; k < tufts; k++) {
3308
+ const angle = random2() * Math.PI * 2;
3309
+ const out = radius * Math.sqrt(random2());
3310
+ cover2(cx + Math.cos(angle) * out, cz + Math.sin(angle) * out, 0.85);
3311
+ }
3312
+ }
3313
+ }
3314
+ if (alpine) {
3315
+ for (let z = -half + 48; z < half - 48; z += 24)
3316
+ for (let x = -half + 48; x < half - 48; x += 24) {
3317
+ const sx = x + (random2() - 0.5) * 12;
3318
+ const sz = z + (random2() - 0.5) * 12;
3319
+ if (slopeDegrees(data, sx, sz) < 40 || clampedHeight(data, sx, sz) < 65 || random2() > 0.55)
3320
+ continue;
3321
+ const metres = 2 + random2() * 3;
3322
+ put("mountain", sx, sz, metres / 24);
3323
+ const fall = data.field.normalAt(sx, sz);
3324
+ const length = Math.hypot(fall.x, fall.z) || 1;
3325
+ const overlapX = sx + fall.x / length * metres * 0.28;
3326
+ const overlapZ = sz + fall.z / length * metres * 0.28;
3327
+ if (clampedHeight(data, overlapX, overlapZ) > 42 && slopeDegrees(data, overlapX, overlapZ) > 28)
3328
+ put("mountain", overlapX, overlapZ, metres * 0.85 / 24);
3329
+ for (let k = 0; k < 28; k++) {
3330
+ const down = 16 + random2() * 24;
3331
+ const across = (random2() - 0.5) * down;
3332
+ const tx = sx + (fall.x * down - fall.z * across) / length;
3333
+ const tz = sz + (fall.z * down + fall.x * across) / length;
3334
+ if (slopeDegrees(data, tx, tz) < 38) put("scree", tx, tz, 0.08 + random2() * 0.28);
3335
+ }
3336
+ }
3337
+ }
3338
+ if (desert) {
3339
+ for (let z = -half + 18; z < half - 18; z += 9)
3340
+ for (let x = -half + 18; x < half - 18; x += 9) {
3341
+ const sx = x + (random2() - 0.5) * 7;
3342
+ const sz = z + (random2() - 0.5) * 7;
3343
+ if (random2() < 0.7) put("volcanic", sx, sz, 0.06 + random2() * 0.12);
3344
+ if (random2() < 0.5) put("reveal", sx, sz, 0.15 + random2() * 0.2);
3345
+ }
3346
+ }
3347
+ for (let i = 0; i < (temperate ? 1100 : 2400); i++) {
3348
+ const x = (random2() - 0.5) * data.size;
3349
+ const z = (random2() - 0.5) * data.size;
3350
+ if (!inside(x, z) || wet(x, z)) continue;
3351
+ const slope = slopeDegrees(data, x, z);
3352
+ const deposits = depositsAt(x, z);
3353
+ if (slope < (tundra ? 3 : desert ? 8 : 15) && deposits < 0.18 || random2() > 0.38 || nearEye(x, z))
3354
+ continue;
3355
+ if (slope > 43) {
3356
+ if (temperate && random2() < 0.22) put("cliff", x, z, 0.65 + random2() * 0.5);
3357
+ continue;
3358
+ }
3359
+ if (deposits > 0.12 && slope < 40 && random2() < 0.65) {
3360
+ for (let k = 0; k < 3; k++)
3361
+ put("scree", x + (random2() - 0.5) * 8, z + (random2() - 0.5) * 8, 0.12 + random2() * 0.3);
3362
+ }
3363
+ if (alpine && slope > 18 && slope < 38) {
3364
+ for (let k = 0; k < 8; k++) {
3365
+ const sx = x + (random2() - 0.5) * 14;
3366
+ const sz = z + (random2() - 0.5) * 14;
3367
+ if (slopeDegrees(data, sx, sz) < 42) put("scree", sx, sz, 0.12 + random2() * 0.22);
3368
+ }
3369
+ }
3370
+ for (let k = 0; k < 2 + Math.floor(random2() * 3); k++)
3371
+ put("boulder", x + (random2() - 0.5) * 8, z + (random2() - 0.5) * 8, 0.45 + random2() * 0.8);
3372
+ }
3373
+ if (temperate && data.waterLevel !== null) {
3374
+ for (let i = 0; i < 2200; i++) {
3375
+ const x = (random2() - 0.5) * data.size;
3376
+ const z = (random2() - 0.5) * data.size;
3377
+ const above = clampedHeight(data, x, z) - data.waterLevel;
3378
+ if (above < 0.4 || above > 4.8 || slopeDegrees(data, x, z) > 38 || random2() > 0.28) continue;
3379
+ put("riverrock", x, z, 0.8 + random2() * 2.4);
3380
+ if (random2() < 0.22) put("boulder", x + 1.2, z - 1.2, 0.3 + random2() * 0.5);
3381
+ }
3382
+ }
3383
+ for (const river of data.rivers ?? []) {
3384
+ for (let i = 1; i < river.points.length; i++) {
3385
+ const a = river.points[i - 1];
3386
+ const b = river.points[i];
3387
+ if (!a || !b) continue;
3388
+ const dx = (b[0] ?? 0) - (a[0] ?? 0);
3389
+ const dz = (b[2] ?? 0) - (a[2] ?? 0);
3390
+ const length = Math.hypot(dx, dz);
3391
+ for (let at = 0; at < length; at += 2.4) {
3392
+ const side = random2() < 0.5 ? -1 : 1;
3393
+ const reach = river.width * (0.42 + random2() * 0.3) * side;
3394
+ put(
3395
+ "riverrock",
3396
+ (a[0] ?? 0) + dx * at / length - dz / length * reach,
3397
+ (a[2] ?? 0) + dz * at / length + dx / length * reach,
3398
+ 0.5 + random2() * 1.2
3399
+ );
3400
+ }
3401
+ }
3402
+ }
3403
+ function cover2(x, z, density) {
3404
+ if (!inside(x, z) || wet(x, z) || slopeDegrees(data, x, z) > 34 || (tundra ? clamp012((tundraCover(x, z) - 0.47) / 0.3) : grassWeight(data, x, z)) < 0.22)
3405
+ return;
3406
+ const drift = coverDriftWeight(rules.drift, x, z);
3407
+ if (random2() > density * drift) return;
3408
+ const shore = rules.shoreGround && clampedHeight(data, x, z) < (data.waterLevel ?? 0) + rules.grassWaterMargin;
3409
+ put("grass", x, z, (shore ? 2.2 : rules.bladeScale) + random2() * rules.bladeJitter);
3410
+ if (desert) {
3411
+ for (let tuft = 0; tuft < 3; tuft++)
3412
+ put(
3413
+ "grass",
3414
+ x + (random2() - 0.5) * 1.4,
3415
+ z + (random2() - 0.5) * 1.4,
3416
+ 0.65 + random2() * 0.55
3417
+ );
3418
+ }
3419
+ if (random2() < rules.scrubChance)
3420
+ put(
3421
+ "scrub",
3422
+ x + (random2() - 0.5),
3423
+ z + (random2() - 0.5),
3424
+ rules.scrubScale + random2() * rules.scrubJitter
3425
+ );
3426
+ if (rules.scrubBush && random2() < 0.02)
3427
+ put("bush", x + (random2() - 0.5) * 2, z + (random2() - 0.5) * 2, 0.6 + random2() * 0.45);
3428
+ }
3429
+ for (let z = -half + 3; z < half - 3; z += rules.grassCell)
3430
+ for (let x = -half + 3; x < half - 3; x += rules.grassCell)
3431
+ cover2(
3432
+ x + (random2() - 0.5) * (temperate ? 1.5 : desert ? 6 : tundra ? 1.7 : 3),
3433
+ z + (random2() - 0.5) * (temperate ? 1.5 : desert ? 6 : tundra ? 1.7 : 3),
3434
+ 0.7
3435
+ );
3436
+ const eyes = [focus, ...clearings.map(([x, z]) => ({ x, z }))];
3437
+ for (const eye of eyes) {
3438
+ const eyeStep = rules.grassDetailSpacing;
3439
+ const eyeReach = temperate ? GRASS_THIN : GRASS_FULL + 22;
3440
+ if (tundra) {
3441
+ for (let i = 0; i < Math.ceil(Math.PI * eyeReach ** 2 / eyeStep ** 2); i++) {
3442
+ const angle = random2() * Math.PI * 2;
3443
+ const distance = Math.sqrt(random2()) * eyeReach;
3444
+ const density = Math.max(
3445
+ 0.08,
3446
+ 1 - Math.max(0, distance - GRASS_FULL) / (eyeReach - GRASS_FULL)
3447
+ );
3448
+ cover2(eye.x + Math.cos(angle) * distance, eye.z + Math.sin(angle) * distance, density);
3449
+ }
3450
+ continue;
3451
+ }
3452
+ for (let dz = -eyeReach; dz < eyeReach; dz += eyeStep)
3453
+ for (let dx = -eyeReach; dx < eyeReach; dx += eyeStep) {
3454
+ const distance = Math.hypot(dx, dz);
3455
+ if (distance > eyeReach) continue;
3456
+ const density = Math.max(
3457
+ 0.08,
3458
+ 1 - Math.max(0, distance - GRASS_FULL) / (eyeReach - GRASS_FULL)
3459
+ );
3460
+ cover2(eye.x + dx + (random2() - 0.5) * 0.6, eye.z + dz + (random2() - 0.5) * 0.6, density);
3461
+ }
3462
+ for (let p = 0; p < (temperate ? 14 : 0); p++) {
3463
+ const angle = random2() * Math.PI * 2;
3464
+ const reach = random2() * 32;
3465
+ const px = eye.x + Math.cos(angle) * reach;
3466
+ const pz = eye.z + Math.sin(angle) * reach;
3467
+ if (forestWeight(px, pz) > 0.62 && !nearEye(px, pz)) continue;
3468
+ const radius = 2.5 + random2() * 3.5;
3469
+ for (let k = 0; k < 100; k++) {
3470
+ const x = px + (random2() - 0.5) * radius * 2;
3471
+ const z = pz + (random2() - 0.5) * radius * 2;
3472
+ if (Math.hypot(x - px, z - pz) > radius || slopeDegrees(data, x, z) > 28 || grassWeight(data, x, z) < 0.4)
3473
+ continue;
3474
+ put("poppy", x, z, 0.8 + random2() * 0.4);
3475
+ }
3476
+ }
3477
+ }
3478
+ if (temperate) {
3479
+ const dressing = createRandom(rules.seed + 12);
3480
+ const outcropSlope = Math.min(
3481
+ 30,
3482
+ slopeQuantile(
3483
+ { height: data.field.heights, resolution: data.resolution, size: data.size },
3484
+ 0.98
3485
+ )
3486
+ );
3487
+ for (let z = -half + 12; z < half - 12; z += 12)
3488
+ for (let x = -half + 12; x < half - 12; x += 12) {
3489
+ const sx = x + (dressing() - 0.5) * 10;
3490
+ const sz = z + (dressing() - 0.5) * 10;
3491
+ const slope = slopeDegrees(data, sx, sz);
3492
+ const height = clampedHeight(data, sx, sz);
3493
+ const shore = data.waterLevel !== null && height > data.waterLevel + 0.4 && height < data.waterLevel + 7;
3494
+ if (nearEye(sx, sz) || wet(sx, sz)) continue;
3495
+ if (shore && slope > 12 && dressing() < 0.65)
3496
+ put("mountain", sx, sz, (5 + dressing() * 10) / 24, ":outcrop");
3497
+ else if (slope > outcropSlope && slope < 64 && dressing() < 0.6)
3498
+ put("mountain", sx, sz, (10 + dressing() * 10) / 24, ":outcrop");
3499
+ }
3500
+ }
3501
+ if (rules.cobbledBed)
3502
+ for (const river of data.rivers ?? [])
3503
+ for (let i = 1; i < river.points.length; i++) {
3504
+ const [ax = 0, ay = 0, az = 0] = river.points[i - 1] ?? [];
3505
+ const [bx = 0, by = 0, bz = 0] = river.points[i] ?? [];
3506
+ const length = Math.hypot(bx - ax, bz - az) || 1;
3507
+ const ux = (bx - ax) / length;
3508
+ const uz = (bz - az) / length;
3509
+ for (let at = 0; at < length; at += 0.6) {
3510
+ const level = ay + (by - ay) * at / length;
3511
+ const across = (o) => [ax + ux * at - uz * o, az + uz * at + ux * o];
3512
+ const depth = (o) => level - clampedHeight(data, ...across(o));
3513
+ for (let n = 0; n < 6; n++) {
3514
+ const o = (random2() - 0.5) * 18;
3515
+ const d = depth(o);
3516
+ if (d > 0.05 && d < 1.6)
3517
+ put("pebble", ...across(o), (0.08 + random2() ** 2 * 0.22) / rules.stoneRadius);
3518
+ }
3519
+ for (const side of [-1, 1]) {
3520
+ let edge = 0;
3521
+ while (edge < 12 && depth(side * edge) > 0) edge += 0.5;
3522
+ const o = side * (edge - 1 - random2() * 1.5);
3523
+ const d = depth(o);
3524
+ if (random2() < 0.08 && d > 0.12 && d < 0.5)
3525
+ put("pebble", ...across(o), (d + 0.12 + random2() * 0.2) / 1.6);
3526
+ const [x, z] = across(side * edge);
3527
+ const run = clamp012((sample01(x * 0.06, 11, z * 0.06) - 0.42) / 0.2);
3528
+ if (random2() < run * 0.45)
3529
+ for (let k = random2() < 0.4 ? 2 : 1; k > 0; k--)
3530
+ put(
3531
+ "riverrock",
3532
+ ...across(side * (edge - 1.1 + random2() * 1.2)),
3533
+ 0.6 + random2() ** 1.5 * 1.6
3534
+ );
3535
+ }
3536
+ }
3537
+ }
3538
+ const drowned = ({ asset, position: [x, , z] }) => GROWING.has(asset) && (TRUNKS.has(asset) ? BANK : BANK.slice(0, 1)).some(
3539
+ ([dx, dz]) => wet(x + dx, z + dz) || nearRiver(x + dx, z + dz)
3540
+ );
3541
+ const growing = {};
3542
+ const kept = placements.filter((placement) => !drowned(placement)).map((placement) => {
3543
+ if (!GROWING.has(placement.asset)) return placement;
3544
+ const index = growing[placement.asset] ?? 0;
3545
+ growing[placement.asset] = index + 1;
3546
+ return { ...placement, id: `temperate-${placement.asset}:${index}` };
3547
+ });
3548
+ for (const asset of GROWING) if (asset in counts) counts[asset] = growing[asset] ?? 0;
3549
+ return { counts, placements: kept };
3550
+ }
3551
+ var GROWING = /* @__PURE__ */ new Set(["spruce", "sapling", "bush", "fern", "grass", "scrub", "poppy", "litter"]);
3552
+ var TRUNKS = /* @__PURE__ */ new Set(["spruce", "sapling"]);
3553
+ var BANK = [
3554
+ [0, 0],
3555
+ [1, 0],
3556
+ [-1, 0],
3557
+ [0, 1],
3558
+ [0, -1]
3559
+ ];
3560
+
3561
+ // src/core/world-package.ts
3562
+ var HEIGHTMAP_MAX = 65535;
3563
+ var RECORD_VALUES = 8;
3564
+ var COMPONENTS = ["r", "g", "b", "a"];
3565
+ var PLANES = MATERIAL_IDS.length / COMPONENTS.length;
3566
+ var SCALE_TOLERANCE = 1e-3;
3567
+ var SLOTS = MATERIAL_IDS.map((id, channel) => ({
3568
+ channel,
3569
+ component: COMPONENTS[channel % COMPONENTS.length],
3570
+ componentIndex: channel % COMPONENTS.length,
3571
+ id,
3572
+ plane: Math.floor(channel / COMPONENTS.length)
3573
+ }));
3574
+ function poseOf(item) {
3575
+ if (item.transform === void 0)
3576
+ return {
3577
+ position: item.position,
3578
+ quaternion: [0, Math.sin(item.rotation / 2), 0, Math.cos(item.rotation / 2)],
3579
+ scale: [item.scale, item.scale, item.scale]
3580
+ };
3581
+ const { position, quaternion, scale } = item.transform;
3582
+ return { position, quaternion, scale };
3583
+ }
3584
+ function uniformScale(asset, id, scale) {
3585
+ const mean = (scale[0] + scale[1] + scale[2]) / 3;
3586
+ const magnitude = Math.abs(mean);
3587
+ const deviation = Math.max(
3588
+ Math.abs(scale[0] - mean),
3589
+ Math.abs(scale[1] - mean),
3590
+ Math.abs(scale[2] - mean)
3591
+ );
3592
+ if (!(magnitude > 0) || deviation > magnitude * SCALE_TOLERANCE)
3593
+ throw Error(
3594
+ `World package: placement '${id}' of asset '${asset}' is scaled ${JSON.stringify(scale)}; a placement record carries one uniform scale.`
3595
+ );
3596
+ return mean;
3597
+ }
3598
+ function writePlacementRecord(out, offset, item, extent) {
3599
+ if (item.transform === void 0 && !Number.isFinite(item.rotation))
3600
+ throw Error(`World package: placement '${item.id}' has a non-finite rotation.`);
3601
+ const { position, quaternion, scale } = poseOf(item);
3602
+ if (!Number.isFinite(position[0]) || !Number.isFinite(position[1]) || !Number.isFinite(position[2]))
3603
+ throw Error(
3604
+ `World package: placement '${item.id}' has a non-finite position [${position.join(", ")}].`
3605
+ );
3606
+ if (position[0] < extent.minX || position[0] > extent.minX + extent.sizeX || position[2] < extent.minZ || position[2] > extent.minZ + extent.sizeZ)
3607
+ throw Error(
3608
+ `World package: placement '${item.id}' position [${position[0]}, ${position[2]}] is outside extent bounds [${extent.minX}..${extent.minX + extent.sizeX}, ${extent.minZ}..${extent.minZ + extent.sizeZ}].`
3609
+ );
3610
+ const length = Math.hypot(...quaternion);
3611
+ if (!(length > 0)) throw Error(`World package: placement '${item.id}' has a zero quaternion.`);
3612
+ out[offset] = position[0];
3613
+ out[offset + 1] = position[1];
3614
+ out[offset + 2] = position[2];
3615
+ out[offset + 3] = quaternion[0] / length;
3616
+ out[offset + 4] = quaternion[1] / length;
3617
+ out[offset + 5] = quaternion[2] / length;
3618
+ out[offset + 6] = quaternion[3] / length;
3619
+ out[offset + 7] = uniformScale(item.asset, item.id, scale);
3620
+ }
3621
+ function placementCells(state, assets, cellSize, extent) {
3622
+ const cells = /* @__PURE__ */ new Map();
3623
+ const cellOf = (value, min, size) => Math.min(
3624
+ Math.max(1, Math.ceil(size / cellSize)) - 1,
3625
+ Math.max(0, Math.floor((value - min) / cellSize))
3626
+ );
3627
+ for (const item of state.instances) {
3628
+ if (assets[item.asset] === void 0)
3629
+ throw Error(
3630
+ `World package: placement '${item.id}' names asset '${item.asset}', which options.assets does not.`
3631
+ );
3632
+ const x = cellOf(item.position[0], extent.minX, extent.sizeX);
3633
+ const z = cellOf(item.position[2], extent.minZ, extent.sizeZ);
3634
+ const key = `${String(x)},${String(z)}`;
3635
+ let cell = cells.get(key);
3636
+ if (cell === void 0) {
3637
+ cell = { items: /* @__PURE__ */ new Map(), x, z };
3638
+ cells.set(key, cell);
3639
+ }
3640
+ const bucket = cell.items.get(item.asset);
3641
+ if (bucket === void 0) cell.items.set(item.asset, [item]);
3642
+ else bucket.push(item);
3643
+ }
3644
+ const buffer = new ArrayBuffer(state.instances.length * RECORD_VALUES * 4);
3645
+ const records = new Float32Array(buffer);
3646
+ const ordered = [];
3647
+ const ids = [];
3648
+ let written = 0;
3649
+ const byId = (left, right) => left[0] < right[0] ? -1 : 1;
3650
+ for (const cell of [...cells.values()].sort((a, b) => a.x - b.x || a.z - b.z)) {
3651
+ const runs = [];
3652
+ for (const [asset, items] of [...cell.items.entries()].sort(byId)) {
3653
+ runs.push({ asset, count: items.length, offset: written });
3654
+ for (const item of items) {
3655
+ writePlacementRecord(records, written * RECORD_VALUES, item, extent);
3656
+ ids.push(item.id);
3657
+ written += 1;
3658
+ }
3659
+ }
3660
+ ordered.push({ runs, x: cell.x, z: cell.z });
3661
+ }
3662
+ return { bytes: new Uint8Array(buffer), cells: ordered, ids };
3663
+ }
3664
+ function bakeWorldPackage(state, options) {
3665
+ const { size, resolution } = state;
3666
+ const cellSize = options.cellSize ?? 64;
3667
+ if (!Number.isFinite(cellSize) || cellSize <= 0)
3668
+ throw Error(
3669
+ `World package: cellSize must be a positive finite number, got ${String(cellSize)}.`
3670
+ );
3671
+ const { assets, layers, names } = options;
3672
+ const heightmapName = names?.heightmap ?? "heightmap.u16";
3673
+ const placementsName = names?.placements ?? "placements.bin";
3674
+ const placementIdsName = names?.placementIds ?? "placement-ids.json";
3675
+ const splatName = names?.splat ?? "splat.rgba";
3676
+ const extent = { minX: -size / 2, minZ: -size / 2, sizeX: size, sizeZ: size };
3677
+ let heightMin = Number.POSITIVE_INFINITY;
3678
+ let heightMax = Number.NEGATIVE_INFINITY;
3679
+ for (const height of state.height) {
3680
+ if (!Number.isFinite(height)) throw Error("World package: terrain heights must be finite.");
3681
+ heightMin = Math.min(heightMin, height);
3682
+ heightMax = Math.max(heightMax, height);
3683
+ }
3684
+ if (heightMax - heightMin < 1e-6) heightMax = heightMin + 1;
3685
+ const heightmap = new Uint8Array(resolution * resolution * 2);
3686
+ const heights = new DataView(heightmap.buffer);
3687
+ for (let i = 0; i < state.height.length; i += 1)
3688
+ heights.setUint16(
3689
+ i * 2,
3690
+ Math.round(
3691
+ (state.height[i] - heightMin) / (heightMax - heightMin) * HEIGHTMAP_MAX
3692
+ ),
3693
+ true
3694
+ );
3695
+ const placements = placementCells(state, assets, cellSize, extent);
3696
+ return {
3697
+ files: {
3698
+ [heightmapName]: heightmap,
3699
+ [placementsName]: placements.bytes,
3700
+ [placementIdsName]: new TextEncoder().encode(`${JSON.stringify(placements.ids)}
3701
+ `),
3702
+ [splatName]: splatBytes(state, resolution)
3703
+ },
3704
+ manifest: {
3705
+ assets,
3706
+ cellSize,
3707
+ cells: placements.cells,
3708
+ extent,
3709
+ placements: placementsName,
3710
+ placementIds: placementIdsName,
3711
+ terrain: {
3712
+ columns: resolution,
3713
+ heightMax,
3714
+ heightMin,
3715
+ heightmap: heightmapName,
3716
+ layers: { splat: splatName, ...layers },
3717
+ rows: resolution,
3718
+ spacing: size / (resolution - 1)
3719
+ },
3720
+ version: 1
3721
+ },
3722
+ splat: {
3723
+ masks: Object.fromEntries(SLOTS.map(({ component, id, plane }) => [id, [plane, component]])),
3724
+ planes: PLANES,
3725
+ size: resolution
3726
+ }
3727
+ };
3728
+ }
3729
+ function splatBytes(state, resolution) {
3730
+ const planeBytes = resolution * resolution * 4;
3731
+ if (state.splat.length !== resolution * resolution * MATERIAL_IDS.length)
3732
+ throw Error(
3733
+ `World package: splat has ${String(state.splat.length)} weights, expected ${String(resolution * resolution * MATERIAL_IDS.length)}.`
3734
+ );
3735
+ const bytes = new Uint8Array(planeBytes * PLANES);
3736
+ for (let row = 0; row < resolution; row += 1) {
3737
+ const source = (resolution - 1 - row) * resolution;
3738
+ const rowOffset = row * resolution * 4;
3739
+ for (let column = 0; column < resolution; column += 1) {
3740
+ const sample = (source + column) * MATERIAL_IDS.length;
3741
+ const rowCol = rowOffset + column * 4;
3742
+ for (const slot of SLOTS) {
3743
+ const weight = state.splat[sample + slot.channel];
3744
+ bytes[slot.plane * planeBytes + rowCol + slot.componentIndex] = Math.round(
3745
+ (weight <= 0 ? 0 : weight >= 1 ? 1 : weight) * 255
3746
+ );
3747
+ }
3748
+ }
3749
+ }
3750
+ return bytes;
3751
+ }
3752
+
3753
+ // src/core/bake-biome.ts
3754
+ var BAKE_BIOME_STAGES = [
3755
+ "surfaceSample",
3756
+ "densityFilter",
3757
+ "selfPrune",
3758
+ "meshSpawn"
3759
+ ];
3760
+ function bakeBiome(options) {
3761
+ const spec = validateBiome(options.spec, options.spec.look);
3762
+ const scatter = (options.stream ?? spec.stream) === "ordered" ? scatterProps(
3763
+ orderedField(options.state, spec),
3764
+ { x: spec.spawn.focus[0], z: spec.spawn.focus[1] },
3765
+ spec.cover.clearings
3766
+ ) : null;
3767
+ const state = scatter === null ? options.state : { ...options.state, instances: scatter.placements };
3768
+ const baked = options.assets === void 0 ? null : bakeWorldPackage(state, {
3769
+ assets: options.assets,
3770
+ ...options.cellSize === void 0 ? {} : { cellSize: options.cellSize },
3771
+ ...options.layers === void 0 ? {} : { layers: options.layers },
3772
+ ...options.names === void 0 ? {} : { names: options.names }
3773
+ });
3774
+ const counts = /* @__PURE__ */ new Map();
3775
+ if (baked !== null) {
3776
+ let placed = 0;
3777
+ for (const cell of baked.manifest.cells)
3778
+ for (const run of cell.runs) {
3779
+ placed += run.count;
3780
+ counts.set(run.asset, (counts.get(run.asset) ?? 0) + run.count);
3781
+ }
3782
+ if (placed !== state.instances.length)
3783
+ throw new Error(
3784
+ `${spec.look}: the package carries ${String(placed)} placements for ${String(state.instances.length)} instances.`
3785
+ );
3786
+ } else if (scatter !== null) {
3787
+ for (const [asset, count2] of Object.entries(scatter.counts)) counts.set(asset, count2);
3788
+ }
3789
+ return {
3790
+ package: baked,
3791
+ bands: measureBands(spec.layers, options.state.height),
3792
+ placements: [...counts.entries()].map(([asset, count2]) => ({ asset, count: count2 })),
3793
+ scatter
3794
+ };
3795
+ }
3796
+ function orderedField(state, spec) {
3797
+ return {
3798
+ erosion: state.erosion,
3799
+ field: new Heightfield({
3800
+ rows: state.resolution,
3801
+ columns: state.resolution,
3802
+ width: state.size,
3803
+ depth: state.size,
3804
+ origin: { x: 0, z: 0 },
3805
+ heights: Float32Array.from(state.height)
3806
+ }),
3807
+ resolution: state.resolution,
3808
+ size: state.size,
3809
+ waterLevel: state.waters.find((water2) => water2.kind === "ocean")?.level ?? null,
3810
+ rules: orderedScatterRules(spec),
3811
+ spec,
3812
+ rivers: state.rivers,
3813
+ lakes: state.waters.flatMap(
3814
+ (water2) => water2.kind === "lake" && water2.at !== void 0 && water2.radius !== void 0 ? [{ at: water2.at, radius: water2.radius, level: water2.level ?? 0 }] : []
3815
+ )
3816
+ };
3817
+ }
3818
+ function collarSampler(collar) {
3819
+ const at = (x, z) => collar.heightAt(x, z);
3820
+ const paint = (attribute, x, z, value) => {
3821
+ const quad = collar.locate(x, z);
3822
+ if (quad === void 0) return;
3823
+ for (const index of [
3824
+ collar.index(quad.lower, quad.from),
3825
+ collar.index(quad.lower, quad.to),
3826
+ collar.index(quad.upper, quad.from),
3827
+ collar.index(quad.upper, quad.to)
3828
+ ])
3829
+ attribute.setX(index, Math.max(attribute.getX(index), value));
3830
+ };
3831
+ return { at, paint };
3832
+ }
3833
+ var macroNoise = new ImprovedNoise();
3834
+ function farForestPlacements(options) {
3835
+ const rules = options.rules;
3836
+ const half = options.size / 2;
3837
+ const collar = collarSampler(options.collar);
3838
+ const random2 = createRandom(rules.seed);
3839
+ const rivers = createSegmentIndex(
3840
+ (options.rivers ?? []).flatMap(
3841
+ (river) => river.points.flatMap((to, index) => {
3842
+ const from = river.points[index - 1];
3843
+ if (!from) return [];
3844
+ const a = [from[0] ?? 0, from[2] ?? 0];
3845
+ const b = [to[0] ?? 0, to[2] ?? 0];
3846
+ const reach = river.width * 2.5;
3847
+ return [{ a, b, reach, data: { a, b, reach } }];
3848
+ })
3849
+ ),
3850
+ 32
3851
+ );
3852
+ const inRiver = (x, z) => rivers.nearby(x, z).some(({ a, b, reach }) => {
3853
+ const dx = b[0] - a[0];
3854
+ const dz = b[1] - a[1];
3855
+ const t = MathUtils.clamp(
3856
+ ((x - a[0]) * dx + (z - a[1]) * dz) / (dx * dx + dz * dz || 1),
3857
+ 0,
3858
+ 1
3859
+ );
3860
+ return Math.hypot(x - a[0] - t * dx, z - a[1] - t * dz) < reach;
3861
+ });
3862
+ const wet = (x, z, height) => inRiver(x, z) || (options.lakes ?? []).some(
3863
+ (lake) => Math.hypot(x - (lake.at[0] ?? 0), z - (lake.at[1] ?? 0)) < lake.radius && height < lake.level + 0.35
3864
+ );
3865
+ const canopy = options.collar.geometry.getAttribute("canopy");
3866
+ const placements = [];
3867
+ const [slopeFrom, slopeTo] = rules.slope;
3868
+ const [standFrom, standTo] = rules.stand;
3869
+ const [treeFrom, treeTo] = options.treeline;
3870
+ for (let gz = -rules.reach; gz < rules.reach; gz += rules.cell)
3871
+ for (let gx = -rules.reach; gx < rules.reach; gx += rules.cell) {
3872
+ const x = gx + (0.1 + 0.8 * random2()) * rules.cell;
3873
+ const z = gz + (0.1 + 0.8 * random2()) * rules.cell;
3874
+ const keep = random2();
3875
+ const past = Math.max(Math.abs(x), Math.abs(z)) - half;
3876
+ if (past < 2) continue;
3877
+ const spacing = MathUtils.lerp(
3878
+ rules.spacing[0],
3879
+ rules.spacing[1],
3880
+ MathUtils.smoothstep(past, rules.spacingAt[0], rules.spacingAt[1])
3881
+ );
3882
+ const spaced = Math.min(1, (rules.cell / spacing) ** 2);
3883
+ if (keep >= spaced) continue;
3884
+ if ((options.clear ?? []).some(([cx, cz, r]) => Math.hypot(x - cx, z - cz) < r)) continue;
3885
+ const height = collar.at(x, z);
3886
+ if (height === null) continue;
3887
+ const step = 4;
3888
+ const dx = (collar.at(x + step, z) ?? height) - (collar.at(x - step, z) ?? height);
3889
+ const dz = (collar.at(x, z + step) ?? height) - (collar.at(x, z - step) ?? height);
3890
+ const slope = MathUtils.radToDeg(Math.atan(Math.hypot(dx, dz) / (2 * step)));
3891
+ const flat = 1 - MathUtils.smoothstep(slope, slopeFrom, slopeTo);
3892
+ if (flat <= 0) continue;
3893
+ const meadow = 1 - (1 - MathUtils.smoothstep(macroNoise.noise(x * 21e-4, 5.3, z * 21e-4), -0.3, -0.12)) * (1 - MathUtils.smoothstep(slope, rules.meadowSlope[0], rules.meadowSlope[1]));
3894
+ if (meadow <= 0) continue;
3895
+ const around = ((collar.at(x + 40, z) ?? height) + (collar.at(x - 40, z) ?? height) + (collar.at(x, z + 40) ?? height) + (collar.at(x, z - 40) ?? height)) / 4;
3896
+ const damp = MathUtils.clamp((around - height) / 8 + 0.3, 0, 1);
3897
+ const stand = MathUtils.smoothstep(
3898
+ fieldWeight(STAND_FIELD, x, z) + (damp - 0.3) * 0.2,
3899
+ standFrom,
3900
+ standTo
3901
+ );
3902
+ if (stand <= 0) continue;
3903
+ const jitter = macroNoise.noise(x * 0.011, 17.7, z * 0.011) * rules.treelineJitter;
3904
+ const alpine = 1 - MathUtils.smoothstep(height + jitter, treeFrom, treeTo);
3905
+ if (alpine <= 0 || wet(x, z, height)) continue;
3906
+ if (random2() >= meadow * stand * alpine * flat) continue;
3907
+ const age = MathUtils.clamp(macroNoise.noise(x * 0.021, 7, z * 0.021) * 0.5 + 0.5, 0, 1);
3908
+ const scale = (0.55 + 1.05 * age ** 1.6 + random2() * 0.16) * (0.6 + 0.4 * Math.min(stand, alpine)) * (1 + 0.25 * damp);
3909
+ const index = placements.length;
3910
+ placements.push({
3911
+ asset: options.asset,
3912
+ id: `temperate-${options.asset}:far-${index}`,
3913
+ layer: options.layer,
3914
+ alignToNormal: false,
3915
+ normal: [0, 1, 0],
3916
+ position: [x, 0, z],
3917
+ rotation: random2() * Math.PI * 2,
3918
+ scale
3919
+ });
3920
+ if (canopy) collar.paint(canopy, x, z, 1);
3921
+ }
3922
+ if (canopy) canopy.needsUpdate = true;
3923
+ return placements;
3924
+ }
3925
+
3926
+ // src/core/stats.ts
3927
+ var CHANNEL_AREA_M2 = 1e5;
3928
+ var quantile = (sorted, q) => sorted[Math.min(sorted.length - 1, Math.floor(q * sorted.length))];
3929
+ function terrainStats(height, n, size) {
3930
+ const spacing = size / (n - 1);
3931
+ let low = Number.POSITIVE_INFINITY;
3932
+ let high = Number.NEGATIVE_INFINITY;
3933
+ let sum = 0;
3934
+ for (let i = 0; i < height.length; i += 1) {
3935
+ const v = height[i];
3936
+ low = Math.min(low, v);
3937
+ high = Math.max(high, v);
3938
+ sum += v;
3939
+ }
3940
+ const relief = high - low;
3941
+ const interior = (n - 2) * (n - 2);
3942
+ const slopes = new Float32Array(interior);
3943
+ const laplacian = new Float32Array(interior);
3944
+ let lapSum = 0;
3945
+ let k = 0;
3946
+ for (let z = 1; z < n - 1; z += 1) {
3947
+ for (let x = 1; x < n - 1; x += 1) {
3948
+ const i = z * n + x;
3949
+ const here = height[i];
3950
+ const east = height[i + 1];
3951
+ const west = height[i - 1];
3952
+ const south = height[i + n];
3953
+ const north = height[i - n];
3954
+ slopes[k] = Math.atan(Math.hypot(east - west, south - north) / (2 * spacing)) * 180 / Math.PI;
3955
+ laplacian[k] = (east + west + south + north - 4 * here) / (spacing * spacing);
3956
+ lapSum += laplacian[k];
3957
+ k += 1;
3958
+ }
3959
+ }
3960
+ const lapMean = lapSum / interior;
3961
+ let m2 = 0;
3962
+ let m4 = 0;
3963
+ for (let i = 0; i < interior; i += 1) {
3964
+ const d = laplacian[i] - lapMean;
3965
+ m2 += d * d;
3966
+ m4 += d * d * d * d;
3967
+ }
3968
+ m2 /= interior;
3969
+ m4 /= interior;
3970
+ slopes.sort();
3971
+ const filled = Float64Array.from(height);
3972
+ fillDepressions(filled, n);
3973
+ const flow = createFlow(n);
3974
+ routeFlow(filled, n, flow);
3975
+ const channelCells = CHANNEL_AREA_M2 / (spacing * spacing);
3976
+ let channels = 0;
3977
+ for (let i = 0; i < flow.cells.length; i += 1)
3978
+ if (flow.cells[i] >= channelCells) channels += 1;
3979
+ const areaKm2 = size * size / 1e6;
3980
+ return {
3981
+ relief,
3982
+ hypsometricIntegral: relief > 0 ? (sum / height.length - low) / relief : 0,
3983
+ slopeP50: quantile(slopes, 0.5),
3984
+ slopeP90: quantile(slopes, 0.9),
3985
+ drainageDensity: channels * spacing / 1e3 / areaKm2,
3986
+ curvatureKurtosis: m2 > 0 ? m4 / (m2 * m2) - 3 : 0
3987
+ };
3988
+ }
3989
+
3990
+ // src/core/bake.ts
3991
+ var toLinear = (color) => color <= 0.04045 ? color / 12.92 : ((color + 0.055) / 1.055) ** 2.4;
3992
+ function bakeMesh(state, {
3993
+ step = 1,
3994
+ x = 0,
3995
+ z = 0,
3996
+ cells = state.resolution - 1,
3997
+ skirtDepth = 0,
3998
+ palette
3999
+ } = {}) {
4000
+ if (!Number.isFinite(skirtDepth) || skirtDepth < 0)
4001
+ throw new RangeError("skirtDepth must be finite and nonnegative");
4002
+ const n = state.resolution;
4003
+ if (!Number.isInteger(n) || n < 2 || !Number.isFinite(state.size) || state.size <= 0)
4004
+ throw new RangeError("Invalid heightfield extent");
4005
+ if (!Number.isInteger(step) || step < 1 || (step & step - 1) !== 0 || cells % step !== 0)
4006
+ throw new RangeError("step must be a power of two dividing chunk cells");
4007
+ if (![x, z, cells].every(Number.isInteger) || x < 0 || z < 0 || cells < 1 || x + cells >= n || z + cells >= n)
4008
+ throw new RangeError("Chunk outside heightfield");
4009
+ if (state.height.length !== n * n || !state.height.every(Number.isFinite))
4010
+ throw new RangeError("Invalid heightfield samples");
4011
+ if (palette && (palette.length !== 8 || Array.from(palette).some(
4012
+ (rgb) => !Array.isArray(rgb) || rgb.length !== 3 || Array.from(rgb).some((value) => !Number.isFinite(value) || value < 0 || value > 1)
4013
+ )))
4014
+ throw new RangeError("palette requires eight finite sRGB triples in 0..1");
4015
+ if (palette && (state.splat.length !== n * n * 8 || !state.splat.every(Number.isFinite)))
4016
+ throw new RangeError("Invalid splat samples");
4017
+ const side = cells / step + 1;
4018
+ const base = side * side;
4019
+ const ring = [];
4020
+ if (skirtDepth > 0) {
4021
+ for (let k2 = 0; k2 < side - 1; k2++) ring.push(k2);
4022
+ for (let k2 = 0; k2 < side - 1; k2++) ring.push(k2 * side + side - 1);
4023
+ for (let k2 = side - 1; k2 > 0; k2--) ring.push((side - 1) * side + k2);
4024
+ for (let k2 = side - 1; k2 > 0; k2--) ring.push(k2 * side);
4025
+ }
4026
+ const count2 = base + ring.length;
4027
+ const positions = new Float32Array(count2 * 3);
4028
+ const normals = new Float32Array(count2 * 3);
4029
+ const uvs = new Float32Array(count2 * 2);
4030
+ const indices = new Uint32Array((side - 1) ** 2 * 6 + ring.length * 6);
4031
+ const colors = palette ? new Float32Array(count2 * 3) : void 0;
4032
+ const cell = state.size / (n - 1);
4033
+ for (let zz = 0; zz < side; zz++)
4034
+ for (let xx = 0; xx < side; xx++) {
4035
+ const gx = x + xx * step;
4036
+ const gz = z + zz * step;
4037
+ const i = gz * n + gx;
4038
+ const j = zz * side + xx;
4039
+ const dx = (state.height[gz * n + Math.min(n - 1, gx + 1)] - state.height[gz * n + Math.max(0, gx - 1)]) / ((gx > 0 && gx < n - 1 ? 2 : 1) * cell);
4040
+ const dz = (state.height[Math.min(n - 1, gz + 1) * n + gx] - state.height[Math.max(0, gz - 1) * n + gx]) / ((gz > 0 && gz < n - 1 ? 2 : 1) * cell);
4041
+ const length = Math.hypot(dx, 1, dz);
4042
+ positions.set([world(state, gx), state.height[i], world(state, gz)], j * 3);
4043
+ normals.set([-dx / length, 1 / length, -dz / length], j * 3);
4044
+ if (colors && palette)
4045
+ for (let k2 = 0; k2 < 3; k2++) {
4046
+ let color = 0;
4047
+ for (let c = 0; c < 8; c++)
4048
+ color += toLinear(palette[c]?.[k2]) * state.splat[i * 8 + c];
4049
+ colors[j * 3 + k2] = color;
4050
+ }
4051
+ uvs.set([gx / (n - 1), 1 - gz / (n - 1)], j * 2);
4052
+ }
4053
+ let k = 0;
4054
+ for (let zz = 0; zz < side - 1; zz++)
4055
+ for (let xx = 0; xx < side - 1; xx++) {
4056
+ const a = zz * side + xx;
4057
+ const b = a + 1;
4058
+ const c = a + side;
4059
+ const d = c + 1;
4060
+ indices.set([a, c, b, b, c, d], k);
4061
+ k += 6;
4062
+ }
4063
+ for (let j = 0; j < ring.length; j++) {
4064
+ const top = ring[j];
4065
+ const bottom = base + j;
4066
+ positions.set(positions.subarray(top * 3, top * 3 + 3), bottom * 3);
4067
+ positions[bottom * 3 + 1] = positions[bottom * 3 + 1] - skirtDepth;
4068
+ normals.set(normals.subarray(top * 3, top * 3 + 3), bottom * 3);
4069
+ colors?.set(colors.subarray(top * 3, top * 3 + 3), bottom * 3);
4070
+ uvs.set(uvs.subarray(top * 2, top * 2 + 2), bottom * 2);
4071
+ const next = (j + 1) % ring.length;
4072
+ indices.set([top, ring[next], bottom, ring[next], base + next, bottom], k);
4073
+ k += 6;
4074
+ }
4075
+ return {
4076
+ name: `terrain_${x}_${z}_step${step}`,
4077
+ positions,
4078
+ normals,
4079
+ colors,
4080
+ uvs,
4081
+ indices,
4082
+ side,
4083
+ topVertexCount: base,
4084
+ bounds: { x, z, cells, step },
4085
+ skirtDepth
4086
+ };
4087
+ }
4088
+ function bakeTerrain(state, {
4089
+ chunkCells = Math.min(64, state.resolution - 1),
4090
+ lodSteps = [1, 2, 4],
4091
+ skirtDepth = 6,
4092
+ palette
4093
+ } = {}) {
4094
+ if (!Number.isInteger(chunkCells) || chunkCells < 1 || (state.resolution - 1) % chunkCells !== 0)
4095
+ throw new RangeError("chunkCells must divide resolution - 1");
4096
+ if (!lodSteps.length) throw new RangeError("lodSteps must not be empty");
4097
+ const lods = lodSteps.map((step) => {
4098
+ const chunks = [];
4099
+ for (let z = 0; z < state.resolution - 1; z += chunkCells)
4100
+ for (let x = 0; x < state.resolution - 1; x += chunkCells)
4101
+ chunks.push(bakeMesh(state, { x, z, cells: chunkCells, step, skirtDepth, palette }));
4102
+ return { step, chunks };
4103
+ });
4104
+ return {
4105
+ version: 1,
4106
+ size: state.size,
4107
+ resolution: state.resolution,
4108
+ lods,
4109
+ collision: {
4110
+ type: "heightfield",
4111
+ size: state.size,
4112
+ resolution: state.resolution,
4113
+ cellSize: state.size / (state.resolution - 1),
4114
+ origin: [-state.size / 2, 0, -state.size / 2],
4115
+ heights: state.height.slice()
4116
+ },
4117
+ instances: structuredClone(state.instances),
4118
+ materialChannels: [...MATERIAL_IDS]
4119
+ };
4120
+ }
4121
+ function validateBakedMesh(mesh) {
4122
+ if (![mesh.positions, mesh.normals, mesh.uvs, ...mesh.colors ? [mesh.colors] : []].every(
4123
+ (array) => array instanceof Float32Array
4124
+ ) || !(mesh.indices instanceof Uint32Array))
4125
+ throw new TypeError("Baked mesh requires Float32 attributes and Uint32 indices");
4126
+ const count2 = mesh.positions.length / 3;
4127
+ if (!count2 || !Number.isInteger(count2) || mesh.normals.length !== count2 * 3 || mesh.uvs.length !== count2 * 2 || mesh.colors && mesh.colors.length !== count2 * 3 || !mesh.indices.length || mesh.indices.length % 3)
4128
+ throw new RangeError("Baked mesh attribute counts do not agree");
4129
+ for (const array of [
4130
+ mesh.positions,
4131
+ mesh.normals,
4132
+ mesh.uvs,
4133
+ ...mesh.colors ? [mesh.colors] : []
4134
+ ])
4135
+ if (!array.every(Number.isFinite)) throw new RangeError("Baked mesh attributes must be finite");
4136
+ if (mesh.indices.some((index) => index >= count2))
4137
+ throw new RangeError("Baked mesh index outside vertex range");
4138
+ }
4139
+
4140
+ // src/core/placements.ts
2177
4141
  function validatePlacementOverrides(value = {}) {
2178
4142
  finiteTree(value, "placementOverrides");
2179
4143
  if (!value || typeof value !== "object" || ![Object.prototype, null].includes(Object.getPrototypeOf(value)))
@@ -2412,10 +4376,12 @@ async function decodeHeightPNG(input, options = {}) {
2412
4376
  throw Error("Heightmap import supports non-interlaced 8/16-bit grayscale PNG only");
2413
4377
  }
2414
4378
  if (type === "tEXt") {
2415
- const text = decoder.decode(data);
2416
- if (text.startsWith("StrataHeightRange\0")) {
4379
+ const text2 = decoder.decode(data);
4380
+ if (text2.startsWith("StrataHeightRange\0")) {
2417
4381
  try {
2418
- metadata = JSON.parse(text.slice(18));
4382
+ const parsed = JSON.parse(text2.slice(18));
4383
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw Error();
4384
+ metadata = parsed;
2419
4385
  } catch {
2420
4386
  throw Error("Invalid PNG height range metadata");
2421
4387
  }
@@ -2517,7 +4483,7 @@ function encodeGLB(input) {
2517
4483
  }
2518
4484
  const binary = join(chunks);
2519
4485
  const doc = {
2520
- asset: { version: "2.0", generator: "Strata Terrain 0.1.0" },
4486
+ asset: { version: "2.0", generator: "@threenative/terrain 0.1.8" },
2521
4487
  scene: 0,
2522
4488
  scenes: [{ nodes: meshes.map((_, i) => i) }],
2523
4489
  nodes: meshes.map((m, i) => ({ mesh: i, name: m.name ?? `Terrain ${i}` })),
@@ -2628,6 +4594,7 @@ async function makeExport(state, recipe, kind) {
2628
4594
  });
2629
4595
  if (kind === "project")
2630
4596
  return result("terrain-recipe.json", "application/json", json("", recipe).bytes);
4597
+ if (!state) throw new Error("Wait for initial build");
2631
4598
  if (kind === "png")
2632
4599
  return result("terrain-height16.png", "image/png", await encodeHeightPNG(state));
2633
4600
  if (kind === "glb") return result("terrain.glb", "model/gltf-binary", encodeGLB(bakeMesh(state)));
@@ -2704,7 +4671,7 @@ async function makeExport(state, recipe, kind) {
2704
4671
  "No navigation mesh"
2705
4672
  ]
2706
4673
  };
2707
- const water = state.waters.map((w, i) => {
4674
+ const water2 = state.waters.map((w, i) => {
2708
4675
  const { mask, ...rest } = w;
2709
4676
  return { ...rest, maskFile: `water-${i}.mask8` };
2710
4677
  });
@@ -2712,216 +4679,130 @@ async function makeExport(state, recipe, kind) {
2712
4679
  json("manifest.json", manifest),
2713
4680
  json("recipe.json", recipe),
2714
4681
  json("placements.json", baked.instances),
2715
- json("water.json", { bodies: water, rivers: state.rivers }),
4682
+ json("water.json", { bodies: water2, rivers: state.rivers }),
2716
4683
  { name: "collision.f32le", bytes: collision },
2717
4684
  { name: "height16.png", bytes: await encodeHeightPNG(state) },
2718
4685
  ...splatFiles,
2719
4686
  ...baked.lods.map((l) => ({ name: `lod-${l.step}.glb`, bytes: encodeGLB(l.chunks) }))
2720
4687
  ];
2721
- for (let i = 0; i < water.length; i++)
4688
+ for (let i = 0; i < water2.length; i++)
2722
4689
  files.push({
2723
- name: water[i]?.maskFile,
4690
+ name: water2[i]?.maskFile,
2724
4691
  bytes: new Uint8Array(state.waters[i]?.mask ?? [])
2725
4692
  });
2726
4693
  return result("terrain-runtime.zip", "application/zip", encodeZIP(files));
2727
4694
  }
2728
4695
 
2729
- // src/core/world-package.ts
2730
- var HEIGHTMAP_MAX = 65535;
2731
- var RECORD_VALUES = 8;
2732
- var COMPONENTS = ["r", "g", "b", "a"];
2733
- var PLANES = MATERIAL_IDS.length / COMPONENTS.length;
2734
- var SCALE_TOLERANCE = 1e-3;
2735
- var SLOTS = MATERIAL_IDS.map((id, channel) => ({
2736
- channel,
2737
- component: COMPONENTS[channel % COMPONENTS.length],
2738
- id,
2739
- plane: Math.floor(channel / COMPONENTS.length)
2740
- }));
2741
- function poseOf(item) {
2742
- if (item.transform === void 0)
2743
- return {
2744
- position: item.position,
2745
- quaternion: [0, Math.sin(item.rotation / 2), 0, Math.cos(item.rotation / 2)],
2746
- scale: [item.scale, item.scale, item.scale]
2747
- };
2748
- const { position, quaternion, scale } = item.transform;
2749
- return { position, quaternion, scale };
2750
- }
2751
- function uniformScale(asset, id, scale) {
2752
- const mean = (scale[0] + scale[1] + scale[2]) / 3;
2753
- const deviation = Math.max(
2754
- Math.abs(scale[0] - mean),
2755
- Math.abs(scale[1] - mean),
2756
- Math.abs(scale[2] - mean)
2757
- );
2758
- if (!(mean > 0) || deviation > mean * SCALE_TOLERANCE)
4696
+ // src/core/prop-package.ts
4697
+ var PROP_CELL_SIZE = 128;
4698
+ var DEFAULT_KIND = "local";
4699
+ var KINDS = ["far", "local", "meadow"];
4700
+ function compilePropBuckets(entries, options = {}) {
4701
+ const cellSize = options.cellSize ?? PROP_CELL_SIZE;
4702
+ if (!Number.isFinite(cellSize) || cellSize <= 0)
2759
4703
  throw Error(
2760
- `World package: placement '${id}' of asset '${asset}' is scaled ${JSON.stringify(scale)}; a placement record carries one uniform scale.`
4704
+ `Prop package: cellSize must be a positive finite number, got ${String(cellSize)}.`
2761
4705
  );
2762
- return mean;
2763
- }
2764
- function placementRecord(item) {
2765
- if (item.transform === void 0 && !Number.isFinite(item.rotation))
2766
- throw Error(`World package: placement '${item.id}' has a non-finite rotation.`);
2767
- const { position, quaternion, scale } = poseOf(item);
2768
- const length = Math.hypot(...quaternion);
2769
- if (!(length > 0)) throw Error(`World package: placement '${item.id}' has a zero quaternion.`);
2770
- return [
2771
- position[0],
2772
- position[1],
2773
- position[2],
2774
- quaternion[0] / length,
2775
- quaternion[1] / length,
2776
- quaternion[2] / length,
2777
- quaternion[3] / length,
2778
- uniformScale(item.asset, item.id, scale)
2779
- ];
2780
- }
2781
- function placementCells(state, assets, cellSize, extent) {
2782
- const cells = /* @__PURE__ */ new Map();
2783
- const across = Math.max(1, Math.ceil(extent.sizeX / cellSize));
2784
- const cellOf = (value, min) => Math.min(across - 1, Math.max(0, Math.floor((value - min) / cellSize)));
2785
- for (const item of state.instances) {
2786
- if (assets[item.asset] === void 0)
4706
+ const buckets = /* @__PURE__ */ new Map();
4707
+ for (const entry of entries) {
4708
+ const kind = entry.kind ?? DEFAULT_KIND;
4709
+ if (!KINDS.includes(kind))
4710
+ throw Error(`Prop package: '${entry.bucket}' names unknown kind '${String(kind)}'.`);
4711
+ if (!Number.isFinite(entry.reach) && entry.reach !== Number.POSITIVE_INFINITY)
4712
+ throw Error(`Prop package: '${entry.placement.id}' has a non-finite reach.`);
4713
+ const seen = buckets.get(entry.bucket);
4714
+ if (seen === void 0)
4715
+ buckets.set(entry.bucket, { bucket: entry.bucket, entries: [entry], kind });
4716
+ else if (seen.kind !== kind)
2787
4717
  throw Error(
2788
- `World package: placement '${item.id}' names asset '${item.asset}', which options.assets does not.`
4718
+ `Prop package: bucket '${entry.bucket}' mixes kinds '${seen.kind}' and '${kind}'.`
2789
4719
  );
2790
- const x = cellOf(item.position[0], extent.minX);
2791
- const z = cellOf(item.position[2], extent.minZ);
2792
- const key = `${String(x)},${String(z)}`;
2793
- let cell = cells.get(key);
2794
- if (cell === void 0) {
2795
- cell = { items: /* @__PURE__ */ new Map(), x, z };
2796
- cells.set(key, cell);
2797
- }
2798
- const bucket = cell.items.get(item.asset);
2799
- if (bucket === void 0) cell.items.set(item.asset, [item]);
2800
- else bucket.push(item);
2801
- }
2802
- const buffer = new ArrayBuffer(state.instances.length * RECORD_VALUES * 4);
2803
- const records = new Float32Array(buffer);
2804
- const ordered = [];
2805
- let written = 0;
2806
- const byId = (left, right) => left[0] < right[0] ? -1 : 1;
2807
- for (const cell of [...cells.values()].sort((a, b) => a.x - b.x || a.z - b.z)) {
2808
- const runs = [];
2809
- for (const [asset, items] of [...cell.items.entries()].sort(byId)) {
2810
- runs.push({ asset, count: items.length, offset: written });
2811
- for (const item of items) {
2812
- records.set(placementRecord(item), written * RECORD_VALUES);
2813
- written += 1;
2814
- }
2815
- }
2816
- ordered.push({ runs, x: cell.x, z: cell.z });
2817
- }
2818
- return { bytes: new Uint8Array(buffer), cells: ordered };
2819
- }
2820
- function bakeWorldPackage(state, options) {
2821
- const { size, resolution } = state;
2822
- const { assets, cellSize = 64, layers, names } = options;
2823
- const heightmapName = names?.heightmap ?? "heightmap.u16";
2824
- const placementsName = names?.placements ?? "placements.bin";
2825
- const splatName = names?.splat ?? "splat.rgba";
2826
- const extent = { minX: -size / 2, minZ: -size / 2, sizeX: size, sizeZ: size };
2827
- let heightMin = Number.POSITIVE_INFINITY;
2828
- let heightMax = Number.NEGATIVE_INFINITY;
2829
- for (const height of state.height) {
2830
- if (!Number.isFinite(height)) throw Error("World package: terrain heights must be finite.");
2831
- heightMin = Math.min(heightMin, height);
2832
- heightMax = Math.max(heightMax, height);
4720
+ else seen.entries.push(entry);
2833
4721
  }
2834
- if (heightMax - heightMin < 1e-6) heightMax = heightMin + 1;
2835
- const heightmap = new Uint8Array(resolution * resolution * 2);
2836
- const heights = new DataView(heightmap.buffer);
2837
- for (let i = 0; i < state.height.length; i += 1)
2838
- heights.setUint16(
2839
- i * 2,
2840
- Math.round(
2841
- (state.height[i] - heightMin) / (heightMax - heightMin) * HEIGHTMAP_MAX
2842
- ),
2843
- true
2844
- );
2845
- const placements = placementCells(state, assets, cellSize, extent);
2846
4722
  return {
2847
- files: {
2848
- [heightmapName]: heightmap,
2849
- [placementsName]: placements.bytes,
2850
- [splatName]: splatBytes(state, resolution)
2851
- },
2852
- manifest: {
2853
- assets,
2854
- cellSize,
2855
- cells: placements.cells,
2856
- extent,
2857
- placements: placementsName,
2858
- terrain: {
2859
- columns: resolution,
2860
- heightMax,
2861
- heightMin,
2862
- heightmap: heightmapName,
2863
- layers: { splat: splatName, ...layers },
2864
- rows: resolution,
2865
- spacing: size / (resolution - 1)
2866
- },
2867
- version: 1
4723
+ buckets: [...buckets.values()].map((acc) => bucketPackage(acc, cellSize, options.bounds)),
4724
+ cellSize
4725
+ };
4726
+ }
4727
+ function bucketPackage(acc, cellSize, bounds) {
4728
+ const extent = bucketExtent(
4729
+ acc.entries.map((entry) => entry.placement.position),
4730
+ cellSize,
4731
+ bounds
4732
+ );
4733
+ const modelOf = (entry) => entry.key ?? entry.placement.asset;
4734
+ const placements = placementCells(
4735
+ {
4736
+ instances: acc.entries.map(
4737
+ (entry) => entry.key === void 0 ? entry.placement : { ...entry.placement, asset: entry.key }
4738
+ )
2868
4739
  },
2869
- splat: {
2870
- masks: Object.fromEntries(SLOTS.map(({ component, id, plane }) => [id, [plane, component]])),
2871
- planes: PLANES,
2872
- size: resolution
2873
- }
4740
+ // The compile validates membership only; the game owns every asset's model, bounds and LODs.
4741
+ Object.fromEntries(acc.entries.map((entry) => [modelOf(entry), true])),
4742
+ cellSize,
4743
+ extent
4744
+ );
4745
+ const reach = new Map(acc.entries.map((entry) => [entry.placement.id, entry.reach]));
4746
+ for (const id of placements.ids)
4747
+ if (!reach.has(id)) throw Error(`Prop package: '${id}' lost its reach in the cell pass.`);
4748
+ return {
4749
+ bucket: acc.bucket,
4750
+ cells: placements.cells,
4751
+ extent,
4752
+ ids: placements.ids,
4753
+ kind: acc.kind,
4754
+ placements: placements.bytes,
4755
+ reach: Float32Array.from(placements.ids, (id) => reach.get(id))
2874
4756
  };
2875
4757
  }
2876
- function splatBytes(state, resolution) {
2877
- const planeBytes = resolution * resolution * 4;
2878
- if (state.splat.length !== resolution * resolution * MATERIAL_IDS.length)
2879
- throw Error(
2880
- `World package: splat has ${String(state.splat.length)} weights, expected ${String(resolution * resolution * MATERIAL_IDS.length)}.`
2881
- );
2882
- const bytes = new Uint8Array(planeBytes * PLANES);
2883
- for (let row = 0; row < resolution; row += 1) {
2884
- const source = (resolution - 1 - row) * resolution;
2885
- for (let column = 0; column < resolution; column += 1) {
2886
- const sample = (source + column) * MATERIAL_IDS.length;
2887
- for (const slot of SLOTS) {
2888
- const weight = state.splat[sample + slot.channel];
2889
- bytes[slot.plane * planeBytes + row * resolution * 4 + column * 4 + COMPONENTS.indexOf(slot.component)] = Math.round(Math.min(1, Math.max(0, weight)) * 255);
2890
- }
2891
- }
4758
+ function bucketExtent(positions, cellSize, bounds) {
4759
+ const first = positions[0];
4760
+ if (first === void 0) throw Error("Prop package: a bucket holds no placement.");
4761
+ let { minX, minZ } = bounds ?? { minX: first[0], minZ: first[2] };
4762
+ let maxX = bounds === void 0 ? first[0] : bounds.minX + bounds.sizeX;
4763
+ let maxZ = bounds === void 0 ? first[2] : bounds.minZ + bounds.sizeZ;
4764
+ for (const [x, , z] of positions) {
4765
+ if (!Number.isFinite(x) || !Number.isFinite(z))
4766
+ throw Error(`Prop package: a placement sits at a non-finite [${String(x)}, ${String(z)}].`);
4767
+ minX = Math.min(minX, x);
4768
+ minZ = Math.min(minZ, z);
4769
+ maxX = Math.max(maxX, x);
4770
+ maxZ = Math.max(maxZ, z);
2892
4771
  }
2893
- return bytes;
4772
+ minX = Math.floor(minX / cellSize) * cellSize;
4773
+ minZ = Math.floor(minZ / cellSize) * cellSize;
4774
+ maxX = (Math.floor(maxX / cellSize) + 1) * cellSize;
4775
+ maxZ = (Math.floor(maxZ / cellSize) + 1) * cellSize;
4776
+ return { minX, minZ, sizeX: maxX - minX, sizeZ: maxZ - minZ };
2894
4777
  }
2895
-
2896
- // src/core/water.ts
2897
- var EMPTY = [];
2898
- function createSegmentIndex(segments, cellSize) {
2899
- if (!(cellSize > 0) || !Number.isFinite(cellSize))
2900
- throw new Error(
2901
- `TN_TERRAIN_WATER_CELL_INVALID: cellSize must be a positive finite number, received ${String(cellSize)}.`
2902
- );
2903
- const cells = /* @__PURE__ */ new Map();
2904
- for (const segment of segments) {
2905
- const { a, b, reach } = segment;
2906
- if (!(reach >= 0) || !Number.isFinite(reach))
2907
- throw new Error(
2908
- `TN_TERRAIN_WATER_REACH_INVALID: reach must be a non-negative finite number, received ${String(reach)}.`
2909
- );
2910
- const fromX = Math.floor((Math.min(a[0], b[0]) - reach) / cellSize);
2911
- const toX = Math.floor((Math.max(a[0], b[0]) + reach) / cellSize);
2912
- const fromZ = Math.floor((Math.min(a[1], b[1]) - reach) / cellSize);
2913
- const toZ = Math.floor((Math.max(a[1], b[1]) + reach) / cellSize);
2914
- for (let cx = fromX; cx <= toX; cx++)
2915
- for (let cz = fromZ; cz <= toZ; cz++) {
2916
- const key = `${cx}:${cz}`;
2917
- const list = cells.get(key);
2918
- if (list) list.push(segment.data);
2919
- else cells.set(key, [segment.data]);
2920
- }
2921
- }
2922
- return {
2923
- nearby: (x, z) => cells.get(`${Math.floor(x / cellSize)}:${Math.floor(z / cellSize)}`) ?? EMPTY
2924
- };
4778
+ function propAssetOf(modelKey) {
4779
+ const at = modelKey.indexOf(":");
4780
+ return at < 0 ? modelKey : modelKey.slice(0, at);
4781
+ }
4782
+ function propPackageFile(world2, bucket, suffix) {
4783
+ return `${world2}.${bucket.replace(/[^a-zA-Z0-9]+/g, "-")}.${suffix}`;
4784
+ }
4785
+ function propPackageFiles(pkg, world2) {
4786
+ const files = {};
4787
+ const buckets = pkg.buckets.map((bucket) => {
4788
+ const names = {
4789
+ ids: propPackageFile(world2, bucket.bucket, "ids.json"),
4790
+ placements: propPackageFile(world2, bucket.bucket, "props.bin"),
4791
+ reach: propPackageFile(world2, bucket.bucket, "reach.bin")
4792
+ };
4793
+ files[names.placements] = bucket.placements;
4794
+ files[names.reach] = new Uint8Array(bucket.reach.buffer, bucket.reach.byteOffset);
4795
+ files[names.ids] = new TextEncoder().encode(JSON.stringify(bucket.ids));
4796
+ return {
4797
+ bucket: bucket.bucket,
4798
+ cells: bucket.cells,
4799
+ extent: bucket.extent,
4800
+ kind: bucket.kind,
4801
+ ...names
4802
+ };
4803
+ });
4804
+ const manifest = { buckets, cellSize: pkg.cellSize, version: 1 };
4805
+ return { files, manifest: new TextEncoder().encode(JSON.stringify(manifest)) };
2925
4806
  }
2926
4807
 
2927
- export { MATERIAL_IDS, Mask, PARAMS, RESOLUTIONS, Terrain, TerrainEvaluator, applyPlacementOverrides, bakeMesh, bakeTerrain, bakeWorldPackage, createSegmentIndex, decodeHeightPNG, decodeRAW16, encodeGLB, encodeHeightPNG, encodeRAW16, encodeSplatPNGs, encodeZIP, gradientAt, makeExport, sampleHeight, slopeAtIndex, slopeQuantile, splinePoints, validateDocument, validatePlacementOverrides };
4808
+ export { BAKE_BIOME_STAGES, LANDFORMS, MATERIAL_IDS, MATS_FIELD, Mask, PARAMS, PROP_CELL_SIZE, RESOLUTIONS, STAND_FIELD, Terrain, TerrainEvaluator, applyPlacementOverrides, bakeBiome, bakeMesh, bakeTerrain, bakeWorldPackage, collarSampler, compilePropBuckets, createSegmentIndex, decodeHeightPNG, decodeRAW16, encodeGLB, encodeHeightPNG, encodeRAW16, encodeSplatPNGs, encodeZIP, farForestPlacements, fieldWeight, gradientAt, landform, landformBackdrop, makeExport, measureBands, orderedScatterRules, propAssetOf, propPackageFile, propPackageFiles, sampleHeight, scatterProps, slopeAtIndex, slopeQuantile, splinePoints, terrainStats, validateBiome, validateDocument, validatePlacementOverrides };