@threenative/terrain 0.1.8 → 0.1.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/dist/editor/index.d.ts +63 -5
  2. package/dist/editor/index.js +323 -6
  3. package/dist/editor/server.d.ts +2 -2
  4. package/dist/editor/server.js +198 -4
  5. package/dist/editor/worker.d.ts +1 -1
  6. package/dist/editor/worker.js +199 -5
  7. package/dist/export.d.ts +1 -1
  8. package/dist/index.d.ts +146 -7
  9. package/dist/index.js +638 -39
  10. package/dist/kit.d.ts +3 -2
  11. package/dist/kit.js +198 -4
  12. package/dist/mcp/cook-child.js +1766 -125
  13. package/dist/mcp/server.js +728 -37
  14. package/dist/{server-C8Ydr_IM.d.ts → server-B5RdvEAC.d.ts} +1 -1
  15. package/dist/starter.d.ts +1 -1
  16. package/dist/starter.js +2 -1
  17. package/dist/{terrain-B3DkduPw.d.ts → terrain-CAEaW0mQ.d.ts} +1 -1
  18. package/dist/three.d.ts +1 -1
  19. package/dist/{types-CPYAc9vo.d.ts → types-BpH00qsx.d.ts} +10 -3
  20. package/dist/{world-package-B7KGYIou.d.ts → world-package-B8QgHjAQ.d.ts} +9 -50
  21. package/package.json +5 -5
  22. package/starter/alpine/biome.data.json +22 -2
  23. package/starter/alpine/world.ts +1 -1
  24. package/starter/coastal/README.md +5 -2
  25. package/starter/coastal/assets.json +2 -1
  26. package/starter/coastal/biome.data.json +23 -2
  27. package/starter/coastal/sea.ts +2 -50
  28. package/starter/desert/biome.data.json +12 -2
  29. package/starter/desert/world.ts +1 -1
  30. package/starter/forest/README.md +1 -1
  31. package/starter/forest/assets.json +2 -1
  32. package/starter/forest/biome.data.json +37 -14
  33. package/starter/forest/water.ts +9 -28
  34. package/starter/forest/world.ts +6 -1
  35. package/starter/tundra/biome.data.json +12 -2
  36. package/starter/tundra/water.ts +9 -28
  37. package/starter/tundra/world.ts +1 -1
@@ -1,13 +1,13 @@
1
1
  import { existsSync, readFileSync } from 'fs';
2
2
  import { mkdir, rm, lstat, realpath, readFile, mkdtemp, rename, writeFile, copyFile } from 'fs/promises';
3
- import { relative, sep, join, dirname, resolve, isAbsolute } from 'path';
3
+ import { relative, sep, join as join$1, dirname, resolve, isAbsolute } from 'path';
4
4
  import { fileURLToPath, pathToFileURL } from 'url';
5
5
  import '@threenative/core/world';
6
6
  import '@threenative/core';
7
7
  import { ImprovedNoise } from 'three/addons/math/ImprovedNoise.js';
8
8
  import { createHash } from 'crypto';
9
9
  import { homedir } from 'os';
10
- import { gunzipSync } from 'zlib';
10
+ import { gunzipSync, inflateSync } from 'zlib';
11
11
 
12
12
  // src/mcp/cook.ts
13
13
 
