@margoengine/terrain 0.0.0-stage → 0.1.0

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 (71) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +4 -0
  3. package/README.md +1808 -3
  4. package/dist/blend.d.ts +70 -0
  5. package/dist/blend.js +159 -0
  6. package/dist/colors.d.ts +164 -0
  7. package/dist/deform.d.ts +103 -0
  8. package/dist/deform.js +322 -0
  9. package/dist/displace.d.ts +60 -0
  10. package/dist/displace.js +254 -0
  11. package/dist/dunes.d.ts +86 -0
  12. package/dist/dunes.js +88 -0
  13. package/dist/errors-fc4i1pSL.js +7 -0
  14. package/dist/grid.d.ts +11 -0
  15. package/dist/ground-change-settings.d.ts +29 -0
  16. package/dist/ground-change-settings.js +69 -0
  17. package/dist/ground-change.d.ts +227 -0
  18. package/dist/ground-change.js +1291 -0
  19. package/dist/ground-model.d.ts +290 -0
  20. package/dist/hdr-format-DRhzGS7G.js +30 -0
  21. package/dist/height-grid.d.ts +65 -0
  22. package/dist/height-grid.js +74 -0
  23. package/dist/heightfield.d.ts +38 -0
  24. package/dist/holes.d.ts +37 -0
  25. package/dist/holes.js +97 -0
  26. package/dist/imagery.d.ts +109 -0
  27. package/dist/imagery.js +472 -0
  28. package/dist/index.d.ts +297 -0
  29. package/dist/index.js +1 -0
  30. package/dist/layers-pbr.d.ts +78 -0
  31. package/dist/layers-pbr.js +128 -0
  32. package/dist/lighting-layout-CaDtDa5G.js +34 -0
  33. package/dist/lighting-layout.d.ts +5 -0
  34. package/dist/mesh-patch-BThCHCeS.js +21 -0
  35. package/dist/mesh-patch.d.ts +14 -0
  36. package/dist/noise3-sQdnbz4B.js +11 -0
  37. package/dist/noise3.d.ts +3 -0
  38. package/dist/overlays.d.ts +74 -0
  39. package/dist/overlays.js +297 -0
  40. package/dist/planet-craters.d.ts +55 -0
  41. package/dist/planet-recipes.d.ts +75 -0
  42. package/dist/planet-recipes.js +216 -0
  43. package/dist/planet.d.ts +139 -0
  44. package/dist/planet.js +602 -0
  45. package/dist/query.d.ts +150 -0
  46. package/dist/query.js +243 -0
  47. package/dist/relief-lighting.d.ts +46 -0
  48. package/dist/relief-lighting.js +208 -0
  49. package/dist/require-webgpu--tUXPsmA.js +7 -0
  50. package/dist/rock-settings.d.ts +39 -0
  51. package/dist/rock-settings.js +84 -0
  52. package/dist/rock-surface.d.ts +111 -0
  53. package/dist/rock-surface.js +368 -0
  54. package/dist/rocks.d.ts +258 -0
  55. package/dist/rocks.js +488 -0
  56. package/dist/rvt.d.ts +136 -0
  57. package/dist/rvt.js +518 -0
  58. package/dist/sculpt.d.ts +103 -0
  59. package/dist/sculpt.js +361 -0
  60. package/dist/settings-B9BSdnhD.js +72 -0
  61. package/dist/settings.d.ts +81 -0
  62. package/dist/settings.js +152 -0
  63. package/dist/shader.d.ts +61 -0
  64. package/dist/shared/settings.d.ts +89 -0
  65. package/dist/src-C6dtSaAb.js +1155 -0
  66. package/dist/stream.d.ts +100 -0
  67. package/dist/stream.js +339 -0
  68. package/dist/surface-height.d.ts +16 -0
  69. package/dist/wet-ground.d.ts +82 -0
  70. package/dist/wet-ground.js +147 -0
  71. package/package.json +148 -6