@@ -686,6 +686,146 @@ function fluvial(height, n, size, {
686
686
  return Float32Array.from(h);
687
687
  }
688
688
 
689
+ // src/core/gully.ts
690
+ var STEP_SECONDS = 0.1;
691
+ var FLUX_KEEP = 0.99;
692
+ var DISSOLVE = 0.3;
693
+ var DEPOSIT = 0.02;
694
+ var EVAPORATE = 0.05;
695
+ var DEPTH_REF = 0.01;
696
+ var DEPTH_MAX = 0.3;
697
+ var MIN_TILT = 0.05;
698
+ var GRAVITY = 9.81;
699
+ var MAX_ITERATIONS = 200;
700
+ function gully(height, n, size, { iterations = 200, capacity = 0.05, rain = 5e-4 } = {}) {
701
+ if (!Number.isInteger(n) || n < 2)
702
+ throw new RangeError("Gully erosion requires grid resolution n >= 2");
703
+ if (!Number.isInteger(iterations) || iterations < 0 || iterations > MAX_ITERATIONS)
704
+ throw new RangeError(`Gully erosion iterations must be between 0 and ${MAX_ITERATIONS}`);
705
+ if (!Number.isFinite(capacity) || capacity < 0 || capacity > 1e6)
706
+ throw new RangeError("Gully erosion capacity must be between 0 and 1000000");
707
+ if (!Number.isFinite(rain) || rain < 0 || rain > 1)
708
+ throw new RangeError("Gully erosion rain must be between 0 and 1 metres per step");
709
+ const total = n * n;
710
+ let h = Float64Array.from(height);
711
+ let hTmp = new Float64Array(total);
712
+ const water2 = new Float64Array(total);
713
+ const waterBefore = new Float64Array(total);
714
+ const speed = new Float64Array(total);
715
+ const sediment = new Float64Array(total);
716
+ const sedTmp = new Float64Array(total);
717
+ const fluxL = new Float64Array(total);
718
+ const fluxR = new Float64Array(total);
719
+ const fluxT = new Float64Array(total);
720
+ const fluxB = new Float64Array(total);
721
+ const cell = size / (n - 1);
722
+ const cellArea = cell * cell;
723
+ const gain = STEP_SECONDS * GRAVITY * cell;
724
+ const evaporateKeep = Math.max(1 - EVAPORATE * STEP_SECONDS, 0);
725
+ const share2 = (flow, depth) => depth > 0 ? flow * STEP_SECONDS / (depth * cellArea) : 0;
726
+ for (let step = 0; step < iterations; step += 1) {
727
+ for (let z = 0; z < n; z += 1) {
728
+ for (let x = 0; x < n; x += 1) {
729
+ const i = z * n + x;
730
+ const depth = water2[i] + rain;
731
+ const surface = h[i] + depth;
732
+ const ground = h[i];
733
+ const left = x > 0 ? h[i - 1] + water2[i - 1] + rain : ground;
734
+ const right = x < n - 1 ? h[i + 1] + water2[i + 1] + rain : ground;
735
+ const top = z > 0 ? h[i - n] + water2[i - n] + rain : ground;
736
+ const bottom = z < n - 1 ? h[i + n] + water2[i + n] + rain : ground;
737
+ let l = fluxL[i] * FLUX_KEEP + gain * (surface - left);
738
+ let r = fluxR[i] * FLUX_KEEP + gain * (surface - right);
739
+ let t = fluxT[i] * FLUX_KEEP + gain * (surface - top);
740
+ let b = fluxB[i] * FLUX_KEEP + gain * (surface - bottom);
741
+ if (l < 0) l = 0;
742
+ if (r < 0) r = 0;
743
+ if (t < 0) t = 0;
744
+ if (b < 0) b = 0;
745
+ const sum = l + r + t + b;
746
+ if (sum > 0) {
747
+ const keep = Math.min(1, depth * cellArea / (sum * STEP_SECONDS));
748
+ l *= keep;
749
+ r *= keep;
750
+ t *= keep;
751
+ b *= keep;
752
+ }
753
+ fluxL[i] = l;
754
+ fluxR[i] = r;
755
+ fluxT[i] = t;
756
+ fluxB[i] = b;
757
+ }
758
+ }
759
+ for (let z = 0; z < n; z += 1) {
760
+ for (let x = 0; x < n; x += 1) {
761
+ const i = z * n + x;
762
+ const inL = x > 0 ? fluxR[i - 1] : 0;
763
+ const inR = x < n - 1 ? fluxL[i + 1] : 0;
764
+ const inT = z > 0 ? fluxB[i - n] : 0;
765
+ const inB = z < n - 1 ? fluxT[i + n] : 0;
766
+ const before = water2[i] + rain;
767
+ const after = Math.max(
768
+ 0,
769
+ before + STEP_SECONDS * (inL + inR + inT + inB - fluxL[i] - fluxR[i] - fluxT[i] - fluxB[i]) / cellArea
770
+ );
771
+ const depth = 0.5 * (before + after);
772
+ const acrossX = inL - fluxL[i] + fluxR[i] - inR;
773
+ const acrossZ = inT - fluxT[i] + fluxB[i] - inB;
774
+ speed[i] = depth > 1e-4 ? Math.sqrt(acrossX * acrossX + acrossZ * acrossZ) * 0.5 / (cell * depth) : 0;
775
+ water2[i] = after;
776
+ waterBefore[i] = before;
777
+ }
778
+ }
779
+ for (let z = 0; z < n; z += 1) {
780
+ for (let x = 0; x < n; x += 1) {
781
+ const i = z * n + x;
782
+ const gx = (h[z * n + Math.min(x + 1, n - 1)] - h[z * n + Math.max(x - 1, 0)]) / (2 * cell);
783
+ const gy = (h[Math.min(z + 1, n - 1) * n + x] - h[Math.max(z - 1, 0) * n + x]) / (2 * cell);
784
+ const squared = gx * gx + gy * gy;
785
+ const sine = Math.max(Math.sqrt(squared / (1 + squared)), MIN_TILT);
786
+ const depth = water2[i];
787
+ const transport = capacity * sine * speed[i] * Math.min(depth / DEPTH_REF, 1) * Math.max(1 - depth / DEPTH_MAX, 0);
788
+ let surface = h[i];
789
+ let load = sediment[i];
790
+ if (transport > load) {
791
+ const cut = DISSOLVE * (transport - load);
792
+ surface -= cut;
793
+ load += cut;
794
+ } else {
795
+ const drop = DEPOSIT * (load - transport);
796
+ surface += drop;
797
+ load -= drop;
798
+ }
799
+ hTmp[i] = surface;
800
+ sedTmp[i] = load;
801
+ }
802
+ }
803
+ const passed = h;
804
+ h = hTmp;
805
+ hTmp = passed;
806
+ for (let z = 0; z < n; z += 1) {
807
+ for (let x = 0; x < n; x += 1) {
808
+ const i = z * n + x;
809
+ let load = sedTmp[i] * (1 - share2(
810
+ fluxL[i] + fluxR[i] + fluxT[i] + fluxB[i],
811
+ waterBefore[i]
812
+ ));
813
+ if (x > 0)
814
+ load += sedTmp[i - 1] * share2(fluxR[i - 1], waterBefore[i - 1]);
815
+ if (x < n - 1)
816
+ load += sedTmp[i + 1] * share2(fluxL[i + 1], waterBefore[i + 1]);
817
+ if (z > 0)
818
+ load += sedTmp[i - n] * share2(fluxB[i - n], waterBefore[i - n]);
819
+ if (z < n - 1)
820
+ load += sedTmp[i + n] * share2(fluxT[i + n], waterBefore[i + n]);
821
+ sediment[i] = load;
822
+ water2[i] = water2[i] * evaporateKeep;
823
+ }
824
+ }
825
+ }
826
+ return Float32Array.from(h, (surface, i) => surface + sediment[i]);
827
+ }
828
+
689
829
  // src/core/masks.ts
690
830
  var MATERIAL_IDS = Object.freeze([
691
831
  "grass",
@@ -784,6 +924,57 @@ function paintWeights(s, i, channel, weight) {
784
924
  s.splat[base + c] = s.splat[base + c] * (1 - w) + (c === channel ? w : 0);
785
925
  }
786
926
 
927
+ // src/core/scree.ts
928
+ var NEIGHBOURS = [
929
+ [-1, -1],
930
+ [0, -1],
931
+ [1, -1],
932
+ [-1, 0],
933
+ [1, 0],
934
+ [-1, 1],
935
+ [0, 1],
936
+ [1, 1]
937
+ ];
938
+ var DISTANCE = Float64Array.from(NEIGHBOURS, ([dx, dz]) => Math.hypot(dx, dz));
939
+ var MAX_ITERATIONS2 = 200;
940
+ function scree(height, n, size, { iterations = 200, talus = 35, rate = 0.05 } = {}) {
941
+ if (!Number.isInteger(n) || n < 2)
942
+ throw new RangeError("Scree slide requires grid resolution n >= 2");
943
+ if (!Number.isInteger(iterations) || iterations < 0 || iterations > MAX_ITERATIONS2)
944
+ throw new RangeError(`Scree slide iterations must be between 0 and ${MAX_ITERATIONS2}`);
945
+ if (!Number.isFinite(talus) || talus < 0 || talus > 89.9)
946
+ throw new RangeError("Scree slide talus must be between 0 and 89.9 degrees");
947
+ if (!Number.isFinite(rate) || rate < 0 || rate > 1)
948
+ throw new RangeError("Scree slide rate must be between 0 and 1");
949
+ const cell = size / (n - 1);
950
+ const limit = Float64Array.from(DISTANCE, (d) => Math.tan(talus * Math.PI / 180) * cell * d);
951
+ let source = Float64Array.from(height);
952
+ let target = new Float64Array(source.length);
953
+ for (let k = 0; k < iterations; k += 1) {
954
+ for (let z = 0; z < n; z += 1) {
955
+ for (let x = 0; x < n; x += 1) {
956
+ const i = z * n + x;
957
+ const here = source[i];
958
+ let received = 0;
959
+ for (let d = 0; d < 8; d += 1) {
960
+ const nx = x + NEIGHBOURS[d][0];
961
+ const nz = z + NEIGHBOURS[d][1];
962
+ if (nx < 0 || nz < 0 || nx >= n || nz >= n) continue;
963
+ const other = source[nz * n + nx];
964
+ const gap = limit[d];
965
+ if (other - here > gap) received += other - here - gap;
966
+ else if (here - other > gap) received -= here - other - gap;
967
+ }
968
+ target[i] = here + rate * received;
969
+ }
970
+ }
971
+ const swap = source;
972
+ source = target;
973
+ target = swap;
974
+ }
975
+ return Float32Array.from(source);
976
+ }
977
+
787
978
  // src/core/operations.ts
788
979
  var OPERATION_TYPES = Object.freeze([
789
980
  "noise",
@@ -1219,7 +1410,7 @@ function applyOperation(s, layer2) {
1219
1410
  evaporation: p.evaporation
1220
1411
  },
1221
1412
  observations
1222
- ) : thermal(s.height, n, s.size, p, observations);
1413
+ ) : p.method === "gully" ? gully(s.height, n, s.size, p) : p.method === "scree" ? scree(s.height, n, s.size, p) : thermal(s.height, n, s.size, p, observations);
1223
1414
  let influence = mask;
1224
1415
  if (p.at || p.points) influence = brushWeights(s, p, mask, seed);
1225
1416
  for (let i = 0; i < s.height.length; i += 1) {
@@ -1373,6 +1564,7 @@ function finalizeState(s) {
1373
1564
  }
1374
1565
  const wet = (i, x, z, h) => {
1375
1566
  if (s.waters.some((water2) => water2.mask[i])) return true;
1567
+ if (s.waters.some((water2) => water2.kind === "ocean" && h < water2.level + 0.35)) return true;
1376
1568
  for (const river of s.rivers) {
1377
1569
  const half = river.width / 2;
1378
1570
  for (let k = 1; k < river.points.length; k += 1) {
@@ -1543,7 +1735,8 @@ var PARAMS = Object.freeze({
1543
1735
  "capacity",
1544
1736
  "erosion",
1545
1737
  "deposition",
1546
- "evaporation"
1738
+ "evaporation",
1739
+ "rain"
1547
1740
  ],
1548
1741
  terrace: ["step", "softness", "strength", "offset"],
1549
1742
  materials: ["base", "rules", "reset"],
@@ -1851,7 +2044,8 @@ function validateLayer(layer2) {
1851
2044
  "rate",
1852
2045
  "value",
1853
2046
  "waterWidth",
1854
- "maxGrade"
2047
+ "maxGrade",
2048
+ "rain"
1855
2049
  ])
1856
2050
  if (params[key] !== void 0) num(params[key], key, 0, 1);
1857
2051
  if (params.spacing !== void 0) num(params.spacing, "spacing", 0.01, 2);
@@ -1907,7 +2101,7 @@ function validateLayer(layer2) {
1907
2101
  }
1908
2102
  }
1909
2103
  if (params.method !== void 0)
1910
- enumeration(params.method, "method", ["thermal", "hydraulic", "fluvial"]);
2104
+ enumeration(params.method, "method", ["thermal", "hydraulic", "fluvial", "gully", "scree"]);
1911
2105
  if (params.mode !== void 0) enumeration(params.mode, "mode", ["fbm", "ridged", "billow"]);
1912
2106
  if (params.shape !== void 0)
1913
2107
  enumeration(
@@ -2534,7 +2728,24 @@ var SPEC_FIELDS = [
2534
2728
  "species",
2535
2729
  "aliases"
2536
2730
  ];
2537
- var COVER_FIELDS = ["ground", "seed", "attempts", "stoneRadius", "clearings"];
2731
+ var COVER_FIELDS = [
2732
+ "ground",
2733
+ "seed",
2734
+ "attempts",
2735
+ "stoneRadius",
2736
+ "clearings",
2737
+ "understorey"
2738
+ ];
2739
+ var UNDERSTOREY_FIELDS = [
2740
+ "attempts",
2741
+ "litter",
2742
+ "fern",
2743
+ "bush",
2744
+ "flower",
2745
+ "deadfall",
2746
+ "shade",
2747
+ "shadeRadius"
2748
+ ];
2538
2749
  var COVER_GROUNDS = ["wood", "crag", "mesa", "mats"];
2539
2750
  var STREAMS = ["ordered", "seeded"];
2540
2751
  var DRIFT_FIELDS = ["field", "frequency", "offset", "amplitude", "band"];
@@ -2705,13 +2916,13 @@ function frequencies(value, biome, field) {
2705
2916
  return [x, z];
2706
2917
  }
2707
2918
  function driftRow(value, biome, field) {
2708
- const row = closed(value, biome, field, DRIFT_FIELDS);
2919
+ const row2 = closed(value, biome, field, DRIFT_FIELDS);
2709
2920
  return {
2710
- field: oneOf(row.field, biome, `${field}.field`, DRIFT_FIELDS_NAMES),
2711
- frequency: frequencies(row.frequency, biome, `${field}.frequency`),
2712
- offset: share(row.offset, biome, `${field}.offset`),
2713
- amplitude: share(row.amplitude, biome, `${field}.amplitude`),
2714
- band: band(row.band, biome, `${field}.band`)
2921
+ field: oneOf(row2.field, biome, `${field}.field`, DRIFT_FIELDS_NAMES),
2922
+ frequency: frequencies(row2.frequency, biome, `${field}.frequency`),
2923
+ offset: share(row2.offset, biome, `${field}.offset`),
2924
+ amplitude: share(row2.amplitude, biome, `${field}.amplitude`),
2925
+ band: band(row2.band, biome, `${field}.band`)
2715
2926
  };
2716
2927
  }
2717
2928
  function clearing(value, biome, field) {
@@ -2721,68 +2932,82 @@ function clearing(value, biome, field) {
2721
2932
  if (radius <= 0) fail2(biome, `${field}[2]`, "must be greater than 0");
2722
2933
  return [x, z, radius];
2723
2934
  }
2935
+ function understorey(value, biome) {
2936
+ const row2 = closed(value, biome, "cover.understorey", UNDERSTOREY_FIELDS);
2937
+ return {
2938
+ attempts: whole(row2.attempts, biome, "cover.understorey.attempts"),
2939
+ litter: count(row2.litter, biome, "cover.understorey.litter"),
2940
+ fern: count(row2.fern, biome, "cover.understorey.fern"),
2941
+ bush: count(row2.bush, biome, "cover.understorey.bush"),
2942
+ flower: count(row2.flower, biome, "cover.understorey.flower"),
2943
+ deadfall: count(row2.deadfall, biome, "cover.understorey.deadfall"),
2944
+ shade: share(row2.shade, biome, "cover.understorey.shade"),
2945
+ shadeRadius: count(row2.shadeRadius, biome, "cover.understorey.shadeRadius")
2946
+ };
2947
+ }
2724
2948
  function cover(value, biome) {
2725
- const row = closed(value, biome, "cover", COVER_FIELDS);
2726
- const clearings = row.clearings;
2949
+ const row2 = closed(value, biome, "cover", COVER_FIELDS);
2950
+ const clearings = row2.clearings;
2727
2951
  if (!Array.isArray(clearings)) fail2(biome, "cover.clearings", "must be an array");
2728
2952
  return {
2729
- ground: oneOf(row.ground, biome, "cover.ground", COVER_GROUNDS),
2730
- seed: whole(row.seed, biome, "cover.seed"),
2731
- attempts: whole(row.attempts, biome, "cover.attempts", 1),
2732
- stoneRadius: positive(row.stoneRadius, biome, "cover.stoneRadius"),
2733
- clearings: clearings.map((entry, index) => clearing(entry, biome, `cover.clearings[${index}]`))
2953
+ ground: oneOf(row2.ground, biome, "cover.ground", COVER_GROUNDS),
2954
+ seed: whole(row2.seed, biome, "cover.seed"),
2955
+ attempts: whole(row2.attempts, biome, "cover.attempts", 1),
2956
+ stoneRadius: positive(row2.stoneRadius, biome, "cover.stoneRadius"),
2957
+ clearings: clearings.map((entry, index) => clearing(entry, biome, `cover.clearings[${index}]`)),
2958
+ understorey: understorey(row2.understorey, biome)
2734
2959
  };
2735
2960
  }
2736
2961
  function foliage(value, biome, field) {
2737
- const row = closed(value, biome, field, FOLIAGE_FIELDS);
2738
- const height = row.height === null ? null : pair(row.height, biome, `${field}.height`);
2962
+ const row2 = closed(value, biome, field, FOLIAGE_FIELDS);
2963
+ const height = row2.height === null ? null : pair(row2.height, biome, `${field}.height`);
2739
2964
  return {
2740
- species: text(row.species, biome, `${field}.species`),
2741
- density: count(row.density, biome, `${field}.density`),
2742
- slope: pair(row.slope, biome, `${field}.slope`, 0, 90),
2965
+ species: text(row2.species, biome, `${field}.species`),
2966
+ density: count(row2.density, biome, `${field}.density`),
2967
+ slope: pair(row2.slope, biome, `${field}.slope`, 0, 90),
2743
2968
  height,
2744
- spacing: pair(row.spacing, biome, `${field}.spacing`),
2745
- collision: oneOf(row.collision, biome, `${field}.collision`, COLLISION_CLASSES),
2746
- stands: flag(row.stands, biome, `${field}.stands`),
2747
- grassThreshold: share(row.grassThreshold, biome, `${field}.grassThreshold`),
2748
- standThreshold: share(row.standThreshold, biome, `${field}.standThreshold`),
2749
- far: far(row.far, biome, `${field}.far`)
2969
+ spacing: pair(row2.spacing, biome, `${field}.spacing`),
2970
+ collision: oneOf(row2.collision, biome, `${field}.collision`, COLLISION_CLASSES),
2971
+ stands: flag(row2.stands, biome, `${field}.stands`),
2972
+ grassThreshold: share(row2.grassThreshold, biome, `${field}.grassThreshold`),
2973
+ standThreshold: share(row2.standThreshold, biome, `${field}.standThreshold`),
2974
+ far: far(row2.far, biome, `${field}.far`)
2750
2975
  };
2751
2976
  }
2752
2977
  function grass(value, biome, field) {
2753
- const row = closed(value, biome, field, GRASS_FIELDS);
2754
- const density = count(row.density, biome, `${field}.density`);
2978
+ const row2 = closed(value, biome, field, GRASS_FIELDS);
2979
+ const density = count(row2.density, biome, `${field}.density`);
2755
2980
  if (density > 1) fail2(biome, `${field}.density`, "must be at most 1");
2756
2981
  return {
2757
- species: text(row.species, biome, `${field}.species`),
2982
+ species: text(row2.species, biome, `${field}.species`),
2758
2983
  density,
2759
- slope: pair(row.slope, biome, `${field}.slope`, 0, 90),
2760
- height: row.height === null ? null : pair(row.height, biome, `${field}.height`),
2761
- spacing: positive(row.spacing, biome, `${field}.spacing`),
2762
- slopeFalloff: count(row.slopeFalloff, biome, `${field}.slopeFalloff`),
2763
- heightFalloff: count(row.heightFalloff, biome, `${field}.heightFalloff`),
2764
- mats: row.mats === null ? null : band(row.mats, biome, `${field}.mats`),
2765
- waterMargin: count(row.waterMargin, biome, `${field}.waterMargin`),
2766
- beach: row.beach === null ? null : pair(row.beach, biome, `${field}.beach`),
2767
- detailSpacing: positive(row.detailSpacing, biome, `${field}.detailSpacing`),
2768
- drift: driftRow(row.drift, biome, `${field}.drift`),
2769
- bladeScale: count(row.bladeScale, biome, `${field}.bladeScale`),
2770
- bladeJitter: count(row.bladeJitter, biome, `${field}.bladeJitter`),
2771
- scrubChance: share(row.scrubChance, biome, `${field}.scrubChance`),
2772
- scrubScale: count(row.scrubScale, biome, `${field}.scrubScale`),
2773
- scrubJitter: count(row.scrubJitter, biome, `${field}.scrubJitter`),
2774
- scrubBush: flag(row.scrubBush, biome, `${field}.scrubBush`),
2775
- shoreGround: flag(row.shoreGround, biome, `${field}.shoreGround`),
2776
- cobbledBed: flag(row.cobbledBed, biome, `${field}.cobbledBed`)
2984
+ slope: pair(row2.slope, biome, `${field}.slope`, 0, 90),
2985
+ height: row2.height === null ? null : pair(row2.height, biome, `${field}.height`),
2986
+ spacing: positive(row2.spacing, biome, `${field}.spacing`),
2987
+ slopeFalloff: count(row2.slopeFalloff, biome, `${field}.slopeFalloff`),
2988
+ heightFalloff: count(row2.heightFalloff, biome, `${field}.heightFalloff`),
2989
+ mats: row2.mats === null ? null : band(row2.mats, biome, `${field}.mats`),
2990
+ waterMargin: count(row2.waterMargin, biome, `${field}.waterMargin`),
2991
+ beach: row2.beach === null ? null : pair(row2.beach, biome, `${field}.beach`),
2992
+ detailSpacing: positive(row2.detailSpacing, biome, `${field}.detailSpacing`),
2993
+ drift: driftRow(row2.drift, biome, `${field}.drift`),
2994
+ bladeScale: count(row2.bladeScale, biome, `${field}.bladeScale`),
2995
+ bladeJitter: count(row2.bladeJitter, biome, `${field}.bladeJitter`),
2996
+ scrubChance: share(row2.scrubChance, biome, `${field}.scrubChance`),
2997
+ scrubScale: count(row2.scrubScale, biome, `${field}.scrubScale`),
2998
+ scrubJitter: count(row2.scrubJitter, biome, `${field}.scrubJitter`),
2999
+ scrubBush: flag(row2.scrubBush, biome, `${field}.scrubBush`),
3000
+ shoreGround: flag(row2.shoreGround, biome, `${field}.shoreGround`),
3001
+ cobbledBed: flag(row2.cobbledBed, biome, `${field}.cobbledBed`)
2777
3002
  };
2778
3003
  }
2779
3004
  function layer(value, biome, field) {
2780
- const row = closed(value, biome, field, LAYER_FIELDS, LAYER_REQUIRED);
2781
- const from = count(row.from, biome, `${field}.from`);
2782
- const to = count(row.to, biome, `${field}.to`);
3005
+ const row2 = closed(value, biome, field, LAYER_FIELDS, LAYER_REQUIRED);
3006
+ const from = count(row2.from, biome, `${field}.from`);
3007
+ const to = count(row2.to, biome, `${field}.to`);
2783
3008
  if (from >= to) fail2(biome, field, "must end above where it starts");
2784
- const shedFrom = row.shedFrom === void 0 ? void 0 : count(row.shedFrom, biome, `${field}.shedFrom`, 0);
2785
- const shedTo = row.shedTo === void 0 ? void 0 : count(row.shedTo, biome, `${field}.shedTo`, 0);
3009
+ const shedFrom = row2.shedFrom === void 0 ? void 0 : count(row2.shedFrom, biome, `${field}.shedFrom`, 0);
3010
+ const shedTo = row2.shedTo === void 0 ? void 0 : count(row2.shedTo, biome, `${field}.shedTo`, 0);
2786
3011
  for (const [key, entry] of [
2787
3012
  ["shedFrom", shedFrom],
2788
3013
  ["shedTo", shedTo]
@@ -2791,7 +3016,7 @@ function layer(value, biome, field) {
2791
3016
  if (shedFrom !== void 0 && shedTo !== void 0 && shedFrom >= shedTo)
2792
3017
  fail2(biome, field, "must shed from a gentler slope than it sheds to");
2793
3018
  return {
2794
- layer: text(row.layer, biome, `${field}.layer`),
3019
+ layer: text(row2.layer, biome, `${field}.layer`),
2795
3020
  from,
2796
3021
  to,
2797
3022
  shedFrom,
@@ -2799,30 +3024,30 @@ function layer(value, biome, field) {
2799
3024
  };
2800
3025
  }
2801
3026
  function water(value, biome, field) {
2802
- const row = closed(value, biome, field, WATER_FIELDS, WATER_REQUIRED);
2803
- const kind = oneOf(row.kind, biome, `${field}.kind`, WATER_KINDS);
2804
- const width = row.width === void 0 ? void 0 : positive(row.width, biome, `${field}.width`);
2805
- const radius = row.radius === void 0 ? void 0 : positive(row.radius, biome, `${field}.radius`);
2806
- const depth = row.depth === void 0 ? void 0 : positive(row.depth, biome, `${field}.depth`);
2807
- const level = row.level === void 0 ? void 0 : count(row.level, biome, `${field}.level`);
3027
+ const row2 = closed(value, biome, field, WATER_FIELDS, WATER_REQUIRED);
3028
+ const kind = oneOf(row2.kind, biome, `${field}.kind`, WATER_KINDS);
3029
+ const width = row2.width === void 0 ? void 0 : positive(row2.width, biome, `${field}.width`);
3030
+ const radius = row2.radius === void 0 ? void 0 : positive(row2.radius, biome, `${field}.radius`);
3031
+ const depth = row2.depth === void 0 ? void 0 : positive(row2.depth, biome, `${field}.depth`);
3032
+ const level = row2.level === void 0 ? void 0 : count(row2.level, biome, `${field}.level`);
2808
3033
  if (kind === "river" && width === void 0) fail2(biome, `${field}.width`, "is missing");
2809
3034
  if (kind === "lake" && radius === void 0) fail2(biome, `${field}.radius`, "is missing");
2810
3035
  if (kind === "ocean" && level === void 0) fail2(biome, `${field}.level`, "is missing");
2811
3036
  return { kind, width, radius, depth, level };
2812
3037
  }
2813
3038
  function bake(value, biome) {
2814
- const row = closed(value, biome, "bake", BAKE_FIELDS);
3039
+ const row2 = closed(value, biome, "bake", BAKE_FIELDS);
2815
3040
  return {
2816
- file: text(row.file, biome, "bake.file"),
2817
- key: row.key === null ? null : text(row.key, biome, "bake.key")
3041
+ file: text(row2.file, biome, "bake.file"),
3042
+ key: row2.key === null ? null : text(row2.key, biome, "bake.key")
2818
3043
  };
2819
3044
  }
2820
3045
  function spawn(value, biome) {
2821
- const row = closed(value, biome, "spawn", SPAWN_FIELDS);
3046
+ const row2 = closed(value, biome, "spawn", SPAWN_FIELDS);
2822
3047
  return {
2823
- at: point2(row.at, biome, "spawn.at"),
2824
- cameraOffset: point3(row.cameraOffset, biome, "spawn.cameraOffset"),
2825
- focus: point2(row.focus, biome, "spawn.focus")
3048
+ at: point2(row2.at, biome, "spawn.at"),
3049
+ cameraOffset: point3(row2.cameraOffset, biome, "spawn.cameraOffset"),
3050
+ focus: point2(row2.focus, biome, "spawn.focus")
2826
3051
  };
2827
3052
  }
2828
3053
  function species(value, biome) {
@@ -3042,12 +3267,12 @@ function splatBytes(state, resolution) {
3042
3267
  `World package: splat has ${String(state.splat.length)} weights, expected ${String(resolution * resolution * MATERIAL_IDS.length)}.`
3043
3268
  );
3044
3269
  const bytes = new Uint8Array(planeBytes * PLANES);
3045
- for (let row = 0; row < resolution; row += 1) {
3046
- const source = (resolution - 1 - row) * resolution;
3047
- const rowOffset = row * resolution * 4;
3048
- for (let column = 0; column < resolution; column += 1) {
3049
- const sample = (source + column) * MATERIAL_IDS.length;
3050
- const rowCol = rowOffset + column * 4;
3270
+ for (let row2 = 0; row2 < resolution; row2 += 1) {
3271
+ const source = (resolution - 1 - row2) * resolution;
3272
+ const rowOffset = row2 * resolution * 4;
3273
+ for (let column2 = 0; column2 < resolution; column2 += 1) {
3274
+ const sample = (source + column2) * MATERIAL_IDS.length;
3275
+ const rowCol = rowOffset + column2 * 4;
3051
3276
  for (const slot of SLOTS) {
3052
3277
  const weight = state.splat[sample + slot.channel];
3053
3278
  bytes[slot.plane * planeBytes + rowCol + slot.componentIndex] = Math.round(
@@ -3062,25 +3287,55 @@ function splatBytes(state, resolution) {
3062
3287
  // src/core/bake-biome.ts
3063
3288
  function foliageScatterRules(foliage2, heights) {
3064
3289
  const [floor] = measureBands([], heights).elevationRange;
3065
- return foliage2.map((row) => ({
3066
- id: `foliage:${row.species}`,
3067
- asset: row.species,
3068
- count: row.density,
3069
- minSlope: row.slope[0],
3070
- maxSlope: row.slope[1],
3071
- minDistance: row.spacing[0],
3072
- ...row.height === null ? {} : { minHeight: floor + row.height[0], maxHeight: floor + row.height[1] },
3290
+ return foliage2.map((row2) => ({
3291
+ id: `foliage:${row2.species}`,
3292
+ asset: row2.species,
3293
+ count: row2.density,
3294
+ minSlope: row2.slope[0],
3295
+ maxSlope: row2.slope[1],
3296
+ minDistance: row2.spacing[0],
3297
+ ...row2.height === null ? {} : { minHeight: floor + row2.height[0], maxHeight: floor + row2.height[1] },
3073
3298
  avoidWater: true,
3074
3299
  opacity: 1,
3075
3300
  clear: []
3076
3301
  }));
3077
3302
  }
3303
+ function withImpostorDistances(assets, spec) {
3304
+ if (assets === void 0) return void 0;
3305
+ const distances = /* @__PURE__ */ new Map();
3306
+ for (const foliage2 of spec.foliage) {
3307
+ const distance = foliage2.far?.impostor;
3308
+ if (distance === void 0) continue;
3309
+ if (!Number.isFinite(distance) || distance <= 0)
3310
+ throw new Error(
3311
+ `${spec.look}: ${foliage2.species}.far.impostor must be a positive distance, got ${String(distance)}.`
3312
+ );
3313
+ distances.set(foliage2.species, distance);
3314
+ }
3315
+ if (distances.size === 0) return assets;
3316
+ const filled = {};
3317
+ for (const [species2, asset] of Object.entries(assets)) {
3318
+ const distance = distances.get(species2);
3319
+ if (distance === void 0 || asset.impostorDistance !== void 0) {
3320
+ filled[species2] = asset;
3321
+ continue;
3322
+ }
3323
+ const gate = asset.lods?.reduce((furthest, lod) => Math.max(furthest, lod.distance), 0) ?? 0;
3324
+ if (distance <= gate)
3325
+ throw new Error(
3326
+ `${species2}: impostorDistance (${String(distance)}) must follow every authored LOD gate (furthest ${String(gate)}), or the impostor replaces a level that still draws.`
3327
+ );
3328
+ filled[species2] = { ...asset, impostorDistance: distance };
3329
+ }
3330
+ return filled;
3331
+ }
3078
3332
  function bakeBiome(options) {
3079
3333
  const spec = validateBiome(options.spec, options.spec.look);
3080
3334
  const scatter = null;
3081
3335
  const state = options.state ;
3082
- const baked = options.assets === void 0 ? null : bakeWorldPackage(state, {
3083
- assets: options.assets,
3336
+ const assets = withImpostorDistances(options.assets, spec);
3337
+ const baked = assets === void 0 ? null : bakeWorldPackage(state, {
3338
+ assets,
3084
3339
  ...options.cellSize === void 0 ? {} : { cellSize: options.cellSize },
3085
3340
  ...options.layers === void 0 ? {} : { layers: options.layers },
3086
3341
  ...options.names === void 0 ? {} : { names: options.names }
@@ -3108,12 +3363,26 @@ function bakeBiome(options) {
3108
3363
 
3109
3364
  // src/core/io.ts
3110
3365
  new TextEncoder();
3111
- new TextDecoder();
3112
- Uint32Array.from({ length: 256 }, (_, initial) => {
3366
+ var decoder = new TextDecoder();
3367
+ var crcTable = Uint32Array.from({ length: 256 }, (_, initial) => {
3113
3368
  let n = initial;
3114
3369
  for (let k = 0; k < 8; k++) n = n & 1 ? 3988292384 ^ n >>> 1 : n >>> 1;
3115
3370
  return n >>> 0;
3116
3371
  });
3372
+ var crc32 = (bytes) => {
3373
+ let c = 4294967295;
3374
+ for (const b of bytes) c = crcTable[(c ^ b) & 255] ^ c >>> 8;
3375
+ return (c ^ 4294967295) >>> 0;
3376
+ };
3377
+ var join = (arrays) => {
3378
+ const out = new Uint8Array(arrays.reduce((n, a) => n + a.length, 0));
3379
+ let offset = 0;
3380
+ for (const a of arrays) {
3381
+ out.set(a, offset);
3382
+ offset += a.length;
3383
+ }
3384
+ return out;
3385
+ };
3117
3386
  function heightRange(values, { min, max } = {}) {
3118
3387
  for (const v of values) if (!Number.isFinite(v)) throw TypeError("Height data must be finite");
3119
3388
  if (min === void 0 || max === void 0) {
@@ -3142,6 +3411,387 @@ function decodeRAW16(input, { width, height, min = 0, max = 1, littleEndian = tr
3142
3411
  values[i] = min + view.getUint16(i * 2, littleEndian) / 65535 * (max - min);
3143
3412
  return { width, height, values, min, max };
3144
3413
  }
3414
+ async function inflate(bytes, expected) {
3415
+ if (typeof DecompressionStream === "undefined")
3416
+ throw Error("PNG import requires DecompressionStream");
3417
+ const reader = new Blob([new Uint8Array(bytes)]).stream().pipeThrough(new DecompressionStream("deflate")).getReader();
3418
+ const parts = [];
3419
+ let length = 0;
3420
+ try {
3421
+ while (true) {
3422
+ const { done, value } = await reader.read();
3423
+ if (done) break;
3424
+ length += value.length;
3425
+ if (length > expected) {
3426
+ await reader.cancel();
3427
+ throw Error("PNG decompressed size exceeds declared dimensions");
3428
+ }
3429
+ parts.push(value);
3430
+ }
3431
+ } finally {
3432
+ reader.releaseLock();
3433
+ }
3434
+ if (length !== expected) throw Error("PNG decompressed byte length mismatch");
3435
+ return join(parts);
3436
+ }
3437
+ var paeth = (a, b, c) => {
3438
+ const p = a + b - c;
3439
+ const pa = Math.abs(p - a);
3440
+ const pb = Math.abs(p - b);
3441
+ const pc = Math.abs(p - c);
3442
+ return pa <= pb && pa <= pc ? a : pb <= pc ? b : c;
3443
+ };
3444
+ async function decodeHeightPNG(input, options = {}) {
3445
+ const bytes = input instanceof Uint8Array ? input : new Uint8Array(input);
3446
+ const signature = [137, 80, 78, 71, 13, 10, 26, 10];
3447
+ if (bytes.length < 33 || !signature.every((v, i) => bytes[i] === v))
3448
+ throw Error("Not a PNG file");
3449
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
3450
+ const idat = [];
3451
+ let offset = 8;
3452
+ let width = 0;
3453
+ let height = 0;
3454
+ let bitDepth = 0;
3455
+ let colorType = 0;
3456
+ let metadata = {};
3457
+ let ended = false;
3458
+ let seenHeader = false;
3459
+ while (offset + 12 <= bytes.length) {
3460
+ const length = view.getUint32(offset);
3461
+ const type = decoder.decode(bytes.subarray(offset + 4, offset + 8));
3462
+ const end = offset + 12 + length;
3463
+ if (length > 64 * 1024 * 1024 || end > bytes.length)
3464
+ throw Error("Truncated or oversized PNG chunk");
3465
+ if (crc32(bytes.subarray(offset + 4, end - 4)) !== view.getUint32(end - 4))
3466
+ throw Error(`PNG CRC mismatch in ${type}`);
3467
+ const data = bytes.subarray(offset + 8, end - 4);
3468
+ if (!seenHeader && type !== "IHDR") throw Error("PNG IHDR must be first");
3469
+ if (type === "IHDR") {
3470
+ if (seenHeader || length !== 13) throw Error("Invalid PNG IHDR");
3471
+ seenHeader = true;
3472
+ width = view.getUint32(offset + 8);
3473
+ height = view.getUint32(offset + 12);
3474
+ bitDepth = data[8];
3475
+ colorType = data[9];
3476
+ if (!width || !height || width > 4097 || height > 4097)
3477
+ throw Error("PNG dimensions must be 1..4097");
3478
+ if (colorType !== 0 || ![8, 16].includes(bitDepth) || data[12] !== 0 || data[10] !== 0 || data[11] !== 0)
3479
+ throw Error("Heightmap import supports non-interlaced 8/16-bit grayscale PNG only");
3480
+ }
3481
+ if (type === "tEXt") {
3482
+ const text2 = decoder.decode(data);
3483
+ if (text2.startsWith("StrataHeightRange\0")) {
3484
+ try {
3485
+ const parsed = JSON.parse(text2.slice(18));
3486
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw Error();
3487
+ metadata = parsed;
3488
+ } catch {
3489
+ throw Error("Invalid PNG height range metadata");
3490
+ }
3491
+ }
3492
+ }
3493
+ if (type === "IDAT") idat.push(data);
3494
+ if (type === "IEND") {
3495
+ ended = true;
3496
+ break;
3497
+ }
3498
+ offset = end;
3499
+ }
3500
+ if (!ended || !idat.length) throw Error("Incomplete PNG chunks");
3501
+ const bpp = bitDepth / 8;
3502
+ const row2 = width * bpp;
3503
+ const raw = await inflate(join(idat), (row2 + 1) * height);
3504
+ const pixels = new Uint8Array(row2 * height);
3505
+ for (let y = 0; y < height; y++) {
3506
+ const filter = raw[y * (row2 + 1)];
3507
+ if (filter > 4) throw Error("Unsupported PNG row filter");
3508
+ for (let x = 0; x < row2; x++) {
3509
+ const v = raw[y * (row2 + 1) + 1 + x];
3510
+ const i = y * row2 + x;
3511
+ const a = x >= bpp ? pixels[i - bpp] : 0;
3512
+ const b = y > 0 ? pixels[i - row2] : 0;
3513
+ const c = y > 0 && x >= bpp ? pixels[i - row2 - bpp] : 0;
3514
+ pixels[i] = v + (filter === 1 ? a : filter === 2 ? b : filter === 3 ? Math.floor((a + b) / 2) : filter === 4 ? paeth(a, b, c) : 0) & 255;
3515
+ }
3516
+ }
3517
+ const { min, max } = heightRange([0, 1], {
3518
+ min: options.min ?? metadata.min ?? 0,
3519
+ max: options.max ?? metadata.max ?? 1
3520
+ });
3521
+ const values = new Float32Array(width * height);
3522
+ for (let i = 0; i < values.length; i++) {
3523
+ const v = bpp === 2 ? pixels[i * 2] << 8 | pixels[i * 2 + 1] : pixels[i];
3524
+ values[i] = min + v / (bpp === 2 ? 65535 : 255) * (max - min);
3525
+ }
3526
+ return {
3527
+ width,
3528
+ height,
3529
+ values,
3530
+ min,
3531
+ max,
3532
+ bitDepth,
3533
+ hasEmbeddedRange: Number.isFinite(metadata.min) && Number.isFinite(metadata.max)
3534
+ };
3535
+ }
3536
+
3537
+ // src/core/massif.ts
3538
+ function perimeterBase(n, edge, window, decay) {
3539
+ const loop = 4 * (n - 1);
3540
+ const at = (k) => {
3541
+ const m = (k % loop + loop) % loop;
3542
+ const side = Math.floor(m / (n - 1));
3543
+ const t = m % (n - 1);
3544
+ return side === 0 ? [0, t] : side === 1 ? [t, n - 1] : side === 2 ? [n - 1, n - 1 - t] : [n - 1 - t, 0];
3545
+ };
3546
+ const raw = Float64Array.from({ length: loop }, (_, k) => {
3547
+ const [row2, column2] = at(k);
3548
+ return edge(row2 * n + column2);
3549
+ });
3550
+ const prefix = new Float64Array(3 * loop + 1);
3551
+ for (let k = 0; k < 3 * loop; k++)
3552
+ prefix[k + 1] = prefix[k] + raw[k % loop];
3553
+ const half = Math.max(1, Math.round(window / 2));
3554
+ const smooth = Float64Array.from(
3555
+ { length: loop },
3556
+ (_, k) => (prefix[loop + k + half + 1] - prefix[loop + k - half]) / (2 * half + 1)
3557
+ );
3558
+ const index = (row2, column2) => {
3559
+ if (row2 === 0) return column2;
3560
+ if (column2 === n - 1) return n - 1 + row2;
3561
+ if (row2 === n - 1) return 2 * (n - 1) + (n - 1 - column2);
3562
+ return 3 * (n - 1) + (n - 1 - row2);
3563
+ };
3564
+ const s = (row2, column2) => smooth[index(row2, column2) % loop];
3565
+ const r = (row2, column2) => raw[index(row2, column2) % loop] - smooth[index(row2, column2) % loop];
3566
+ const base = new Float32Array(n * n);
3567
+ const last = n - 1;
3568
+ for (let row2 = 0; row2 < n; row2++) {
3569
+ const v = row2 / last;
3570
+ for (let column2 = 0; column2 < n; column2++) {
3571
+ const u = column2 / last;
3572
+ const coons = (1 - v) * s(0, column2) + v * s(last, column2) + (1 - u) * s(row2, 0) + u * s(row2, last) - ((1 - u) * (1 - v) * s(0, 0) + u * (1 - v) * s(0, last) + (1 - u) * v * s(last, 0) + u * v * s(last, last));
3573
+ const detail = r(0, column2) * Math.exp(-row2 / decay) + r(last, column2) * Math.exp(-(last - row2) / decay) + r(row2, 0) * Math.exp(-column2 / decay) + r(row2, last) * Math.exp(-(last - column2) / decay);
3574
+ base[row2 * n + column2] = coons + detail;
3575
+ }
3576
+ }
3577
+ for (let k = 0; k < loop; k++) {
3578
+ const [row2, column2] = at(k);
3579
+ base[row2 * n + column2] = raw[k];
3580
+ }
3581
+ return base;
3582
+ }
3583
+ function liftMassif(tile) {
3584
+ const n = tile.resolution;
3585
+ if (tile.heights.length !== n * n)
3586
+ throw new RangeError(`Massif ${tile.id}: ${n}^2 heights expected`);
3587
+ const spacing = tile.size / (n - 1);
3588
+ const base = perimeterBase(n, (i) => tile.heights[i], 200 / spacing, 50 / spacing);
3589
+ return Float32Array.from(
3590
+ { length: n * n },
3591
+ (_, i) => tile.heights[i] - base[i]
3592
+ );
3593
+ }
3594
+ var catmullRom = (a, b, c, d, t) => b + 0.5 * t * (c - a + t * (2 * a - 5 * b + 4 * c - d + t * (3 * (b - c) + d - a)));
3595
+ function faceDirection(lifted, n, spacing) {
3596
+ let x = 0;
3597
+ let z = 0;
3598
+ const step = Math.max(1, Math.floor(n / 128));
3599
+ for (let row2 = step; row2 < n - step; row2 += step)
3600
+ for (let column2 = step; column2 < n - step; column2 += step) {
3601
+ if (lifted[row2 * n + column2] < 50) continue;
3602
+ const dx = (lifted[row2 * n + column2 + step] - lifted[row2 * n + column2 - step]) / (2 * step * spacing);
3603
+ const dz = (lifted[(row2 + step) * n + column2] - lifted[(row2 - step) * n + column2]) / (2 * step * spacing);
3604
+ const g2 = dx * dx + dz * dz;
3605
+ if (g2 < 1) continue;
3606
+ const g = Math.sqrt(g2);
3607
+ x -= dx / g * g2;
3608
+ z -= dz / g * g2;
3609
+ }
3610
+ return Math.atan2(z, x);
3611
+ }
3612
+ var KEEP_OUT_RAMP = 600;
3613
+ function placeMassif(terrain, options) {
3614
+ const draw = random(options.seed * 2654435761 ^ 1835103091);
3615
+ const tiles = Array.isArray(options.tile) ? options.tile : [options.tile];
3616
+ if (tiles.length === 0) throw new RangeError("placeMassif needs at least one tile");
3617
+ const tile = tiles[Math.floor(draw() * tiles.length) % tiles.length];
3618
+ const lifted = liftMassif(tile);
3619
+ const n = tile.resolution;
3620
+ const spacing = tile.size / (n - 1);
3621
+ let summit = 0;
3622
+ for (let i = 1; i < lifted.length; i++)
3623
+ if (lifted[i] > lifted[summit]) summit = i;
3624
+ const tall = lifted[summit];
3625
+ if (!(tall > 0)) throw new RangeError(`Massif ${tile.id} has no relief above its border`);
3626
+ const mirror = draw() < 0.5;
3627
+ const local = (i) => {
3628
+ const x = (i % n / (n - 1) - 0.5) * tile.size;
3629
+ return [mirror ? -x : x, (Math.floor(i / n) / (n - 1) - 0.5) * tile.size];
3630
+ };
3631
+ const [sx, sz] = local(summit);
3632
+ const state = terrain.evaluate();
3633
+ const N = state.resolution;
3634
+ const cell = state.size / (N - 1);
3635
+ const halfWorld = state.size / 2;
3636
+ const at = options.at !== void 0 ? [options.at[0], options.at[1]] : (() => {
3637
+ const [b0, b1] = options.bearing ?? [0, 360];
3638
+ const [d0, d1] = options.distance ?? [tile.size / 2, halfWorld - tile.size / 4];
3639
+ const bearing = (b0 + draw() * (b1 - b0)) * Math.PI / 180;
3640
+ const distance = d0 + draw() * (d1 - d0);
3641
+ return [Math.cos(bearing) * distance, Math.sin(bearing) * distance];
3642
+ })();
3643
+ if (options.at !== void 0) {
3644
+ draw();
3645
+ draw();
3646
+ }
3647
+ const faceTile = faceDirection(lifted, n, spacing);
3648
+ const face = mirror ? Math.PI - faceTile : faceTile;
3649
+ const toCentre = options.face !== void 0 ? options.face * Math.PI / 180 : Math.atan2(-at[1], -at[0]);
3650
+ const jitter = (draw() - 0.5) * 40 * Math.PI / 180;
3651
+ const turn = toCentre + jitter - face;
3652
+ const pick = draw();
3653
+ const keepOut = options.keepOut ?? 320;
3654
+ const cos = Math.cos(turn);
3655
+ const sin = Math.sin(turn);
3656
+ const toTile = (x, z) => {
3657
+ const dx = x - at[0];
3658
+ const dz = z - at[1];
3659
+ const mx = sx + dx * cos + dz * sin;
3660
+ const mz = sz - dx * sin + dz * cos;
3661
+ return [(mirror ? -mx : mx) / tile.size + 0.5, mz / tile.size + 0.5];
3662
+ };
3663
+ const toWorld = (u, v) => {
3664
+ const mx = (mirror ? -1 : 1) * (u - 0.5) * tile.size - sx;
3665
+ const mz = (v - 0.5) * tile.size - sz;
3666
+ return [at[0] + mx * cos - mz * sin, at[1] + mx * sin + mz * cos];
3667
+ };
3668
+ const hostAt = (x, z) => sampleGrid(state.height, N, N, (x + halfWorld) / state.size, (z + halfWorld) / state.size);
3669
+ const hostSmooth = (x, z) => {
3670
+ const gx = clamp((x + halfWorld) / cell, 0, N - 1);
3671
+ const gz = clamp((z + halfWorld) / cell, 0, N - 1);
3672
+ const ix = Math.min(N - 2, Math.floor(gx));
3673
+ const iz = Math.min(N - 2, Math.floor(gz));
3674
+ const tx = gx - ix;
3675
+ const tz = gz - iz;
3676
+ const h = (r, c) => state.height[clamp(r, 0, N - 1) * N + clamp(c, 0, N - 1)];
3677
+ const row2 = (r) => catmullRom(h(r, ix - 1), h(r, ix), h(r, ix + 1), h(r, ix + 2), tx);
3678
+ return catmullRom(row2(iz - 1), row2(iz), row2(iz + 1), row2(iz + 2), tz);
3679
+ };
3680
+ const B = 129;
3681
+ const hostEdge = new Float32Array(B * B);
3682
+ for (let row2 = 0; row2 < B; row2++)
3683
+ for (let column2 = 0; column2 < B; column2++)
3684
+ if (row2 === 0 || column2 === 0 || row2 === B - 1 || column2 === B - 1)
3685
+ hostEdge[row2 * B + column2] = hostAt(...toWorld(column2 / (B - 1), row2 / (B - 1)));
3686
+ const hostBase = perimeterBase(
3687
+ B,
3688
+ (i) => hostEdge[i],
3689
+ 200 / (tile.size / (B - 1)),
3690
+ 1e-6
3691
+ );
3692
+ const foot = sampleGrid(hostBase, B, B, ...toTile(at[0], at[1]));
3693
+ let floor = Number.POSITIVE_INFINITY;
3694
+ for (let i = 0; i < B * B; i++) {
3695
+ const row2 = Math.floor(i / B);
3696
+ const column2 = i % B;
3697
+ if (row2 === 0 || column2 === 0 || row2 === B - 1 || column2 === B - 1)
3698
+ floor = Math.min(floor, hostEdge[i]);
3699
+ }
3700
+ let scale;
3701
+ if (options.top) {
3702
+ const top = options.top[0] + pick * (options.top[1] - options.top[0]);
3703
+ scale = Number.POSITIVE_INFINITY;
3704
+ for (let row2 = 0; row2 < n; row2 += 4)
3705
+ for (let column2 = 0; column2 < n; column2 += 4) {
3706
+ const rise = lifted[row2 * n + column2];
3707
+ if (rise < 1) continue;
3708
+ const u = column2 / (n - 1);
3709
+ const v = row2 / (n - 1);
3710
+ const [x, z] = toWorld(u, v);
3711
+ if (Math.abs(x) > halfWorld || Math.abs(z) > halfWorld) continue;
3712
+ scale = Math.min(scale, (top - sampleGrid(hostBase, B, B, u, v)) / rise);
3713
+ }
3714
+ } else {
3715
+ const [h0, h1] = options.height ?? [0.85 * tall, 1.15 * tall];
3716
+ scale = (h0 + pick * (h1 - h0)) / tall;
3717
+ }
3718
+ if (!(scale > 0))
3719
+ throw new RangeError(`Massif ${tile.id}: top under its foot at ${foot.toFixed(0)} m`);
3720
+ const height = scale * tall;
3721
+ const factor = Math.max(1, Math.round(cell / spacing));
3722
+ const coarseN = Math.floor((n - 1) / factor) + 1;
3723
+ const coarse = new Float32Array(coarseN * coarseN);
3724
+ const tent = (d) => factor - Math.abs(d);
3725
+ for (let row2 = 0; row2 < coarseN; row2++)
3726
+ for (let column2 = 0; column2 < coarseN; column2++) {
3727
+ let sum = 0;
3728
+ let total = 0;
3729
+ for (let dr = 1 - factor; dr < factor; dr++)
3730
+ for (let dc = 1 - factor; dc < factor; dc++) {
3731
+ const r = row2 * factor + dr;
3732
+ const c = column2 * factor + dc;
3733
+ if (r < 0 || c < 0 || r >= n || c >= n) continue;
3734
+ const w = tent(dr) * tent(dc);
3735
+ sum += w * lifted[r * n + c];
3736
+ total += w;
3737
+ }
3738
+ coarse[row2 * coarseN + column2] = sum / total;
3739
+ }
3740
+ const finalAt = (x, z, grid, gridN) => {
3741
+ const [u, v] = toTile(x, z);
3742
+ if (u <= 0 || u >= 1 || v <= 0 || v >= 1) return [0, 0];
3743
+ const edge = Math.min(u, v, 1 - u, 1 - v);
3744
+ const reach = Math.max(Math.abs(x), Math.abs(z));
3745
+ const weight = smoothstep(0, 0.04, edge) * smoothstep(keepOut, keepOut + KEEP_OUT_RAMP, reach);
3746
+ if (weight === 0) return [0, 0];
3747
+ const raw = sampleGrid(hostBase, B, B, u, v) + scale * sampleGrid(grid, gridN, gridN, u, v);
3748
+ const value = (raw + floor + Math.sqrt((raw - floor) ** 2 + 40 ** 2)) / 2;
3749
+ return [value, weight];
3750
+ };
3751
+ const delta = new Float32Array(N * N);
3752
+ for (let row2 = 0; row2 < N; row2++)
3753
+ for (let column2 = 0; column2 < N; column2++) {
3754
+ const x = column2 * cell - halfWorld;
3755
+ const z = row2 * cell - halfWorld;
3756
+ const [value, weight] = finalAt(x, z, coarse, coarseN);
3757
+ if (weight > 0) {
3758
+ const host = state.height[row2 * N + column2];
3759
+ delta[row2 * N + column2] = weight * (value - host);
3760
+ }
3761
+ }
3762
+ const corners = [toWorld(0, 0), toWorld(1, 0), toWorld(0, 1), toWorld(1, 1)];
3763
+ const x0 = clamp(Math.min(...corners.map((p) => p[0])), -halfWorld, halfWorld);
3764
+ const x1 = clamp(Math.max(...corners.map((p) => p[0])), -halfWorld, halfWorld);
3765
+ const z0 = clamp(Math.min(...corners.map((p) => p[1])), -halfWorld, halfWorld);
3766
+ const z1 = clamp(Math.max(...corners.map((p) => p[1])), -halfWorld, halfWorld);
3767
+ const columns = Math.floor((x1 - x0) / spacing) + 1;
3768
+ const rows = Math.floor((z1 - z0) / spacing) + 1;
3769
+ const detail = new Float32Array(columns * rows);
3770
+ for (let row2 = 0; row2 < rows; row2++)
3771
+ for (let column2 = 0; column2 < columns; column2++) {
3772
+ const x = x0 + column2 * spacing;
3773
+ const z = z0 + row2 * spacing;
3774
+ const host = hostSmooth(x, z);
3775
+ const [value, weight] = finalAt(x, z, lifted, n);
3776
+ detail[row2 * columns + column2] = host + weight * (value - host);
3777
+ }
3778
+ const id = options.id ?? "massif";
3779
+ return {
3780
+ terrain: terrain.heightmap({
3781
+ id,
3782
+ data: { width: N, height: N, values: Array.from(delta) },
3783
+ blend: "add"
3784
+ }),
3785
+ placement: {
3786
+ tile: tile.id,
3787
+ at,
3788
+ rotation: turn * 180 / Math.PI,
3789
+ mirror,
3790
+ height,
3791
+ detail: { origin: [x0, z0], spacing, columns, rows, heights: detail }
3792
+ }
3793
+ };
3794
+ }
3145
3795
 
3146
3796
  // src/core/placements.ts
3147
3797
  function validatePlacementOverrides(value = {}) {
@@ -3194,6 +3844,194 @@ function applyPlacementOverrides(state, value) {
3194
3844
  ]
3195
3845
  };
3196
3846
  }
3847
+
3848
+ // src/core/stats.ts
3849
+ var CHANNEL_AREA_M2 = 1e5;
3850
+ var quantile = (sorted, q) => sorted[Math.min(sorted.length - 1, Math.floor(q * sorted.length))];
3851
+ function terrainStats(height, n, size) {
3852
+ const spacing = size / (n - 1);
3853
+ let low = Number.POSITIVE_INFINITY;
3854
+ let high = Number.NEGATIVE_INFINITY;
3855
+ let sum = 0;
3856
+ for (let i = 0; i < height.length; i += 1) {
3857
+ const v = height[i];
3858
+ low = Math.min(low, v);
3859
+ high = Math.max(high, v);
3860
+ sum += v;
3861
+ }
3862
+ const relief = high - low;
3863
+ const interior = (n - 2) * (n - 2);
3864
+ const slopes = new Float32Array(interior);
3865
+ const laplacian = new Float32Array(interior);
3866
+ let lapSum = 0;
3867
+ let k = 0;
3868
+ for (let z = 1; z < n - 1; z += 1) {
3869
+ for (let x = 1; x < n - 1; x += 1) {
3870
+ const i = z * n + x;
3871
+ const here = height[i];
3872
+ const east = height[i + 1];
3873
+ const west = height[i - 1];
3874
+ const south = height[i + n];
3875
+ const north = height[i - n];
3876
+ slopes[k] = Math.atan(Math.hypot(east - west, south - north) / (2 * spacing)) * 180 / Math.PI;
3877
+ laplacian[k] = (east + west + south + north - 4 * here) / (spacing * spacing);
3878
+ lapSum += laplacian[k];
3879
+ k += 1;
3880
+ }
3881
+ }
3882
+ const lapMean = lapSum / interior;
3883
+ let m2 = 0;
3884
+ let m4 = 0;
3885
+ for (let i = 0; i < interior; i += 1) {
3886
+ const d = laplacian[i] - lapMean;
3887
+ m2 += d * d;
3888
+ m4 += d * d * d * d;
3889
+ }
3890
+ m2 /= interior;
3891
+ m4 /= interior;
3892
+ slopes.sort();
3893
+ const filled = Float64Array.from(height);
3894
+ fillDepressions(filled, n);
3895
+ const flow = createFlow(n);
3896
+ routeFlow(filled, n, flow);
3897
+ const channelCells = CHANNEL_AREA_M2 / (spacing * spacing);
3898
+ let channels = 0;
3899
+ for (let i = 0; i < flow.cells.length; i += 1)
3900
+ if (flow.cells[i] >= channelCells) channels += 1;
3901
+ const areaKm2 = size * size / 1e6;
3902
+ return {
3903
+ relief,
3904
+ hypsometricIntegral: relief > 0 ? (sum / height.length - low) / relief : 0,
3905
+ slopeP50: quantile(slopes, 0.5),
3906
+ slopeP90: quantile(slopes, 0.9),
3907
+ drainageDensity: channels * spacing / 1e3 / areaKm2,
3908
+ curvatureKurtosis: m2 > 0 ? m4 / (m2 * m2) - 3 : 0
3909
+ };
3910
+ }
3911
+
3912
+ // src/core/surveys.ts
3913
+ var TILES = "AWS Terrain Tiles (github.com/tilezen/joerd, Mapzen terrain tiles).";
3914
+ var USGS_3DEP = "United States 3DEP (formerly NED) terrain data courtesy of the U.S. Geological Survey.";
3915
+ var EU_DEM = "Produced using Copernicus data and information funded by the European Union - EU-DEM layers.";
3916
+ var SRTM = "SRTM data courtesy of the U.S. Geological Survey.";
3917
+ var SURVEYS = {
3918
+ alpine: {
3919
+ name: "Matterhorn massif, Pennine Alps (Switzerland / Italy)",
3920
+ lat: 45.9763,
3921
+ lon: 7.6586,
3922
+ extentMeters: 6e3,
3923
+ zoom: 12,
3924
+ attribution: `${EU_DEM} ${TILES}`
3925
+ // measured: 2 168..4 352 m (the summit is 4 478 m, at about 30 m per pixel)
3926
+ },
3927
+ temperateMountains: {
3928
+ name: "Sprague Lake and Glacier Creek, Rocky Mountain National Park, Colorado",
3929
+ lat: 40.32,
3930
+ lon: -105.6067,
3931
+ extentMeters: 6e3,
3932
+ zoom: 12,
3933
+ attribution: `${USGS_3DEP} ${TILES}`
3934
+ // measured: 2 387..3 434 m
3935
+ },
3936
+ rollingHills: {
3937
+ name: "Coon Valley, Driftless Area, Wisconsin",
3938
+ lat: 43.7019,
3939
+ lon: -91.0139,
3940
+ extentMeters: 6e3,
3941
+ zoom: 12,
3942
+ attribution: `${USGS_3DEP} ${TILES}`
3943
+ // measured: 209..391 m: 3 % relief over its 6 km, which is the preset's own 0.03 ratio
3944
+ },
3945
+ desertMesa: {
3946
+ name: "Monument Valley, Arizona / Utah",
3947
+ lat: 36.998,
3948
+ lon: -110.0985,
3949
+ extentMeters: 5e3,
3950
+ zoom: 12,
3951
+ attribution: `${USGS_3DEP} ${TILES}`
3952
+ // measured: 1 542..1 972 m (the valley floor to the butte tops)
3953
+ },
3954
+ coastalCliffs: {
3955
+ name: "\xC9tretat chalk cliffs, Normandy, France",
3956
+ lat: 49.707,
3957
+ lon: 0.203,
3958
+ extentMeters: 4e3,
3959
+ zoom: 12,
3960
+ attribution: `${EU_DEM} ${TILES}`
3961
+ // measured: -9..112 m (the sea to the cliff top)
3962
+ },
3963
+ tundra: {
3964
+ name: "Trail Ridge, Rocky Mountain National Park, Colorado",
3965
+ lat: 40.4103,
3966
+ lon: -105.735,
3967
+ extentMeters: 5e3,
3968
+ zoom: 12,
3969
+ attribution: `${USGS_3DEP} ${TILES}`
3970
+ // measured: 2 956..3 797 m, above the tree line
3971
+ },
3972
+ volcanic: {
3973
+ name: "Mount Fuji, Honshu, Japan",
3974
+ lat: 35.3606,
3975
+ lon: 138.7274,
3976
+ extentMeters: 6e3,
3977
+ zoom: 12,
3978
+ attribution: `${SRTM} ${TILES}`
3979
+ // measured: 1 548..3 753 m (the summit is 3 776 m)
3980
+ }
3981
+ };
3982
+ var MASSIFS = {
3983
+ temperateMountains: [
3984
+ {
3985
+ name: "Longs Peak and Mount Meeker, Rocky Mountain National Park, Colorado",
3986
+ lat: 40.2549,
3987
+ lon: -105.6101,
3988
+ extentMeters: 4400,
3989
+ zoom: 12,
3990
+ attribution: `${USGS_3DEP} ${TILES}`
3991
+ }
3992
+ ],
3993
+ alpine: [
3994
+ {
3995
+ name: "Grand Teton and the Cathedral Group, Wyoming",
3996
+ lat: 43.7455,
3997
+ lon: -110.8024,
3998
+ extentMeters: 3600,
3999
+ zoom: 12,
4000
+ attribution: `${USGS_3DEP} ${TILES}`
4001
+ },
4002
+ {
4003
+ name: "Maroon Bells, Elk Mountains, Colorado",
4004
+ lat: 39.0708,
4005
+ lon: -106.989,
4006
+ extentMeters: 3600,
4007
+ zoom: 12,
4008
+ attribution: `${USGS_3DEP} ${TILES}`
4009
+ }
4010
+ ]
4011
+ };
4012
+ var LOCATION_EXTENT_METERS = 6e3;
4013
+ var LOCATION_ZOOM = 12;
4014
+ var finite = (value, axis) => {
4015
+ if (!Number.isFinite(value))
4016
+ throw new TypeError(`ground.location.${axis} must be a finite number.`);
4017
+ return value;
4018
+ };
4019
+ function locationSurvey(lat, lon) {
4020
+ const latitude = finite(lat, "lat");
4021
+ const longitude = finite(lon, "lon");
4022
+ if (Math.abs(latitude) > 90)
4023
+ throw new RangeError("ground.location.lat must be between -90 and 90.");
4024
+ if (Math.abs(longitude) > 180)
4025
+ throw new RangeError("ground.location.lon must be between -180 and 180.");
4026
+ return {
4027
+ name: `${latitude}, ${longitude}`,
4028
+ lat: latitude,
4029
+ lon: longitude,
4030
+ extentMeters: LOCATION_EXTENT_METERS,
4031
+ zoom: LOCATION_ZOOM,
4032
+ attribution: `${SRTM} ${TILES}`
4033
+ };
4034
+ }
3197
4035
  function fail3(reason) {
3198
4036
  throw new Error(`TN_TERRAIN_ASSETS_${reason}`);
3199
4037
  }
@@ -3239,7 +4077,7 @@ async function extract(archive, target) {
3239
4077
  fail3("SIZE");
3240
4078
  const next = at + 512 + Math.ceil(size / 512) * 512;
3241
4079
  if (next > tar.length) fail3("TRUNCATED");
3242
- const path = join(target, ...name.split("/").slice(1));
4080
+ const path = join$1(target, ...name.split("/").slice(1));
3243
4081
  if (type === 53) await mkdir(path, { recursive: true, mode: 493 });
3244
4082
  else {
3245
4083
  await mkdir(dirname(path), { recursive: true, mode: 493 });
@@ -3251,13 +4089,13 @@ async function extract(archive, target) {
3251
4089
  }
3252
4090
  async function starterAssetsDir() {
3253
4091
  const root = dirname(fileURLToPath(import.meta.resolve("@threenative/terrain/package.json")));
3254
- const local = join(root, "starter-assets");
4092
+ const local = join$1(root, "starter-assets");
3255
4093
  if (await isDirectory(local)) return local;
3256
- const manifest = JSON.parse(await readFile(join(root, "starter-assets.json"), "utf8"));
4094
+ const manifest = JSON.parse(await readFile(join$1(root, "starter-assets.json"), "utf8"));
3257
4095
  if (!/^[a-f0-9]{64}$/u.test(manifest.sha256) || !Number.isSafeInteger(manifest.bytes) || manifest.bytes <= 0 || manifest.bytes > 128 * 1024 * 1024)
3258
4096
  fail3("MANIFEST");
3259
- const cache = join(
3260
- process.env.XDG_CACHE_HOME || join(homedir(), ".cache"),
4097
+ const cache = join$1(
4098
+ process.env.XDG_CACHE_HOME || join$1(homedir(), ".cache"),
3261
4099
  "threenative",
3262
4100
  "terrain-starter-assets",
3263
4101
  manifest.sha256
@@ -3354,6 +4192,196 @@ function measureGlb(bytes) {
3354
4192
  for (const root of scene?.nodes ?? (gltf.scenes === void 0 ? nodes.keys() : [])) visit(root);
3355
4193
  return stats;
3356
4194
  }
4195
+ var TERRARIUM = "https://s3.amazonaws.com/elevation-tiles-prod/terrarium";
4196
+ var TILE_PX = 256;
4197
+ var M_PER_DEG_LAT = 110574;
4198
+ var M_PER_DEG_LON = 111320;
4199
+ var tileUrl = (z, x, y) => `${TERRARIUM}/${z}/${x}/${y}.png`;
4200
+ function tileCacheDir() {
4201
+ const configured = process.env.TN_TERRAIN_TILE_CACHE;
4202
+ if (configured !== void 0 && configured !== "") return configured;
4203
+ return join$1(process.env.XDG_CACHE_HOME ?? join$1(homedir(), ".cache"), "threenative", "terrarium");
4204
+ }
4205
+ var column = (lon, z) => (lon + 180) / 360 * 2 ** z;
4206
+ function row(lat, z) {
4207
+ const rad = lat * Math.PI / 180;
4208
+ return (1 - Math.log(Math.tan(rad) + 1 / Math.cos(rad)) / Math.PI) / 2 * 2 ** z;
4209
+ }
4210
+ function readPNGChunks(bytes, url) {
4211
+ const signature = [137, 80, 78, 71, 13, 10, 26, 10];
4212
+ if (bytes.length < 33 || !signature.every((value, at) => bytes[at] === value)) {
4213
+ throw new Error(`cook: ground survey tile ${url} is not a PNG.`);
4214
+ }
4215
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
4216
+ const decoder2 = new TextDecoder();
4217
+ const idat = [];
4218
+ let width = 0;
4219
+ let height = 0;
4220
+ let bitDepth = 0;
4221
+ let colorType = 0;
4222
+ let interlace = 0;
4223
+ let offset = 8;
4224
+ while (offset + 12 <= bytes.length) {
4225
+ const length = view.getUint32(offset);
4226
+ const type = decoder2.decode(bytes.subarray(offset + 4, offset + 8));
4227
+ const end = offset + 12 + length;
4228
+ if (end > bytes.length) throw new Error(`cook: ground survey tile ${url} is truncated.`);
4229
+ if (type === "IHDR") {
4230
+ width = view.getUint32(offset + 8);
4231
+ height = view.getUint32(offset + 12);
4232
+ bitDepth = bytes[offset + 16];
4233
+ colorType = bytes[offset + 17];
4234
+ interlace = bytes[offset + 20];
4235
+ }
4236
+ if (type === "IDAT") idat.push(bytes.subarray(offset + 8, end - 4));
4237
+ if (type === "IEND") return { width, height, bitDepth, colorType, interlace, idat };
4238
+ offset = end;
4239
+ }
4240
+ throw new Error(`cook: ground survey tile ${url} is incomplete.`);
4241
+ }
4242
+ function paeth2(left, up, corner) {
4243
+ const p = left + up - corner;
4244
+ const pa = Math.abs(p - left);
4245
+ const pb = Math.abs(p - up);
4246
+ const pc = Math.abs(p - corner);
4247
+ if (pa <= pb && pa <= pc) return left;
4248
+ return pb <= pc ? up : corner;
4249
+ }
4250
+ function predicted(filter, left, up, corner) {
4251
+ if (filter === 1) return left;
4252
+ if (filter === 2) return up;
4253
+ if (filter === 3) return left + up >> 1;
4254
+ if (filter === 4) return paeth2(left, up, corner);
4255
+ return 0;
4256
+ }
4257
+ function unfilter(raw, width, height, channels, url) {
4258
+ const stride = width * channels;
4259
+ const pixels = new Uint8Array(stride * height);
4260
+ for (let y = 0; y < height; y += 1) {
4261
+ const filter = raw[y * (stride + 1)];
4262
+ if (filter > 4)
4263
+ throw new Error(`cook: ground survey tile ${url} uses PNG row filter ${filter}.`);
4264
+ for (let x = 0; x < stride; x += 1) {
4265
+ const at = y * stride + x;
4266
+ const left = x >= channels ? pixels[at - channels] : 0;
4267
+ const up = y > 0 ? pixels[at - stride] : 0;
4268
+ const corner = y > 0 && x >= channels ? pixels[at - stride - channels] : 0;
4269
+ const value = raw[y * (stride + 1) + 1 + x];
4270
+ pixels[at] = value + predicted(filter, left, up, corner) & 255;
4271
+ }
4272
+ }
4273
+ return pixels;
4274
+ }
4275
+ function decodeTerrarium(bytes, url) {
4276
+ const png = readPNGChunks(bytes, url);
4277
+ if (png.bitDepth !== 8 || png.colorType !== 2 || png.interlace !== 0) {
4278
+ throw new Error(
4279
+ `cook: ground survey tile ${url} is not an 8-bit RGB PNG (bit depth ${png.bitDepth}, colour type ${png.colorType}, interlace ${png.interlace}).`
4280
+ );
4281
+ }
4282
+ const channels = 3;
4283
+ const raw = inflateSync(Buffer.concat(png.idat));
4284
+ if (raw.length !== (png.width * channels + 1) * png.height) {
4285
+ throw new Error(`cook: ground survey tile ${url} decodes to ${raw.length} bytes, not a tile.`);
4286
+ }
4287
+ const pixels = unfilter(raw, png.width, png.height, channels, url);
4288
+ const heights = new Float32Array(png.width * png.height);
4289
+ for (let at = 0; at < heights.length; at += 1) {
4290
+ heights[at] = pixels[at * channels] * 256 + pixels[at * channels + 1] + pixels[at * channels + 2] / 256 - 32768;
4291
+ }
4292
+ return { width: png.width, height: png.height, heights };
4293
+ }
4294
+ async function loadTile(z, x, y) {
4295
+ const url = tileUrl(z, x, y);
4296
+ const file = join$1(tileCacheDir(), String(z), String(x), `${y}.png`);
4297
+ const cached = await readFile(file).catch(() => void 0);
4298
+ if (cached !== void 0) return decodeTerrarium(new Uint8Array(cached), url);
4299
+ let bytes;
4300
+ try {
4301
+ const response = await fetch(url);
4302
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
4303
+ bytes = new Uint8Array(await response.arrayBuffer());
4304
+ } catch (error) {
4305
+ throw new Error(
4306
+ `cook: ground survey tile ${url} is not cached in ${tileCacheDir()} and could not be fetched (${error instanceof Error ? error.message : String(error)}). Pass ground: "procedural" to cook the preset's own noise instead.`
4307
+ );
4308
+ }
4309
+ const tile = decodeTerrarium(bytes, url);
4310
+ await mkdir(dirname(file), { recursive: true });
4311
+ await writeFile(file, bytes);
4312
+ return tile;
4313
+ }
4314
+ var bilinear = (values, width, height, x, y) => {
4315
+ const fx = Math.min(width - 1, Math.max(0, x));
4316
+ const fy = Math.min(height - 1, Math.max(0, y));
4317
+ const x0 = Math.floor(fx);
4318
+ const y0 = Math.floor(fy);
4319
+ const x1 = Math.min(width - 1, x0 + 1);
4320
+ const y1 = Math.min(height - 1, y0 + 1);
4321
+ const tx = fx - x0;
4322
+ const ty = fy - y0;
4323
+ const top = values[y0 * width + x0] * (1 - tx) + values[y0 * width + x1] * tx;
4324
+ const bottom = values[y1 * width + x0] * (1 - tx) + values[y1 * width + x1] * tx;
4325
+ return top * (1 - ty) + bottom * ty;
4326
+ };
4327
+ async function surveyHeights(survey, resolution) {
4328
+ if (!Number.isInteger(resolution) || resolution < 2 || resolution > 4097) {
4329
+ throw new RangeError(`cook: a survey needs a grid of 2..4097 samples, not ${resolution}.`);
4330
+ }
4331
+ const z = survey.zoom;
4332
+ const halfLat = survey.extentMeters / 2 / M_PER_DEG_LAT;
4333
+ const halfLon = survey.extentMeters / 2 / (M_PER_DEG_LON * Math.cos(survey.lat * Math.PI / 180));
4334
+ const west = column(survey.lon - halfLon, z);
4335
+ const east = column(survey.lon + halfLon, z);
4336
+ const north = row(survey.lat + halfLat, z);
4337
+ const south = row(survey.lat - halfLat, z);
4338
+ const x0 = Math.floor(west);
4339
+ const x1 = Math.floor(east);
4340
+ const y0 = Math.floor(north);
4341
+ const y1 = Math.floor(south);
4342
+ const columns = x1 - x0 + 1;
4343
+ const rows = y1 - y0 + 1;
4344
+ const width = columns * TILE_PX;
4345
+ const height = rows * TILE_PX;
4346
+ const stitched = new Float32Array(width * height);
4347
+ const tiles = [];
4348
+ for (let y = y0; y <= y1; y += 1) {
4349
+ for (let x = x0; x <= x1; x += 1) {
4350
+ tiles.push(
4351
+ loadTile(z, x, y).then((tile) => {
4352
+ for (let ty = 0; ty < TILE_PX; ty += 1) {
4353
+ for (let tx = 0; tx < TILE_PX; tx += 1) {
4354
+ stitched[((y - y0) * TILE_PX + ty) * width + (x - x0) * TILE_PX + tx] = tile.heights[ty * TILE_PX + tx];
4355
+ }
4356
+ }
4357
+ })
4358
+ );
4359
+ }
4360
+ }
4361
+ await Promise.all(tiles);
4362
+ const left = (west - x0) * TILE_PX;
4363
+ const top = (north - y0) * TILE_PX;
4364
+ const spanX = (east - west) * TILE_PX;
4365
+ const spanY = (south - north) * TILE_PX;
4366
+ const values = new Float32Array(resolution * resolution);
4367
+ let min = Number.POSITIVE_INFINITY;
4368
+ let max = Number.NEGATIVE_INFINITY;
4369
+ for (let y = 0; y < resolution; y += 1) {
4370
+ for (let x = 0; x < resolution; x += 1) {
4371
+ const value = bilinear(
4372
+ stitched,
4373
+ width,
4374
+ height,
4375
+ left + x / (resolution - 1) * spanX,
4376
+ top + y / (resolution - 1) * spanY
4377
+ );
4378
+ values[y * resolution + x] = value;
4379
+ min = Math.min(min, value);
4380
+ max = Math.max(max, value);
4381
+ }
4382
+ }
4383
+ return { width: resolution, height: resolution, values, min, max };
4384
+ }
3357
4385
 
3358
4386
  // src/core/kits.ts
3359
4387
  var TERRAIN_KITS = ["forest", "coastal", "alpine", "desert", "tundra"];
@@ -3361,7 +4389,7 @@ function isRecord(value) {
3361
4389
  return typeof value === "object" && value !== null && !Array.isArray(value);
3362
4390
  }
3363
4391
  async function resolveAssetSource(projectRoot) {
3364
- const configFile = join(projectRoot, "threenative.config.ts");
4392
+ const configFile = join$1(projectRoot, "threenative.config.ts");
3365
4393
  const exists = await lstat(configFile).then(
3366
4394
  () => true,
3367
4395
  (error) => {
@@ -3416,7 +4444,7 @@ function parseBounds(value, species2) {
3416
4444
  function installedEntry(projectRoot, name) {
3417
4445
  let directory = resolve(projectRoot);
3418
4446
  while (true) {
3419
- const manifestFile = join(directory, "node_modules", name, "package.json");
4447
+ const manifestFile = join$1(directory, "node_modules", name, "package.json");
3420
4448
  if (existsSync(manifestFile)) {
3421
4449
  const manifest = JSON.parse(readFileSync(manifestFile, "utf8"));
3422
4450
  const root = manifest.exports?.["."];
@@ -3450,8 +4478,8 @@ async function cookKit(request2) {
3450
4478
  );
3451
4479
  }
3452
4480
  const cooker = await loadCooker(request2.projectRoot);
3453
- const packageRoot = join(dirname(fileURLToPath(import.meta.url)), "..", "..");
3454
- const kitDir = join(packageRoot, "starter", request2.kit);
4481
+ const packageRoot = join$1(dirname(fileURLToPath(import.meta.url)), "..", "..");
4482
+ const kitDir = join$1(packageRoot, "starter", request2.kit);
3455
4483
  const assetsDir = await starterAssetsDir();
3456
4484
  await mkdir(dirname(request2.out), { recursive: true });
3457
4485
  try {
@@ -3470,38 +4498,301 @@ async function cookKit(request2) {
3470
4498
  }
3471
4499
  }
3472
4500
  function applyWaterRows(layers, rows) {
4501
+ const unrouted = [];
3473
4502
  const queue = (kind) => layers.filter(
3474
4503
  (layer2) => kind === "river" ? layer2.type === "river" : layer2.type === "water" && layer2.params.kind !== "ocean"
3475
4504
  );
3476
4505
  const rivers = queue("river");
3477
4506
  const lakes = queue("lake");
3478
4507
  const keep = /* @__PURE__ */ new Set();
3479
- for (const row of rows) {
3480
- if (row.kind === "ocean") {
4508
+ for (const row2 of rows) {
4509
+ if (row2.kind === "ocean") {
3481
4510
  layers.push({
3482
4511
  id: `ocean-${keep.size}`,
3483
4512
  type: "water",
3484
- params: { kind: "ocean", level: row.level }
4513
+ params: { kind: "ocean", level: row2.level }
3485
4514
  });
3486
4515
  keep.add(layers[layers.length - 1]);
3487
4516
  continue;
3488
4517
  }
3489
- const layer2 = (row.kind === "river" ? rivers : lakes).shift();
4518
+ const layer2 = (row2.kind === "river" ? rivers : lakes).shift();
3490
4519
  if (layer2 === void 0) {
3491
- throw new Error(
3492
- `cook: water row '${row.kind}' has no ${row.kind} layer in the recipe to take it.`
3493
- );
4520
+ unrouted.push(row2);
4521
+ continue;
3494
4522
  }
3495
- if (row.kind === "river") {
3496
- layer2.params.waterWidth = row.width / (layer2.params.width ?? 12);
3497
- if (row.depth !== void 0) layer2.params.depth = row.depth;
3498
- } else layer2.params.radius = row.radius;
4523
+ if (row2.kind === "river") {
4524
+ layer2.params.waterWidth = row2.width / (layer2.params.width ?? 12);
4525
+ if (row2.depth !== void 0) layer2.params.depth = row2.depth;
4526
+ } else layer2.params.radius = row2.radius;
3499
4527
  keep.add(layer2);
3500
4528
  }
3501
4529
  const dropped = layers.filter(
3502
4530
  (layer2) => (layer2.type === "river" || layer2.type === "water") && !keep.has(layer2)
3503
4531
  );
3504
4532
  for (const layer2 of dropped) layers.splice(layers.indexOf(layer2), 1);
4533
+ return unrouted;
4534
+ }
4535
+ function seaLevel(recipe) {
4536
+ return Math.max(
4537
+ Number.NEGATIVE_INFINITY,
4538
+ ...recipe.layers.flatMap(
4539
+ (layer2) => layer2.type === "water" && layer2.params.kind === "ocean" ? [layer2.params.level ?? 0] : []
4540
+ )
4541
+ );
4542
+ }
4543
+ function carveFeatures(recipe, features) {
4544
+ if (features.length === 0) return;
4545
+ const { height, size } = Terrain.fromJSON(recipe).evaluate();
4546
+ let low = Number.POSITIVE_INFINITY;
4547
+ let high = Number.NEGATIVE_INFINITY;
4548
+ for (const value of height) {
4549
+ low = Math.min(low, value);
4550
+ high = Math.max(high, value);
4551
+ }
4552
+ const sea = seaLevel(recipe);
4553
+ const seed = recipe.config.seed ?? 0;
4554
+ const canyonDepth = Math.min(90, Math.max(30, 0.35 * (high - low)));
4555
+ const cuts = features.map((feature, index) => {
4556
+ const turn = (seed * 47 + index * 70) % 180;
4557
+ const radians = turn * Math.PI / 180;
4558
+ const reach = feature === "canyon" ? 0 : size * 0.45;
4559
+ return {
4560
+ enabled: true,
4561
+ opacity: 1,
4562
+ id: `${feature}-${String(index)}`,
4563
+ type: "stamp",
4564
+ params: {
4565
+ shape: "mesa",
4566
+ at: [-Math.sin(radians) * reach, Math.cos(radians) * reach],
4567
+ // A wall spans half the half-width: at 0.9 m per metre of depth it stands about 66 degrees,
4568
+ // the steepest a 2 m heightfield draws without a ladder of stretched cells.
4569
+ radius: feature === "canyon" ? [Math.max(size * 0.1, canyonDepth * 0.9), size * 1.2] : [size * 0.05, size * 0.5],
4570
+ rotation: turn,
4571
+ amplitude: feature === "canyon" ? -canyonDepth : -(high - (sea === Number.NEGATIVE_INFINITY ? low : sea) + 12),
4572
+ roughness: 0.15,
4573
+ blend: "add"
4574
+ }
4575
+ };
4576
+ });
4577
+ const erosion = recipe.layers.findIndex((layer2) => layer2.type === "erode");
4578
+ recipe.layers.splice(erosion < 0 ? recipe.layers.length : erosion, 0, ...cuts);
4579
+ }
4580
+ function shapeCoast(recipe) {
4581
+ const sea = seaLevel(recipe);
4582
+ if (sea === Number.NEGATIVE_INFINITY) return;
4583
+ const state = Terrain.fromJSON(recipe).evaluate();
4584
+ const n = state.resolution;
4585
+ let border = Number.NEGATIVE_INFINITY;
4586
+ for (let k = 0; k < n; k += 1)
4587
+ for (const i of [k, (n - 1) * n + k, k * n, k * n + n - 1])
4588
+ border = Math.max(border, state.height[i]);
4589
+ if (border < sea) return;
4590
+ recipe.layers.push({
4591
+ enabled: true,
4592
+ opacity: 1,
4593
+ id: "coast",
4594
+ type: "noise",
4595
+ params: { amplitude: 0, scale: 1, island: true, coastDepth: (border - sea + 3) / 0.676 }
4596
+ });
4597
+ }
4598
+ function placeLakes(recipe, rows) {
4599
+ const sea = seaLevel(recipe);
4600
+ const placed = [];
4601
+ rows.forEach((row2, index) => {
4602
+ let radius = row2.radius;
4603
+ const site = () => {
4604
+ const state = Terrain.fromJSON(recipe).evaluate();
4605
+ const { resolution: n, size } = state;
4606
+ const filled = Float64Array.from(state.height);
4607
+ fillDepressions(filled, n);
4608
+ const world2 = (i) => [
4609
+ (i % n / (n - 1) - 0.5) * size,
4610
+ (Math.floor(i / n) / (n - 1) - 0.5) * size
4611
+ ];
4612
+ const shore = new Float64Array(n * n).fill(Number.POSITIVE_INFINITY);
4613
+ const queue = [];
4614
+ for (let i = 0; i < n * n; i += 1)
4615
+ if (state.height[i] <= sea + 1) {
4616
+ shore[i] = 0;
4617
+ queue.push(i);
4618
+ }
4619
+ for (let head = 0; head < queue.length; head += 1) {
4620
+ const i = queue[head];
4621
+ const x = i % n;
4622
+ const z = Math.floor(i / n);
4623
+ for (let dz = -1; dz <= 1; dz += 1)
4624
+ for (let dx = -1; dx <= 1; dx += 1) {
4625
+ if (x + dx < 0 || x + dx >= n || z + dz < 0 || z + dz >= n) continue;
4626
+ const j = i + dz * n + dx;
4627
+ if (shore[j] > shore[i] + 1) {
4628
+ shore[j] = shore[i] + 1;
4629
+ queue.push(j);
4630
+ }
4631
+ }
4632
+ }
4633
+ const cell = size / (n - 1);
4634
+ let best = -1;
4635
+ let low = -1;
4636
+ let inland = -1;
4637
+ for (let i = 0; i < n * n; i += 1) {
4638
+ const [x, z] = world2(i);
4639
+ if (shore[i] > 0 && (inland < 0 || shore[i] > shore[inland]))
4640
+ inland = i;
4641
+ if (Math.max(Math.abs(x), Math.abs(z)) > size / 2 - radius) continue;
4642
+ if (shore[i] * cell <= radius) continue;
4643
+ if (!placed.every(([px, pz, r]) => Math.hypot(x - px, z - pz) > r + radius)) continue;
4644
+ const depth2 = filled[i] - state.height[i];
4645
+ if (best < 0 || depth2 > filled[best] - state.height[best]) best = i;
4646
+ if (low < 0 || state.height[i] < state.height[low]) low = i;
4647
+ }
4648
+ if (low < 0) low = best = inland;
4649
+ if (low < 0)
4650
+ throw new Error("cook: water row 'lake' found no ground above the sea to sit on.");
4651
+ let flooded = 0;
4652
+ if (filled[best] - state.height[best] >= 1) {
4653
+ const level = filled[best];
4654
+ const [bx, bz] = world2(best);
4655
+ const seen = new Uint8Array(n * n);
4656
+ const stack = [best];
4657
+ seen[best] = 1;
4658
+ while (stack.length > 0) {
4659
+ const i = stack.pop();
4660
+ flooded += 1;
4661
+ for (const j of [i - 1, i + 1, i - n, i + n]) {
4662
+ if (j < 0 || j >= n * n || seen[j] || Math.abs(j % n - i % n) > 1) continue;
4663
+ const [x, z] = world2(j);
4664
+ if (state.height[j] >= level || Math.hypot(x - bx, z - bz) > radius)
4665
+ continue;
4666
+ seen[j] = 1;
4667
+ stack.push(j);
4668
+ }
4669
+ }
4670
+ }
4671
+ const holds = flooded * cell * cell >= 0.25 * Math.PI * radius * radius;
4672
+ const depth = holds ? filled[best] - state.height[best] : 0;
4673
+ const at = holds ? best : low;
4674
+ const ground = state.height[at];
4675
+ return {
4676
+ depth,
4677
+ ground,
4678
+ level: holds ? filled[at] : ground + 2,
4679
+ // Metres from this cell to the nearest sea: the room a dug basin has on this ground.
4680
+ room: shore[at] * cell,
4681
+ world: world2(at)
4682
+ };
4683
+ };
4684
+ let found = site();
4685
+ if (found.depth < 1) {
4686
+ radius = Math.min(radius, found.room * 0.55);
4687
+ recipe.layers.push({
4688
+ enabled: true,
4689
+ opacity: 1,
4690
+ id: `lake-${String(index)}-shelf`,
4691
+ type: "flatten",
4692
+ params: {
4693
+ at: found.world,
4694
+ radius: radius / 0.55,
4695
+ height: found.ground,
4696
+ strength: 1,
4697
+ falloff: 0.35
4698
+ }
4699
+ });
4700
+ recipe.layers.push({
4701
+ enabled: true,
4702
+ opacity: 1,
4703
+ id: `lake-${String(index)}-basin`,
4704
+ type: "stamp",
4705
+ params: {
4706
+ shape: "crater",
4707
+ at: found.world,
4708
+ radius: radius / 0.55,
4709
+ amplitude: 10,
4710
+ roughness: 0,
4711
+ blend: "add"
4712
+ }
4713
+ });
4714
+ found = site();
4715
+ }
4716
+ placed.push([found.world[0], found.world[1], radius]);
4717
+ recipe.layers.push({
4718
+ enabled: true,
4719
+ opacity: 1,
4720
+ id: `lake-${String(index)}`,
4721
+ type: "water",
4722
+ params: { kind: "lake", at: found.world, radius, level: found.level }
4723
+ });
4724
+ });
4725
+ }
4726
+ function routeRivers(recipe, rows) {
4727
+ const state = Terrain.fromJSON(recipe).evaluate();
4728
+ const { resolution: n, size } = state;
4729
+ const filled = Float64Array.from(state.height);
4730
+ fillDepressions(filled, n);
4731
+ const flow = createFlow(n);
4732
+ routeFlow(filled, n, flow);
4733
+ const roots = [];
4734
+ for (let i = 0; i < n * n; i += 1) if (flow.receiver[i] < 0) roots.push(i);
4735
+ roots.sort((a, b) => flow.cells[b] - flow.cells[a]);
4736
+ const world2 = (i) => [
4737
+ (i % n / (n - 1) - 0.5) * size,
4738
+ (Math.floor(i / n) / (n - 1) - 0.5) * size
4739
+ ];
4740
+ const outlets = [];
4741
+ for (const root of roots) {
4742
+ if (outlets.length === rows.length) break;
4743
+ const [x, z] = world2(root);
4744
+ const apart = outlets.every((o) => {
4745
+ const [ox, oz] = world2(o);
4746
+ return Math.hypot(x - ox, z - oz) >= size / 8;
4747
+ });
4748
+ if (apart) outlets.push(root);
4749
+ }
4750
+ const step = Math.max(1, Math.round(16 / size * (n - 1)));
4751
+ rows.forEach((row2, index) => {
4752
+ const outlet = outlets[index];
4753
+ if (outlet === void 0)
4754
+ throw new Error(`cook: water row 'river' found no drainage basin to run down.`);
4755
+ const stem = [outlet];
4756
+ const source = flow.cells[outlet] * 0.1;
4757
+ for (let cell = outlet; ; ) {
4758
+ let next = -1;
4759
+ const x = cell % n;
4760
+ const z = Math.floor(cell / n);
4761
+ for (let dz = -1; dz <= 1; dz += 1)
4762
+ for (let dx = -1; dx <= 1; dx += 1) {
4763
+ if (dx === 0 && dz === 0) continue;
4764
+ if (x + dx < 0 || x + dx >= n || z + dz < 0 || z + dz >= n) continue;
4765
+ const j = cell + dz * n + dx;
4766
+ if (flow.receiver[j] !== cell) continue;
4767
+ if (next < 0 || flow.cells[j] > flow.cells[next]) next = j;
4768
+ }
4769
+ if (next < 0 || flow.cells[next] < source) break;
4770
+ stem.push(next);
4771
+ cell = next;
4772
+ }
4773
+ if (stem.length < 2 * step)
4774
+ throw new Error(`cook: water row 'river' found no stem longer than 32 m to run down.`);
4775
+ const cells = stem.reverse().filter((_, k) => k % step === 0 || k === stem.length - 1);
4776
+ const points = cells.map((cell) => {
4777
+ const [x, z] = world2(cell);
4778
+ return [x, null, z];
4779
+ });
4780
+ const bed = row2.width / 0.76;
4781
+ recipe.layers.push({
4782
+ enabled: true,
4783
+ opacity: 1,
4784
+ id: `river-${index}`,
4785
+ type: "river",
4786
+ params: {
4787
+ followTerrain: true,
4788
+ points,
4789
+ width: bed,
4790
+ waterWidth: 0.76,
4791
+ depth: row2.depth ?? 1.8,
4792
+ shoulder: 10
4793
+ }
4794
+ });
4795
+ });
3505
4796
  }
3506
4797
  function floodedBodies(state) {
3507
4798
  return [
@@ -3511,41 +4802,372 @@ function floodedBodies(state) {
3511
4802
  ...state.rivers.map((river) => ({ kind: "river", width: round(river.width) }))
3512
4803
  ];
3513
4804
  }
4805
+ var PLAY_AREA_CLEAR_RADIUS = 23;
4806
+ var PLAY_AREA_CLEAR = {
4807
+ mask: { type: "circle", at: [0, 0], radius: PLAY_AREA_CLEAR_RADIUS / 0.98, falloff: 0.02 },
4808
+ opacity: 1
4809
+ };
3514
4810
  function scatterFoliage(state, biome, kind, assetTable) {
3515
- const foliage2 = kind === void 0 ? [] : biome.foliage.filter((row) => row.density > 0 && row.species in assetTable);
4811
+ if (kind === void 0) return state;
4812
+ const tree = Object.keys(assetTable).find((id) => assetTable[id]?.tree === true);
4813
+ const foliage2 = biome.foliage.flatMap((row2, at) => {
4814
+ if (row2.density === 0) return [];
4815
+ if (row2.species in assetTable) return [row2];
4816
+ return at === 0 && tree !== void 0 ? [{ ...row2, species: tree }] : [];
4817
+ });
3516
4818
  if (foliage2.length === 0) return state;
3517
4819
  return finalizeState({
3518
4820
  ...state,
3519
- scatterRules: [...state.scatterRules, ...foliageScatterRules(foliage2, state.height)]
4821
+ scatterRules: [
4822
+ ...state.scatterRules,
4823
+ ...foliageScatterRules(foliage2, state.height).map((rule) => ({
4824
+ ...rule,
4825
+ clear: [...rule.clear, PLAY_AREA_CLEAR]
4826
+ }))
4827
+ ]
4828
+ });
4829
+ }
4830
+ async function readGroundHeightmap(projectRoot, asked) {
4831
+ const file = isAbsolute(asked.heightmap) ? asked.heightmap : resolve(projectRoot, asked.heightmap);
4832
+ const bytes = await readFile(file).catch(() => {
4833
+ throw new Error(`terrain_generate: ground.heightmap '${asked.heightmap}' cannot be read.`);
4834
+ });
4835
+ const range2 = asked.min === void 0 || asked.max === void 0 ? void 0 : { min: asked.min, max: asked.max };
4836
+ try {
4837
+ if (file.toLowerCase().endsWith(".r16")) {
4838
+ const side = Math.sqrt(bytes.length / 2);
4839
+ if (!Number.isInteger(side)) {
4840
+ throw new TypeError("a .r16 grid has no width of its own, so it must be square");
4841
+ }
4842
+ if (range2 === void 0) {
4843
+ throw new TypeError("a .r16 grid carries no elevation range; name min and max in metres");
4844
+ }
4845
+ return decodeRAW16(bytes, { width: side, height: side, ...range2 });
4846
+ }
4847
+ const decoded = await decodeHeightPNG(bytes, range2 ?? {});
4848
+ if (decoded.bitDepth !== 16) {
4849
+ throw new TypeError(`it is ${decoded.bitDepth}-bit; export a 16-bit grayscale PNG`);
4850
+ }
4851
+ if (!decoded.hasEmbeddedRange && range2 === void 0) {
4852
+ throw new TypeError("it carries no elevation range; name min and max in metres");
4853
+ }
4854
+ return decoded;
4855
+ } catch (error) {
4856
+ throw new TypeError(
4857
+ `terrain_generate: ground.heightmap '${asked.heightmap}': ${error instanceof Error ? error.message : String(error)}`
4858
+ );
4859
+ }
4860
+ }
4861
+ function applyGroundLayer(layers, grid, scale, offset) {
4862
+ const at = layers.findIndex((layer2) => layer2.type === "heightmap" || layer2.type === "noise");
4863
+ const replaced = layers[at];
4864
+ if (replaced === void 0)
4865
+ throw new Error("cook: the recipe authors no ground layer to replace.");
4866
+ const preset = replaced.type === "noise";
4867
+ layers[at] = {
4868
+ id: "ground",
4869
+ type: "heightmap",
4870
+ enabled: replaced.enabled ?? true,
4871
+ opacity: replaced.opacity ?? 1,
4872
+ params: {
4873
+ // The recipe inlines its heights, so they are plain numbers on a 0.1 m lattice like the
4874
+ // starters' own crops: the same precision, and the same size of recipe.json.
4875
+ data: {
4876
+ width: grid.width,
4877
+ height: grid.height,
4878
+ values: Array.from(grid.values, (value) => Math.round(value * 10) / 10)
4879
+ },
4880
+ scale,
4881
+ offset
4882
+ }
4883
+ };
4884
+ if (!preset) return;
4885
+ for (let index = layers.length - 1; index >= 0; index -= 1) {
4886
+ const layer2 = layers[index];
4887
+ const shape = layer2.type === "stamp" ? layer2.params.shape : void 0;
4888
+ if (shape === "mountain" || shape === "crater") layers.splice(index, 1);
4889
+ }
4890
+ }
4891
+ function seededCrop(row2, seed) {
4892
+ if (seed === void 0) return row2;
4893
+ const next = random(hashString(`survey:${seed}`));
4894
+ const east = (next() * 2 - 1) * 0.6 * row2.extentMeters;
4895
+ const north = (next() * 2 - 1) * 0.6 * row2.extentMeters;
4896
+ return {
4897
+ ...row2,
4898
+ lat: row2.lat + north / 111320,
4899
+ lon: row2.lon + east / (111320 * Math.cos(row2.lat * Math.PI / 180))
4900
+ };
4901
+ }
4902
+ async function forestFloor(document, row2, seed) {
4903
+ const { resolution, size } = document.config;
4904
+ const next = random(hashString(`floor:${seed ?? 0}`));
4905
+ const spots = Array.from({ length: seed === void 0 ? 0 : 12 }, () => {
4906
+ const east = (next() * 2 - 1) * 0.4 * row2.extentMeters;
4907
+ const north = (next() * 2 - 1) * 0.4 * row2.extentMeters;
4908
+ return [north, east];
4909
+ });
4910
+ const patch = (north, east) => ({
4911
+ ...row2,
4912
+ lat: row2.lat + north / 111320,
4913
+ lon: row2.lon + east / (111320 * Math.cos(row2.lat * Math.PI / 180)),
4914
+ extentMeters: size,
4915
+ zoom: 15
4916
+ });
4917
+ let picked;
4918
+ for (const [north, east] of [...spots, [0, 0]]) {
4919
+ const survey2 = patch(north, east);
4920
+ const grid2 = await surveyHeights(survey2, resolution);
4921
+ const stats = terrainStats(grid2.values, resolution, size);
4922
+ picked = { survey: survey2, grid: grid2 };
4923
+ if (isForestFloor(grid2.max - grid2.min, stats.slopeP90, size, flatShare(grid2.values, resolution)))
4924
+ break;
4925
+ }
4926
+ const { survey, grid } = picked;
4927
+ applyGroundLayer(document.layers, grid, 1, -grid.min);
4928
+ const at = document.layers.findIndex((layer2) => layer2.type === "erode");
4929
+ document.layers = document.layers.filter((layer2) => layer2.type !== "erode");
4930
+ document.layers.splice(at < 0 ? 1 : at, 0, ...structuredClone(SURVEYED_EROSION));
4931
+ return {
4932
+ survey: { row: survey, scale: 1, offset: -grid.min },
4933
+ ground: {
4934
+ source: "survey",
4935
+ name: survey.name,
4936
+ lat: survey.lat,
4937
+ lon: survey.lon,
4938
+ attribution: survey.attribution
4939
+ },
4940
+ readme: groundReadme(survey)
4941
+ };
4942
+ }
4943
+ var groundReadme = (survey) => [
4944
+ "# Cooked terrain world",
4945
+ "",
4946
+ `The ground is a real survey: ${survey.name} at ${survey.lat}, ${survey.lon},`,
4947
+ `${survey.extentMeters} m across at zoom ${survey.zoom}, resampled onto the recipe's grid.`,
4948
+ "",
4949
+ "## Data attribution",
4950
+ "",
4951
+ survey.attribution,
4952
+ ""
4953
+ ].join("\n");
4954
+ var SURVEYED_EROSION = [
4955
+ {
4956
+ type: "erode",
4957
+ id: "surface-runoff",
4958
+ params: {
4959
+ method: "hydraulic",
4960
+ droplets: 2e4,
4961
+ maxSteps: 45,
4962
+ capacity: 2,
4963
+ erosion: 0.015,
4964
+ strength: 2e-3,
4965
+ deposition: 0.2,
4966
+ evaporation: 0.035
4967
+ }
4968
+ },
4969
+ {
4970
+ type: "erode",
4971
+ id: "loose-talus",
4972
+ params: { method: "thermal", talus: 38, iterations: 1, rate: 4e-3 }
4973
+ }
4974
+ ];
4975
+ var FLOOR_RELIEF = 90;
4976
+ var FLOOR_SLOPE = 28;
4977
+ var FLOOR_FLAT = 0.02;
4978
+ function flatShare(values, resolution) {
4979
+ let flat = 0;
4980
+ for (let r = 1; r < resolution - 1; r++)
4981
+ for (let c = 1; c < resolution - 1; c++) {
4982
+ const h = values[r * resolution + c];
4983
+ const near = [
4984
+ values[r * resolution + c - 1],
4985
+ values[r * resolution + c + 1],
4986
+ values[(r - 1) * resolution + c],
4987
+ values[(r + 1) * resolution + c]
4988
+ ];
4989
+ if (near.every((n) => Math.abs(n - h) < 0.02)) flat++;
4990
+ }
4991
+ return flat / (resolution - 2) ** 2;
4992
+ }
4993
+ function isForestFloor(relief, slopeP90, size, flat = 0) {
4994
+ return relief <= FLOOR_RELIEF * Math.max(1, size / 512) && slopeP90 <= FLOOR_SLOPE && flat <= FLOOR_FLAT;
4995
+ }
4996
+ async function applyGround(document, request2, kind) {
4997
+ const asked = request2.ground;
4998
+ if (asked === "procedural") return { ground: { source: "procedural" } };
4999
+ if (asked !== void 0 && "heightmap" in asked) {
5000
+ applyGroundLayer(document.layers, await readGroundHeightmap(request2.projectRoot, asked), 1, 0);
5001
+ return { ground: { source: "heightmap", heightmap: asked.heightmap } };
5002
+ }
5003
+ const survey = asked !== void 0 ? locationSurvey(asked.location.lat, asked.location.lon) : kind === void 0 ? void 0 : seededCrop(SURVEYS[kind], request2.seed);
5004
+ if (survey === void 0) return { ground: { source: "procedural" } };
5005
+ if (request2.backdropRange !== void 0 && asked === void 0)
5006
+ return forestFloor(document, kind === void 0 ? survey : SURVEYS[kind], request2.seed);
5007
+ const grid = await surveyHeights(survey, document.config.resolution);
5008
+ const relief = kind === void 0 ? void 0 : LANDFORMS[kind].reliefRatio * document.config.size;
5009
+ const scale = relief === void 0 ? 1 : relief / (grid.max - grid.min || 1);
5010
+ applyGroundLayer(document.layers, grid, scale, -grid.min * scale);
5011
+ return {
5012
+ survey: { row: survey, scale, offset: -grid.min * scale },
5013
+ ground: {
5014
+ source: "survey",
5015
+ name: survey.name,
5016
+ lat: survey.lat,
5017
+ lon: survey.lon,
5018
+ attribution: survey.attribution
5019
+ },
5020
+ // The attribution rides with the kit: the data source requires it wherever the world is shipped.
5021
+ readme: groundReadme(survey)
5022
+ };
5023
+ }
5024
+ var RING_SCALE = 10;
5025
+ function massifBearing(cameraOffset) {
5026
+ const look = Math.atan2(-cameraOffset[2], -cameraOffset[0]) * 180 / Math.PI;
5027
+ return [look - MASSIF_SPREAD, look + MASSIF_SPREAD];
5028
+ }
5029
+ var MASSIF_SPREAD = 25;
5030
+ var MASSIF_ATTEMPTS = 6;
5031
+ var WOODED_FOOT = 0.6;
5032
+ function woodedFoot(detail, height) {
5033
+ const at = (r, c) => detail.heights[r * detail.columns + c];
5034
+ let floor = Number.POSITIVE_INFINITY;
5035
+ for (let i = 0; i < detail.heights.length; i++)
5036
+ floor = Math.min(floor, detail.heights[i]);
5037
+ const steep = Math.tan(40 * Math.PI / 180);
5038
+ let lower = 0;
5039
+ let gentle = 0;
5040
+ for (let r = 1; r < detail.rows - 1; r++)
5041
+ for (let c = 1; c < detail.columns - 1; c++) {
5042
+ const h = at(r, c);
5043
+ if (h < floor + 50 || h > floor + height / 2) continue;
5044
+ const dx = (at(r, c + 1) - at(r, c - 1)) / (2 * detail.spacing);
5045
+ const dz = (at(r + 1, c) - at(r - 1, c)) / (2 * detail.spacing);
5046
+ lower++;
5047
+ if (Math.hypot(dx, dz) < steep) gentle++;
5048
+ }
5049
+ return lower === 0 ? 0 : gentle / lower;
5050
+ }
5051
+ async function farRing(request2, kind, ground, config, cameraOffset) {
5052
+ const range2 = request2.backdropRange ?? kind;
5053
+ const rows = range2 === void 0 ? void 0 : MASSIFS[range2];
5054
+ if (request2.backdrop === "none" || rows === void 0 || ground.survey === void 0)
5055
+ return { decision: { source: "none" } };
5056
+ const { row: row2, scale, offset } = ground.survey;
5057
+ const resolution = 257;
5058
+ const MASSIF_RESOLUTION = 257;
5059
+ const fetchMassif = async (massif2) => {
5060
+ const grid = await surveyHeights({ ...massif2, zoom: massif2.zoom + 1 }, MASSIF_RESOLUTION).catch(
5061
+ (error) => {
5062
+ throw new Error(
5063
+ `cook: far-ring massif '${massif2.name}': ${error instanceof Error ? error.message : String(error)} Pass backdrop: "none" to cook without the far ring.`
5064
+ );
5065
+ }
5066
+ );
5067
+ return {
5068
+ id: massif2.name,
5069
+ size: massif2.extentMeters,
5070
+ resolution: MASSIF_RESOLUTION,
5071
+ heights: grid.values
5072
+ };
5073
+ };
5074
+ const [ringGrid, ...tiles] = await Promise.all([
5075
+ surveyHeights(
5076
+ { ...row2, extentMeters: row2.extentMeters * RING_SCALE, zoom: Math.max(1, row2.zoom - 2) },
5077
+ resolution
5078
+ ),
5079
+ ...rows.map(fetchMassif)
5080
+ ]);
5081
+ const size = config.size * RING_SCALE;
5082
+ const host = new Terrain({ size, resolution, seed: config.seed }).heightmap({
5083
+ id: "ring",
5084
+ data: {
5085
+ width: resolution,
5086
+ height: resolution,
5087
+ values: Array.from(ringGrid.values, (value) => value * scale + offset)
5088
+ }
3520
5089
  });
5090
+ let chosen;
5091
+ let best = -1;
5092
+ for (let attempt = 0; attempt < MASSIF_ATTEMPTS && best < WOODED_FOOT; attempt++) {
5093
+ const placed = placeMassif(host, {
5094
+ seed: (request2.seed ?? config.seed) + attempt * 7919,
5095
+ tile: tiles,
5096
+ keepOut: config.size * 1.25,
5097
+ bearing: massifBearing(cameraOffset)
5098
+ });
5099
+ const foot = woodedFoot(placed.placement.detail, placed.placement.height);
5100
+ if (foot > best) {
5101
+ best = foot;
5102
+ chosen = placed;
5103
+ }
5104
+ }
5105
+ const { terrain, placement } = chosen;
5106
+ const picked = rows[tiles.findIndex((tile) => tile.id === placement.tile)];
5107
+ const decision = {
5108
+ source: "massif",
5109
+ name: picked.name,
5110
+ lat: picked.lat,
5111
+ lon: picked.lon,
5112
+ attribution: picked.attribution,
5113
+ at: [round(placement.at[0]), round(placement.at[1])],
5114
+ rotation: round(placement.rotation),
5115
+ mirror: placement.mirror,
5116
+ height: round(placement.height)
5117
+ };
5118
+ const heights = Array.from(terrain.evaluate().height, round);
5119
+ const { detail } = placement;
5120
+ const massif = {
5121
+ ...decision,
5122
+ detail: { ...detail, heights: Array.from(detail.heights, (h) => Math.round(h * 10) / 10) }
5123
+ };
5124
+ return {
5125
+ decision,
5126
+ file: `${JSON.stringify({ size, resolution, heights, massif })}
5127
+ `
5128
+ };
3521
5129
  }
3522
5130
  async function cookInto(request2, cooker, kitDir, assetsDir) {
3523
5131
  const started = performance.now();
3524
- const file = request2.spec ?? JSON.parse(await readFile(join(kitDir, "biome.data.json"), "utf8"));
5132
+ const file = request2.spec ?? JSON.parse(await readFile(join$1(kitDir, "biome.data.json"), "utf8"));
3525
5133
  const declared = request2.water === void 0 ? file : { ...file, water: request2.water };
3526
5134
  const biome = validateBiome(declared, request2.biome ?? request2.kit);
3527
5135
  const kind = request2.landform ?? (request2.spec === void 0 ? void 0 : biome.landform);
3528
- const recipe = kind === void 0 ? JSON.parse(await readFile(join(kitDir, "recipe.json"), "utf8")) : {
5136
+ const recipe = kind === void 0 ? JSON.parse(await readFile(join$1(kitDir, "recipe.json"), "utf8")) : {
3529
5137
  recipe: landform(kind, {
3530
5138
  resolution: 257,
3531
5139
  seed: request2.seed ?? biome.seed,
3532
5140
  size: request2.sizeMeters ?? biome.sizeMeters
3533
5141
  }).toJSON()
3534
5142
  };
3535
- if (request2.water !== void 0) applyWaterRows(recipe.recipe.layers, request2.water);
5143
+ const unrouted = request2.water === void 0 ? [] : applyWaterRows(recipe.recipe.layers, request2.water);
3536
5144
  if (request2.sizeMeters !== void 0) recipe.recipe.config.size = request2.sizeMeters;
3537
5145
  if (request2.seed !== void 0) recipe.recipe.config.seed = request2.seed;
5146
+ const ground = await applyGround(recipe.recipe, request2, kind);
5147
+ const farRingResult = await farRing(
5148
+ request2,
5149
+ kind,
5150
+ ground,
5151
+ recipe.recipe.config,
5152
+ biome.spawn.cameraOffset
5153
+ );
3538
5154
  for (const layer2 of recipe.recipe.layers) {
3539
5155
  const data = layer2.params?.data;
3540
5156
  if (data?.raw16 === void 0) continue;
3541
- const raw = await readFile(join(kitDir, data.raw16));
5157
+ const raw = await readFile(join$1(kitDir, data.raw16));
3542
5158
  data.values = Array.from(
3543
5159
  decodeRAW16(raw, data).values,
3544
5160
  (value) => Math.round(value * 10) / 10
3545
5161
  );
3546
5162
  }
3547
- const assetTable = JSON.parse(await readFile(join(kitDir, "assets.json"), "utf8"));
3548
- const surface = JSON.parse(await readFile(join(kitDir, "surface.json"), "utf8"));
5163
+ const assetTable = JSON.parse(await readFile(join$1(kitDir, "assets.json"), "utf8"));
5164
+ const surface = JSON.parse(await readFile(join$1(kitDir, "surface.json"), "utf8"));
5165
+ carveFeatures(recipe.recipe, request2.features ?? []);
5166
+ shapeCoast(recipe.recipe);
5167
+ const lakes = unrouted.filter((row2) => row2.kind === "lake");
5168
+ if (lakes.length > 0) placeLakes(recipe.recipe, lakes);
5169
+ const rivers = unrouted.filter((row2) => row2.kind === "river");
5170
+ if (rivers.length > 0) routeRivers(recipe.recipe, rivers);
3549
5171
  const evaluated = Terrain.fromJSON(recipe.recipe).evaluate();
3550
5172
  const state = applyPlacementOverrides(
3551
5173
  scatterFoliage(evaluated, biome, kind, assetTable),
@@ -3555,9 +5177,9 @@ async function cookInto(request2, cooker, kitDir, assetsDir) {
3555
5177
  Object.entries(assetTable).map(([id, spec]) => [
3556
5178
  id,
3557
5179
  {
3558
- glb: join(assetsDir, spec.near),
5180
+ glb: join$1(assetsDir, spec.near),
3559
5181
  bounds: parseBounds(spec.bounds, id),
3560
- lods: spec.mid ? [{ distance: spec.midDistance ?? 40, glb: join(assetsDir, spec.mid) }] : [],
5182
+ lods: spec.mid ? [{ distance: spec.midDistance ?? 40, glb: join$1(assetsDir, spec.mid) }] : [],
3561
5183
  maxDistance: spec.maxDistance
3562
5184
  }
3563
5185
  ])
@@ -3576,8 +5198,18 @@ async function cookInto(request2, cooker, kitDir, assetsDir) {
3576
5198
  out: request2.out,
3577
5199
  extraLayers: { table: "terrain-table.json" }
3578
5200
  });
5201
+ const readme = farRingResult.decision.source === "massif" ? `${ground.readme ?? ""}
5202
+ ## Far ring
5203
+
5204
+ ring.json continues the survey to ${RING_SCALE} times the world's size, with ${farRingResult.decision.name} (${farRingResult.decision.lat}, ${farRingResult.decision.lon}) standing past the playable square.
5205
+
5206
+ ${farRingResult.decision.attribution}
5207
+ ` : ground.readme;
5208
+ if (readme !== void 0) await writeFile(join$1(request2.out, "README.md"), readme);
5209
+ if (farRingResult.file !== void 0)
5210
+ await writeFile(join$1(request2.out, "ring.json"), farRingResult.file);
3579
5211
  await writeFile(
3580
- join(request2.out, "water.json"),
5212
+ join$1(request2.out, "water.json"),
3581
5213
  `${JSON.stringify(
3582
5214
  {
3583
5215
  lakes: state.waters.map((lake) => ({
@@ -3606,15 +5238,15 @@ async function cookInto(request2, cooker, kitDir, assetsDir) {
3606
5238
  if (pkg === null) throw new Error("cook: the bake wrote no world package.");
3607
5239
  const { splat, manifest, files } = pkg;
3608
5240
  await writeFile(
3609
- join(request2.out, "terrain-table.json"),
5241
+ join$1(request2.out, "terrain-table.json"),
3610
5242
  `${JSON.stringify({ ...surface, splat, textures: "textures" }, null, 2)}
3611
5243
  `
3612
5244
  );
3613
5245
  await copyFile(
3614
- join(assetsDir, "hdri", "kloofendal_48d_partly_cloudy_1k.hdr"),
3615
- join(request2.out, "sky.hdr")
5246
+ join$1(assetsDir, "hdri", "kloofendal_48d_partly_cloudy_1k.hdr"),
5247
+ join$1(request2.out, "sky.hdr")
3616
5248
  );
3617
- await writeFile(join(request2.out, "recipe.json"), JSON.stringify(recipe.recipe));
5249
+ await writeFile(join$1(request2.out, "recipe.json"), JSON.stringify(recipe.recipe));
3618
5250
  const shown = relative(await realpath(request2.projectRoot), request2.out).split(sep).join("/");
3619
5251
  const url = relative(request2.assetSource, request2.out).split(sep).join("/");
3620
5252
  const worldUrl = `${url}/world.json`;
@@ -3645,6 +5277,10 @@ async function cookInto(request2, cooker, kitDir, assetsDir) {
3645
5277
  ...measureGlb(cooked.worldGlb),
3646
5278
  placementCounts: cooked.placementCounts,
3647
5279
  biome: biome.look,
5280
+ ground: ground.ground,
5281
+ // The seed this world was cooked with: pass another as `seed` to reroll it.
5282
+ seed: recipe.recipe.config.seed,
5283
+ backdrop: farRingResult.decision,
3648
5284
  water: floodedBodies(state),
3649
5285
  bands,
3650
5286
  worldGlbBytes: cooked.worldGlb.length,
@@ -3665,8 +5301,12 @@ async function cookInto(request2, cooker, kitDir, assetsDir) {
3665
5301
  " sampleHeight: sampleTerrainHeight(terrainWorld.terrain, terrainWorld.extent, terrainHeights),",
3666
5302
  " width: terrainWorld.extent.sizeX,",
3667
5303
  "});",
5304
+ "const terrainCentre = { x: terrainWorld.extent.minX + terrainWorld.extent.sizeX / 2, z: terrainWorld.extent.minZ + terrainWorld.extent.sizeZ / 2 };",
5305
+ "// Seats the cooked centre pad 5 cm under the game's floor (y = 0), so the floor draws over it. Add",
5306
+ "// terrainSeat to a terrainField.heightAt read. Named override: terrainSeat = 0 keeps the cooked heights.",
5307
+ "const terrainSeat = -terrainField.heightAt(terrainCentre.x, terrainCentre.z) - 0.05;",
3668
5308
  "const terrainAnchor = new TerrainAnchor();",
3669
- "terrainAnchor.position.set(terrainWorld.extent.minX + terrainWorld.extent.sizeX / 2, 0, terrainWorld.extent.minZ + terrainWorld.extent.sizeZ / 2);",
5309
+ "terrainAnchor.position.set(terrainCentre.x, terrainSeat, terrainCentre.z);",
3670
5310
  "const terrainBody = new TerrainRigidBody({",
3671
5311
  ' entity: "terrain",',
3672
5312
  " object: terrainAnchor,",
@@ -3689,6 +5329,7 @@ async function cookInto(request2, cooker, kitDir, assetsDir) {
3689
5329
  ` ring: ${ring}, budgets: ${JSON.stringify(budgets)}, terrain: { streamRadius: ${ring + 1} },`,
3690
5330
  " shadows: { cast: true, receive: true, invalidate: (region) => terrainInvalidate?.(region) },",
3691
5331
  "});",
5332
+ " world.position.y = terrainSeat;",
3692
5333
  " ctx.add(world);",
3693
5334
  "} catch (error) { terrainAnchor.removeFromParent(); throw error; }",
3694
5335
  'const loadCells = (follow: TerrainAnchor, invalidate?: NonNullable<TerrainWorldOptions["shadows"]>["invalidate"]) => { terrainFollow = follow; terrainInvalidate = invalidate; };',