package/README.md CHANGED
@@ -1,3 +1,1808 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
1
+ # @margoengine/terrain
2
+
3
+ All terrain plugins remove their actual scene registration on `dispose()`,
4
+ preserving a same-name plugin in another scene. Device restoration retains
5
+ registration. Stream disposal also removes its owned terrain; blend and sculpt
6
+ leave their borrowed terrain and virtual texture attached. The public `owner`
7
+ fields of `TerrainMaterials`, `TerrainDisplacement`, `TerrainVirtualTexture` and
8
+ `TerrainDeformation` identify the Engine; use `engine.sceneOf(effect)` for the scene.
9
+
10
+ ```ts
11
+ import {Engine} from 'margoengine/core';
12
+ import {TerrainHeightmap} from 'margoengine/terrain';
13
+ const engine = await Engine.create(document.querySelector('canvas')!);
14
+ const product = engine.createScene('product');
15
+ const heightmap = new TerrainHeightmap(() => 0, {size: [4, 4], resolution: 16});
16
+ product.use(heightmap);
17
+ console.assert(engine.sceneOf(heightmap) === product);
18
+ heightmap.dispose(); // Frees its texture and registration; product can register a replacement.
19
+ ```
20
+
21
+ Import `margoengine/terrain` from the `margoengine` package, or `@margoengine/terrain` from this package alone; the two are the same module. Neither is on npm yet: the [Install](../../README.md#install) section lists the two routes that work today (run in a clone, or install local tarballs).
22
+
23
+ `heightfieldGeometry(height, {size, origin?, resolution?})` generates a Y-up mesh
24
+ with recomputed slope normals; `heightfield(height, options)` gives the same grid as a core `Geometry`, ready for
25
+ `mesh.setGeometry`. `origin` is the minimum world XZ corner; it defaults
26
+ to a centered rectangle, and mesh resolution defaults to 192 segments.
27
+ `TerrainHeightmap.attach(engine, height, {size, origin?, resolution?})` owns an
28
+ `r32float` texture sampled at cell centers, exposed as `.texture` for scatter and
29
+ water. `Terrain` and `TerrainQuery` read a heightmap corner-aligned instead (texel 0 at `origin`, the last texel at
30
+ `origin + size`), so to draw this texture as a `Terrain` give the terrain `origin + size / (2 resolution)` and
31
+ `size (resolution - 1) / resolution`; the same `origin` and `size` shift the ground by half a cell and stretch it by
32
+ `resolution / (resolution - 1)`. Texture resolution defaults to 256. Resolutions are integers in 1..1024.
33
+ The module validates finite samples and device limits, regenerates the texture
34
+ on device restoration, and destroys it on disposal. Sampling arrays are released
35
+ after upload; there is no per-frame CPU sampling or allocation.
36
+
37
+ `TerrainColors.attach(engine, mesh, options?)` applies height/slope colors and wet
38
+ shoreline darkening to one ordinary terrain mesh using its mesh ID. It preserves
39
+ the existing PBR/shadow shader and caches the patch. Options are captured at
40
+ attachment, and every one has a default, so `TerrainColors.attach(engine, mesh)` alone gives sand at sea level
41
+ (world Y 0, as `@margoengine/water`), grass over the rest and rock on slopes past about 35 degrees:
42
+
43
+ | Option | Default | Source |
44
+ | --- | --- | --- |
45
+ | `sand` | `[0.5, 0.42, 0.29]` | dry sand albedo 0.35 to 0.45 (Oke 1987, table 1.1) |
46
+ | `meadow` | `[0.133, 0.263, 0.033]`, `[0.274, 0.342, 0.064]` | grass albedo 0.16 to 0.26 (Oke 1987); the biomes package's grass and meadow |
47
+ | `stone` | `[0.253, 0.223, 0.187]` | the biomes package's rock |
48
+ | `shore` | `[0.3, 1.5]` m | beaches up to 1.5 m above sea level |
49
+ | `meadowHeight` | the mesh's lowest to highest point, under its position and Y scale | |
50
+ | `stoneHeight` | above the mesh's highest point (only slopes are stone) | pass a range for rocky peaks |
51
+ | `stoneNormal` | `[0.75, 0.85]` (normal Y: 32 to 41 degrees) | angle of repose of loose soil and scree, 30 to 40 degrees (Carrigy 1970) |
52
+ | `wetHeight` | `[-0.1, 0.4]` m | just above sea level |
53
+ | `wetDarkening` | `0.6` | wet ground at about 0.6 of its dry albedo (Lekner and Dorf 1988) |
54
+ | `wetDryTime` | `900` s (1 to 604,800) | with `wetness`: sand the water has left dries to 1/e of its moisture (Namikas et al. 2010) |
55
+ | `wetGlossTime` | `20` s (0.1 to 3,600) | with `wetness`: its glossy water film drains to 1/e (Horn 2006) |
56
+ | `variation` | `0` (0..1) | |
57
+ | `detail` | `1` (0..1) | |
58
+ | `sandSurface` | `{wind: [1, 0], ripple: 0.1, ripples: 1, streaks: 1, sorting: 1, broad: 0}`; `false` removes it | wind-built sand, below |
59
+
60
+ Ranges must be increasing; colors are linear RGB in 0..1. Other meshes keep their materials. Sources: T. R. Oke,
61
+ "Boundary Layer Climates", 2nd ed., 1987; J. Lekner and M. Dorf, "Why some things are darker when wet", Applied Optics
62
+ 27(7), 1988, https://doi.org/10.1364/AO.27.001278 ; J. Carrigy, "Experiments on the angles of repose of granular
63
+ materials", Sedimentology 14, 1970, https://doi.org/10.1111/j.1365-3091.1970.tb00184.x
64
+
65
+ ```ts
66
+ import {Engine} from 'margoengine/core';
67
+ import {TerrainColors, heightfield} from 'margoengine/terrain';
68
+
69
+ const engine = await Engine.create(document.querySelector('canvas')!);
70
+ const ground = engine.createMesh();
71
+ ground.setGeometry(heightfield((x, z) => 6 * Math.sin(x / 9) * Math.cos(z / 11) + 2, {size: [120, 120]}));
72
+ TerrainColors.attach(engine, ground); // sand, grass and rock with no options
73
+ engine.camera.position = [0, 40, 90];
74
+ engine.camera.target = [0, 0, 0];
75
+ ```
76
+
77
+ ### Wind-built sand: `sandSurface`
78
+
79
+ The sand band carries what the wind does to dry sand, on by default (with `detail` above 0): impact ripples across
80
+ the wind, streaks along it, and sorting by slope, so a dune field reads as dunes in flat overcast light instead of one
81
+ beige sheet. Pass the direction the wind blows toward; a scene with a north wind blows toward +z:
82
+
83
+ ```ts
84
+ import {Engine} from 'margoengine/core';
85
+ import {TerrainColors, heightfield} from 'margoengine/terrain';
86
+ import {duneField} from 'margoengine/terrain/dunes';
87
+
88
+ const engine = await Engine.create(document.querySelector('canvas')!);
89
+ const heights = duneField({width: 129, depth: 129, cellSize: 1, origin: [-64, -64], height: 2, wind: 90, seed: 3});
90
+ const ground = engine.createMesh().setGeometry(heightfield((x, z) => {
91
+ const i = Math.min(128, Math.max(0, Math.round(x + 64))), j = Math.min(128, Math.max(0, Math.round(z + 64)));
92
+ return heights[j * 129 + i];
93
+ }, {size: [128, 128], resolution: 128}));
94
+ TerrainColors.attach(engine, ground, {shore: [20, 30], sandSurface: {wind: [0, 1], ripple: 0.1}});
95
+ engine.camera.position = [0, 1.7, -20];
96
+ engine.camera.target = [0, 0, 0];
97
+ ```
98
+
99
+ | `sandSurface` field | Default | Meaning |
100
+ | --- | --- | --- |
101
+ | `wind` | `[1, 0]` | direction the wind blows toward, world `[x, z]`, any length above 0 |
102
+ | `ripple` | `0.1` m (0.02 to 1) | ripple spacing; impact ripples of fine to medium sand are 5 to 20 cm apart |
103
+ | `ripples` | `1` (0 to 2) | relief: height 1/15 of the spacing, a 5.5 degree windward side and a 19 degree lee side |
104
+ | `streaks` | `1` (0 to 1) | streaks along the wind, 1 to 2 m wide, albedo up to 8% either way |
105
+ | `sorting` | `1` (0 to 1) | lee slip faces up to 10% paler and smooth, with grainflow strips; windward faces up to 7% darker |
106
+ | `broad` | `0` (0 to 1) | broad scour bands along the wind, 8 to 15 m wide and about 80 m long, up to 15% albedo either way; they never fade with distance, so far dune faces keep the wind's marks |
107
+
108
+ - Ripples: crests run across the wind and wander and break off at defects (a two-octave phase warp and an amplitude
109
+ noise), with coarse grains darkening the crests and lee sides. Their relief bends the shading normal as a surface
110
+ gradient. Before a pixel covers half a ripple they fade out in object space (the footprint is the pixel's own, the
111
+ longer screen-space derivative of the position, so it follows the frame size, device pixel ratio and grazing
112
+ angle; `test/sand-footprint.browser.mjs` checks 540 and 270-line frames against a filtered 2160-line one), and the crest band has zero mean, so the far ground keeps its colour and
113
+ does not shimmer. They are left off avalanching slip faces, and with a `wetness` record they fade with its
114
+ moisture: wet and submerged sand carries none (moisture holds the grains; Namikas and Sherman 1995, Wiggs et al.
115
+ 2004), so a sea floor seen through water is smooth.
116
+ - Sorting: a face turned downwind past about 15 to 27 degrees is a slip face (paler, fresh avalanche sand in strips
117
+ about 1 m wide); a face turned upwind is windward (darker coarse lag). On sand only; meadow and stone are unchanged.
118
+ - Measured (`npm run test:gpu` in this package runs `test/sand.browser.mjs`; RTX A6000, WebGPU and the WebGL2
119
+ layer): near ground luma spread 1.77 times that of `sandSurface: false`, slip face 1.047 and windward face 0.963
120
+ times in sRGB luma, far ground pixel-to-pixel change 1.08 times.
121
+ - Sources: R. S. Anderson, "A theoretical model for aeolian impact ripples", Sedimentology 34, 1987; B. Andreotti,
122
+ P. Claudin and O. Pouliquen, "Aeolian sand ripples: experimental study of fully developed states", Physical Review
123
+ Letters 96, 2006; R. P. Sharp, "Wind ripples", Journal of Geology 71, 1963; R. A. Bagnold, "The Physics of Blown Sand
124
+ and Desert Dunes", 1941; B. T. Werner and G. Kocurek, "Bedform spacing from defect dynamics", Geology 27, 1999; R. E.
125
+ Hunter, "Basic types of stratification in small eolian dunes", Sedimentology 24, 1977; N. Lancaster, "Geomorphology
126
+ of Desert Dunes", 1995; R. Greeley and J. D. Iversen, "Wind as a Geological Process", 1985; M. Mikkelsen, "Surface
127
+ Gradient-Based Bump Mapping Framework", JCGT 9(3), 2020; A. Norton, A. Rockwood and P. Skolmoski, "Clamping: a method
128
+ of antialiasing textured surfaces by bandwidth limiting in object space", SIGGRAPH 1982.
129
+
130
+ Colors are worked out per pixel from the interpolated world height and normal, so
131
+ band borders follow the true height and slope instead of the mesh's triangles.
132
+ `variation` darkens colors by up to twice its value with two octaves of smooth
133
+ value noise (14 m and 1.1 m cells, the fine one rotated 37° and faded out between
134
+ 20 and 60 m from the camera so it cannot shimmer). The noise is hashed per lattice
135
+ cell and never repeats, so there is no tile to hide. The patch flags the mesh in a
136
+ flat varying (location 6), then wraps the rest of core's fragment after its
137
+ shading-normal line in a block whose `i` and `n` are the terrain's own copies:
138
+ shadows, clustered lights, sky ambient, IBL and post replays shade the per-pixel
139
+ albedo, roughness and normal without changing their own patches. Without core's
140
+ standard shader the patch does nothing and the mesh keeps its material color.
141
+
142
+ `detail` makes the bands read as materials. The 14 m noise moves every border by
143
+ up to 30% of its range, so beaches, meadow patches and the stone line wander.
144
+ Sand, meadow and stone then blend by procedural height maps, the height-based
145
+ blending of Mishkinis's "Advanced Terrain Texture Splatting" (2013): grass tufts
146
+ from the fine noise, sand settling in their hollows, rock bumps from the stone
147
+ pattern, so the higher surface wins near each transition instead of a smooth
148
+ crossfade. Where stone shows, its pattern is triplanar: anisotropic noise on the
149
+ two vertical projections reads as horizontal strata, the top projection as
150
+ lumps, so cliffs never stretch a top-down pattern. The noise's analytic gradient
151
+ tilts the normal by up to about 17° (surface-gradient bump mapping), lighting the
152
+ strata; the geometric normal still drives shadow bias. Stone brightness follows
153
+ the bumps (±30%), sand grain the fine noise (±10%). Fine detail fades out between
154
+ 20 and 60 m. `detail: 0` removes all of it from the shader and keeps smooth
155
+ per-pixel bands; values in between scale it.
156
+
157
+ Cost: one flat compare on every core-mesh pixel. On terrain pixels about 40 ALU
158
+ operations for the bands; with `variation` or `detail`, about 60 per noise
159
+ octave: two octaves everywhere (one beyond 60 m) and three more triplanar ones
160
+ where stone shows within 60 m, plus about 30 for the blends and the bump. That is
161
+ roughly 200 operations on meadow and sand and 380 on near stone (counted from the
162
+ WGSL, not timed). There are no texture fetches and no derivatives, so it runs
163
+ inside the mesh-ID branch without uniformity limits.
164
+
165
+ For a moving wet-sand band, add `wetness: {texture: () => water.coastalDepthTexture,
166
+ origin: [-80,-80], size: [160,160]}` using the same world bounds as water's terrain.
167
+ The borrowed texture's red channel contains water depth in meters; it must be a
168
+ single-layer, single-sample 2D `r32float`, `rgba32float` or `rgba16float` texture
169
+ with `COPY_SRC`. Undefined uses dry sand while water initializes or restores.
170
+ The module keeps a stable GPU snapshot so flow ping-pong does not rebuild scene
171
+ or vegetation bindings each frame. A 256 × 256 `rgba32float` snapshot costs 1 MiB
172
+ and one GPU copy per frame. Terrain owns that snapshot, not the provider texture.
173
+
174
+ Sand the swash has left stays wet (KB-TERRAIN-WETSAND1). Terrain keeps a moisture
175
+ record over the water's grid, one `rgba32float` texel per water texel, updated once
176
+ a frame by a small compute pass from the depth snapshot: wherever water stands the
177
+ moisture and the surface film are full, and once it has gone the moisture falls as
178
+ `exp(-t / wetDryTime)` and the film as `exp(-t / wetGlossTime)`. The darkening share
179
+ is `(1 - e^-3m) / (1 - e^-3)` of the moisture `m`, since reflectance falls fastest
180
+ with the first moisture and levels off near saturation (Lobell and Asner 2002;
181
+ Nolet et al. 2014), so drying sand holds its dark tone and pales late; the film
182
+ sets the sheen. `wetSandAfter(seconds, dryTime, glossTime)` returns what the record
183
+ holds that long after the water left. Both times are live (`setLook`, and the
184
+ `wet.dryTime` and `wet.glossTime` rows). The record costs two more textures the size
185
+ of the water grid (2 MiB for 256 × 256) and starts dry: a shot that needs the wet
186
+ band in its first frame lets the water run before it.
187
+
188
+ ```ts
189
+ import {Engine} from 'margoengine/core';
190
+ import {TerrainColors, heightfield, wetSandAfter} from 'margoengine/terrain';
191
+
192
+ const engine = await Engine.create(document.querySelector('canvas')!);
193
+ const depth = engine.gpu!.createTexture({
194
+ size: [64, 64],
195
+ format: 'r32float',
196
+ usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_SRC | GPUTextureUsage.COPY_DST,
197
+ });
198
+ const beach = engine.createMesh().setGeometry(heightfield((x) => x * 0.02, {size: [80, 80], origin: [-40, -40]}));
199
+ const colors = TerrainColors.attach(engine, beach, {
200
+ wetness: {texture: () => depth, origin: [-40, -40], size: [80, 80]},
201
+ wetDryTime: 600, // sand behind the swash dries to 1/e in 10 minutes
202
+ });
203
+ colors.setLook({wetGlossTime: 10});
204
+ console.log(wetSandAfter(60, 600, 10).darkening); // 0.98 of the full darkening a minute after the swash
205
+ ```
206
+
207
+ Sources: D. P. Horn, "Beach groundwater dynamics", Geomorphology 48, 2002,
208
+ https://doi.org/10.1016/S0169-555X(02)00178-2 ; D. P. Horn, "Measurements and modelling of beach groundwater flow in
209
+ the swash-zone: a review", Continental Shelf Research 26(5), 2006, https://doi.org/10.1016/j.csr.2006.02.001 ; R. A.
210
+ Namikas, B. L. Edwards, M. C. Bitton, J. L. Booth and Y. Zhu, "Temporal and spatial variabilities in the surface
211
+ moisture content of a fine-grained beach", Geomorphology 114(3), 2010, https://doi.org/10.1016/j.geomorph.2009.07.011 ;
212
+ D. B. Lobell and G. P. Asner, "Moisture effects on soil reflectance", Soil Sci. Soc. Am. J. 66, 2002,
213
+ https://doi.org/10.2136/sssaj2002.7220 ; C. Nolet, A. Poortinga, P. Roosjen, H. Bartholomeus and G. Ruessink,
214
+ "Measuring and modeling the effect of surface moisture on the spectral reflectance of coastal beach sand", PLoS ONE
215
+ 9(11), 2014, https://doi.org/10.1371/journal.pone.0112151 ; S. A. Twomey, C. F. Bohren and J. L. Mergenthaler,
216
+ Applied Optics 25(3), 1986, https://doi.org/10.1364/AO.25.000431 . The 900 s and 20 s defaults are Margo's values
217
+ inside those ranges (minutes of drainage behind the swash, hours of drying landward), not a groundwater model.
218
+
219
+ Wetness samples world XZ per fragment and darkens only the sand albedo below
220
+ `wetHeight[1]`; fully wet sand is also 40% smoother while its film lasts, so it
221
+ catches a sheen toward the sun. Meadow/stone blends and geometry stay fixed to
222
+ terrain height and slope. It uses a group 0 binding from 40 up and flat output
223
+ location 6 in the standard PBR shader. No core changes are required. Physical
224
+ regression on WebGPU and the WebGL2 layer: `node packages/terrain/test/wetness.browser.mjs`
225
+ from the repository root after building the packages (MARGO_COMPAT=1 for the layer).
226
+
227
+ Optional geometry clipmaps with vertex texture height and normal sampling and 4 to 16 terrain layers. Fixed grids form a centre and concentric rings. Inner edges align to the finer grid and outer-edge vertices collapse onto the next coarser lattice to close seams. In moving-window mode, [seams.browser.mjs](test/seams.browser.mjs) checks 200 camera offsets for clear pixels through the ground on WebGPU and the WebGL2 layer. Height sampling uses bilinear `textureLoad`, including non-filterable `r32float` maps. Cliff faces use triplanar splatting and normalized slope and height weights blend an sRGB texture array.
228
+
229
+ The rings anchor at the main camera's world XZ on the first render. Camera motion then preserves the terrain triangles,
230
+ ridge silhouettes, and static shadow cache. Pass `clipmapAnchor: [x, z]` for a fixed centre you choose. Set `levels`,
231
+ `resolution`, or `cellSize` so the outer ring spans the terrain in view. For a route that exceeds the fixed outer ring,
232
+ pass `clipmapAnchor: 'camera'` to select a moving window on the same world lattice. `TerrainStream` defaults to that mode.
233
+ The fixed ring origin remains in world coordinates with `floatingOrigin` and survives rebases and device restoration.
234
+ [The rendered regression](test/clipmap-anchor.browser.mjs) checks a subpixel camera move across a clipmap boundary.
235
+ The clipmap lattice and seam treatment follow Frank Losasso and Hugues Hoppe,
236
+ [Geometry Clipmaps](https://hhoppe.com/geomclipmap.pdf) (2004), and Arul Asirvatham and Hugues Hoppe,
237
+ [Terrain Rendering Using GPU-Based Geometry Clipmaps](https://hhoppe.com/gpugcm.pdf) (2005).
238
+
239
+ Set `captureSurfaceHeight: true` when an object-placement pass needs the heights of the triangles on screen.
240
+ `terrain.surfaceHeightTexture` becomes available when the first frame prepares the terrain. The texture shares
241
+ the source heightmap's UVs and stores world metres in R. It refreshes on changes to the clipmap or source heights,
242
+ so call `terrain.invalidate()` after editing samples. The target is capped at 2,049 texels per side. It uses R32F
243
+ on WebGPU and the full compatibility tier, RGBA16F on the half-float tier. The LDR tier cannot render the float target.
244
+ [The height regression](test/surface-height.browser.mjs) checks a fine source peak that the coarse rendered triangles omit.
245
+ Each ring's 176-byte uniform (and each shadow cascade's and local shadow layer's copy) is uploaded only when its bits
246
+ differ from the last upload to that buffer, so a still camera under unchanged light uploads nothing; buffers made
247
+ after a device restore always get their first write.
248
+
249
+ ```ts
250
+ import {EngineKernel} from 'margoengine/core';
251
+ import {Terrain} from 'margoengine/terrain';
252
+ const engine = await EngineKernel.create(document.querySelector<HTMLCanvasElement>('#viewport')!, {backend:'webgpu'});
253
+ const terrain = Terrain.attach(engine, {
254
+ resolution:64, levels:6, cellSize:1, origin:[-50,-50], size:[100,100], heightScale:20,
255
+ layers:[
256
+ {height:[-20,100],slope:[0,0.3],scale:0.3},
257
+ {height:[-20,100],slope:[0.2,1],scale:0.2},
258
+ {height:[-20,2],slope:[0,0.4],scale:0.4},
259
+ {height:[10,100],slope:[0,0.5],scale:0.2}
260
+ ],
261
+ textures:device=>{
262
+ // 6 = TEXTURE_BINDING | COPY_DST. Replace these tiny demo maps with your assets.
263
+ const heightmap = device.createTexture({size:[4,4],format:'r32float',usage:6});
264
+ device.queue.writeTexture({texture:heightmap},new Float32Array(16),{bytesPerRow:16},[4,4]);
265
+ const layers = device.createTexture({size:[1,1,4],format:'rgba8unorm-srgb',usage:6});
266
+ device.queue.writeTexture({texture:layers},new Uint8Array([
267
+ 60,120,40,255, 110,110,100,255, 120,90,60,255, 240,245,255,255
268
+ ]),{bytesPerRow:4,rowsPerImage:1},[1,1,4]);
269
+ return {heightmap,layers};
270
+ }
271
+ });
272
+ engine.start();
273
+ ```
274
+
275
+ The texture factory runs at attachment and after device restoration. Terrain owns and destroys returned textures; recreate them from retained asset data. Height maps support `r32float`, `rgba16float`, or `rgba8unorm` (R channel); optional normal maps support `rgba8unorm` or `rgba16float`, with XYZ encoded in 0..1. Without a normal map, the vertex shader samples neighboring heights. Layer arrays support `rgba8unorm-srgb`, `rgba8unorm`, or `rgba16float` and must contain exactly as many layers as the rules. Supply mipmaps for real assets. `heightScale`/`heightOffset` map samples to world Y; origin/size define XZ texture coverage. The clipmap's outer rings reach past the map; nothing is drawn or casts a shadow there (fragments outside the origin/size rectangle are discarded in the colour, capture and shadow passes), so past the map's edge the sky or whatever lies behind shows, not a shelf of clamped edge heights. Checked on a real GPU by `test/edge.browser.mjs` (in `test:gpu`).
276
+
277
+ Optional painted weights: return `weights: [a, b]` from the factory, 2 to 4 `rgba8unorm` 2D textures over the same
278
+ bounds as the heightmap, one per 4 layers, so up to 16 layers (pass the same texture twice for up to 4 layers). Layer
279
+ i's weight is channel `i % 4` of texture `i / 4`, sampled bilinearly, and replaces the height and slope rules; each
280
+ rule's `scale` still sets that layer's texture repeat. A layer whose weight is 0 at a pixel skips its three triplanar
281
+ samples there, so 16 layers cost about what the ones that show do. This is how `@margoengine/biomes/view` draws biome ground layers. Without `weights` the shader, bind
282
+ group layout and draw calls are exactly as before (`examples/package-benchmarks/proofs/terrain-ssr.proof.js` checks the
283
+ whole call sequence). Update the textures with `queue.writeTexture` and call `terrain.invalidate()`.
284
+
285
+ Optional tint, with `weights` only: return `tint` from the factory, one `rgba8unorm` or `rgba8unorm-srgb` 2D texture of
286
+ any size over the heightmap's bounds, and set `tint: true` on the layers it should colour (plant cover, not rock). Each
287
+ such layer is mixed toward the texel's RGB by its A, in linear light, before relief and macro tone; other layers are
288
+ drawn as they are. `@margoengine/biomes/view` draws seasons this way. Without `tint` the shader, bindings and rules
289
+ are unchanged, whatever the layers say.
290
+
291
+ ```ts
292
+ import { Terrain } from 'margoengine/terrain';
293
+ import {Engine} from 'margoengine/core';
294
+ const engine = await Engine.create(document.querySelector('canvas')!);
295
+ // Your heightmap, layers and weights textures, as above; here small demo maps.
296
+ function make(device: GPUDevice) {
297
+ const heightmap = device.createTexture({ size: [4, 4], format: 'r32float', usage: 6 });
298
+ device.queue.writeTexture({ texture: heightmap }, new Float32Array(16), { bytesPerRow: 16 }, [4, 4]);
299
+ const layers = device.createTexture({ size: [1, 1, 4], format: 'rgba8unorm-srgb', usage: 6 });
300
+ const colours = [60, 120, 40, 255, 110, 110, 100, 255, 120, 90, 60, 255, 240, 245, 255, 255];
301
+ device.queue.writeTexture({ texture: layers }, new Uint8Array(colours), { bytesPerRow: 4, rowsPerImage: 1 }, [1, 1, 4]);
302
+ const weight = device.createTexture({ size: [1, 1], format: 'rgba8unorm', usage: 6 });
303
+ device.queue.writeTexture({ texture: weight }, new Uint8Array([255, 0, 0, 0]), { bytesPerRow: 4 }, [1, 1]);
304
+ return { heightmap, layers, weights: [weight, weight] };
305
+ }
306
+ Terrain.attach(engine, {
307
+ size: [512, 512],
308
+ layers: [0, 1, 2, 3].map((i) => ({ height: [-1e6, 1e6], slope: [0, 1], scale: 0.25, tint: i === 0 })),
309
+ textures(device) {
310
+ const tint = device.createTexture({
311
+ size: [64, 64],
312
+ format: 'rgba8unorm-srgb',
313
+ usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST,
314
+ });
315
+ // RGB: the colour to mix toward; A: how far (0 keeps the layer).
316
+ device.queue.writeTexture({ texture: tint }, new Uint8Array(64 * 64 * 4).fill(200), { bytesPerRow: 256 }, [64, 64]);
317
+ return { ...make(device), tint };
318
+ },
319
+ });
320
+ ```
321
+
322
+ ## Sliders for the sand and ground look: `@margoengine/terrain/settings`
323
+
324
+ `TerrainColors` keeps its look (the colours, the height and slope ranges, the wet darkening and the sand surface's wind,
325
+ ripples, streaks, sorting and broad bands) in one small uniform, so any of it changes while the scene runs with
326
+ `colors.setLook(values)`: nothing is rebuilt, the next frame writes 176 bytes. `@margoengine/terrain/settings` lists those
327
+ controls as a table for sliders and panels: `TERRAIN_SETTINGS` has 24 rows (`name`, `group`, `kind`, `default`, `min`,
328
+ `max`, `step`, `unit`, `about` and `live`, which is true for every row), `applyTerrainSettings(colors, values)` writes a
329
+ set of values (a name left out takes its default) with one `setLook` call, and `TERRAIN_LOOKS` names four looks made only
330
+ of row values: `paleDesert`, `redDesert`, `volcanicBeach` and `saltFlat`. An unknown name throws `TypeError`, a value
331
+ outside its row's range `RangeError`, and `null` is accepted only on the rows that say `nullable`: the four height
332
+ ranges (null is the mesh's own range) and `sand.windDirection` (null leaves the wind to the weather drive).
333
+ `detail`, `variation`, `wetness` and whether `sandSurface` is on were compiled in at construction and are not rows; a
334
+ sand row on a `TerrainColors` built with `sandSurface: false` throws `TypeError`. Writing every live row each frame for 60
335
+ frames creates no pipeline, buffer or texture (`test/sand.browser.mjs`, native WebGPU and the WebGL2 layer), and the
336
+ defaults written draw exactly what a plain `TerrainColors` draws.
337
+
338
+ ```ts
339
+ import {Engine} from 'margoengine/core';
340
+ import {TerrainColors, heightfield} from 'margoengine/terrain';
341
+ import {TERRAIN_LOOKS, applyTerrainSettings} from 'margoengine/terrain/settings';
342
+
343
+ const engine = await Engine.create(document.querySelector('canvas')!);
344
+ const ground = engine.createMesh().setGeometry(heightfield((x, z) => 0.3 * Math.sin(x * 0.2) * Math.cos(z * 0.2), {size: [128, 128], resolution: 128}));
345
+ const colors = TerrainColors.attach(engine, ground, {shore: [20, 30]});
346
+ applyTerrainSettings(colors, {...TERRAIN_LOOKS.paleDesert, 'sand.windDirection': 45});
347
+ // Key a row over a shot: the sand drifts from fine ripples to long scour bands.
348
+ let time = 0;
349
+ engine.onFrame((_, delta) => {
350
+ time += delta;
351
+ applyTerrainSettings(colors, {...TERRAIN_LOOKS.paleDesert, 'sand.windDirection': 45, 'sand.broad': Math.min(1, time / 10)});
352
+ });
353
+ engine.camera.position = [0, 1.7, -20];
354
+ engine.camera.target = [0, 0, 0];
355
+ ```
356
+
357
+ ## Relief and far detail: `bump` and `macro`
358
+
359
+ Past about 50 m a layer texture's mips average it to its mean colour, and the ground is lit by the vertex normal only,
360
+ so rock and snow read as flat grey. Two optional layer settings, each 0 to 1 (`RangeError` outside), keep them
361
+ readable:
362
+
363
+ - `bump` (default 0): the layer's own luma becomes a height of up to half a texture repeat per unit of luma, times
364
+ `bump` (2 m at `scale` 0.25 for luma 0 to 1), and the shading normal follows its slope: derivative bump mapping from
365
+ Mikkelsen's "Bump Mapping Unparametrized Surfaces on the GPU" (2010), screen-space derivatives of the height and the
366
+ position, no extra texture samples. The mips flatten it with distance, as they flatten the colour, and past a footprint
367
+ of 1/64 of a repeat (6 cm at 0.25) its slope falls with the longer of the pixel's two sides on the ground, so distant or
368
+ grazing ground draws no pixel grain.
369
+ - `macro` (default 0): the same layer at 1/24 of its `scale` (a 96 m repeat at 0.25) scales the colour by
370
+ `1 - macro + macro * luma / mean`, where `mean` is the luma of the layer's top mip, so the average colour stays and far
371
+ slopes keep a pattern. A much larger, smooth sample of the layer (about 318 m at 0.25, four mips below the top) adds
372
+ slow variation and picks the repeat's offset, two offsets blended at a time (after Quilez's "Texture Repetition"), so
373
+ the 96 m repeat never lines up into a grid. Give the layers texture a full mip chain for a true mean.
374
+
375
+ ```ts
376
+ import {EngineKernel} from 'margoengine/core';
377
+ import {Terrain} from 'margoengine/terrain';
378
+ const engine = await EngineKernel.create(document.querySelector<HTMLCanvasElement>('#viewport')!, {backend:'webgpu'});
379
+ const terrain = Terrain.attach(engine, {
380
+ size:[100,100], origin:[-50,-50], heightScale:20,
381
+ layers:[
382
+ {height:[-20,100],slope:[0,0.3],scale:0.25,bump:0.3,macro:0.35},
383
+ {height:[-20,100],slope:[0.2,1],scale:0.25,bump:1,macro:0.5},
384
+ {height:[-20,2],slope:[0,0.4],scale:0.25,bump:0.25,macro:0.3},
385
+ {height:[10,100],slope:[0,0.5],scale:0.25,bump:0.35,macro:0.15}
386
+ ],
387
+ textures:device=>{
388
+ // 6 = TEXTURE_BINDING | COPY_DST. Use real layer textures with full mip chains here.
389
+ const heightmap = device.createTexture({size:[4,4],format:'r32float',usage:6});
390
+ device.queue.writeTexture({texture:heightmap},new Float32Array(16),{bytesPerRow:16},[4,4]);
391
+ const layers = device.createTexture({size:[1,1,4],format:'rgba8unorm-srgb',usage:6});
392
+ device.queue.writeTexture({texture:layers},new Uint8Array([
393
+ 60,120,40,255, 110,110,100,255, 120,90,60,255, 240,245,255,255
394
+ ]),{bytesPerRow:4,rowsPerImage:1},[1,1,4]);
395
+ return {heightmap,layers};
396
+ }
397
+ });
398
+ engine.start();
399
+ ```
400
+
401
+ Leaving both out (or 0 on every layer) keeps the shader text, the 8-float rules and so every GPU call exactly as
402
+ before; when any layer sets one, the rules grow to 12 floats a layer and the shader adds the relief and the macro
403
+ sample for every layer whose value is above 0. This works with painted `weights` and SSR's capture. Cost: `bump`
404
+ adds about 30 ALU operations and four derivatives per pixel; `macro` adds, per showing layer, one top-mip sample and
405
+ three texture samples for each triplanar axis that shows (one axis on most of the ground, all three at most). Checked on
406
+ a real GPU by `test/bump.browser.mjs` (in `test:gpu`): on flat ground with one grey noise texture, 0 draws the same pixels
407
+ as leaving them out, `bump: 1` spreads the near ground's luma 4.3 times as wide, `macro: 0.5` spreads the means of 32 px
408
+ blocks of a view from 60 m 9 times as wide, and straight down from 1.5 km the luma at a 96 m lag correlates under 0.2
409
+ (RTX A6000).
410
+ Where a crest is seen edge-on, the relief's slope is limited to what the pixel can resolve, so crests draw no dark
411
+ specks: `test/crest.browser.mjs` (in `test:gpu`) draws alpine crests under the noon sun with `bump: 1` and counts
412
+ none more than without it, by rules and by painted weights.
413
+
414
+ Resolution is a multiple of four from 8-256; levels range from 1-12. The default is 64 cells and six rings, with doubled cell spacing per level. Geometry buffers are allocated once and reused as the camera moves. Layer slope is `1-normal.y` in 0..1; height is world Y. Rules blend smoothly around their thresholds and fall back to layer zero if none match. Terrain uses GGX directional lighting and the scene's reversed depth.
415
+
416
+ `shadows.add(terrain,{static:true})` registers depth rendering and reception; moving clipmap origins invalidates its static shadow cache. `clustered.add(terrain)` adds local PBR lights. Call `terrain.invalidate()` after changing height texture contents. For picking, foot placement and game logic, ask `@margoengine/terrain/query` (below); rendering itself performs no GPU height readback. The clipmap does not add physics or streaming. `dispose()`/`destroy()` releases textures and geometry. `clipmapGrid()` is exported for custom grid consumers.
417
+
418
+ ## Height and ray queries: `@margoengine/terrain/query`
419
+
420
+ `TerrainQuery` answers the height, the normal and a ray's first hit on the surface the clipmap's vertex shader samples
421
+ (bilinear between texels, texel 0 at `origin`, the last at `origin + size`, times `heightScale` plus `heightOffset`),
422
+ on the CPU, so picking, foot placement and game logic need no BVH of the ground. Build it from the heights you upload
423
+ (`new TerrainQuery(heights, columns, rows, terrain.options)`; it keeps the array, no copy), or read a live terrain's
424
+ heightmap back once with `await TerrainQuery.read(engine, terrain, {signal})` (the heightmap needs
425
+ `GPUTextureUsage.COPY_SRC`; `r32float`, `rgba16float` and `rgba8unorm` are read as the shader reads them).
426
+
427
+ ```ts
428
+ import {Engine} from 'margoengine/core';
429
+ import {Terrain} from 'margoengine/terrain';
430
+ import {TerrainQuery} from 'margoengine/terrain/query';
431
+ const engine = await Engine.create(document.querySelector('canvas')!);
432
+ const columns = 65, heights = new Float32Array(columns * columns).map((_, i) => Math.sin(i % columns / 6) * 0.1);
433
+ const terrain = Terrain.attach(engine, {
434
+ size: [128, 128], origin: [-64, -64], heightScale: 20,
435
+ layers: Array.from({length: 4}, () => ({height: [-100, 100] as [number, number], slope: [0, 1] as [number, number], scale: 0.25})),
436
+ textures(device) {
437
+ const heightmap = device.createTexture({size: [columns, columns], format: 'r32float', usage: 6});
438
+ device.queue.writeTexture({texture: heightmap}, heights, {bytesPerRow: columns * 4}, [columns, columns]);
439
+ const layers = device.createTexture({size: [1, 1, 4], format: 'rgba8unorm-srgb', usage: 6});
440
+ device.queue.writeTexture({texture: layers}, new Uint8Array(16).fill(128), {bytesPerRow: 4, rowsPerImage: 1}, [1, 1, 4]);
441
+ return {heightmap, layers};
442
+ },
443
+ });
444
+ const ground = new TerrainQuery(heights, columns, columns, terrain.options);
445
+ const y = ground.height(10, -5); // world Y, or undefined outside the map
446
+ const up = ground.normal(10, -5); // unit shading normal, as the vertex shader works it out
447
+ const hit = ground.raycast([0, 50, 0], [0.2, -1, 0.1]); // {distance, position, normal} or null
448
+ console.log(y, up, hit?.position);
449
+ ```
450
+
451
+ - `height(x, z)` is the bilinear height; `normal(x, z, out?)` uses the vertex shader's central differences one texel
452
+ either way (a terrain with its own `normalmap` shades with that instead). Both return undefined outside the map's
453
+ rectangle, where the terrain draws nothing.
454
+ - `raycast(origin, direction, maxDistance?, out?)` returns the first point where the ray meets the surface, from above or
455
+ below, inside the map, or null. Each cell's bilinear patch is hit exactly (the height along a ray is quadratic in its
456
+ distance), and an implicit min-max quadtree over the cells (Tevs, Ihrke and Seidel's maximum mipmaps, 2008) skips
457
+ ground the ray passes over. The hit has `@margoengine/animator`'s `GroundHit` shape, so
458
+ `raycast: (o, d) => ground.raycast(o, d)` plants a `FootIK` leg as it is; pass `out` to reuse one hit object.
459
+ - After changing `heights` in place (a sculpt, a crater), call `ground.refresh(x, z, width, depth)` over the changed
460
+ samples; it rebuilds the tree there. Without it a raised cell is skipped.
461
+ - The clipmap draws the surface as triangles at its own cell spacing, morphing between rings, so a drawn point lies
462
+ within that triangulation's error of the query's answer (none at texels the finest ring's vertices sit on).
463
+ - Memory: the heights you pass plus a min-max tree of two thirds of their count in floats (2.8 MB for a 1,025 x 1,025 map).
464
+ - `triangles({ step?, region? })` returns the surface as a world-space triangle mesh, `{ positions, normals, indices }`
465
+ (xyz per vertex, three indices per triangle, counter-clockwise seen from above), for a path tracer
466
+ (`@margoengine/voxel-pathtracer/from-engine` takes it as a `terrain` source), a collider or an export. Vertices sit on
467
+ the height samples, every `step`-th each way (default 1; the last row and column are always kept), with the normals
468
+ `normal` gives; `region` (world XZ `min` and `max`) is widened to whole cells and clipped to the heightmap; a cell whose
469
+ centre lies in a hole is left out. Up to 16,777,216 vertices a call (RangeError past that: pass a larger step or a
470
+ smaller region). Evidence: `test/query-triangles.test.js`.
471
+
472
+ ```ts
473
+ import { TerrainQuery } from '@margoengine/terrain/query';
474
+
475
+ const heights = new Float32Array(65 * 65).map((_, i) => Math.sin(i * 0.01));
476
+ const ground = new TerrainQuery(heights, 65, 65, { origin: [-32, -32], size: [64, 64], heightScale: 4 });
477
+ const { positions, normals, indices } = ground.triangles({ step: 2, region: { min: [-16, -16], max: [16, 16] } });
478
+ console.log(positions.length / 3, normals.length / 3, indices.length / 3); // 289 289 512
479
+ ```
480
+
481
+ Checked on the CPU by `test/query.test.js` (rays against a brute-force march, heights and normals against the shader's
482
+ formulas) and on a real GPU by `test/query.browser.mjs` (in `test:gpu`), on real elevation (the Mount Rainier tile in
483
+ `packages/shadows/test/fixtures`, 256 x 256 texels, 3.9 km of relief): `TerrainQuery.read` returns every texel as
484
+ uploaded (r32float and rgba8unorm exactly, rgba16float within half precision), the terrain's own WGSL `height` run on
485
+ the GPU at 3,584 points matches `height` to 2.6 mm, and 512 rays cast onto the mountain all hit, each within 2.3 mm of
486
+ the shader's height at the hit (Radeon 680M; the bound from float32 rounding is 4.9 mm).
487
+
488
+ ## Full PBR layer materials: `@margoengine/terrain/layers-pbr`
489
+
490
+ `TerrainMaterials.attach(engine, terrain, options)` gives every layer its own normal map, ambient occlusion,
491
+ roughness and height, sampled triplanar at the layer's `scale` like its colour, so rock, mud and snow read as
492
+ materials up close. Its `textures` factory returns two 2D array textures with one layer per terrain layer
493
+ (`rgba8unorm` or `rgba16float`), made at attachment and again after device restoration:
494
+
495
+ - `normals`: tangent-space normals, XYZ encoded 0..1 with +Y up (the OpenGL convention, Poly Haven's `nor_gl`; flip
496
+ green for a DirectX map).
497
+ - `surface`: R ambient occlusion, G roughness (glTF's ORM order, Poly Haven's `arm`), B unused, A height 0..1 (a
498
+ `disp` map).
499
+
500
+ ```ts
501
+ import {Engine} from 'margoengine/core';
502
+ import {Terrain} from 'margoengine/terrain';
503
+ import {TerrainMaterials} from 'margoengine/terrain/layers-pbr';
504
+ const engine = await Engine.create(document.querySelector('canvas')!);
505
+ // Four 1 x 1 layers here; use your layers' full-size, mipmapped maps.
506
+ function array(device: GPUDevice, rgba: number[]) {
507
+ const texture = device.createTexture({size: [1, 1, 4], format: 'rgba8unorm', usage: 6});
508
+ device.queue.writeTexture({texture}, new Uint8Array([...rgba, ...rgba, ...rgba, ...rgba]), {bytesPerRow: 4, rowsPerImage: 1}, [1, 1, 4]);
509
+ return texture;
510
+ }
511
+ const terrain = Terrain.attach(engine, {
512
+ size: [128, 128], origin: [-64, -64], heightScale: 20,
513
+ layers: [0, 1, 2, 3].map(() => ({height: [-100, 100] as [number, number], slope: [0, 1] as [number, number], scale: 0.25})),
514
+ textures(device) {
515
+ const heightmap = device.createTexture({size: [2, 2], format: 'r32float', usage: 6});
516
+ device.queue.writeTexture({texture: heightmap}, new Float32Array(4), {bytesPerRow: 8}, [2, 2]);
517
+ const layers = device.createTexture({size: [1, 1, 4], format: 'rgba8unorm-srgb', usage: 6});
518
+ device.queue.writeTexture({texture: layers}, new Uint8Array(16).fill(150), {bytesPerRow: 4, rowsPerImage: 1}, [1, 1, 4]);
519
+ return {heightmap, layers};
520
+ },
521
+ });
522
+ TerrainMaterials.attach(engine, terrain, {
523
+ heightBlend: 0.5, // 0 crossfades by weight; 1 lets the higher surface win
524
+ layers: [{normal: 1, occlusion: 1, roughness: 1}], // per layer, the rest take these defaults
525
+ textures: (device) => ({normals: array(device, [128, 128, 255, 255]), surface: array(device, [255, 230, 0, 128])}),
526
+ });
527
+ engine.start();
528
+ ```
529
+
530
+ - Normals: each projection's tangent-space normal becomes the slope of a height over that projection's plane; the
531
+ three are blended by the triplanar weights as one gradient and tilt the shading normal as a surface gradient
532
+ (Mikkelsen's "Surface Gradient-Based Bump Mapping Framework", 2020), so cliffs need no tangents and the three
533
+ projections agree. `normal` (0 to 2, default 1) scales the tilt. It stacks with `bump`.
534
+ - Roughness replaces the terrain's `roughness` per pixel, times the layer's `roughness` (0 to 2, default 1), clamped
535
+ to 0.02..1; shadows and clustered lights use it and the tilted normal. AO, times `occlusion` (0 to 1, default 1),
536
+ darkens the terrain's own ambient term only, not image-based light another effect adds.
537
+ - Height blending: where layers' weights overlap (rules or painted weights), each weight is scaled by
538
+ 2^(8 x `heightBlend` x (height - 1)), so stones stand out of mud and snow fills the hollows first (after Mishkinis,
539
+ "Advanced Terrain Texture Splatting", 2013). `heightBlend: 0` keeps the terrain's own crossfade.
540
+ - Where no layer's rule applies (the terrain falls back to layer 0's colour) the vertex normal and the terrain's
541
+ roughness are used. SSR's capture (`ssr.add(terrain)`) takes the blended colour but the terrain's own normal and
542
+ roughness.
543
+ - Attach it before any effect that replaces the terrain's lit shader; it patches the layer loop and the fragment.
544
+ - Cost per pixel: each showing layer adds three samples of `surface` and up to three of `normals` (one triplanar axis
545
+ on most ground, all three on cliffs); with height rules every layer's `surface` is sampled, with painted weights
546
+ only those that show. About 40 ALU operations a layer more.
547
+
548
+ Checked on a real GPU by `test/layers-pbr.browser.mjs` (in `test:gpu`), on flat ground seen from above (Radeon 680M):
549
+ flat maps draw exactly the terrain's own pixels (0 of 255 apart) with rules, painted weights and `bump`; a normal tilted
550
+ toward +U lights the ground from +X (luma 146 against 62 from -X, the plain terrain 123 from both), one toward +V (green
551
+ up) from -Z; AO 0 removes the ambient light (151 to 0); roughness 0.1 draws the overhead sun's highlight (254 against
552
+ 147); full height blending gives the highest of four equal layers the ground; and Poly Haven's CC0 Aerial Rocks 02 maps
553
+ (`test/fixtures/aerial-rocks-02`) give a low-sun close-up 1.6 times the luminance spread of its colour alone.
554
+
555
+ ## Height streaming: `@margoengine/terrain/stream`
556
+
557
+ `TerrainStream.attach(engine, options)` makes a `Terrain` whose heightmap, and painted weights, stream in tiles around
558
+ the camera, so a world can be far bigger than one heightmap. The terrain draws a window of `window` x `window` tiles
559
+ (default 4) centred on the engine camera; `load(x, z, signal)` returns tile (x, z)'s heights (`tileTexels` squared
560
+ float32 samples, rows along +Z) and, with `weights: n`, its n weight byte arrays, or null where there is no data.
561
+
562
+ ```ts
563
+ import {Engine} from 'margoengine/core';
564
+ import {TerrainStream} from 'margoengine/terrain/stream';
565
+ const engine = await Engine.create(document.querySelector('canvas')!);
566
+ const stream = TerrainStream.attach(engine, {
567
+ tileSize: 256, tileTexels: 256, window: 4, heightScale: 1, // 1 m texels; a 1,024 x 1,024 window
568
+ layers: [0, 1, 2, 3].map(() => ({height: [-1e4, 1e4] as [number, number], slope: [0, 1] as [number, number], scale: 0.1})),
569
+ colors(device) {
570
+ const texture = device.createTexture({size: [1, 1, 4], format: 'rgba8unorm-srgb', usage: 6});
571
+ device.queue.writeTexture({texture}, new Uint8Array(16).fill(140), {bytesPerRow: 4, rowsPerImage: 1}, [1, 1, 4]);
572
+ return texture;
573
+ },
574
+ async load(x, z, signal) {
575
+ const response = await fetch(`/tiles/${x}/${z}.f32`, {signal}); // your tile server
576
+ return response.ok ? {heights: new Float32Array(await response.arrayBuffer())} : null;
577
+ },
578
+ });
579
+ engine.start();
580
+ await stream.ready(); // every tile of the first window is in
581
+ stream.onChange((change) => console.log(change)); // bands uploaded, or the window moved (`shifted`)
582
+ ```
583
+
584
+ - The window moves a whole tile when the camera is more than 0.75 of a tile from its centre, so ground at least
585
+ `(window / 2 - 0.75) * tileSize` from the camera on each axis is always in it; the terrain draws nothing past the
586
+ window, as past any heightmap. Tiles leaving it have their loads aborted (`signal`).
587
+ - No hitches: the kept texels scroll by two GPU texture copies through a scratch texture (no CPU upload), exposed
588
+ tiles show `fill` (default 0) until they load, and loaded tiles go in as bands of rows within `budget` texels a frame
589
+ (default 65,536), the nearest tile first, with `concurrency` loads in flight (default 4). This is the incremental
590
+ clipmap update of Tanner, Migdal and Jones (1998) and Losasso and Hoppe (2004), scrolled instead of wrapped
591
+ toroidally so the terrain's shader is unchanged.
592
+ - A tile's samples sit at the same world positions in every window (sample k of tile x at
593
+ `origin + (x * tileTexels + k) * tileSize / tileTexels`), so the ground does not move when the window does; adjacent
594
+ tiles share no samples and the surface is bilinear across their seam.
595
+ - `heights` and `weights` are the window's CPU copies, kept in place; `origin`, `tile` (the window's minimum tile) and
596
+ `version` follow it. For queries, build `new TerrainQuery(stream.heights, stream.columns, stream.columns,
597
+ stream.terrain.options)` and on each `onChange` refresh it over the band, or rebuild it when `shifted`.
598
+ - `ready(signal?)` resolves once the current window is all in (uploads go in as frames are drawn) and rejects with a
599
+ tile's load error; a failed tile keeps `fill` until it leaves the window. `options.signal` aborts every load.
600
+ `dispose()` aborts the loads and disposes the terrain.
601
+ - Memory: the window's heightmap, a scratch copy and the CPU copy, 4 bytes a texel each (12 MB at 1,024 x 1,024), plus
602
+ three times 4 bytes a texel per weight texture. The window must fit the device's 2D texture limit.
603
+
604
+ Checked on a real GPU by `test/stream.browser.mjs` (in `test:gpu`) on nine adjacent Terrarium tiles around Mount
605
+ Rainier (`test/fixtures/terrarium-10`, Terrain Tiles on AWS), 256 x 256 each with weights made from their heights,
606
+ in a 2 x 2 window: through moves along +X, +Z, -X and -Z, a move inside the margin and teleports off the data and back,
607
+ the CPU copy, the GPU heightmap read back and the weights hold exactly the mosaic's texels for the expected tiles, the
608
+ streamed terrain draws exactly the pixels of a plain `Terrain` given that window whole, no frame uploads more than the
609
+ budget (16,384 texels: 17 frames for the first four tiles), and a stream disposed mid-load aborts it and rejects
610
+ `ready` with MargoError `'disposed'` (Radeon 680M). Cost not timed.
611
+
612
+ ## Sculpt and paint brushes: `@margoengine/terrain/sculpt`
613
+
614
+ `await TerrainSculpt.attach(engine, terrain, options?)` adds GPU brushes to any terrain, for in-game editors and level
615
+ tools: `raise`, `lower`, `smooth`, `flatten` and `paint` (layer weights), with undo and redo. The heightmap must be
616
+ `r32float` and the weight textures (for `paint`) `rgba8unorm`, created with usage 15 (`TEXTURE_BINDING |
617
+ STORAGE_BINDING | COPY_SRC | COPY_DST`); attaching reads them back once into the CPU copies `heights` and `weights`.
618
+
619
+ ```ts
620
+ import {Engine} from 'margoengine/core';
621
+ import {Terrain} from 'margoengine/terrain';
622
+ import {TerrainSculpt} from 'margoengine/terrain/sculpt';
623
+ import {TerrainQuery} from 'margoengine/terrain/query';
624
+ const engine = await Engine.create(document.querySelector('canvas')!);
625
+ const n = 257, heights = new Float32Array(n * n);
626
+ const terrain = Terrain.attach(engine, {
627
+ size: [256, 256], origin: [-128, -128], heightScale: 1,
628
+ layers: [0, 1, 2, 3].map(() => ({height: [-100, 100] as [number, number], slope: [0, 1] as [number, number], scale: 0.25})),
629
+ textures(device) {
630
+ const heightmap = device.createTexture({size: [n, n], format: 'r32float', usage: 15});
631
+ device.queue.writeTexture({texture: heightmap}, heights, {bytesPerRow: n * 4}, [n, n]);
632
+ const weight = device.createTexture({size: [n, n], format: 'rgba8unorm', usage: 15});
633
+ device.queue.writeTexture({texture: weight}, new Uint8Array(n * n * 4).map((_, i) => (i % 4 ? 0 : 255)), {bytesPerRow: n * 4}, [n, n]);
634
+ const layers = device.createTexture({size: [1, 1, 4], format: 'rgba8unorm-srgb', usage: 6});
635
+ device.queue.writeTexture({texture: layers}, new Uint8Array(16).fill(140), {bytesPerRow: 4, rowsPerImage: 1}, [1, 1, 4]);
636
+ return {heightmap, layers, weights: [weight, weight]};
637
+ },
638
+ });
639
+ const sculpt = await TerrainSculpt.attach(engine, terrain, {radius: 12, strength: 0.5});
640
+ const ground = new TerrainQuery(sculpt.heights, sculpt.columns, sculpt.rows, terrain.options);
641
+ sculpt.onChange((c) => { if (c.weights === undefined) ground.refresh(c.u, c.v, c.width, c.depth); });
642
+ {
643
+ using stroke = sculpt.stroke({brush: 'raise', amount: 4}); // one undo step
644
+ for (let x = -40; x <= 40; x += 4) sculpt.dab(x, 0);
645
+ }
646
+ sculpt.dab(0, 20, {brush: 'paint', layer: 2, radius: 16}); // a dab is a stroke of its own
647
+ sculpt.dab(10, 10, {brush: 'flatten', height: 2});
648
+ await sculpt.undo(); // the flatten
649
+ await sculpt.flush(); // heights and the query hold every finished stroke
650
+ console.log(ground.height(0, 0));
651
+ engine.start();
652
+ ```
653
+
654
+ - Brushes: `raise` and `lower` move heights by `amount` world units (default a tenth of `radius`) times the brush
655
+ weight; `smooth` moves them toward the 5 x 5 binomial blur of the ground under the brush (Burt and Adelson's
656
+ [1 4 6 4 1] filter), `flatten` toward `height` (default the height under the stroke's first dab), `paint` the
657
+ weights toward `layer` (the other layers fall, so the shares still add up). The weight is `strength` (0 to 1,
658
+ default 0.5) times the falloff of the distance over `radius` (world units, default 8): `smooth` (default) is
659
+ Wendland's (1 - t)^4 (4t + 1), `linear` and `constant` as named.
660
+ - Each dab is one compute pass over the texels under the brush (a copy with a 2 texel border is read, the terrain's
661
+ texture written), on the GPU, at once; the terrain's shadow is invalidated.
662
+ - `stroke(options?)` groups dabs into one undo step (`using`, or call `end()`); `undoLimit` strokes are kept (default
663
+ 32), each as the changed rectangle's values before and after it, so `undo()` and `redo()` are exact. A new stroke
664
+ clears the redo steps. Await `undo()` before the next dab.
665
+ - `heights` and `weights` follow the GPU when a stroke's rectangle has been read back (`await flush()`); `onChange`
666
+ reports each rectangle they take, for a `TerrainQuery` built on `heights` (refresh it there).
667
+ - After device restoration the CPU copies, edits included, are written into the terrain's new textures.
668
+ - Memory: the CPU copies (4 bytes a texel each), the scratch copy of the largest dab, and per kept stroke its
669
+ rectangle's values twice.
670
+
671
+ Checked on a real GPU by `test/sculpt.browser.mjs` (in `test:gpu`) on the Mount Rainier tile (256 x 256 texels 100 m
672
+ apart) with painted weights (Radeon 680M): raise, lower, smooth and flatten dabs match the brush formulas worked on the
673
+ CPU to 0.14 mm inside the brush and leave every texel outside it exactly as it was; a 30-dab smoothing stroke cuts the
674
+ ground's squared Laplacian there by 96%; full-strength paint sets the layer exactly and soft paint is within one 8-bit
675
+ step of the formula; after every stroke the CPU copy equals the GPU read back and a `TerrainQuery` refreshed from
676
+ `onChange` (height and a ray cast) answers the raised ground; undoing all 8 strokes gives back the original heightmap,
677
+ weights and picture exactly, and redoing them the edited ones; a heightmap without storage usage is refused. Cost not
678
+ timed.
679
+
680
+ ## Holes and cutouts: `@margoengine/terrain/holes`
681
+
682
+ `TerrainTextures.holes` takes a mask over the heightmap's bounds (`r8unorm` or `rgba8unorm`, a texel per cell); where
683
+ its R is below 0.5 the terrain draws nothing, in its colour, SSR capture, shadow and occluder passes alike, so caves,
684
+ tunnels, basements and mine entrances pass through the ground and light falls through them. `TerrainHoles` makes and
685
+ edits that mask on the CPU, by cell centre: `circle`, `rect` and `polygon` (even-odd rule) cut, or fill with
686
+ `hole: false`; `texture(device)` makes the texture for the factory and `upload(terrain)` sends later cuts.
687
+ `TerrainQuery` takes the same mask as its `holes` option: no height or normal there, and rays pass through.
688
+
689
+ ```ts
690
+ import {Engine} from 'margoengine/core';
691
+ import {Terrain} from 'margoengine/terrain';
692
+ import {TerrainHoles} from 'margoengine/terrain/holes';
693
+ import {TerrainQuery} from 'margoengine/terrain/query';
694
+ const engine = await Engine.create(document.querySelector('canvas')!);
695
+ const n = 129, heights = new Float32Array(n * n).fill(0.05);
696
+ const options = {size: [128, 128] as [number, number], origin: [-64, -64] as [number, number], heightScale: 20};
697
+ const holes = new TerrainHoles(options, n - 1); // one mask cell per heightmap cell
698
+ holes.circle(10, -5, 6).polygon([[-30, 20], [-20, 20], [-25, 30]]);
699
+ const terrain = Terrain.attach(engine, {
700
+ ...options,
701
+ layers: [0, 1, 2, 3].map(() => ({height: [-100, 100] as [number, number], slope: [0, 1] as [number, number], scale: 0.25})),
702
+ textures(device) {
703
+ const heightmap = device.createTexture({size: [n, n], format: 'r32float', usage: 6});
704
+ device.queue.writeTexture({texture: heightmap}, heights, {bytesPerRow: n * 4}, [n, n]);
705
+ const layers = device.createTexture({size: [1, 1, 4], format: 'rgba8unorm-srgb', usage: 6});
706
+ device.queue.writeTexture({texture: layers}, new Uint8Array(16).fill(140), {bytesPerRow: 4, rowsPerImage: 1}, [1, 1, 4]);
707
+ return {heightmap, layers, holes: holes.texture(device)};
708
+ },
709
+ });
710
+ const ground = new TerrainQuery(heights, n, n, {...options, holes});
711
+ console.log(ground.height(10, -5)); // undefined: a hole
712
+ holes.rect(30, 30, 40, 36); // a basement, cut later
713
+ holes.upload(terrain);
714
+ engine.start();
715
+ ```
716
+
717
+ - A mask cell covers the bounds split evenly into the mask's width by height, so one per heightmap cell
718
+ (`columns - 1` by `rows - 1`) cuts the ground cell by cell; any size works. Hole edges follow the cells, not the
719
+ triangles, so a hole's rim is exact on the drawn surface.
720
+ - `TerrainQuery` reads the mask live (no refresh after a cut). A ray that meets a hole cell passes on to the next
721
+ ground it meets; with a mask finer than the heightmap's cells, a cell hit inside a hole is skipped whole.
722
+ - Without `holes` every shader and binding is as it was. With it, one texel load and a compare a fragment in each
723
+ pass; the mask binds after the weights and tint.
724
+
725
+ Checked on a real GPU by `test/holes.browser.mjs` (in `test:gpu`) on the Mount Rainier tile (Radeon 680M): a mask
726
+ with no hole draws exactly the terrain without one and a mask of all holes exactly no terrain, alone and with SSR on;
727
+ a 3 km crater shows the empty scene's pixels through it; a flat roof 50 m over flat ground, sun overhead, lets the
728
+ ground under its hole be lit exactly as with no roof, while a slanted sun shades the hole's far edge; an all-hole
729
+ occluder writes no depth; a cut sent with `upload` draws as one made before attaching. The node tests check the
730
+ bindings and that the colour, shadow and occluder shaders each declare and test the mask, and that queries skip holes.
731
+
732
+ ## Erosion: `erode` from `@margoengine/biomes/erosion`
733
+
734
+ Weathered ground needs no terrain entry of its own: `erode(grid, options)` in `@margoengine/biomes/erosion` erodes
735
+ any height grid (integer millimetres, so the same heights and options give the same bytes on every machine): thermal
736
+ erosion slides material down slopes steeper than the angle of repose (`talus`, default 35 degrees) into scree, and
737
+ hydraulic erosion lets every cell's water run to an outlet, cutting gullies where a flow can carry more than it holds
738
+ and dropping the excess where its slope eases, in fans at the foot of slopes. It is deterministic: noise you generate
739
+ from a seed erodes to the same ground every time. Convert a terrain's heights to millimetres, erode, and upload:
740
+
741
+ ```ts
742
+ import {Engine} from 'margoengine/core';
743
+ import {Terrain} from 'margoengine/terrain';
744
+ import {erode} from 'margoengine/biomes/erosion';
745
+ const engine = await Engine.create(document.querySelector('canvas')!);
746
+ const n = 129, size = 1280, heightScale = 400; // 10 m cells, heights 0..1 times 400 m
747
+ let seed = 7;
748
+ const random = () => (seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0) / 2 ** 32;
749
+ const heights = new Float32Array(n * n).map((_, i) =>
750
+ Math.max(0, 1 - Math.hypot(i % n - 64, Math.floor(i / n) - 64) / 50) + random() * 0.01);
751
+ const eroded = erode(
752
+ {height: Int32Array.from(heights, (h) => Math.round(h * heightScale * 1000)), nx: n, nz: n, step: (size / (n - 1)) * 1000},
753
+ {iterations: 64, talus: 35, capacity: 0.05},
754
+ );
755
+ const weathered = Float32Array.from(eroded.height, (mm) => mm / 1000 / heightScale);
756
+ Terrain.attach(engine, {
757
+ size: [size, size], origin: [-size / 2, -size / 2], heightScale, cellSize: 5,
758
+ layers: [0, 1, 2, 3].map(() => ({height: [-1e4, 1e4] as [number, number], slope: [0, 1] as [number, number], scale: 0.05})),
759
+ textures(device) {
760
+ const heightmap = device.createTexture({size: [n, n], format: 'r32float', usage: 6});
761
+ device.queue.writeTexture({texture: heightmap}, weathered, {bytesPerRow: n * 4}, [n, n]);
762
+ const layers = device.createTexture({size: [1, 1, 4], format: 'rgba8unorm-srgb', usage: 6});
763
+ device.queue.writeTexture({texture: layers}, new Uint8Array(16).fill(140), {bytesPerRow: 4, rowsPerImage: 1}, [1, 1, 4]);
764
+ return {heightmap, layers};
765
+ },
766
+ });
767
+ engine.start();
768
+ ```
769
+
770
+ `eroded.wear` and `eroded.deposit` (mm a cell) make good painted weights: rock where it wore, gravel or mud where it
771
+ filled. On a 1.3 km cone of 10 m cells with seeded noise (run on the CPU, 2026-11-07): 64 rounds took the steepest
772
+ slope from tan 1.19 to 0.89 toward the talus slope's 0.70 (scree), hydraulic erosion alone (`thermal: 0, capacity:
773
+ 0.05`) raised the relief across the slope (height spread around rings of the cone) from 0.86 m to 6.6 m (gullies), with the defaults the
774
+ foot of the cone took 6.4 m of deposit on average against 0.07 m on the far plain (fans), and two runs gave the same
775
+ bytes. It runs on the CPU (in a worker if you like); a GPU port would be a second erosion with float results that
776
+ differ by GPU.
777
+
778
+ ## Runtime virtual texture: `@margoengine/terrain/rvt`
779
+
780
+ `TerrainVirtualTexture.attach(engine, terrain, options)` bakes the terrain's blended ground colour, with decals and
781
+ roads on top, into a cache around the camera: clipmap levels of `size` texels, the finest `texel` wide and each next
782
+ twice as coarse, addressed toroidally, so a camera move bakes only the rows and columns it exposes and a still frame
783
+ bakes nothing. The terrain's lit shader then reads its ground from the cache, one or two samples a pixel whatever the
784
+ number of layers and decals, and draws with its own shader only where the cache does not reach or the ground is
785
+ steeper than `steep` (the cache is baked top down). The coarsest level reaches `(size / 2 - 2) * texel *
786
+ 2^(levels - 1)` along X or Z (1,632 m at 1,024 texels of 5 cm and 7 levels); the cache fades into the terrain's own
787
+ shader over the outer 29% of that reach (batch 132b, 2026-11-11: it used to fade from half the reach, so the outer half
788
+ of the coarsest level was baked and never read). `declarations(group, binding)` and `entries(binding)` let any
789
+ other material read the ground under it (`terrainVirtualColor(position, footprint)`), to blend a rock or a path into
790
+ the terrain.
791
+
792
+ ```ts
793
+ import {Engine} from 'margoengine/core';
794
+ import {Terrain} from 'margoengine/terrain';
795
+ import {TerrainVirtualTexture} from 'margoengine/terrain/rvt';
796
+ const engine = await Engine.create(document.querySelector('canvas')!);
797
+ const n = 129, heights = new Float32Array(n * n).map((_, i) => 0.02 * Math.sin(i % n / 9) + 0.02 * Math.cos(i / n / 7));
798
+ const terrain = Terrain.attach(engine, {
799
+ size: [512, 512], origin: [-256, -256], heightScale: 100,
800
+ layers: [0, 1, 2, 3].map((i) => ({height: [-100 + i, 100] as [number, number], slope: [0, 1] as [number, number], scale: 0.25})),
801
+ textures(device) {
802
+ const heightmap = device.createTexture({size: [n, n], format: 'r32float', usage: 6});
803
+ device.queue.writeTexture({texture: heightmap}, heights, {bytesPerRow: n * 4}, [n, n]);
804
+ const layers = device.createTexture({size: [1, 1, 4], format: 'rgba8unorm-srgb', usage: 6});
805
+ device.queue.writeTexture({texture: layers}, new Uint8Array(16).fill(140), {bytesPerRow: 4, rowsPerImage: 1}, [1, 1, 4]);
806
+ return {heightmap, layers};
807
+ },
808
+ });
809
+ const ground = TerrainVirtualTexture.attach(engine, terrain, {
810
+ texel: 0.05, size: 1024, levels: 6,
811
+ decals(device) { // layer 0 a puddle, layer 1 a road surface
812
+ const pictures = device.createTexture({size: [1, 1, 2], format: 'rgba8unorm-srgb', usage: 6});
813
+ device.queue.writeTexture({texture: pictures}, new Uint8Array([40, 50, 60, 200, 70, 70, 70, 255]),
814
+ {bytesPerRow: 4, rowsPerImage: 1}, [1, 1, 2]);
815
+ return pictures;
816
+ },
817
+ });
818
+ ground.addDecal({center: [12, 30], size: [6, 4], angle: 0.3, layer: 0});
819
+ ground.road([[-40, 0], [0, 20], [50, 25]], 5, {layer: 1});
820
+ ground.invalidate(-20, -20, 20, 20); // after sculpting or painting there
821
+ engine.start();
822
+ ```
823
+
824
+ On a Radeon 680M, on the real Mount Rainier tile under four layers of real rock (levels of 1,024 texels, 7 levels,
825
+ a 160 by 160 view, 2026-11-07): the cached ground drew within 0.33 of 255 of the terrain's own shader on average
826
+ (99th percentile 2, worst 5); a camera that moved there over four frames drew exactly what a cache made there drew, a
827
+ still frame baked nothing and a one-texel move baked one 1,024-texel strip; a 14 m decal laid later showed red on 240
828
+ pixels with no change more than 2 pixels from it, and removing it restored the picture exactly; a compute pass reading
829
+ through `declarations` and `entries` saw the decal's red at its centre and no coverage past the cache. Cost not timed.
830
+
831
+ - Memory: `size * size * levels` texels, 4 bytes each (`rgba8unorm-srgb`) or 8 (`rgba16float`): 24 MiB at the
832
+ defaults. The first frame bakes every level whole; later frames bake the texels a move exposes plus invalidated
833
+ areas.
834
+ - The cache holds colour only: not with `TerrainMaterials` (whose normals and roughness come from the layer loop it
835
+ replaces); `bump` relief shows only where the terrain's own shader draws. SSR's capture keeps the terrain's own
836
+ colour. Edits to heights, weights, tint or streamed tiles show after `invalidate(area)`.
837
+ - Decals (up to 4,096) are baked in the order added, each over its rectangle; a road is a decal a segment, so sharp
838
+ bends leave a gap on their outer side.
839
+
840
+ ## Near displacement and parallax: `@margoengine/terrain/displace`
841
+
842
+ `TerrainDisplacement.attach(engine, terrain, materials, options)` gives ground near the camera the depth of its layer
843
+ height maps (the `surface` maps' alpha that `TerrainMaterials` binds): each pixel within `distance` walks its view ray
844
+ down through the relief (parallax occlusion mapping), and the terrain shades the point the ray hits, so pebbles hide
845
+ the ground behind them and cracks look deep. With `shadows` (the default) the relief also shadows itself from the sun:
846
+ a ray from the hit toward the sun runs through a maximum mipmap of the height maps, passing over every square of the
847
+ map whose highest point stays under it, so no thin ridge is stepped over. A pixel that spans several texels of the
848
+ finest layer traces up to 4 by 4 such rays over its footprint and takes their mean, so far relief shows the share of
849
+ its area in sunlight rather than aliasing on whichever texel its centre lands. No geometry moves: the ground's outline
850
+ against the sky stays the clipmap's.
851
+
852
+ ```ts
853
+ import {Engine} from 'margoengine/core';
854
+ import {Terrain} from 'margoengine/terrain';
855
+ import {TerrainMaterials} from 'margoengine/terrain/layers-pbr';
856
+ import {TerrainDisplacement} from 'margoengine/terrain/displace';
857
+ const engine = await Engine.create(document.querySelector('canvas')!);
858
+ // Four 2 x 2 layers here; use your layers' full-size maps (square, a power of two in size for shadows).
859
+ function array(device: GPUDevice, rgba: (i: number) => number[]) {
860
+ const texture = device.createTexture({size: [2, 2, 4], format: 'rgba8unorm', usage: 6});
861
+ const data = new Uint8Array(Array.from({length: 16}, (_, i) => rgba(i % 4)).flat());
862
+ device.queue.writeTexture({texture}, data, {bytesPerRow: 8, rowsPerImage: 2}, [2, 2, 4]);
863
+ return texture;
864
+ }
865
+ const terrain = Terrain.attach(engine, {
866
+ size: [128, 128], origin: [-64, -64], heightScale: 20,
867
+ layers: [0, 1, 2, 3].map(() => ({height: [-100, 100] as [number, number], slope: [0, 1] as [number, number], scale: 0.5})),
868
+ textures(device) {
869
+ const heightmap = device.createTexture({size: [2, 2], format: 'r32float', usage: 6});
870
+ device.queue.writeTexture({texture: heightmap}, new Float32Array(4), {bytesPerRow: 8}, [2, 2]);
871
+ const layers = device.createTexture({size: [1, 1, 4], format: 'rgba8unorm-srgb', usage: 6});
872
+ device.queue.writeTexture({texture: layers}, new Uint8Array(16).fill(150), {bytesPerRow: 4, rowsPerImage: 1}, [1, 1, 4]);
873
+ return {heightmap, layers};
874
+ },
875
+ });
876
+ const materials = TerrainMaterials.attach(engine, terrain, {
877
+ textures: (device) => ({
878
+ normals: array(device, () => [128, 128, 255, 255]),
879
+ surface: array(device, (texel) => [255, 230, 0, texel === 0 ? 255 : 40]), // one raised stone in four
880
+ }),
881
+ });
882
+ TerrainDisplacement.attach(engine, terrain, materials, {
883
+ depth: 0.05, // world depth from height 1 to 0 (per layer: layers: [{depth}])
884
+ distance: 30, // shown within 30 m, fading over the last quarter
885
+ steps: 24, // most view-ray steps a pixel takes
886
+ shadows: true,
887
+ });
888
+ engine.start();
889
+ ```
890
+
891
+ Checked on a real GPU by `test/displace.browser.mjs` (in `test:gpu`), on Poly Haven's CC0 Aerial Rocks 02 maps (one
892
+ 4 m repeat of 1,024 texels, Radeon 680M, 2026-11-08): seen from 0.35 m at a slant with 10 cm of relief, the parallax
893
+ picture was 3.07 of 255 from the same rock built as real geometry (a terrain whose heightmap is the displacement map,
894
+ on a 4 mm clipmap), the flat one 24.5; depth 0 and a reach short of the view drew the flat picture exactly; painted
895
+ weights drew the same rock. Seen from straight above under a 14 degree sun, with white, flat materials and no ambient
896
+ light, the share of the ground in shadow was 2.71% against 2.76% from a CPU trace of the same relief at 10 cm deep, and
897
+ 30.7% against 30.85% at 30 cm; the shadowed pixels overlapped the CPU's by 0.57 and 0.56 (union), the rest being
898
+ texels finer than a pixel. There a pixel spans about 6.7 texels; against the share of each pixel's area a CPU trace
899
+ finds lit (4 by 4 traces a pixel), the mean per-pixel error is 0.109 at 30 cm and 0.0125 at 10 cm (one ray from the
900
+ pixel's centre: 0.176 and 0.024). Cost not timed.
901
+
902
+ - Relief: the layers' heights blended by the terrain's weights with the materials' `heightBlend`, from the top
903
+ projection only, on ground no steeper than about 57 degrees (fading out from about 32); cliffs stay flat. The view
904
+ ray reads the height maps' mipmaps at the pixel's footprint; the shadow ray reads the full-size map.
905
+ - Shadows: soft over about 1.1 degrees either side of the relief's horizon; a ray takes at most 160 steps through the
906
+ mipmap (squares passed over, descended into or tested) and counts what it has not reached as lit. Where layers of
907
+ different `scale` overlap, the mipmap of the finest decides the squares and the coarser ones are bounded by up to
908
+ four of their own texels. They need square surface maps a power of two in size (`'unsupported'` otherwise; pass
909
+ `shadows: false`) and add an `r32float` maximum mipmap: 4 bytes a texel a layer plus a third, about 21 MiB for four
910
+ 1,024-texel layers.
911
+ - Attach it after `TerrainMaterials`, before any effect that replaces the terrain's lit shader. `shadows` darkens the
912
+ sun's light only, not ambient or image-based light.
913
+ - Shadow maps: with `@margoengine/shadows` (`Shadows` or `VirtualShadows`, attached before or after the displacement)
914
+ objects' sun shadows fall on the relief. The maps hold the clipmap surface, the relief's top, so each point reads
915
+ them where its ray toward the sun leaves that surface: the relief is not shadowed by its own ground (checked on a
916
+ real GPU by `test/displace-shadows.browser.mjs`: none of the lit relief darkened; before, 95.2% did), and an object
917
+ sitting within the relief's depth does not shadow it. The relief casts no shadow onto other objects.
918
+
919
+ ## Wind-built dunes: `@margoengine/terrain/dunes`
920
+
921
+ `duneField(options)` returns the heights of a dune field (a `Float32Array`, `width` heights a row, `depth` rows, in
922
+ metres) to feed a `Terrain` heightmap or a `BiomeWorld`'s `height.samples`. Each dune has a long gentle windward side
923
+ whose steepest slope is `stoss` and a short slip face at the angle of repose `lee`, the profile measured on real
924
+ dunes: a 5 m dune is about 37 m from its windward toe to the crest and 8 m from the crest to the foot of its face.
925
+ `transverse` lays ridges across the wind every `spacing` metres, their crests wandering and varying in height
926
+ (`irregularity`); a ridge too high for its spacing is lowered so it fits. `barchan` lays isolated crescents, about 11
927
+ heights wide, with their horns trailing downwind and some cells left bare where sand is short. `base` builds the dunes on
928
+ ground you already have (real heights, a beach), and `amount(x, z)` (0 to 1) keeps them off wet sand or a launch flat.
929
+
930
+ ```ts
931
+ import {duneField, duneLengths, slopeAt} from 'margoengine/terrain/dunes';
932
+ const heights = duneField({width: 256, depth: 256, cellSize: 1, type: 'transverse', height: 5, spacing: 70, wind: 90, seed: 2});
933
+ console.log(heights.length, duneLengths(5).stoss.toFixed(1), slopeAt(heights, 256, 128, 128).toFixed(1)); // 65536 37.0 ...
934
+ ```
935
+
936
+ | Option | Default | Meaning |
937
+ | --- | --- | --- |
938
+ | `width`, `depth` | required | heights along x and z (2 or more each, at most 67,108,864 in all) |
939
+ | `cellSize` | 1 | metres between heights |
940
+ | `origin` | [0, 0] | world x and z of the first height |
941
+ | `wind` | 90 | degrees from +x toward +z that the wind blows toward; slip faces face downwind |
942
+ | `type` | `'transverse'` | `'transverse'` ridges (plenty of sand) or `'barchan'` crescents (scarce sand), Werner 1995 |
943
+ | `height` | 4 | crest height in metres |
944
+ | `spacing` | 70 | crest-to-crest spacing (transverse) or the cell each barchan stands in, metres |
945
+ | `stoss` | 12 | steepest windward slope, 3 to 20 degrees |
946
+ | `lee` | 32 | slip face, the angle of repose of dry sand, 25 to 36 degrees |
947
+ | `irregularity` | 0.35 | 0 to 1: crest wander, height variation, bare cells and low hummocks between dunes |
948
+ | `seed` | 1 | the same seed gives the same heights on every machine |
949
+ | `base` | flat 0 | heights to build on, the grid's layout (not changed) |
950
+ | `amount` | 1 | `(x, z) => 0..1`, the share of dune height at each point |
951
+ | `round` | 0 | metres over which each brink is rounded; 0 keeps a sharp brink |
952
+
953
+ `duneHill(x, z, {crest, height, wind, halfWidth, stoss, lee, round})` is the height of one big isolated dune, such as
954
+ a coastal hill built by one main wind: a long windward side at `stoss` (default 12 degrees), a crest rounded over
955
+ `round` metres (default a third of the height), a lee face at `lee` (default 30 degrees, a settled face) and a crest
956
+ that falls off as a raised cosine to `halfWidth` across the wind (default 5 heights). Add it to a field or to real
957
+ heights:
958
+
959
+ ```ts
960
+ import {duneHill} from 'margoengine/terrain/dunes';
961
+ const hill = {crest: [0, 0] as [number, number], height: 30, wind: 90, stoss: 12, lee: 30};
962
+ console.log(duneHill(0, 0, hill).toFixed(1), duneHill(0, -100, hill).toFixed(1), duneHill(0, 40, hill).toFixed(1)); // crest, windward, lee
963
+ ```
964
+
965
+ `duneProfile(p, height, tanStoss, tanLee, toe, round)` is one dune's height `p` metres downwind of its windward toe, `duneLengths`
966
+ its windward and lee lengths, `barchan(u, v, height, tanStoss, tanLee)` one crescent around its crest, and
967
+ `slopeAt(heights, width, i, j, cellSize)` the steepest slope at a height in degrees. Aeolian ripples (5 to 20 cm,
968
+ Anderson 1987) are far finer than a terrain cell and belong in the sand material's relief, not the height field. Plain
969
+ JavaScript with no GPU and no dependency; the dunes do not move (no saltation or avalanche simulation in v1.0.0,
970
+ docs/limits.md).
971
+
972
+ Sources: Bagnold 1941, *The Physics of Blown Sand and Desert Dunes* (London, 1941), slip faces at the angle of repose;
973
+ Sauermann, Kroy and Herrmann 2001, "Continuum saltation model for sand dunes", Phys. Rev. E 64, 031305
974
+ (https://doi.org/10.1103/PhysRevE.64.031305), and Kroy, Sauermann and Herrmann 2002, "Minimal model for sand dunes", Phys.
975
+ Rev. Lett. 88, 054301 (https://doi.org/10.1103/PhysRevLett.88.054301), the convex windward profile and the brink at the
976
+ crest; Hersen, Douady and Andreotti 2002, "Relevant length scale of barchan dunes", Phys. Rev. Lett. 89, 264301
977
+ (https://doi.org/10.1103/PhysRevLett.89.264301), barchan width in proportion to height; Andreotti, Claudin and Douady 2002,
978
+ "Selection of dune shapes and velocities", Eur. Phys. J. B 28, 321 (https://doi.org/10.1140/epjb/e2002-00236-4), sinuous
979
+ crests; Werner 1995, "Eolian dunes: computer simulations and attractor interpretation", Geology 23(12), 1107
980
+ (https://doi.org/10.1130/0091-7613(1995)023<1107:EDCSAA>2.3.CO;2), ridges against crescents by sand supply; Anderson 1987,
981
+ "A theoretical model for aeolian impact ripples", Sedimentology 34, 943 (https://doi.org/10.1111/j.1365-3091.1987.tb00814.x).
982
+
983
+ ## Stored height grids: `@margoengine/terrain/height-grid`
984
+
985
+ `gridHeightField(options)` turns a height grid you already have (a USGS 3DEP or SRTM tile read from a GeoTIFF, a decoded
986
+ heightmap, any row-major numbers) into the `(x, z) => height` function that `heightfield`, `heightfieldGeometry` and
987
+ `TerrainHeightmap` take. It reads bilinearly between texels over the grid's real ground size, holds the edge heights
988
+ outside the box, and fills missing samples (NaN, or the file's no-data value such as -32768 or -999999) before the first
989
+ read. The function also carries `min`, `max`, `origin`, `size` and `filled` (how many samples were missing).
990
+
991
+ ```ts
992
+ import {heightfield} from 'margoengine/terrain';
993
+ import {gridHeightField} from 'margoengine/terrain/height-grid';
994
+ const heights = new Float32Array([0, 1, 0, 1, 2, -999999, 0, 1, 0]); // 3 by 3, one missing sample
995
+ const ground = gridHeightField({width: 3, height: 3, heights, size: [300, 300], noData: -999999, exaggeration: 1.5});
996
+ console.log(ground(0, 0), ground.max, ground.filled); // 3 3 1
997
+ const mesh = heightfield(ground, {size: [300, 300], resolution: 96});
998
+ ```
999
+
1000
+ | Option | Default | Meaning |
1001
+ | --- | --- | --- |
1002
+ | `width`, `height` | required | texels across x and down z, integers 2 to 65,536 |
1003
+ | `heights` | required | `width * height` numbers, row-major; row 0 at the minimum z (the north edge of a north-up raster when north is -z), copied once |
1004
+ | `size` | required | real ground extent `[x, z]`, each above 0 to 100,000 |
1005
+ | `origin` | centred on 0 | world x and z of the minimum corner |
1006
+ | `exaggeration` | 1 | vertical scale applied to the samples |
1007
+ | `base` | 0 | added to every height after `exaggeration` |
1008
+ | `noData` | none | a sample value that means no data (compared as float32); NaN always does |
1009
+ | `fill` | `'nearest'` | what a missing sample becomes: a number (world height), `'nearest'` valid texel over the eight neighbours, `'min'` or `'mean'` of the valid heights; a grid with no valid sample needs a number |
1010
+ | `registration` | `'point'` | `'point'`: texel (0, 0) at the corner and the last at `origin + size`, as `Terrain` and `TerrainQuery` read heights; `'area'`: texels are cells centred half a cell in (GeoTIFF PixelIsArea) |
1011
+ | `flipRows` | false | row 0 at the maximum z (a south-up grid) |
1012
+
1013
+ Sources: bilinear interpolation, W. Press and others, Numerical Recipes, 3rd ed., 2007, section 3.6; no-data values,
1014
+ the GDAL raster data model (https://gdal.org/user/raster_data_model.html); PixelIsArea and PixelIsPoint, OGC GeoTIFF
1015
+ standard 1.1 (OGC 19-008r4); the nearest-valid sweep, A. Rosenfeld and J. Pfaltz, "Sequential operations in digital
1016
+ picture processing", Journal of the ACM 13(4), 1966. Our own code from those descriptions.
1017
+
1018
+ ## Footprints, tracks and trails: `@margoengine/terrain/deform`
1019
+
1020
+ `TerrainDeformation.attach(engine, terrain, options)` presses footprints, tyre tracks and trails into snow, mud and sand.
1021
+ Prints go into a deformation map of `size` texels a side, `texel` wide each, centred on the camera (or on what
1022
+ `follow` returns) and moved with it a texel at a time, so prints stay while they are within half its width; the
1023
+ ground pushed aside rises in a rim around each print; prints fill back in over `fade` seconds. The terrain's lit shader
1024
+ walks each near pixel's view ray down through the prints (parallax occlusion mapping) and shades the ground it meets,
1025
+ with the print's slope as its normal and darkened where it is pressed, so a footprint shows its walls and hides its far
1026
+ floor. No vertex moves: clipmap cells are far wider than a footprint.
1027
+
1028
+ ```ts
1029
+ import {Engine} from 'margoengine/core';
1030
+ import {Terrain} from 'margoengine/terrain';
1031
+ import {TerrainDeformation} from 'margoengine/terrain/deform';
1032
+ const engine = await Engine.create(document.querySelector('canvas')!);
1033
+ const terrain = Terrain.attach(engine, {
1034
+ size: [256, 256], origin: [-128, -128], heightScale: 10,
1035
+ layers: [0, 1, 2, 3].map(() => ({height: [-100, 100] as [number, number], slope: [0, 1] as [number, number], scale: 0.5})),
1036
+ textures(device) {
1037
+ const heightmap = device.createTexture({size: [2, 2], format: 'r32float', usage: 6});
1038
+ device.queue.writeTexture({texture: heightmap}, new Float32Array(4), {bytesPerRow: 8}, [2, 2]);
1039
+ const layers = device.createTexture({size: [1, 1, 4], format: 'rgba8unorm-srgb', usage: 6});
1040
+ device.queue.writeTexture({texture: layers}, new Uint8Array(16).fill(230), {bytesPerRow: 4, rowsPerImage: 1}, [1, 1, 4]);
1041
+ return {heightmap, layers};
1042
+ },
1043
+ });
1044
+ const snow = TerrainDeformation.attach(engine, terrain, {
1045
+ depth: 0.15, // deepest print, and a print's depth by default
1046
+ fade: 120, // seconds for a full-depth print to fill back in; 0 keeps prints
1047
+ rim: 0.25, // the rim's height as a share of the print's depth
1048
+ });
1049
+ for (let step = 0; step < 10; step++) // a walk along +X, left and right feet
1050
+ snow.footprint(step * 0.35, step % 2 ? 0.12 : -0.12, {angle: 0, depth: 0.08});
1051
+ snow.track([-5, 2], [5, 2.5], {width: 0.22}); // a tyre
1052
+ snow.trail([[0, -3], [1, -3.5], [2, -3.2]], {width: 0.5, depth: 0.04}); // a sledge
1053
+ engine.start();
1054
+ ```
1055
+
1056
+ - A print is pressed on the GPU at the next frame: a footprint is an ellipse (`length` 0.28 and `width` 0.11 by
1057
+ default, turned by `angle`), a track a band of `width` with round ends; the full depth reaches 55% of the way to
1058
+ the edge and falls smoothly to 0 there, and the rim peaks at 1.2 times the half size. Each texel keeps the deepest
1059
+ print over it. With painted `weights`, `layers` gives each layer's softness (rock 0 takes no print).
1060
+ - Defaults: `size` 1,024 texels of 2.5 cm (25.6 m), `depth` 0.15, `rim` 0.25, `fade` 120, `darken` 0.25,
1061
+ `distance` 40 (prints shown within, fading over the last quarter), `steps` 12.
1062
+ - Memory: 16 bytes a texel (the depths and rims, and the `rgba16float` relief `texture`): 16 MiB at the defaults.
1063
+ A frame with a print, a move or `fade` runs a compute pass over the map; a still frame with `fade: 0` runs none.
1064
+ - Prints the window leaves are gone when it comes back; device loss clears every print. The terrain's geometry,
1065
+ shadows and SSR capture do not see prints. Attach it after the terrain's other effects.
1066
+
1067
+ Checked on a real GPU by `test/deform.browser.mjs` (in `test:gpu`, Radeon 680M, 2026-11-08): a footprint and a track
1068
+ read back from the GPU are the profile above worked on the CPU to 0.06 mm (half-float storage) and its slopes to 0.1%;
1069
+ nothing pressed draws exactly the picture without deformation; seen from 0.6 m under a slanted sun, the deformed picture
1070
+ is 6.6 of 255 on average from the same prints built as real geometry (a terrain on a 4 mm clipmap whose heightmap is the
1071
+ read-back relief), the flat picture 33.3; a print fills back in by `depth / fade` a second of frame time (0.075, 0.050
1072
+ and 0 deep after 0.5, 1 and 2 s at 0.05 m a second); a 2 m move keeps it, a 12 m one clears it; a painted layer of
1073
+ softness 0 takes none. Cost not timed.
1074
+
1075
+ ## Ground that changes on screen: `@margoengine/terrain/ground-change`
1076
+
1077
+ `GroundChange.attach(engine, mesh, options)` changes a heightfield mesh's ground over film time: gullies cut back from
1078
+ their mouths, river banks retreat, scour holes deepen, slopes fail and run out, a flood leaves mud that dries, ash falls
1079
+ from a vent, lava flows and cools, and fire leaves a burn scar that whitens. Each event is a closed form of film time,
1080
+ so the ground at a time is the same whether a film is rendered in order, seeked to that time or rendered again. Each
1081
+ frame whose time moved recomputes only the vertices the active events can touch, writes their heights and normals into
1082
+ the mesh's own vertex buffer (so shadows and every other pass see the new shape) and lays the covers over the mesh's
1083
+ colour (after `TerrainColors`, if attached), with lava's glow added to its light.
1084
+
1085
+ ```ts
1086
+ import {Engine, PbrMaterial} from 'margoengine/core';
1087
+ import {heightfieldGeometry, TerrainColors} from 'margoengine/terrain';
1088
+ import {toGeometry} from 'margoengine/geometry/utils';
1089
+ import {GroundChange} from 'margoengine/terrain/ground-change';
1090
+ import {applyGroundChangeSettings} from 'margoengine/terrain/ground-change-settings';
1091
+ const engine = await Engine.create(document.querySelector('canvas')!);
1092
+ const grid = {size: [400, 400] as [number, number], origin: [-200, -200] as [number, number], resolution: 512};
1093
+ const hills = (x: number, z: number) => 0.05 * z + 4 * Math.sin(x * 0.02) * Math.cos(z * 0.015);
1094
+ const ground = engine.createMesh()
1095
+ .setGeometry(toGeometry(heightfieldGeometry(hills, grid)))
1096
+ .setMaterial(new PbrMaterial({color: [0.3, 0.26, 0.2], roughness: 0.9}));
1097
+ TerrainColors.attach(engine, ground);
1098
+ const change = GroundChange.attach(engine, ground, {
1099
+ grid, // the grid the mesh was built on
1100
+ events: [
1101
+ {kind: 'gully', path: [[-80, -120], [-60, -40], [-70, 30]], width: 6, depth: 2.5, duration: 40},
1102
+ {kind: 'bank', path: [[-200, 120], [200, 140]], river: 'left', retreat: 12, bed: 2, duration: 60},
1103
+ {kind: 'scour', center: [60, -20], radius: 8, depth: 3, flow: [0, 1], start: 10},
1104
+ {kind: 'slide', from: [120, 160], to: [140, 60], width: 30, depth: 4, start: 20},
1105
+ {kind: 'mud', shore: [[-200, -180], [200, -180]], land: 'right', reach: 250, thickness: 0.3, duration: 90},
1106
+ {kind: 'ash', vent: [150, -150], thickness: 0.08, half: 80, wind: [6, 2], start: 30, duration: 60},
1107
+ {kind: 'lava', path: [[150, -150], [100, -60], [40, -40]], width: 14, thickness: 2, start: 30, duration: 120},
1108
+ {kind: 'burn', ignition: [-120, 60], wind: [5, -1], rate: 0.6, start: 5, duration: 240},
1109
+ ],
1110
+ });
1111
+ applyGroundChangeSettings(change, {'lava.glow': 16, 'wet.rain': null}); // null: wet with the weather's rain
1112
+ change.setTime(45); // or let frames advance it
1113
+ engine.start();
1114
+ const {height, lava, heat} = change.sample(100, -60); // stand a person or a prop on it
1115
+ console.log(height, lava, heat);
1116
+ ```
1117
+
1118
+ On a clipmap `Terrain`, attach it to the terrain instead: the grid is the heightmap's texels, the changed heights are
1119
+ written into the heightmap itself (so every ring, the terrain's shadows and its normals show them), and the covers lie
1120
+ over `terrainColor` as a terrain lighting effect (after the terrain's other effects that replace its shader). The
1121
+ heightmap must be `r32float` with `COPY_SRC | COPY_DST` usage; its base is read back once (`await change.ready`).
1122
+
1123
+ ```ts
1124
+ import {Engine} from 'margoengine/core';
1125
+ import {Terrain} from 'margoengine/terrain';
1126
+ import {GroundChange} from 'margoengine/terrain/ground-change';
1127
+ const engine = await Engine.create(document.querySelector('canvas')!);
1128
+ const n = 513, heights = new Float32Array(n * n).map((_, k) => 0.02 * Math.floor(k / n));
1129
+ const terrain = Terrain.attach(engine, {
1130
+ size: [512, 512], origin: [-256, -256], heightScale: 1,
1131
+ layers: Array.from({length: 4}, () => ({height: [-1e4, 1e4] as [number, number], slope: [0, 1] as [number, number], scale: 0.1})),
1132
+ textures: (device) => {
1133
+ const heightmap = device.createTexture({size: [n, n], format: 'r32float', usage: 15}); // COPY_SRC | COPY_DST | ...
1134
+ device.queue.writeTexture({texture: heightmap}, heights, {bytesPerRow: n * 4}, [n, n]);
1135
+ const layers = device.createTexture({size: [1, 1, 4], format: 'rgba8unorm-srgb', usage: 6});
1136
+ device.queue.writeTexture({texture: layers}, new Uint8Array(16).fill(128), {bytesPerRow: 4, rowsPerImage: 1}, [1, 1, 4]);
1137
+ return {heightmap, layers};
1138
+ },
1139
+ });
1140
+ const change = GroundChange.attach(engine, terrain, { // grid left out: the heightmap's texels
1141
+ events: [{kind: 'lava', path: [[0, 0], [60, 120]], width: 20, thickness: 3, duration: 90}],
1142
+ });
1143
+ await change.ready; // the base heights are read back
1144
+ engine.start();
1145
+ ```
1146
+
1147
+
1148
+ default 0.3) and `seed`:
1149
+ - `gully` (`path` mouth first, `width` 4, `depth` 1.5, `shape` `'v'` or `'u'`, `deposit` 0.6 of the eroded volume
1150
+ left as a fan of radius `fan` below the mouth): the headcut climbs the path at a steady rate and the channel behind
1151
+ it deepens and widens toward its full section.
1152
+ - `bank` (`path`, `river` side, `retreat` 6, `bed` world Y, `face` 60 degrees): the land side retreats at a steady
1153
+ rate, cut down to the bed with its face at the angle.
1154
+ - `scour` (`center`, `radius` 5, `depth` 2, `flow`, `deposit` 0.5): depth grows as 1 - exp(-t / T) to the full depth
1155
+ at the end; with a `flow` the scoured sand forms a mound downstream.
1156
+ - `crater` (`center`, `radius` 30, `depth` 10, `heave` 0.4 depth, `heaveTime` sqrt(2 heave / g), `domeSpread` 1.3,
1157
+ `ejecta` 0.7, `duration` 6 s after the heave): a buried explosion. The ground first heaves into a dome
1158
+ `domeSpread` times the crater's radius, the surface thrown up ballistically to `heave` metres (1.43 s for 10 m);
1159
+ then the dome vents and the crater opens over `duration`, a paraboloid bowl of `radius` and `depth` with a lip at
1160
+ the rim and an ejecta blanket thinning as (r / R)^-3 (McGetchin et al. 1973) out to 5 R, holding `ejecta` of the
1161
+ bowl's volume. Pair it with `BlastCloud` of `margoengine/weather/eruption` for the cloud:
1162
+ `{kind: 'crater', center: [0, 0], radius: 120, depth: 30, heave: 20, start: 2}`.
1163
+ - `slide` (`from` crown, `to` toe, `width` 20, `depth` 3, `length` 40% of the way, `bulking` 1.15): the scar fails in
1164
+ the first third and the lobe runs out as a block under friction, holding the scar's volume times `bulking`.
1165
+ - `mud` (`shore`, `land` side, `reach` 400, `thickness` 0.25, `decay` reach / 3, `drying` 1,800 s): the front slows
1166
+ inland, the deposit thins by e every `decay` metres and dries by e every `drying` seconds after the water passes.
1167
+ - `ash` (`vent`, `thickness` 0.1, `half` 400, `wind`, `elongation` 1 + 0.25 wind speed): thickness halves every
1168
+ `half` metres of an isopach's crosswind half width, the isopachs stretched downwind; it falls at a steady rate.
1169
+ - `lava` (`path` vent first, `width` 12, `thickness` 2, `levee` 0.35, `cooling` 1, `glowCrust` 0.03): the front
1170
+ advances and slows, the sheet stands between levees, and its glow fades as the crust grows 0.0779 sqrt(hours) m
1171
+ (`cooling` real seconds per film second). With `arrival` (film seconds the front reaches each path point), and
1172
+ optionally `widths`, `thicknesses` and `glows` (one per point), the front follows those times instead and stops
1173
+ where they stop: `LavaFlow.lavaEvent()` of `margoengine/weather/lava` gives all four for a flow that runs down the
1174
+ slope. `pond` (`center`, `start`, `end`, `flux` m^3/s, `viscosity` Pa s, `density` 2,600) fills a pond where the
1175
+ flow can run no further: it spreads as Huppert's (1982) R = 0.715 (g Q^3 / (3 nu))^(1/8) t^(1/2) while fed and
1176
+ holds after `end`, its thickness H (1 - (r/R)^2)^(1/3) with H = Q t / (0.75 pi R^2), so it holds the volume fed
1177
+ into it (to 1 percent on a 0.5 m lattice in the tests), and its surface glows by the time since its edge passed;
1178
+ `lavaEvent()` gives it for a flow that ponds. `roofs` (film seconds, one per point, 1e9 for never) roofs the
1179
+ channel from each point into a lava tube: from the front's arrival to then a crust grows in from the levees
1180
+ (Peterson et al. 1994) until it closes level with their crests, and nothing under it glows; `lavaEvent()` gives
1181
+ them for a flow on gentle ground. `skylights` (metres, default 200, 0 for none) is the mean spacing of skylights
1182
+ in a closed roof (Kauahikaua et al. 1998): a hole 0.8 widths long and half a width across in three of four
1183
+ stretches of that length, at a seeded place, showing the stream half a sheet down, fresh until `drains` (film
1184
+ seconds per point, 1e9 for never) and crusting from then on.
1185
+ - `burn` (`ignition`, `wind`, `rate` 0.3 m/s, `severity` 1, `ashing` 900 s, `consume` 0.03 m): a wind ellipse grows
1186
+ with the head running `rate`, its length to breadth from the wind; char whitens to ash by e every `ashing` seconds.
1187
+ - Look (all live, `setLook` or the rows of `@margoengine/terrain/ground-change-settings`): `soil`, `mud`, `ash`,
1188
+ `char`, `ashen` and `lava` colours, `glow` 12, `cracks` 0.7, `crackSize` 0.8 m, `wetDarkening` 0.55, `wetGloss` 0.5,
1189
+ and `rain` (null: a `WeatherDrive` writes the weather's rain; a number holds it).
1190
+ - Time: frames add their delta, or `clock` returns a shot's time, or `setTime(t)`; `advanceTime(delta)` is the clock
1191
+ step `seek` from `@margoengine/cutscene/seek` replays. Pass `shadows` so a cached still shadow map re-renders when the
1192
+ ground moves.
1193
+ - CPU model alone: `new GroundChange({grid, base, events})`, then `setTime` and `update()`; `change`, `heights` and
1194
+ `covers` hold the grid, `sample(x, z, t)` the exact value anywhere, `onChange` reports each changed rectangle.
1195
+ - Plants follow the ground: spread `change.scatterGround()` into a `Scatter` or `GrassScatter`
1196
+ (`@margoengine/scatter`). Its `heightmap` holds base plus change in metres, so plants rise and sink with the ground;
1197
+ its `densityMap` keeps them where the ground keeps its own cover and clears them under fresh soil, mud, ash, char and
1198
+ lava (255 less the strongest cover byte), so a gully or slide scar is bare, mud, ash and lava bury them and a burn
1199
+ scar is burned clear as its front passes; `bounds` is the rectangle both cover. On a terrain, `await change.ready`
1200
+ before the first frame. Dispose the scatter before the change (the maps go with it). Plants left standing at the edge
1201
+ of a cover take its char, ash and mud through `change.plantCovers()` (`{covers, bounds}`, rgba8 mud, ash, char and
1202
+ wetness per grid vertex) as the `ground` source of a `PlantStates` map (`@margoengine/scatter/states`).
1203
+
1204
+ ```ts
1205
+ import {Engine, box} from 'margoengine/core';
1206
+ import {heightfieldGeometry} from 'margoengine/terrain';
1207
+ import {toGeometry} from 'margoengine/geometry/utils';
1208
+ import {GroundChange} from 'margoengine/terrain/ground-change';
1209
+ import {Scatter} from 'margoengine/scatter';
1210
+ const engine = await Engine.create(document.querySelector('canvas')!);
1211
+ const grid = {size: [48, 48] as [number, number], resolution: 96};
1212
+ const ground = engine.createMesh().setGeometry(toGeometry(heightfieldGeometry((x, z) => 0.05 * z, grid)));
1213
+ const change = GroundChange.attach(engine, ground, {
1214
+ grid,
1215
+ events: [{kind: 'burn', ignition: [-12, 0], rate: 0.25, duration: 60}],
1216
+ });
1217
+ Scatter.attach(engine, box(0.2, 0.8, 0.2), {count: 60000, area: [48, 48], ...change.scatterGround()});
1218
+ engine.start();
1219
+ ```
1220
+ - A terrain's heightmap must be `r32float` with `COPY_SRC` and `COPY_DST` (the read back and the writes); the grid is
1221
+ its texels over the terrain's `origin` and `size` (`resolution` may differ along X and Z). Each changed frame writes
1222
+ the changed texels (base plus change over `heightScale`) and invalidates the terrain's cached shadows; `dispose()` or
1223
+ `engine.removePlugin(change.name)` writes the read-back texels back exactly. Normals the terrain takes from a
1224
+ `normalmap` are tilted by the change's slope in the fragment shader. The terrain's CPU copies (`TerrainQuery`,
1225
+ `TerrainSculpt.heights`) keep the base: read heights from `change.sample`. Memory on the GPU: 12 bytes a texel.
1226
+ - The mesh must be a `heightfieldGeometry` on the same grid at the identity transform (any vertex order). The mesh's
1227
+ culling sphere grows over any raise past it, so ground lifted at the edge of a small mesh is never culled early.
1228
+ `dispose()` or `engine.removePlugin(change.name)` gives the mesh its base heights, normals and sphere back, on the GPU
1229
+ and in the CPU copy. Memory: 8 bytes of cover textures and 25 bytes of CPU grids a
1230
+ vertex (26 MiB at 1,024 cells a side).
1231
+
1232
+ Checked by `test/ground-change.test.js` against each law (Sumer's scour curve to 1e-9, Pyle's halving, Hon's crust,
1233
+ Alexander's length to breadth to 3%, volumes kept to 2 to 5%, the same grid whatever order the times come in) and on a
1234
+ real GPU by `test/ground-change.browser.mjs` (in `test:gpu`, WebGPU and `MARGO_COMPAT=1`, 2026-11-17): a gully and a
1235
+ scour drawn through GroundChange are 0.05 of 255 on average from a mesh built from the same final heights, the uncut
1236
+ ground 1.29; fresh lava glows orange (235, 132, 63), cooled lava is dark (33, 28, 25), ash greys and char blackens the
1237
+ ground; time 40 reached directly or in 1,200 steps draws the same pixels; `dispose` and `engine.removePlugin` draw the
1238
+ uncut ground exactly; lava 3 m thick at the edge of a 4 m mesh grows its culling sphere from 2.83 to 4.65 m, every
1239
+ vertex inside, and dispose puts 2.83 back. On a clipmap terrain (`test/ground-change-terrain.browser.mjs`, 129 x 129 texels 0.5 m
1240
+ apart, rings of 16 cells, WebGPU and `MARGO_COMPAT=1`): the heightmap holds base plus change exactly; the cut draws
1241
+ 0.016 of 255 on average from a terrain whose heightmap is the final heights (the uncut 1.0); lava glows (235, 131, 63)
1242
+ and cools to (33, 28, 25); with a normal map the tilted cut is 0.12 from a normal map of the cut ground (untilted
1243
+ 1.15); `dispose` and `engine.removePlugin` give every texel and pixel back. With a `Scatter` (`test/ground-change-scatter.browser.mjs`, both
1244
+ backends): its heightmap equals the changed heights exactly and its density map the cleared covers exactly; the burn
1245
+ scar and the lava draw no plants, the ground beside them 98 to 100% green.
1246
+ The whole-scene test page `examples/test-pages/ground-change.html` runs all eight kinds on one hillside with a weather
1247
+ drive (`node scripts/test-pages-browser.mjs --page=ground-change`). A changed frame recomputes the box around every
1248
+ active event on the CPU: 31 ms for 148,225 vertices with all eight active, measured once on a loaded dev PC.
1249
+ Sources: Mei, Decaudin and Hu 2007 (Pacific Graphics); Galin et al. 2019 (Computer Graphics Forum 38(2)); Bennett et
1250
+ al. 2000 (Water Resources Research 36(7)); Ikeda, Parker and Sawai 1981 (J. Fluid Mech. 112); Sumer, Fredsoe and
1251
+ Christiansen 1992 (J. Waterway, Port, Coastal and Ocean Eng. 118(1)); Heim 1932; Scheidegger 1973 (Rock Mechanics 5);
1252
+ Goto et al. 2011 (Marine Geology 290); Abe, Goto and Sugawara 2012 (Sedimentary Geology 282); Pyle 1989 (Bulletin of
1253
+ Volcanology 51); Hulme 1974 (Geophys. J. R. Astr. Soc. 39); Hon et al. 1994 (GSA Bulletin 106); Anderson 1983 (USDA
1254
+ INT-305); Alexander 1985 (8th Conf. Fire and Forest Meteorology); Key and Benson 2006 (USDA RMRS-GTR-164-CD).
1255
+
1256
+ ## Wet ground where a flood has been: `@margoengine/terrain/wet-ground`
1257
+
1258
+ `WetGround.attach(engine, terrain, {record, origin, size})` draws a clipmap `Terrain` darker and glossier wherever a
1259
+ wetting record says the water has been, and dries it back over time. The record is `Flood.wetTexture` of
1260
+ `margoengine/water/flood` (rgba32float, one texel a flood cell: green the seconds since the cell was last wet above
1261
+ 1 cm, blue 1 once it has been wet), read every frame, so the wet ground follows each tick, seek and device restore of
1262
+ the flood. A cell's wetness is `exp(-seconds since wet / dryTime)`; fully wet ground has `darkening` of the dry albedo
1263
+ (Lekner and Dorf 1988, https://doi.org/10.1364/AO.27.001278) and `1 - gloss` of the roughness, so the sun's highlight
1264
+ sharpens. It is a terrain lighting effect, so it composes with `GroundChange`, shadows and lights.
1265
+
1266
+ ```ts
1267
+ import {Engine} from 'margoengine/core';
1268
+ import {Terrain} from 'margoengine/terrain';
1269
+ import {WetGround, applyWetGroundSettings} from 'margoengine/terrain/wet-ground';
1270
+ import {Water} from 'margoengine/water';
1271
+ import {Flood} from 'margoengine/water/flood';
1272
+ const engine = await Engine.create(document.querySelector('canvas')!, {
1273
+ backend: 'webgpu',
1274
+ camera: {position: [0, 30, 40], target: [0, 0, 0], near: 0.5, far: 1000},
1275
+ });
1276
+ // A street 64 m square falling gently east, and 1 m of water held west of x = -20 m that breaks loose.
1277
+ const n = 129, heights = new Float32Array(n * n).map((_, k) => 1 - 0.01 * (k % n));
1278
+ const terrain = Terrain.attach(engine, {
1279
+ size: [64, 64], origin: [-32, -32], heightScale: 1, cellSize: 0.5,
1280
+ layers: Array.from({length: 4}, () => ({height: [-1e4, 1e4] as [number, number], slope: [0, 1] as [number, number], scale: 0.1})),
1281
+ textures: (device) => {
1282
+ const heightmap = device.createTexture({size: [n, n], format: 'r32float', usage: 15});
1283
+ device.queue.writeTexture({texture: heightmap}, heights, {bytesPerRow: n * 4}, [n, n]);
1284
+ const layers = device.createTexture({size: [1, 1, 4], format: 'rgba8unorm-srgb', usage: 6});
1285
+ device.queue.writeTexture({texture: layers}, new Uint8Array(16).fill(128), {bytesPerRow: 4, rowsPerImage: 1}, [1, 1, 4]);
1286
+ return {heightmap, layers};
1287
+ },
1288
+ });
1289
+ const water = Water.attach(engine, {
1290
+ height: -50,
1291
+ terrain: {heightmap: () => terrain.heightmap, origin: [-32, -32], size: [64, 64]},
1292
+ fill: (x) => (x < -20 ? 2 : undefined),
1293
+ });
1294
+ const flood = Flood.attach(engine, {surface: water, maxDepth: 2, maxSpeed: 6});
1295
+ const wet = WetGround.attach(engine, terrain, {record: () => flood.wetTexture, origin: [-32, -32], size: [64, 64]});
1296
+ applyWetGroundSettings(wet, {'wet.dryTime': 120}); // dries within minutes for this shot (live, keyable)
1297
+ engine.start();
1298
+ ```
1299
+
1300
+ - Look (all live, `setLook` or the rows of `WET_GROUND_SETTINGS`, the shared slider row shape): `darkening` 0.55,
1301
+ `gloss` 0.5, `dryTime` 10,800 s (3 hours; a soil surface dries over hours to a day, Idso et al. 1974,
1302
+ https://doi.org/10.2136/sssaj1974.03615995003800050037x). `wetGroundSettingDefaults()` gives a panel's state.
1303
+ - `binding` (default 116) moves its two lighting-group bindings if another effect uses them. `dispose()` gives the
1304
+ terrain its shader back; the record stays the flood's.
1305
+ - Measured on WebGPU and the WebGL2 layer (`test/wet-ground.browser.mjs`): fully wet ground draws as the terrain whose
1306
+ layer is 0.55 of the dry albedo and, under the sun's mirror direction, as the terrain at roughness 0.45 (its highlight
1307
+ 1.19 times the dry ground's); at `dryTime` it is the layer times 1 - 0.45 / e, and at 20 x `dryTime` the plain terrain.
1308
+ Limits: one wetness a flood cell, the same darkening for every layer, no evaporation model (docs/limits.md).
1309
+
1310
+ ## Mesh to terrain blending: `@margoengine/terrain/blend`
1311
+
1312
+ `TerrainBlend.attach(engine, terrain, virtualTexture, options)` blends rocks, cliffs and buildings into the ground they
1313
+ stand on, so a placed asset shows no hard seam line where its surface meets the terrain's. `add(mesh, options)` picks
1314
+ the meshes. On each pixel of an added mesh the ground height under it is read from the heightmap (as the terrain's
1315
+ vertex shader reads it); over the lowest `height` above that ground the mesh fades into the ground: its colour to the
1316
+ terrain's colour there, read from the runtime virtual texture (`@margoengine/terrain/rvt`), its roughness to the
1317
+ terrain's and its shading normal to the ground's, so core's lighting then shades the foot of the mesh as it shades the
1318
+ ground. Value noise moves the fade up and down so it never reads as a ruled line.
1319
+
1320
+ ```ts
1321
+ import {Engine, PbrMaterial, box} from 'margoengine/core';
1322
+ import {Terrain} from 'margoengine/terrain';
1323
+ import {TerrainVirtualTexture} from 'margoengine/terrain/rvt';
1324
+ import {TerrainBlend} from 'margoengine/terrain/blend';
1325
+ const engine = await Engine.create(document.querySelector('canvas')!, {camera: {position: [0, 1, -6], target: [0, 0.5, 0]}});
1326
+ const terrain = Terrain.attach(engine, {
1327
+ size: [64, 64], origin: [-32, -32], heightScale: 1,
1328
+ layers: [0, 1, 2, 3].map(() => ({height: [-100, 100] as [number, number], slope: [0, 1] as [number, number], scale: 1})),
1329
+ textures(device) {
1330
+ const heightmap = device.createTexture({size: [2, 2], format: 'r32float', usage: 6});
1331
+ device.queue.writeTexture({texture: heightmap}, new Float32Array(4), {bytesPerRow: 8}, [2, 2]);
1332
+ const layers = device.createTexture({size: [1, 1, 4], format: 'rgba8unorm-srgb', usage: 6});
1333
+ device.queue.writeTexture({texture: layers}, new Uint8Array(16).fill(160), {bytesPerRow: 4, rowsPerImage: 1}, [1, 1, 4]);
1334
+ return {heightmap, layers};
1335
+ },
1336
+ });
1337
+ const ground = TerrainVirtualTexture.attach(engine, terrain);
1338
+ const rock = engine.createMesh().setGeometry(box(2, 2, 2)).setPosition([0, 0.5, 0])
1339
+ .setMaterial(new PbrMaterial({color: '#4f6f9f', roughness: 0.5}));
1340
+ const blend = TerrainBlend.attach(engine, terrain, ground, {
1341
+ height: 0.5, // world units above the ground over which a mesh fades into it
1342
+ noise: 0.5, // how far noise moves the fade, as a share of height
1343
+ normal: 1, // how far the shading normal turns to the ground's
1344
+ });
1345
+ blend.add(rock); // or blend.add(rock, {height: 1}) for this mesh alone
1346
+ engine.start();
1347
+ ```
1348
+
1349
+ - Defaults: `height` 0.5, `noise` 0.5 (the fade's top and bottom move by up to a quarter of `height` either way),
1350
+ `normal` 1. Each mesh can override them; adding a mesh again changes its settings, `remove(mesh)` stops it, and
1351
+ neither recompiles the shader after the first mesh (the settings are a storage buffer row per mesh id).
1352
+ - It works on meshes drawn with core's standard material, next to `TerrainColors` (they share one varying and one
1353
+ per-pixel block). Meshes on other shaders (glTF PBR, custom materials) draw as they were.
1354
+ - The ground colour is the virtual texture's, so the terrain must use one (`TerrainVirtualTexture` refuses layer
1355
+ materials); past the cache's reach the mesh does not fade. The normal is the heightmap's (a terrain `normalmap` is
1356
+ not read). The fade is in the mesh's colour, roughness and normal only: its shape and shadow stay as they are, and a
1357
+ mesh floating higher than `height` above the ground is not touched.
1358
+ - Cost: five group-0 bindings (from 40, past any taken) and, on an added mesh's pixels, five height reads, one noise
1359
+ and one or two cache samples; other meshes pay one storage read. WebGPU only.
1360
+
1361
+ Checked on a real GPU by `test/blend.browser.mjs` (in `test:gpu`, Radeon 680M, 2026-11-08): a 2 m box half a metre into
1362
+ flat sandy ground, seen square from 6 m. Without the blend the colour jumps by 126.6 of 255 across the contact line;
1363
+ with it 6.8 (noise 0.5) and 8.0 (noise 0), and the box's lowest row is 3.5 of 255 from the ground below it (126.7
1364
+ without). Every pixel that changes lies on the box's foot (within the fade's reach): the rest of the picture is the
1365
+ same bytes. With noise 0 the fade's top is the same row across the face (spread 1), with noise 1 it wanders over 10
1366
+ rows. Cost not timed.
1367
+
1368
+ ## Cliffs, overhangs and sea rocks: `@margoengine/terrain/rocks`
1369
+
1370
+ A heightfield holds one height per point, so it can draw neither an overhang nor a sea stack with a notch cut at its
1371
+ foot, and its steep slopes stretch into smooth ramps. `findRockSites(ground, options)` finds where rock belongs on a
1372
+ height grid (any grid: a `Terrain`'s heightmap texels, a `@margoengine/biomes` world's heights, a sculpted grid) from
1373
+ its relief and slope; `buildCliff`, `buildSeaRock` and `buildBoulder` build each piece as a closed mesh standing a little
1374
+ proud of the heightfield; `TerrainBlend` fades their feet into the ground and `RockSurface`
1375
+ (`@margoengine/terrain/rock-surface`) shades them as rock that holds up close.
1376
+
1377
+ ```ts
1378
+ import {Engine, PbrMaterial} from 'margoengine/core';
1379
+ import {Terrain} from 'margoengine/terrain';
1380
+ import {TerrainVirtualTexture} from 'margoengine/terrain/rvt';
1381
+ import {TerrainBlend} from 'margoengine/terrain/blend';
1382
+ import {findRockSites, buildRocks} from 'margoengine/terrain/rocks';
1383
+ import {RockSurface} from 'margoengine/terrain/rock-surface';
1384
+ // A 30 m cliffed headland falling to the sea (sea level 0), as heights on a 129 x 129 grid over 256 m.
1385
+ const n = 129, heights = new Float32Array(n * n);
1386
+ for (let j = 0; j < n; j++)
1387
+ for (let i = 0; i < n; i++) heights[j * n + i] = 30 / (1 + Math.exp(-(j * 2 - 138) / 2.5)) - 8;
1388
+ const ground = {heights, resolution: [n, n] as [number, number], origin: [-128, -128] as [number, number], size: [256, 256] as [number, number]};
1389
+ const engine = await Engine.create(document.querySelector('canvas')!, {camera: {position: [0, 12, -40], target: [0, 8, 10]}});
1390
+ const terrain = Terrain.attach(engine, {
1391
+ size: [256, 256], origin: [-128, -128], heightScale: 1,
1392
+ layers: [0, 1, 2, 3].map(() => ({height: [-100, 100] as [number, number], slope: [0, 1] as [number, number], scale: 1})),
1393
+ textures(device) {
1394
+ const heightmap = device.createTexture({size: [n, n], format: 'r32float', usage: 6});
1395
+ device.queue.writeTexture({texture: heightmap}, heights, {bytesPerRow: n * 4}, [n, n]);
1396
+ const layers = device.createTexture({size: [1, 1, 4], format: 'rgba8unorm-srgb', usage: 6});
1397
+ device.queue.writeTexture({texture: layers}, new Uint8Array(16).fill(150), {bytesPerRow: 4, rowsPerImage: 1}, [1, 1, 4]);
1398
+ return {heightmap, layers};
1399
+ },
1400
+ });
1401
+ const sites = findRockSites(ground, {
1402
+ seaLevel: 0, // the water the sea rocks stand in
1403
+ cliffSlope: 50, // degrees of slope that can hold a cliff
1404
+ cliffRelief: 8, // metres of local relief a cliff needs, within reliefRadius (16 m)
1405
+ seaRocks: 12, // most stacks and skerries
1406
+ boulders: 3, // fallen blocks at each cliff piece's foot
1407
+ });
1408
+ const blend = TerrainBlend.attach(engine, terrain, TerrainVirtualTexture.attach(engine, terrain), {height: 1});
1409
+ const rock = RockSurface.attach(engine, {moss: 0.3, tideHeight: 1.5});
1410
+ for (const piece of buildRocks(sites, ground, {cliff: {overhang: 3, strata: 1.4}, seaRock: {notchDepth: 0.8}})) {
1411
+ const mesh = engine.createMesh().setGeometry(piece.geometry).setPosition(piece.position)
1412
+ .setMaterial(new PbrMaterial({color: '#888888', roughness: 0.9}));
1413
+ blend.add(mesh);
1414
+ rock.add(mesh, {type: 'sandstone', seaLevel: 0});
1415
+ }
1416
+ engine.start();
1417
+ ```
1418
+
1419
+ - Sites. Slope is Horn's 3 x 3 weighted difference (Horn 1981); local relief is the highest less the lowest ground in a
1420
+ square of `reliefRadius` (van Herk 1992, Gil and Werman 1993: linear in the grid whatever the radius). A cliff piece
1421
+ stands where ground at least `cliffSlope` steep (default 50 degrees) has `cliffRelief` of relief (default 8 m); its
1422
+ foot and crest are found by walking down and up the slope until it eases to half the cliff slope, its `position` is
1423
+ mid-face and `facing` points down the slope. Pieces are `cliffWidth` wide (24 m) and 0.75 of that apart at mid-face,
1424
+ so they overlap; none is placed nearer the grid's edge than half a width. Sea rocks stand in water `seaRockDepth`
1425
+ deep (1 to 15 m) within `shoreDistance` (80 m) of land (a two-pass chamfer distance, Borgefors 1986), most often about
1426
+ half that reach out, at least `seaRockSpacing` (14 m) apart: stacks (0.35 to 0.85 of the nearby cliff's height) off
1427
+ cliffed coast as its remnants, skerries (0.4 to 2.5 m above the sea) elsewhere (Sunamura 1992, Trenhaile 1987).
1428
+ Boulders lie in front of each cliff's foot, bigger ones further out (fall sorting, Kirkby and Statham 1975). Sites
1429
+ are a pure function of the ground and options (`seed` picks again); `slope` and `relief` come back as grids too.
1430
+ - Cliff pieces. The face is the ground's own crossing of each height along the facing, so the piece follows the real
1431
+ relief, moved `proud` (0.6 m) out past its deepest crack, soft bed and bump so the smooth slope never shows. It leans
1432
+ `overhang` (2.5 m) out over its top third (a true overhang once that beats the slope's lean back), steps in strata of
1433
+ `strata` (1.4 m) beds whose hard ones stand up to `ledges` (0.5 m) out (tilted by `dip`), is cut by vertical joints
1434
+ every `joints` (3 m), shifted bed by bed, `crackDepth` (0.35 m) deep (jointed blocks after Paris et al. 2020), carries
1435
+ 3D bumps of `roughness` (0.35 m), stops just under the crest and goes `embed` (1.5 m) into the ground at its foot; its
1436
+ ends fold back into the hill. Rock volumes over a heightfield after Peytavie et al. 2009 (Arches), Paris et al. 2019
1437
+ and Gamito and Musgrave 2001.
1438
+ - Sea rocks. A lumpy (`lobes` 0.22 of the radius), tapering (`taper` 0.25, a skerry 0.5) column with a wave-cut notch
1439
+ `notchDepth` (0.6 m, at most 0.45 of the radius) deep in a band `notchHeight` (1.2 m) high, centred a tenth of it over
1440
+ the still water, so the rock above overhangs it; strata ledges, `joints` (7) around it and a rounded top. Boulders
1441
+ use `facets` (9) bed, joint and corner cuts through a seeded block. The bed face sits under the ground at the
1442
+ default `embed` (0.3). The upper face has a seeded pitch and each side has its own cut, with `rounding` (0.18)
1443
+ controlling edge wear. These cuts draw on [A. Peytavie, E. Galin, J. Grosjean and S. Mérillou,
1444
+ *Procedural Generation of Rock Piles using Aperiodic Tiling* (2009)](https://perso.liris.cnrs.fr/eric.galin/Articles/2009-aperiodic.pdf)
1445
+ and [A. Paris, A. Peytavie, E. Guérin, J.-M. Dischler and E. Galin, *Modeling Rocky Scenery using Implicit Blocks*
1446
+ (2020)](https://perso.liris.cnrs.fr/aparis/public_html/projects/paris2020_Blocks.html).
1447
+ - Meshes. Each piece is a signed distance field polygonized by Marching Cubes (Lorensen and Cline 1987, `marchingCubes`
1448
+ of `@margoengine/procedural`) at `cell` spacing (cliffs 0.5 m, sea rocks radius / 12, boulders radius / 10) in blocks
1449
+ of up to 127 cells whose shared vertices are welded and whose normals all come from the field's central differences,
1450
+ so every mesh is closed and shows no seam between blocks. Geometry is about `position` (set the mesh there). A 24 m
1451
+ wide, 30 m high cliff piece at 0.5 m is about 25,000 triangles and takes about a fifth of a second on one core; build
1452
+ a long coast in a worker. `cliffField`, `seaRockField` and `boulderField` return the signed distance and its box, for
1453
+ collision or your own polygonizer.
1454
+ - `RockSurface` replaces an added mesh's colour, roughness and metalness, per pixel from the world position (no UVs or
1455
+ textures): six octaves of triplanar relief as a surface gradient on the normal (Mikkelsen 2020, Blinn 1978), each
1456
+ octave fading as its wavelength nears the pixel's footprint so far rock does not shimmer (Norton et al. 1982); the
1457
+ rock type's two bed tones banded by its `strata` with thin bedding lines; broad tone variation; broken joint cracks;
1458
+ moss on faces that look up; a wet, algae-dark band up to `tideHeight` over the rock's `seaLevel`; and rain that
1459
+ darkens and smooths it (Lekner and Dorf 1988, Jensen et al. 1999). Rock types: `sandstone` (default), `limestone`,
1460
+ `chalk`, `granite`, `basalt`, `shale` (`ROCK_TYPES`; give `color`, `color2`, `strata` or `porosity` to override).
1461
+ At close range, granite has light quartz and dark mica grains, basalt has subtle dark pits, and shale has thin
1462
+ laminations between beds. Grain color and relief fade when the screen footprint can no longer resolve them.
1463
+ These materials use visual characteristics from the [British Columbia Geological Survey, *Rock Identification
1464
+ Key* (1987)](https://cmscontent.nrs.gov.bc.ca/geoscience/publicationcatalogue/InformationCircular/BCGS_IC1987-05_METC1980.pdf)
1465
+ and [Utah Geological Survey, *Igneous, Sedimentary, & Metamorphic Rocks*](https://geology.utah.gov/map-pub/survey-notes/glad-you-asked/igneous-sedimentary-metamorphic-rocks/).
1466
+ Set `tideHeight: 0` for inland scenes to disable shoreline darkening, including below the assigned sea level. The
1467
+ look (`RockLook`, defaults in `ROCK_LOOK_DEFAULTS`) is live through `setLook`; `look.rain` null follows a
1468
+ `WeatherDrive`, which finds the surface by its name. One group-0 binding (from 40, past any taken); an added mesh's
1469
+ pixels cost about twenty value-noise reads plus three triplanar grain samples in close shots, other meshes one
1470
+ storage read. WebGPU, and WebGPU on the WebGL2 layer.
1471
+ Its patch runs after `TerrainBlend`'s, so the blend's fade into the ground is laid over the rock.
1472
+ - Sliders: `@margoengine/terrain/rock-settings` holds every control on the shared row shape: the live look rows
1473
+ (`detail.*`, `moss.*`, `tide.*`, `wet.*`; `wet.rain` null follows the weather's `rainRate`) for
1474
+ `applyRockSettings(surface, values)`, and the shape rows (`cliff.*`, `sea.*`, `live` false) that `rockShapeOf(values)`
1475
+ turns into the builders' options.
1476
+
1477
+ Checked by `test/rocks.test.js` (CPU): slope exact on a 45 degree plane, relief equal to a brute-force window; on a
1478
+ coast of a 30 m headland beside a beach, cliffs only on the steep high ground and facing down it, sea rocks in their
1479
+ depth band within reach of the shore and spaced, stacks off the cliffs, boulders in front of the feet; 98% of the
1480
+ ground's slope behind the face; an overhang of 4 m standing 3.4 m or more past the plain face at 85% of the height
1481
+ with the lower face unmoved, and a 12 m one past the face below it; a stack's notch cut 1.1 m or more at the sea
1482
+ surface and under 0.05 m 2.5 m away; meshes closed (every edge in two triangles) across polygonizer blocks, normals out
1483
+ of the rock, the same input giving the same bytes. On a real GPU by `test/rocks.browser.mjs` (in `test:gpu`, WebGPU and
1484
+ `MARGO_COMPAT=1`, RTX A6000, 2026-11-18): a cliff piece seen from 12 m has 3.0 times the plain mesh's mean absolute Laplacian of
1485
+ luminance; rain darkens it to 0.69 of its light, the tide band to 0.61 with the rock above unchanged; with
1486
+ `TerrainBlend` the changed foot pixels sit 40 of 255 from the bare ground against 96 without; 150 m off, a quarter-pixel
1487
+ camera move changes the picture by 0.17 against the plain mesh's 0.15. Both backends give the same figures.
1488
+
1489
+ ## Planet terrain: `@margoengine/terrain/planet`
1490
+
1491
+ `PlanetTerrain.attach(engine, options)` draws a whole planet that can be flown around from orbit down to a metre above
1492
+ the ground. The six faces of a cube are each a quadtree of height patches mapped onto the sphere, so the ground curves
1493
+ and the horizon dips as on a real world. A patch splits into four while its vertices would be more than `screenError`
1494
+ pixels apart on screen (the ground nearest the camera first); patches behind the horizon or outside the view are not
1495
+ drawn, and skirts hung from patch edges close the seams between levels. Each patch keeps its centre in float64 and is
1496
+ drawn relative to the camera, so an Earth-sized planet holds still at any distance with no setting. With a
1497
+ `FloatingOrigin` (`@margoengine/cameras/origin`) the planet's centre follows each rebase, so meshes placed near the
1498
+ camera stay precise too.
1499
+
1500
+ ```ts
1501
+ import {Engine} from 'margoengine/core';
1502
+ import {FloatingOrigin} from 'margoengine/cameras/origin';
1503
+ import {PlanetTerrain} from 'margoengine/terrain/planet';
1504
+ const engine = await Engine.create(document.querySelector('canvas')!, {
1505
+ camera: {position: [0, 0, 2e7], target: [0, 0, 0], near: 1, far: 1e9},
1506
+ });
1507
+ const origin = FloatingOrigin.attach(engine);
1508
+ const planet = PlanetTerrain.attach(engine, {
1509
+ radius: 6371000, // metres at height 0 (the Earth's mean radius)
1510
+ relief: 8000, // the default ground spans about -8 km to 8 km
1511
+ seaLevel: 0, // lower ground draws as flat sea; false for none
1512
+ screenError: 4, // pixels between vertices before a patch splits
1513
+ origin, // the planet's centre follows the origin's rebases
1514
+ });
1515
+ engine.start();
1516
+ console.log(planet.altitude(engine.camera.position)); // metres above the ground under the camera
1517
+ ```
1518
+
1519
+ - Options and defaults: `radius` 6,371,000 m; `center` [0, 0, 0] (a float64 world position); `height` (default
1520
+ `planetNoise({radius, relief, seed})`, fractal value noise); `relief` 8,000 m; `seed` 1; `seaLevel` 0 (or `false`);
1521
+ `resolution` 32 quads a patch side (even, 4 to 64); `maxLevel` 20 (vertices 0.3 m apart on the Earth); `screenError`
1522
+ 4 px; `budget` 4 ms of patch building a frame (at least one patch; `Infinity` builds everything a view needs in one
1523
+ frame); `maxPatches` 2,048 on the GPU at once (about 24 KB each at resolution 32, so 50 MB; when every slot holds a
1524
+ patch the view uses, the planet keeps drawing the coarser parents where it wanted finer ones, never a hole, and
1525
+ `stats.resident` equals `maxPatches`: raise it, up to 16,384, for more detail; the patches share one vertex buffer
1526
+ that must fit the device's `maxBufferSize`, 256 MiB by default, so 10,992 patches at resolution 32 and 2,992 at 64,
1527
+ and `attach` throws `RangeError` past it, batch 132b); `origin` a
1528
+ `FloatingOrigin` to follow. Invalid values throw `RangeError` or `TypeError`.
1529
+ - The same patches on every machine (KB-FILM-CLOCK1): the millisecond `budget` makes a slower machine build fewer patches
1530
+ a frame, so a frame drawn mid-refinement differs. For a film pass `maxBuilds` (patches a frame, 1 or more, `Infinity`
1531
+ until nothing more is wanted): it replaces `budget`, and the patches built and drawn are the same on every run. `clock`
1532
+ (milliseconds, default `performance.now`) is the clock the `budget` reads, for a simulation clock in replay.
1533
+ - Your own ground: `height(x, y, z, detail)` gets a unit direction from the centre (float64) and returns metres above
1534
+ `radius`; `detail` is the spacing of the vertices being built there, so a procedural height can skip finer detail.
1535
+ `cubeSphere(face, s, t)` maps a cube face point to its direction.
1536
+ - `heightAt(direction)` and `altitude(position)` read the ground on the CPU (the drawn surface is that ground sampled at
1537
+ the patch's vertices). `update(camera, [width, height])` plans and builds the patches for a view ahead of time (the
1538
+ frame calls it); `stats` says what the last frame drew and built, `patches` lists the drawn patches.
1539
+ - Shading: the sun (`engine.lighting`) and ambient light over colours by height and slope (sea, sand, grass, dry
1540
+ ground, rock, snow). No shadows, SSR, lighting effects or layer textures yet; one view per frame.
1541
+
1542
+ Checked on a real GPU by `test/planet.browser.mjs` (in `test:gpu`, Radeon 680M, Edge 157, 2026-11-08), an Earth-sized
1543
+ planet at 320 x 240: from 3 radii out the planet is a disc of 16,939 px against the 16,965 px of a sphere's projection;
1544
+ on a smooth planet 100 km up, looking level, the horizon dips to the row `acos(R / (R + h))` predicts (157 against
1545
+ 156.97 in the middle), within a pixel in every column; 300 m above the default ground, 6,371 km from the world origin,
1546
+ no sky shows through the ground, and the same view with a `FloatingOrigin` (which rebases the camera to near zero) is
1547
+ the same picture, pixel for pixel; a 41-frame flight from two radii up to 2.8 m above the ground draws ground in every
1548
+ frame, reaches level 20 and rebases once, with no validation error. `test/planet.test.js` checks the cube sphere's
1549
+ seams and cell areas, the horizon culling, the screen error, that refining with no budget never leaves a hole, the
1550
+ patch limit, sea level and following an origin. Building a patch costs about 1.3 ms of main-thread time at
1551
+ resolution 32 with the default ground (Node, AMD mini PC, busy machine: diagnostic); the 1,682 patches a view 100 m above
1552
+ the ground at 1280 x 720 needs took 2.2 s, which the `budget` spreads over frames. Frame cost not timed.
1553
+
1554
+ ## Far from the origin: `floatingOrigin`
1555
+
1556
+ GPUs draw in float32, which holds about 7 digits: a terrain 10,000 km out has its vertices rounded to a metre and its
1557
+ textures swim. Give the terrain the scene's `FloatingOrigin` (`@margoengine/cameras/origin`) as `floatingOrigin` and it
1558
+ plans everything in float64 world space first: the ring lattice, the layer texture phases, the virtual texture's
1559
+ windows and decals, the deformation window, streamed tiles and imagery views. Only small local numbers (world less the
1560
+ origin) reach the GPU. A terrain 1e7 m out then draws the same vertices, levels, cache texels and pixels as the same
1561
+ terrain at zero, and a rebase moves nothing on screen and bakes nothing again.
1562
+
1563
+ ```ts
1564
+ import {Engine} from 'margoengine/core';
1565
+ import {FloatingOrigin} from 'margoengine/cameras/origin';
1566
+ import {Terrain, type TerrainOptions} from 'margoengine/terrain';
1567
+ import {TerrainQuery} from 'margoengine/terrain/query';
1568
+ const engine = await Engine.create(document.querySelector('canvas')!);
1569
+ // ratio 10: rebase once the camera is 10 times its target distance from local zero, so local numbers stay small.
1570
+ const origin = FloatingOrigin.attach(engine, {ratio: 10});
1571
+ const columns = 65, heights = new Float32Array(columns * columns).map((_, i) => Math.sin(i % columns / 6) * 0.1);
1572
+ const options: TerrainOptions = {
1573
+ origin: [1e7 - 64, 1e7 - 64], // world XZ, float64, as without the option
1574
+ size: [128, 128],
1575
+ heightScale: 20,
1576
+ floatingOrigin: origin,
1577
+ layers: Array.from({length: 4}, () => ({height: [-100, 100] as const, slope: [0, 1] as const, scale: 0.25})),
1578
+ textures(device) {
1579
+ const heightmap = device.createTexture({size: [columns, columns], format: 'r32float', usage: 6});
1580
+ device.queue.writeTexture({texture: heightmap}, heights, {bytesPerRow: columns * 4}, [columns, columns]);
1581
+ const layers = device.createTexture({size: [1, 1, 4], format: 'rgba8unorm-srgb', usage: 6});
1582
+ device.queue.writeTexture({texture: layers}, new Uint8Array(16).fill(128), {bytesPerRow: 4, rowsPerImage: 1}, [1, 1, 4]);
1583
+ return {heightmap, layers};
1584
+ },
1585
+ };
1586
+ const terrain = Terrain.attach(engine, options);
1587
+ origin.lookAt([1e7 + 50, 80, 1e7 + 50], [1e7 + 60, 30, 1e7 + 90]); // world points; the camera becomes local
1588
+ engine.start();
1589
+ // CPU calls stay in world coordinates: convert the local camera ray with origin.toWorld.
1590
+ const query = new TerrainQuery(heights, columns, columns, options);
1591
+ console.log(query.height(1e7, 1e7), query.raycast(origin.toWorld(engine.camera.position), [0.2, -1, 0.8]));
1592
+ console.log(terrain.shift); // the float64 world point at local zero, which every terrain entry follows
1593
+ ```
1594
+
1595
+ - `floatingOrigin` takes any `{origin, onRebase}` (a `FloatingOrigin` as is). Without it the shaders, uniforms and
1596
+ layer rules are byte for byte what they were. `terrain.shift` is the world point at local zero (zeros without the
1597
+ option); `terrain.anchor` is `origin` at construction.
1598
+ - World in, world out: `origin`, `size`, `TerrainQuery`, holes, sculpt dabs, virtual texture decals, roads and
1599
+ `invalidate` areas, overlays, imagery bounds and deformation prints (and its `follow`) take float64 world
1600
+ coordinates, as without the option.
1601
+ - Why `ratio` 10: core rebases when the camera is `ratio` times its target distance from local zero, so local numbers
1602
+ reach about `ratio` times the view distance before a rebase. float32 is clean to about 1e4 m (0.5 mm steps), so 10
1603
+ keeps a view a few hundred metres across well inside it; `FloatingOrigin`'s default of 1000 lets positions grow to
1604
+ kilometres first and shows float32 noise.
1605
+ - Layer textures repeat on terrain-relative coordinates (world less `anchor`), so moving a terrain and its camera
1606
+ together draws the same picture; a terrain at zero draws as before. A streamed terrain (`/stream`) keeps the anchor
1607
+ where it started, and its overlays and imagery read XZ relative to it in float32: precise within about 1e4 m of the
1608
+ start, as at zero.
1609
+ - The virtual texture addresses its cache by world texel (`floor(world / texel)`, a 32-bit integer): up to 1e8 m from
1610
+ zero at the default 5 cm texel. Its texel and the deformation's are taken as the float32 the GPU holds (a relative
1611
+ change under 1e-7), so the CPU's texel indices and the GPU's coordinates agree at any distance.
1612
+
1613
+ Checked on a real GPU by `test/origin.browser.mjs` (in `test:gpu`, RTX A6000, Edge 157, WebGPU and the WebGL2 layer,
1614
+ 2026-11-11), a 320 x 240 scene of rules with bump and macro, a hole, and a virtual texture with a decal and a road,
1615
+ moved with its camera by 0, 100,352 and 10,000,384 m: with the origin at the offset every picture is the zero case's,
1616
+ pixel for pixel, with the same draw calls and 1,324,960 texels baked; rebased onto the camera at 1e7, rebased in place
1617
+ (which bakes nothing that frame) and after a 400 m flight that rebases on the way, every pixel is within 1 of 255 of it
1618
+ (99.93, 99.93 and 99.84 percent equal; the flight ends on an origin 2/3 m off the metre grid, and the same pose drawn
1619
+ at rest on that origin, with no rebase at all, is 99.83 percent equal: float32 rounding of the frame, not the rebase,
1620
+ which changes 0.004 percent of pixels). Cached imagery with an overlay polygon, layer materials with displacement,
1621
+ footprints, imagery on the lit path, a mesh blended into the ground and a streamed terrain each draw the same picture
1622
+ at 1e7 as at zero, and blend and stream stay within 1 of 255 after a rebase in place. `test/origin.test.js` checks
1623
+ `planRings` and `planWindows` bit for bit at those offsets, the layer wrap and tone, a rebase rewriting the rules once
1624
+ and redrawing shadows once, and `TerrainQuery` at the offsets.
1625
+
1626
+ ## Textures after a device restore
1627
+
1628
+ `textures` is a function `(device) => TerrainTextures`, never a plain set, so a device restore needs nothing from you. The terrain calls it once
1629
+ for each device (at attach and again after `engine.rebootDevice()` or core's own recovery), binds the textures it returns, and destroys the old
1630
+ set. Make the textures from data you keep (the heights, the layer colours, the painted weights, the holes mask), not from a texture you made
1631
+ earlier, and nothing is lost and nothing is reported.
1632
+
1633
+ ## On the WebGL2 compatibility layer
1634
+
1635
+ Where the browser has no WebGPU, install the layer (`margoengine/webgl2-compat`) before `Engine.create` and the
1636
+ clipmap terrain draws with nothing else changed: the same options, the same textures factory, the same pixels. The
1637
+ root entry and `rvt` have no compute pass, so they need no route of their own there: this package holds no WebGL2
1638
+ code and a page with WebGPU downloads nothing extra.
1639
+
1640
+ ```ts
1641
+ import {Engine} from 'margoengine/core';
1642
+ import {install} from 'margoengine/webgl2-compat';
1643
+ import {Terrain} from 'margoengine/terrain';
1644
+ await install(); // changes nothing where WebGPU has an adapter; else navigator.gpu draws through WebGL2
1645
+ const engine = await Engine.create(document.querySelector('canvas')!, {camera: {position: [0, 20, -40], target: [0, 0, 0]}});
1646
+ Terrain.attach(engine, {
1647
+ size: [64, 64], origin: [-32, -32], heightScale: 4,
1648
+ layers: [0, 1, 2, 3].map(() => ({height: [-100, 100] as [number, number], slope: [0, 1] as [number, number], scale: 1})),
1649
+ textures(device) {
1650
+ const heightmap = device.createTexture({size: [2, 2], format: 'r32float', usage: 6});
1651
+ device.queue.writeTexture({texture: heightmap}, new Float32Array([0, 1, 1, 0]), {bytesPerRow: 8}, [2, 2]);
1652
+ const layers = device.createTexture({size: [1, 1, 4], format: 'rgba8unorm-srgb', usage: 6});
1653
+ device.queue.writeTexture({texture: layers}, new Uint8Array(16).fill(160), {bytesPerRow: 4, rowsPerImage: 1}, [1, 1, 4]);
1654
+ return {heightmap, layers};
1655
+ },
1656
+ });
1657
+ engine.start();
1658
+ ```
1659
+
1660
+ Checked on a real GPU by `test/compat.browser.mjs` (in `test:gpu`, Radeon 680M, ANGLE on Direct3D 11, Edge 157,
1661
+ 2026-11-08): a 129 x 129 heightmap of hills and a ridge with four checked layers, drawn natively and on the layer
1662
+ (`install({force: true})`) in exact-pixel mode, in three cases: layer rules alone; painted weights with a hole; and a
1663
+ runtime virtual texture (`@margoengine/terrain/rvt`), which bakes the same 1,310,720 texels on both. In every case no
1664
+ pixel differs by more than 1 of 255 (the layer roadmap allows 0.1% of pixels over 2 and a mean of 0.25). Cost on the
1665
+ layer, counted, not timed: a frame of six clipmap levels is 6 engine draws, 6 GL draws and 48 GL calls (50 with the
1666
+ virtual texture).
1667
+
1668
+ - Checked on the layer: the root entry (rules, painted weights, holes) and `rvt`. Not run there yet: `layers-pbr`,
1669
+ `stream`, `sculpt`, `deform` and `displace` (the last three have compute passes, which the layer runs on its own
1670
+ tiers), `blend`, the SSR capture, shadows and the occluder pass.
1671
+ - Frame times on the layer are not measured; only one GPU and one ANGLE back end ran it.
1672
+
1673
+ ## Screen-space reflections
1674
+
1675
+ `Terrain` takes SSR's capture hook (`@margoengine/post/ssr`): `ssr.add(terrain)` draws its own normal, layer colour and
1676
+ roughness into SSR's material targets (through the hook's `margoSSR`, metal 0), depth tested and written, so wet
1677
+ ground, ice or polished stone reflect what is on screen. `roughness` (GGX, 0-1, default 0.9; `RangeError` outside)
1678
+ sets the terrain's roughness for the sun's highlight and for SSR, whose default `maxRoughness` of 0.6 skips the
1679
+ default 0.9. With an `EnvironmentLighting` on the terrain the IBL specular it added is what SSR replaces where its ray
1680
+ hits; without one the reflection is added (as for core meshes). Leaving out `roughness` and the hook keeps the GPU
1681
+ calls exactly as before (`examples/package-benchmarks/proofs/terrain-ssr.proof.js`, against `6c20076d`).
1682
+ Checked on a real GPU (NVIDIA RTX A6000, Edge 155; `examples/package-benchmarks/post-effects-gpu.mjs --only=ssr-surfaces`, [ssr-surfaces-gpu.json](../../examples/package-benchmarks/results/ssr-surfaces-gpu.json)): a red box above a flat terrain (roughness 0.05, albedo 0.04) appears in it inside the box's planar
1683
+ mirror (24,929 pixels, none outside the projected mirror bounds by more than 6 px) and red at the mirrored centre,
1684
+ at 4x and 1x MSAA. A terrain is reflected only on screen and, being a dielectric, reflects 4-10% at most view angles.
1685
+
1686
+ ## Shadows
1687
+
1688
+ `shadows.add(terrain, {static: true})` casts and receives, in `Shadows` and in `VirtualShadows` alike, through the vertex entry of its colour pass, its position `@invariant` (WGSL 12.10) as every Margo shadow caster's is, so another program drawing the same surface writes the same depth bit for bit; give either a `distance` that reaches as far as the camera sees. Any lighting effect may bind what it declares in its WGSL: the lighting group's layout is read from there.
1689
+
1690
+ ## Terrain as an occluder
1691
+
1692
+ A hill can hide GPU-culled parts: `parts.addOccluder(terrain)` (`CulledParts` from `margoengine/culling/parts`, in
1693
+ `'occlusion'` mode) draws the terrain's depth through `terrain.drawOccluder`, with the rings and uniforms of its main pass.
1694
+
1695
+ ## Preview tier contract
1696
+
1697
+ The small `@margoengine/webgl2-compat/preview` renderer reports `backend: 'webgl2'` and has no GPU device. GPU-only attachments throw a linked `MargoError` with code `unsupported` before allocating resources. Native WebGPU and the full WebGL2 compatibility layer both report `backend: 'webgpu'`. Use [`autoEngine` with `loadCompat`](../webgl2-compat/README.md#automatic-escalation) during scene setup to select a complete tier automatically.
1698
+
1699
+ The renderer now refuses the preview during setup, allowing automatic escalation instead of accepting an attachment that cannot draw.
1700
+
1701
+ `TerrainImagery` refuses the small preview through the shared `requireWebGPU` (`TerrainImagery needs WebGPU`, code `unsupported`, help link). Before 2026-11-10 it threw `unsupported` with `Imagery requires WebGPU or its compatibility device` and no help link, which the preview-contract gate counted as a silent skip, so `npm run verify` failed. It now also refuses an engine whose backend is `webgl2` even when a device object is present, as every shared refusal does. Regression: `test/imagery.test.js`.
1702
+
1703
+ ## Planet recipes: `@margoengine/terrain/planet-recipes`
1704
+
1705
+ Ground functions for `PlanetTerrain`: impact craters with a real size distribution and profile, ridged noise, domain
1706
+ warp and ready-made moons, Mars-like worlds, asteroids and ice moons. Every function returns a `PlanetHeight`, so it
1707
+ goes straight into `PlanetTerrain`'s `height` and composes with `planetNoise`.
1708
+
1709
+ ```ts
1710
+ import {Engine} from 'margoengine/core';
1711
+ import {PlanetTerrain} from 'margoengine/terrain/planet';
1712
+ import {planetPreset, planetPresetRadius} from 'margoengine/terrain/planet-recipes';
1713
+ const radius = planetPresetRadius('moon'); // 1,737,400 m
1714
+ const engine = await Engine.create(document.querySelector('canvas')!, {
1715
+ camera: {position: [0, 0, 3 * radius], target: [0, 0, 0], near: 1, far: 1e9},
1716
+ });
1717
+ PlanetTerrain.attach(engine, {radius, height: planetPreset('moon', {radius}), relief: 4000, seaLevel: false});
1718
+ engine.render({delta: 0});
1719
+ ```
1720
+
1721
+ - `craterField({radius, density | count, dMin, dMax, exponent, seed, depthRatio, rimRatio, maxDepth, floor, ejecta, blend})`:
1722
+ craters are Poisson placed, uniformly over the sphere, with diameters from a power law (cumulative exponent 2 by
1723
+ default, Neukum et al. 2001) between `dMin` (default `radius / 20,000`) and `dMax` (`radius / 4`). `density` counts
1724
+ craters of `dMin` or more per million square kilometres (default 1,000), or give `count` for the whole planet. Depth is
1725
+ `0.196 D^1.01` and rim height `0.036 D^1.01` with D in kilometres (Pike 1977), a crater is never deeper than
1726
+ `maxDepth` 3,400 m (larger ones are scaled, not clipped). The ejecta blanket is `0.14 R^0.74 (r / R)^-3` metres beyond
1727
+ the rim (McGetchin et al. 1973), the rim uplift falls off as `(r / R)^-4`, both fade to nothing by 3 radii. `floor`
1728
+ is the fraction of the radius that is flat floor (default 0). A younger crater replaces what an older one left inside
1729
+ its rim and fades into it over `blend` radii (0.15). Heights are relative to the undisturbed ground: `combine` it with a base.
1730
+ The result also has `craters(x, y, z, detail)`, the list of craters that reach a point (centre, diameter, age), for decals
1731
+ or labels. A sample reads the 27 lattice cells around it for each octave of diameter; craters under twice `detail`
1732
+ are skipped. A density that puts over 256 craters in one cell throws a `RangeError` that says to raise `dMin`.
1733
+ - `ridgeNoise({radius, relief, octaves, gain, frequency, seed})`: ridged multifractal noise between 0 and `relief`
1734
+ (Musgrave et al. 1989); defaults 8,000 m, 6 octaves, gain 2, 2 cycles around the planet.
1735
+ - `domainWarp(height, {radius, amplitude, frequency, levels, seed})`: reads `height` at positions shifted by noise,
1736
+ up to `amplitude` metres (default 100,000) along each axis, so up to sqrt(3) times it in all; `levels: 2` warps by a
1737
+ warped noise, which moves a point no further.
1738
+ - `combine(heights, {mode, smooth})`: `'add'` (default), `'max'` or `'smoothMax'` (rounded joins, `smooth` 100 m).
1739
+ - `planetPreset('moon' | 'mars' | 'asteroid' | 'ice', {radius, seed})` and `planetPresetRadius(name)`: authored looks
1740
+ (numbers in [limits](../../docs/limits.md)), made for the body's own radius; pass the same `radius` to `PlanetTerrain`.
1741
+ The preset is shaded by `PlanetTerrain` with its height colours, so set `relief` to suit and `seaLevel: false`.
1742
+
1743
+ Checked in `test/planet-recipes.test.js` (an isolated crater's depth and rim over diameter against the Pike ratios and its
1744
+ ejecta against McGetchin within 2%, a flat floor within 1e-6, diameters against the power law with a
1745
+ Kolmogorov-Smirnov statistic under 0.02, determinism, pruning by detail, bounded reads, validation) and on both GPU backends by
1746
+ `test/planet-recipes.browser.mjs` (every preset drawn on `PlanetTerrain`, deterministic, no validation error).
1747
+
1748
+ ## Terrain relief lighting
1749
+
1750
+ Use `@margoengine/terrain/relief-lighting` to shade terrain from its measured or generated heightfield. A ridge can
1751
+ block the sun on the floor of a valley, even if the ridge is outside the camera view. The visible sky supplies the
1752
+ remaining diffuse light. The bake keeps sunlight visibility and projected sky visibility separate so layer albedo,
1753
+ roughness and explicit light sources retain their roles.
1754
+
1755
+ ```ts
1756
+ import { Engine } from '@margoengine/core';
1757
+ import { Terrain } from '@margoengine/terrain';
1758
+ import { TerrainReliefLighting } from '@margoengine/terrain/relief-lighting';
1759
+
1760
+ const canvas = document.body.appendChild(document.createElement('canvas'));
1761
+ const engine = await Engine.create(canvas, {
1762
+ backend: 'webgpu',
1763
+ camera: { position: [31, 43, 65], target: [31, 0, 25] },
1764
+ });
1765
+ engine.lighting.direction.set([1, 0.28, 0, 3]);
1766
+ const terrain = Terrain.attach(engine, {
1767
+ size: [64, 64],
1768
+ heightScale: 1,
1769
+ layers: Array.from({ length: 4 }, () => ({ height: [-1, 100], slope: [0, 1], scale: 1 })),
1770
+ textures(device) {
1771
+ const heightmap = device.createTexture({ size: [65, 65], format: 'r32float', usage: 6 });
1772
+ const samples = new Float32Array(65 * 65);
1773
+ for (let z = 0; z < 65; z++) samples[z * 65 + 32] = 18;
1774
+ device.queue.writeTexture({ texture: heightmap }, samples, { bytesPerRow: 260 }, [65, 65]);
1775
+ const layers = device.createTexture({ size: [1, 1, 4], format: 'rgba8unorm', usage: 6 });
1776
+ device.queue.writeTexture(
1777
+ { texture: layers }, new Uint8Array(16).fill(140), { bytesPerRow: 4, rowsPerImage: 1 }, [1, 1, 4],
1778
+ );
1779
+ return { heightmap, layers };
1780
+ },
1781
+ });
1782
+ const relief = TerrainReliefLighting.attach(engine, terrain);
1783
+ engine.start();
1784
+ // After a height or sun change, call relief.rebake(). Call engine.dispose() when leaving the view.
1785
+ ```
1786
+
1787
+ - Attach to a live clipmap terrain. On device restore the effect bakes from the heightmap on the restored device.
1788
+ Disposing the effect releases its texture and detaches it from its actual scene.
1789
+ - `direction` defaults to the engine light at the time of the bake. `radius` defaults to one quarter of the
1790
+ shorter extent. The defaults are 12 sky azimuths, 48 samples per ray and a 0.75-degree half-width for the sun.
1791
+ Use 4–32 azimuths, 8–256 samples and a positive half-width of up to 10 degrees.
1792
+ - Height samples must be finite and corner aligned. The effect uses the terrain height scale by default. It
1793
+ works with a single sampled 2D `r32float`, `rgba16float` or `rgba8unorm` height texture at least 2×2.
1794
+ - For Blender meshes and custom terrain draws, `bakeTerrainReliefLighting(device, heightmap, size, options)`
1795
+ returns an owned filterable `rgba16float` texture. Its R channel is sun visibility and its G channel is
1796
+ projected sky visibility. Call `texture.destroy()` when finished. `terrainReliefLightingWGSL` provides
1797
+ `terrainReliefLight(map, sampler, uv)`, with UV coordinates 0 and 1 at the first and last height samples.
1798
+ - Work is bounded by `width × height × (rays + 1) × steps` horizon samples per bake. Draws fetch one texel
1799
+ bilinearly. Radii and sample spacing limit the result. Distant narrow ridges can fall between samples.
1800
+ Overhangs and occluders absent from the heightfield require regular shadow casters.
1801
+
1802
+ Terrain horizons follow Nicolas Max, *Horizon Mapping: Shadows for Bump-Mapped Surfaces* (1988), and
1803
+ A. James Stewart, *Fast Horizon Computation at All Points of a Terrain with Visibility and Shading Applications*
1804
+ (1998). The azimuth-sampled sky view follows Klemen Zakšek, Krištof Oštir and Žiga Kokalj, *Sky-View Factor as
1805
+ a Relief Visualization Technique* (2011).
1806
+ [Max](https://cir.nii.ac.jp/crid/1573387451457112064)
1807
+ [Stewart](https://research.cs.queensu.ca/home/jstewart/papers/tvcg97.html)
1808
+ [Zakšek, Oštir and Kokalj](https://doi.org/10.3390/RS3020398)