@margoengine/terrain 0.0.0-stage → 1.0.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.
- package/LICENSE +201 -0
- package/NOTICE +4 -0
- package/README.md +2366 -2
- package/dist/bed-mesh.d.ts +40 -0
- package/dist/bed-mesh.js +95 -0
- package/dist/blend.d.ts +70 -0
- package/dist/blend.js +159 -0
- package/dist/colors.d.ts +170 -0
- package/dist/deform.d.ts +134 -0
- package/dist/deform.js +404 -0
- package/dist/displace.d.ts +60 -0
- package/dist/displace.js +254 -0
- package/dist/dunes.d.ts +86 -0
- package/dist/dunes.js +88 -0
- package/dist/elevation.d.ts +182 -0
- package/dist/elevation.js +155 -0
- package/dist/errors-fc4i1pSL.js +7 -0
- package/dist/far.d.ts +66 -0
- package/dist/far.js +191 -0
- package/dist/furrows.d.ts +74 -0
- package/dist/furrows.js +157 -0
- package/dist/grid.d.ts +14 -0
- package/dist/ground-change-settings.d.ts +29 -0
- package/dist/ground-change-settings.js +69 -0
- package/dist/ground-change.d.ts +227 -0
- package/dist/ground-change.js +1412 -0
- package/dist/ground-contact-settings.d.ts +27 -0
- package/dist/ground-contact-settings.js +22 -0
- package/dist/ground-contact.d.ts +91 -0
- package/dist/ground-contact.js +241 -0
- package/dist/ground-model.d.ts +372 -0
- package/dist/hdr-format-DRhzGS7G.js +30 -0
- package/dist/height-grid.d.ts +65 -0
- package/dist/height-grid.js +74 -0
- package/dist/heightfield.d.ts +38 -0
- package/dist/holes.d.ts +37 -0
- package/dist/holes.js +97 -0
- package/dist/imagery.d.ts +109 -0
- package/dist/imagery.js +472 -0
- package/dist/index.d.ts +408 -0
- package/dist/index.js +1 -0
- package/dist/layers-pbr.d.ts +78 -0
- package/dist/layers-pbr.js +128 -0
- package/dist/lighting-layout-CaDtDa5G.js +34 -0
- package/dist/lighting-layout.d.ts +5 -0
- package/dist/mesh-patch-BThCHCeS.js +21 -0
- package/dist/mesh-patch.d.ts +14 -0
- package/dist/noise3-sQdnbz4B.js +11 -0
- package/dist/noise3.d.ts +3 -0
- package/dist/overlays.d.ts +74 -0
- package/dist/overlays.js +297 -0
- package/dist/planet-complex.d.ts +31 -0
- package/dist/planet-craters.d.ts +80 -0
- package/dist/planet-rays.d.ts +37 -0
- package/dist/planet-recipes.d.ts +84 -0
- package/dist/planet-recipes.js +442 -0
- package/dist/planet.d.ts +144 -0
- package/dist/planet.js +610 -0
- package/dist/query.d.ts +150 -0
- package/dist/query.js +243 -0
- package/dist/relief-lighting.d.ts +53 -0
- package/dist/relief-lighting.js +221 -0
- package/dist/require-webgpu--tUXPsmA.js +7 -0
- package/dist/rock-settings.d.ts +39 -0
- package/dist/rock-settings.js +84 -0
- package/dist/rock-surface.d.ts +114 -0
- package/dist/rock-surface.js +380 -0
- package/dist/rocks.d.ts +258 -0
- package/dist/rocks.js +488 -0
- package/dist/rvt.d.ts +136 -0
- package/dist/rvt.js +518 -0
- package/dist/scour.d.ts +90 -0
- package/dist/scour.js +153 -0
- package/dist/sculpt.d.ts +103 -0
- package/dist/sculpt.js +361 -0
- package/dist/settings-B9BSdnhD.js +72 -0
- package/dist/settings.d.ts +81 -0
- package/dist/settings.js +152 -0
- package/dist/shader.d.ts +176 -0
- package/dist/shared/settings.d.ts +89 -0
- package/dist/src-Cr7Gm4n0.js +1366 -0
- package/dist/stream-window.d.ts +123 -0
- package/dist/stream.d.ts +169 -0
- package/dist/stream.js +531 -0
- package/dist/surface-height.d.ts +16 -0
- package/dist/wet-ground.d.ts +82 -0
- package/dist/wet-ground.js +147 -0
- package/package.json +173 -4
package/README.md
CHANGED
|
@@ -1,3 +1,2367 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @margoengine/terrain
|
|
2
2
|
|
|
3
|
-
|
|
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. A scene that
|
|
42
|
+
colours other parts with its sand (a floor, blown grains) takes the same measured value from `DRY_SAND`:
|
|
43
|
+
|
|
44
|
+
```js
|
|
45
|
+
import {DRY_SAND} from '@margoengine/terrain';
|
|
46
|
+
console.log(DRY_SAND); // [0.5, 0.42, 0.29], frozen
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
| Option | Default | Source |
|
|
50
|
+
| --- | --- | --- |
|
|
51
|
+
| `sand` | `[0.5, 0.42, 0.29]`, exported as `DRY_SAND` | dry sand albedo 0.35 to 0.45 (Oke 1987, table 1.1); luminance 0.43 |
|
|
52
|
+
| `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 |
|
|
53
|
+
| `stone` | `[0.253, 0.223, 0.187]` | the biomes package's rock |
|
|
54
|
+
| `shore` | `[0.3, 1.5]` m | beaches up to 1.5 m above sea level |
|
|
55
|
+
| `meadowHeight` | the mesh's lowest to highest point, under its position and Y scale | |
|
|
56
|
+
| `stoneHeight` | above the mesh's highest point (only slopes are stone) | pass a range for rocky peaks |
|
|
57
|
+
| `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) |
|
|
58
|
+
| `wetHeight` | `[-0.1, 0.4]` m | just above sea level |
|
|
59
|
+
| `wetDarkening` | `0.6` | wet ground at about 0.6 of its dry albedo (Lekner and Dorf 1988) |
|
|
60
|
+
| `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) |
|
|
61
|
+
| `wetGlossTime` | `20` s (0.1 to 3,600) | with `wetness`: its glossy water film drains to 1/e (Horn 2006) |
|
|
62
|
+
| `variation` | `0` (0..1) | |
|
|
63
|
+
| `detail` | `1` (0..1) | |
|
|
64
|
+
| `sandSurface` | `{wind: [1, 0], ripple: 0.1, ripples: 1, streaks: 1, sorting: 1, broad: 0}`; `false` removes it | wind-built sand, below |
|
|
65
|
+
|
|
66
|
+
Ranges must be increasing; colors are linear RGB in 0..1. Other meshes keep their materials. Sources: T. R. Oke,
|
|
67
|
+
"Boundary Layer Climates", 2nd ed., 1987; J. Lekner and M. Dorf, "Why some things are darker when wet", Applied Optics
|
|
68
|
+
27(7), 1988, https://doi.org/10.1364/AO.27.001278 ; J. Carrigy, "Experiments on the angles of repose of granular
|
|
69
|
+
materials", Sedimentology 14, 1970, https://doi.org/10.1111/j.1365-3091.1970.tb00184.x
|
|
70
|
+
|
|
71
|
+
```ts
|
|
72
|
+
import {Engine} from 'margoengine/core';
|
|
73
|
+
import {TerrainColors, heightfield} from 'margoengine/terrain';
|
|
74
|
+
|
|
75
|
+
const engine = await Engine.create(document.querySelector('canvas')!);
|
|
76
|
+
const ground = engine.createMesh();
|
|
77
|
+
ground.setGeometry(heightfield((x, z) => 6 * Math.sin(x / 9) * Math.cos(z / 11) + 2, {size: [120, 120]}));
|
|
78
|
+
TerrainColors.attach(engine, ground); // sand, grass and rock with no options
|
|
79
|
+
engine.camera.position = [0, 40, 90];
|
|
80
|
+
engine.camera.target = [0, 0, 0];
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
### Wind-built sand: `sandSurface`
|
|
84
|
+
|
|
85
|
+
The sand band carries what the wind does to dry sand, on by default (with `detail` above 0): impact ripples across
|
|
86
|
+
the wind, streaks along it, and sorting by slope, so a dune field reads as dunes in flat overcast light instead of one
|
|
87
|
+
beige sheet. Pass the direction the wind blows toward; a scene with a north wind blows toward +z:
|
|
88
|
+
|
|
89
|
+
```ts
|
|
90
|
+
import {Engine} from 'margoengine/core';
|
|
91
|
+
import {TerrainColors, heightfield} from 'margoengine/terrain';
|
|
92
|
+
import {duneField} from 'margoengine/terrain/dunes';
|
|
93
|
+
|
|
94
|
+
const engine = await Engine.create(document.querySelector('canvas')!);
|
|
95
|
+
const heights = duneField({width: 129, depth: 129, cellSize: 1, origin: [-64, -64], height: 2, wind: 90, seed: 3});
|
|
96
|
+
const ground = engine.createMesh().setGeometry(heightfield((x, z) => {
|
|
97
|
+
const i = Math.min(128, Math.max(0, Math.round(x + 64))), j = Math.min(128, Math.max(0, Math.round(z + 64)));
|
|
98
|
+
return heights[j * 129 + i];
|
|
99
|
+
}, {size: [128, 128], resolution: 128}));
|
|
100
|
+
TerrainColors.attach(engine, ground, {shore: [20, 30], sandSurface: {wind: [0, 1], ripple: 0.1}});
|
|
101
|
+
engine.camera.position = [0, 1.7, -20];
|
|
102
|
+
engine.camera.target = [0, 0, 0];
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
| `sandSurface` field | Default | Meaning |
|
|
106
|
+
| --- | --- | --- |
|
|
107
|
+
| `wind` | `[1, 0]` | direction the wind blows toward, world `[x, z]`, any length above 0 |
|
|
108
|
+
| `ripple` | `0.1` m (0.02 to 1) | ripple spacing; impact ripples of fine to medium sand are 5 to 20 cm apart |
|
|
109
|
+
| `ripples` | `1` (0 to 2) | relief: height 1/15 of the spacing, a 5.5 degree windward side and a 19 degree lee side |
|
|
110
|
+
| `streaks` | `1` (0 to 1) | streaks along the wind, 1 to 2 m wide, albedo up to 8% either way |
|
|
111
|
+
| `sorting` | `1` (0 to 1) | lee slip faces up to 10% paler and smooth, with grainflow strips; windward faces up to 7% darker |
|
|
112
|
+
| `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 |
|
|
113
|
+
|
|
114
|
+
- Ripples: crests run across the wind and wander and break off at defects (a two-octave phase warp and an amplitude
|
|
115
|
+
noise), with coarse grains darkening the crests and lee sides. Their relief bends the shading normal as a surface
|
|
116
|
+
gradient. Before a pixel covers half a ripple they fade out in object space (the footprint is the pixel's own, the
|
|
117
|
+
longer screen-space derivative of the position, so it follows the frame size, device pixel ratio and grazing
|
|
118
|
+
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
|
|
119
|
+
does not shimmer. They are left off avalanching slip faces, and with a `wetness` record they fade with its
|
|
120
|
+
moisture: wet and submerged sand carries none (moisture holds the grains; Namikas and Sherman 1995, Wiggs et al.
|
|
121
|
+
2004), so a sea floor seen through water is smooth.
|
|
122
|
+
- Sorting: a face turned downwind past about 15 to 27 degrees is a slip face (paler, fresh avalanche sand in strips
|
|
123
|
+
about 1 m wide); a face turned upwind is windward (darker coarse lag). On sand only; meadow and stone are unchanged.
|
|
124
|
+
- Measured (`npm run test:gpu` in this package runs `test/sand.browser.mjs`; RTX A6000, WebGPU and the WebGL2
|
|
125
|
+
layer): near ground luma spread 1.77 times that of `sandSurface: false`, slip face 1.047 and windward face 0.963
|
|
126
|
+
times in sRGB luma, far ground pixel-to-pixel change 1.08 times.
|
|
127
|
+
- Sources: R. S. Anderson, "A theoretical model for aeolian impact ripples", Sedimentology 34, 1987; B. Andreotti,
|
|
128
|
+
P. Claudin and O. Pouliquen, "Aeolian sand ripples: experimental study of fully developed states", Physical Review
|
|
129
|
+
Letters 96, 2006; R. P. Sharp, "Wind ripples", Journal of Geology 71, 1963; R. A. Bagnold, "The Physics of Blown Sand
|
|
130
|
+
and Desert Dunes", 1941; B. T. Werner and G. Kocurek, "Bedform spacing from defect dynamics", Geology 27, 1999; R. E.
|
|
131
|
+
Hunter, "Basic types of stratification in small eolian dunes", Sedimentology 24, 1977; N. Lancaster, "Geomorphology
|
|
132
|
+
of Desert Dunes", 1995; R. Greeley and J. D. Iversen, "Wind as a Geological Process", 1985; M. Mikkelsen, "Surface
|
|
133
|
+
Gradient-Based Bump Mapping Framework", JCGT 9(3), 2020; A. Norton, A. Rockwood and P. Skolmoski, "Clamping: a method
|
|
134
|
+
of antialiasing textured surfaces by bandwidth limiting in object space", SIGGRAPH 1982.
|
|
135
|
+
|
|
136
|
+
Colors are worked out per pixel from the interpolated world height and normal, so
|
|
137
|
+
band borders follow the true height and slope instead of the mesh's triangles.
|
|
138
|
+
`variation` darkens colors by up to twice its value with two octaves of smooth
|
|
139
|
+
value noise (14 m and 1.1 m cells, the fine one rotated 37° and faded out between
|
|
140
|
+
20 and 60 m from the camera so it cannot shimmer). The noise is hashed per lattice
|
|
141
|
+
cell and never repeats, so there is no tile to hide. The patch flags the mesh in a
|
|
142
|
+
flat varying (location 6), then wraps the rest of core's fragment after its
|
|
143
|
+
shading-normal line in a block whose `i` and `n` are the terrain's own copies:
|
|
144
|
+
shadows, clustered lights, sky ambient, IBL and post replays shade the per-pixel
|
|
145
|
+
albedo, roughness and normal without changing their own patches. Without core's
|
|
146
|
+
standard shader the patch does nothing and the mesh keeps its material color.
|
|
147
|
+
|
|
148
|
+
`detail` makes the bands read as materials. The 14 m noise moves every border by
|
|
149
|
+
up to 30% of its range, so beaches, meadow patches and the stone line wander.
|
|
150
|
+
Sand, meadow and stone then blend by procedural height maps, the height-based
|
|
151
|
+
blending of Mishkinis's "Advanced Terrain Texture Splatting" (2013): grass tufts
|
|
152
|
+
from the fine noise, sand settling in their hollows, rock bumps from the stone
|
|
153
|
+
pattern, so the higher surface wins near each transition instead of a smooth
|
|
154
|
+
crossfade. Where stone shows, its pattern is triplanar: anisotropic noise on the
|
|
155
|
+
two vertical projections reads as horizontal strata, the top projection as
|
|
156
|
+
lumps, so cliffs never stretch a top-down pattern. The noise's analytic gradient
|
|
157
|
+
tilts the normal by up to about 17° (surface-gradient bump mapping), lighting the
|
|
158
|
+
strata; the geometric normal still drives shadow bias. Stone brightness follows
|
|
159
|
+
the bumps (±30%), sand grain the fine noise (±10%). Fine detail fades out between
|
|
160
|
+
20 and 60 m. `detail: 0` removes all of it from the shader and keeps smooth
|
|
161
|
+
per-pixel bands; values in between scale it.
|
|
162
|
+
|
|
163
|
+
Cost: one flat compare on every core-mesh pixel. On terrain pixels about 40 ALU
|
|
164
|
+
operations for the bands; with `variation` or `detail`, about 60 per noise
|
|
165
|
+
octave: two octaves everywhere (one beyond 60 m) and three more triplanar ones
|
|
166
|
+
where stone shows within 60 m, plus about 30 for the blends and the bump. That is
|
|
167
|
+
roughly 200 operations on meadow and sand and 380 on near stone (counted from the
|
|
168
|
+
WGSL, not timed). There are no texture fetches and no derivatives, so it runs
|
|
169
|
+
inside the mesh-ID branch without uniformity limits.
|
|
170
|
+
|
|
171
|
+
For a moving wet-sand band, add `wetness: {texture: () => water.coastalDepthTexture,
|
|
172
|
+
origin: [-80,-80], size: [160,160]}` using the same world bounds as water's terrain.
|
|
173
|
+
The borrowed texture's red channel contains water depth in meters; it must be a
|
|
174
|
+
single-layer, single-sample 2D `r32float`, `rgba32float` or `rgba16float` texture
|
|
175
|
+
with `COPY_SRC`. Undefined uses dry sand while water initializes or restores.
|
|
176
|
+
The module keeps a stable GPU snapshot so flow ping-pong does not rebuild scene
|
|
177
|
+
or vegetation bindings each frame. A 256 × 256 `rgba32float` snapshot costs 1 MiB
|
|
178
|
+
and one GPU copy per frame. Terrain owns that snapshot, not the provider texture.
|
|
179
|
+
|
|
180
|
+
Sand the swash has left stays wet (KB-TERRAIN-WETSAND1). Terrain keeps a moisture
|
|
181
|
+
record over the water's grid, one `rgba32float` texel per water texel, updated once
|
|
182
|
+
a frame by a small compute pass from the depth snapshot: wherever water stands the
|
|
183
|
+
moisture and the surface film are full, and once it has gone the moisture falls as
|
|
184
|
+
`exp(-t / wetDryTime)` and the film as `exp(-t / wetGlossTime)`. The darkening share
|
|
185
|
+
is `(1 - e^-3m) / (1 - e^-3)` of the moisture `m`, since reflectance falls fastest
|
|
186
|
+
with the first moisture and levels off near saturation (Lobell and Asner 2002;
|
|
187
|
+
Nolet et al. 2014), so drying sand holds its dark tone and pales late; the film
|
|
188
|
+
sets the sheen. `wetSandAfter(seconds, dryTime, glossTime)` returns what the record
|
|
189
|
+
holds that long after the water left. Both times are live (`setLook`, and the
|
|
190
|
+
`wet.dryTime` and `wet.glossTime` rows). The record costs two more textures the size
|
|
191
|
+
of the water grid (2 MiB for 256 × 256) and starts dry: a shot that needs the wet
|
|
192
|
+
band in its first frame lets the water run before it.
|
|
193
|
+
|
|
194
|
+
```ts
|
|
195
|
+
import {Engine} from 'margoengine/core';
|
|
196
|
+
import {TerrainColors, heightfield, wetSandAfter} from 'margoengine/terrain';
|
|
197
|
+
|
|
198
|
+
const engine = await Engine.create(document.querySelector('canvas')!);
|
|
199
|
+
const depth = engine.gpu!.createTexture({
|
|
200
|
+
size: [64, 64],
|
|
201
|
+
format: 'r32float',
|
|
202
|
+
usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_SRC | GPUTextureUsage.COPY_DST,
|
|
203
|
+
});
|
|
204
|
+
const beach = engine.createMesh().setGeometry(heightfield((x) => x * 0.02, {size: [80, 80], origin: [-40, -40]}));
|
|
205
|
+
const colors = TerrainColors.attach(engine, beach, {
|
|
206
|
+
wetness: {texture: () => depth, origin: [-40, -40], size: [80, 80]},
|
|
207
|
+
wetDryTime: 600, // sand behind the swash dries to 1/e in 10 minutes
|
|
208
|
+
});
|
|
209
|
+
colors.setLook({wetGlossTime: 10});
|
|
210
|
+
console.log(wetSandAfter(60, 600, 10).darkening); // 0.98 of the full darkening a minute after the swash
|
|
211
|
+
```
|
|
212
|
+
|
|
213
|
+
Sources: D. P. Horn, "Beach groundwater dynamics", Geomorphology 48, 2002,
|
|
214
|
+
https://doi.org/10.1016/S0169-555X(02)00178-2 ; D. P. Horn, "Measurements and modelling of beach groundwater flow in
|
|
215
|
+
the swash-zone: a review", Continental Shelf Research 26(5), 2006, https://doi.org/10.1016/j.csr.2006.02.001 ; R. A.
|
|
216
|
+
Namikas, B. L. Edwards, M. C. Bitton, J. L. Booth and Y. Zhu, "Temporal and spatial variabilities in the surface
|
|
217
|
+
moisture content of a fine-grained beach", Geomorphology 114(3), 2010, https://doi.org/10.1016/j.geomorph.2009.07.011 ;
|
|
218
|
+
D. B. Lobell and G. P. Asner, "Moisture effects on soil reflectance", Soil Sci. Soc. Am. J. 66, 2002,
|
|
219
|
+
https://doi.org/10.2136/sssaj2002.7220 ; C. Nolet, A. Poortinga, P. Roosjen, H. Bartholomeus and G. Ruessink,
|
|
220
|
+
"Measuring and modeling the effect of surface moisture on the spectral reflectance of coastal beach sand", PLoS ONE
|
|
221
|
+
9(11), 2014, https://doi.org/10.1371/journal.pone.0112151 ; S. A. Twomey, C. F. Bohren and J. L. Mergenthaler,
|
|
222
|
+
Applied Optics 25(3), 1986, https://doi.org/10.1364/AO.25.000431 . The 900 s and 20 s defaults are Margo's values
|
|
223
|
+
inside those ranges (minutes of drainage behind the swash, hours of drying landward), not a groundwater model.
|
|
224
|
+
|
|
225
|
+
Wetness samples world XZ per fragment and darkens only the sand albedo below
|
|
226
|
+
`wetHeight[1]`; fully wet sand is also 40% smoother while its film lasts, so it
|
|
227
|
+
catches a sheen toward the sun. Meadow/stone blends and geometry stay fixed to
|
|
228
|
+
terrain height and slope. It uses a group 0 binding from 40 up and flat output
|
|
229
|
+
location 6 in the standard PBR shader. No core changes are required. Physical
|
|
230
|
+
regression on WebGPU and the WebGL2 layer: `node packages/terrain/test/wetness.browser.mjs`
|
|
231
|
+
from the repository root after building the packages (MARGO_COMPAT=1 for the layer).
|
|
232
|
+
|
|
233
|
+
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. Each cell is a fan of four triangles around a centre vertex that sits on the diagonal whose mean height is nearer the cubic (Catmull-Rom) height at the cell's centre, so a crest along either diagonal draws as a straight line instead of a row of teeth ([teeth.browser.mjs](test/teeth.browser.mjs)). Cliff faces use triplanar splatting and normalized slope and height weights blend an sRGB texture array; with `rock`, the projections still follow the surface's own normal, so the structure shades the face without smearing its texture.
|
|
234
|
+
|
|
235
|
+
The rings anchor at the main camera's world XZ on the first render. Camera motion then preserves the terrain triangles,
|
|
236
|
+
ridge silhouettes, and static shadow cache. Pass `clipmapAnchor: [x, z]` for a fixed centre you choose. Set `levels`,
|
|
237
|
+
`resolution`, or `cellSize` so the outer ring spans the terrain in view. For a route that exceeds the fixed outer ring,
|
|
238
|
+
pass `clipmapAnchor: 'camera'` to select a moving window on the same world lattice. `TerrainStream` defaults to that mode.
|
|
239
|
+
The fixed ring origin remains in world coordinates with `floatingOrigin` and survives rebases and device restoration.
|
|
240
|
+
[The rendered regression](test/clipmap-anchor.browser.mjs) checks a subpixel camera move across a clipmap boundary.
|
|
241
|
+
The clipmap lattice and seam treatment follow Frank Losasso and Hugues Hoppe,
|
|
242
|
+
[Geometry Clipmaps](https://hhoppe.com/geomclipmap.pdf) (2004), and Arul Asirvatham and Hugues Hoppe,
|
|
243
|
+
[Terrain Rendering Using GPU-Based Geometry Clipmaps](https://hhoppe.com/gpugcm.pdf) (2005).
|
|
244
|
+
|
|
245
|
+
Set `captureSurfaceHeight: true` when an object-placement pass needs the heights of the triangles on screen.
|
|
246
|
+
`terrain.surfaceHeightTexture` becomes available when the first frame prepares the terrain. The texture shares
|
|
247
|
+
the source heightmap's UVs and stores world metres in R. It refreshes on changes to the clipmap or source heights,
|
|
248
|
+
so call `terrain.invalidate()` after editing samples. The target is capped at 2,049 texels per side. It uses R32F
|
|
249
|
+
on WebGPU and the full compatibility tier, RGBA16F on the half-float tier. The LDR tier cannot render the float target.
|
|
250
|
+
[The height regression](test/surface-height.browser.mjs) checks a fine source peak that the coarse rendered triangles omit.
|
|
251
|
+
Each ring's 192-byte uniform (and each shadow cascade's and local shadow layer's copy) is uploaded only when its bits
|
|
252
|
+
differ from the last upload to that buffer, so a still camera under unchanged light uploads nothing; buffers made
|
|
253
|
+
after a device restore always get their first write.
|
|
254
|
+
|
|
255
|
+
```ts
|
|
256
|
+
import {EngineKernel} from 'margoengine/core';
|
|
257
|
+
import {Terrain} from 'margoengine/terrain';
|
|
258
|
+
const engine = await EngineKernel.create(document.querySelector<HTMLCanvasElement>('#viewport')!, {backend:'webgpu'});
|
|
259
|
+
const terrain = Terrain.attach(engine, {
|
|
260
|
+
resolution:64, levels:6, cellSize:1, origin:[-50,-50], size:[100,100], heightScale:20,
|
|
261
|
+
layers:[
|
|
262
|
+
{height:[-20,100],slope:[0,0.3],scale:0.3},
|
|
263
|
+
{height:[-20,100],slope:[0.2,1],scale:0.2},
|
|
264
|
+
{height:[-20,2],slope:[0,0.4],scale:0.4},
|
|
265
|
+
{height:[10,100],slope:[0,0.5],scale:0.2}
|
|
266
|
+
],
|
|
267
|
+
textures:device=>{
|
|
268
|
+
// 6 = TEXTURE_BINDING | COPY_DST. Replace these tiny demo maps with your assets.
|
|
269
|
+
const heightmap = device.createTexture({size:[4,4],format:'r32float',usage:6});
|
|
270
|
+
device.queue.writeTexture({texture:heightmap},new Float32Array(16),{bytesPerRow:16},[4,4]);
|
|
271
|
+
const layers = device.createTexture({size:[1,1,4],format:'rgba8unorm-srgb',usage:6});
|
|
272
|
+
device.queue.writeTexture({texture:layers},new Uint8Array([
|
|
273
|
+
60,120,40,255, 110,110,100,255, 120,90,60,255, 240,245,255,255
|
|
274
|
+
]),{bytesPerRow:4,rowsPerImage:1},[1,1,4]);
|
|
275
|
+
return {heightmap,layers};
|
|
276
|
+
}
|
|
277
|
+
});
|
|
278
|
+
engine.start();
|
|
279
|
+
```
|
|
280
|
+
|
|
281
|
+
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`).
|
|
282
|
+
|
|
283
|
+
Optional painted weights: return `weights: [a, b]` from the factory, 2 to 4 `rgba8unorm` 2D textures over the same
|
|
284
|
+
bounds as the heightmap, one per 4 layers, so up to 16 layers (pass the same texture twice for up to 4 layers). Layer
|
|
285
|
+
i's weight is channel `i % 4` of texture `i / 4`, sampled bilinearly, and replaces the height and slope rules; each
|
|
286
|
+
rule's `scale` still sets that layer's texture repeat. A layer whose weight is 0 at a pixel skips its three triplanar
|
|
287
|
+
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
|
|
288
|
+
group layout and draw calls are exactly as before (`examples/package-benchmarks/proofs/terrain-ssr.proof.js` checks the
|
|
289
|
+
whole call sequence). Update the textures with `queue.writeTexture` and call `terrain.invalidate()`.
|
|
290
|
+
|
|
291
|
+
Optional tint, with `weights` only: return `tint` from the factory, one `rgba8unorm` or `rgba8unorm-srgb` 2D texture of
|
|
292
|
+
any size over the heightmap's bounds, and set `tint: true` on the layers it should colour (plant cover, not rock). Each
|
|
293
|
+
such layer is mixed toward the texel's RGB by its A, in linear light, before relief and macro tone; other layers are
|
|
294
|
+
drawn as they are. `@margoengine/biomes/view` draws seasons this way. Without `tint` the shader, bindings and rules
|
|
295
|
+
are unchanged, whatever the layers say.
|
|
296
|
+
|
|
297
|
+
```ts
|
|
298
|
+
import { Terrain } from 'margoengine/terrain';
|
|
299
|
+
import {Engine} from 'margoengine/core';
|
|
300
|
+
const engine = await Engine.create(document.querySelector('canvas')!);
|
|
301
|
+
// Your heightmap, layers and weights textures, as above; here small demo maps.
|
|
302
|
+
function make(device: GPUDevice) {
|
|
303
|
+
const heightmap = device.createTexture({ size: [4, 4], format: 'r32float', usage: 6 });
|
|
304
|
+
device.queue.writeTexture({ texture: heightmap }, new Float32Array(16), { bytesPerRow: 16 }, [4, 4]);
|
|
305
|
+
const layers = device.createTexture({ size: [1, 1, 4], format: 'rgba8unorm-srgb', usage: 6 });
|
|
306
|
+
const colours = [60, 120, 40, 255, 110, 110, 100, 255, 120, 90, 60, 255, 240, 245, 255, 255];
|
|
307
|
+
device.queue.writeTexture({ texture: layers }, new Uint8Array(colours), { bytesPerRow: 4, rowsPerImage: 1 }, [1, 1, 4]);
|
|
308
|
+
const weight = device.createTexture({ size: [1, 1], format: 'rgba8unorm', usage: 6 });
|
|
309
|
+
device.queue.writeTexture({ texture: weight }, new Uint8Array([255, 0, 0, 0]), { bytesPerRow: 4 }, [1, 1]);
|
|
310
|
+
return { heightmap, layers, weights: [weight, weight] };
|
|
311
|
+
}
|
|
312
|
+
Terrain.attach(engine, {
|
|
313
|
+
size: [512, 512],
|
|
314
|
+
layers: [0, 1, 2, 3].map((i) => ({ height: [-1e6, 1e6], slope: [0, 1], scale: 0.25, tint: i === 0 })),
|
|
315
|
+
textures(device) {
|
|
316
|
+
const tint = device.createTexture({
|
|
317
|
+
size: [64, 64],
|
|
318
|
+
format: 'rgba8unorm-srgb',
|
|
319
|
+
usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST,
|
|
320
|
+
});
|
|
321
|
+
// RGB: the colour to mix toward; A: how far (0 keeps the layer).
|
|
322
|
+
device.queue.writeTexture({ texture: tint }, new Uint8Array(64 * 64 * 4).fill(200), { bytesPerRow: 256 }, [64, 64]);
|
|
323
|
+
return { ...make(device), tint };
|
|
324
|
+
},
|
|
325
|
+
});
|
|
326
|
+
```
|
|
327
|
+
|
|
328
|
+
Optional patches, with `weights` only: `patches: { size, contrast }` draws layers that share a texel as patches with
|
|
329
|
+
crisp edges instead of their average, the way an alpine slope is turf, scree and rock side by side rather than one
|
|
330
|
+
grey-brown felt from a kilometre off. Each layer with a weight above 0 adds `contrast` (0 to 1, default 0.6) times its
|
|
331
|
+
own value-noise fBm (cells of `size` metres, default 14, three octaves) to its weight, and only the layers within
|
|
332
|
+
0.05 x `contrast` of the highest sum keep weight (height-based splatting: Mishkinis 2013, "Advanced Terrain Texture
|
|
333
|
+
Splatting"; noise-masked splats as in Andersson 2007, "Terrain Rendering in Frostbite Using Procedural Shader
|
|
334
|
+
Splatting", SIGGRAPH; noise cells from the pcg3d hash of Jarzynski and Olano 2020, "Hash Functions for GPU Rendering",
|
|
335
|
+
JCGT 9(3); quintic fade of Perlin 2002, "Improving Noise"). Weights of 0 and 1 draw as painted (0 of 255 apart), octaves
|
|
336
|
+
finer than half a pixel fade to their mean, and as a pixel grows from 0.3 to 0.8 of a cell the patched weights hand
|
|
337
|
+
back to the painted ones, so far ground does not alias. On a 50/50 texel seen from 90 m, 84 percent of pixels are one
|
|
338
|
+
layer or the other ([patches.browser.mjs](test/patches.browser.mjs), RTX A6000, the same figures on WebGPU and the
|
|
339
|
+
WebGL2 layer); without the option the shader is unchanged. Cost: one noise of three octaves per shown layer per pixel.
|
|
340
|
+
|
|
341
|
+
```ts
|
|
342
|
+
import { Terrain } from 'margoengine/terrain';
|
|
343
|
+
import { Engine } from 'margoengine/core';
|
|
344
|
+
const engine = await Engine.create(document.querySelector('canvas')!);
|
|
345
|
+
Terrain.attach(engine, {
|
|
346
|
+
size: [512, 512],
|
|
347
|
+
layers: [0, 1, 2, 3].map(() => ({ height: [-1e6, 1e6], slope: [0, 1], scale: 0.25 })),
|
|
348
|
+
patches: { size: 18, contrast: 0.7 },
|
|
349
|
+
textures(device) {
|
|
350
|
+
const usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST;
|
|
351
|
+
const heightmap = device.createTexture({ size: [2, 2], format: 'r32float', usage });
|
|
352
|
+
device.queue.writeTexture({ texture: heightmap }, new Float32Array(4), { bytesPerRow: 8 }, [2, 2]);
|
|
353
|
+
const layers = device.createTexture({ size: [1, 1, 4], format: 'rgba8unorm-srgb', usage });
|
|
354
|
+
const colours = [90, 100, 50, 255, 120, 115, 105, 255, 0, 0, 0, 255, 0, 0, 0, 255];
|
|
355
|
+
device.queue.writeTexture({ texture: layers }, new Uint8Array(colours), { bytesPerRow: 4, rowsPerImage: 1 }, [1, 1, 4]);
|
|
356
|
+
// Turf and rock half and half everywhere: drawn as turf and rock patches.
|
|
357
|
+
const weight = device.createTexture({ size: [1, 1], format: 'rgba8unorm', usage });
|
|
358
|
+
device.queue.writeTexture({ texture: weight }, new Uint8Array([128, 127, 0, 0]), { bytesPerRow: 4 }, [1, 1]);
|
|
359
|
+
return { heightmap, layers, weights: [weight, weight] };
|
|
360
|
+
},
|
|
361
|
+
});
|
|
362
|
+
```
|
|
363
|
+
|
|
364
|
+
Patches of one cell size read as camouflage from the air. `warp` (0 to 1, default 0) displaces the patch noise by a
|
|
365
|
+
broader value noise, up to 1.1 `warp` cells each way, and adds an octave of 3.3 cells (domain distortion: Perlin 1985,
|
|
366
|
+
"An image synthesizer"; Ebert, Musgrave et al. 2003, "Texturing and Modeling", ch. 16), so patches come in clusters and
|
|
367
|
+
strands of several sizes. `terraces` (metres of height a cycle, 0 or 0.5 to 1,000, default 0) adds to each layer a sine
|
|
368
|
+
of the height with a wandering phase, shifted per layer, so patches stretch along the contours as turf banks and gravel
|
|
369
|
+
strips do, on slopes of about 10 to 35 degrees and in stretches that come and go; it fades where a cycle covers under
|
|
370
|
+
about 3 pixels. Both default to off, and then the shader is the one
|
|
371
|
+
above: `patches: { size: 23, contrast: 0.6, warp: 0.65, terraces: 3.5 }` is what the Above the Treeline film draws.
|
|
372
|
+
|
|
373
|
+
## Rock structure: `rock` and `TerrainTextures.structure`
|
|
374
|
+
|
|
375
|
+
A heightmap of 4 to 30 m cells draws a steep face as one smooth plane, which reads as grey felt from 100 m to 5 km.
|
|
376
|
+
`rock` adds the structure of bare rock at 10 to 100 m to the shading (the normal and the colour's tone; the heights do
|
|
377
|
+
not change):
|
|
378
|
+
|
|
379
|
+
- ledges: beds `strata` metres thick (default 9; 0 for none), tilted by `dip` (rise per metre along x and z, default
|
|
380
|
+
[0, 0]) and wandering by noise, each a riser and a bench; the normal takes the bench's or the riser's slope
|
|
381
|
+
analytically, a quarter of the face's on the top 30 percent of a bed and the rest on the riser, so the mean slope is
|
|
382
|
+
the heightmap's (`ledges` 0 to 1, default 0.6). Ledges break off and come back along a bed;
|
|
383
|
+
- facets: jointed blocks `facets` metres across and 2.4 times as tall (default 18; 0 for none), ribs and columns as a
|
|
384
|
+
steep joint set cuts them, and buttresses 4.1 times that, each tilting the
|
|
385
|
+
normal by up to `relief` (0 to 1, default 0.45), with dark joints between them (Worley cells, one point anywhere in
|
|
386
|
+
each cell, the nearest two of the 27 cells around). Each tilt blends into its neighbour's across the cell edge (by
|
|
387
|
+
F2 - F1, over 0.14 of a cell plus two pixels), and relief, tone and joint shade fall to 0.3 as a block shrinks from
|
|
388
|
+
about 170 to 25 pixels across, then to none, so blocks 200 to 600 m away do not read as low-poly shards;
|
|
389
|
+
- gullies, with `TerrainTextures.structure` (one `rgba8unorm` texture over the bounds): its R, drainage 0 to 1, is
|
|
390
|
+
carved `gullies` metres deep (default 6) and darkened as wet, shaded rock, and its G is loose debris such as talus
|
|
391
|
+
fans. `@margoengine/biomes/hydrology` `drainageStructure` makes both from a height grid;
|
|
392
|
+
- `debris`, with `weights`: the layer index that benches, gully floors below the faces and the debris fans take;
|
|
393
|
+
- `undulation`, metres (0 to 10, default 0): the 5 to 50 m forms of gentle ground (felsenmeer, turf banks, solifluction
|
|
394
|
+
lobes) that a heightmap of several metres a texel smooths away, so plateau tops do not read as smooth, streaked
|
|
395
|
+
ground at low angles. Three octaves of 48, 20 and 8 m tilt the shading and shade crests and hollows on ground below
|
|
396
|
+
`slope`'s start; a 10 degree slope seen from 160 m goes from a tone spread of 0.3 to 5.9 with `undulation: 5`, and
|
|
397
|
+
from 2.5 km it draws as without. Sources: Mark and Aronson 1984, "Scale-dependent fractal dimensions of topographic
|
|
398
|
+
surfaces" (Mathematical Geology 16(7)); Ballantyne 2018, "Periglacial Geomorphology" (Wiley); Norton, Rockwood and
|
|
399
|
+
Skolmoski 1982, clamping (SIGGRAPH).
|
|
400
|
+
|
|
401
|
+
All of it fades in between `slope` degrees (default [28, 44]) and fades out where a pixel covers a good share of a
|
|
402
|
+
feature, so far ground keeps its mean. Seen at 50 degrees from 160 m, a plane of one grey layer goes from a tone spread
|
|
403
|
+
of 0.5 to 26 (8-bit standard deviation); from 2.5 km it is even again within 0.2 of its mean; a 10 degree slope draws
|
|
404
|
+
exactly as without; a drainage line changes the face by 0.89 on average and full debris turns every pixel to the debris
|
|
405
|
+
layer ([rock-structure.browser.mjs](test/rock-structure.browser.mjs), RTX A6000, the same figures on WebGPU and the
|
|
406
|
+
WebGL2 layer). Without the option the shader is unchanged. Cost: 54 hashes for the two facet scales, two noises for the
|
|
407
|
+
beds and five texel reads for the gullies per pixel. Sources: Benes and Forsbach 2001, "Layered data representation for
|
|
408
|
+
visual simulation of terrain erosion" (SCCG); Peytavie, Galin, Grosjean and Merillou 2009, "Arches: a framework for
|
|
409
|
+
modeling complex terrains" (Computer Graphics Forum 28(2)); Worley 1996, "A cellular texture basis function"
|
|
410
|
+
(SIGGRAPH); Jarzynski and Olano 2020, "Hash Functions for GPU Rendering" (JCGT 9(3)).
|
|
411
|
+
|
|
412
|
+
```ts
|
|
413
|
+
import { Terrain } from 'margoengine/terrain';
|
|
414
|
+
import { Engine } from 'margoengine/core';
|
|
415
|
+
const engine = await Engine.create(document.querySelector('canvas')!);
|
|
416
|
+
Terrain.attach(engine, {
|
|
417
|
+
size: [512, 512],
|
|
418
|
+
layers: [0, 1, 2, 3].map(() => ({ height: [-1e6, 1e6], slope: [0, 1], scale: 0.25 })),
|
|
419
|
+
rock: { strata: 8, facets: 20, debris: 1, undulation: 2 },
|
|
420
|
+
textures(device) {
|
|
421
|
+
const usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST;
|
|
422
|
+
// A 45 degree face rising along z.
|
|
423
|
+
const heightmap = device.createTexture({ size: [2, 2], format: 'r32float', usage });
|
|
424
|
+
device.queue.writeTexture({ texture: heightmap }, new Float32Array([0, 0, 512, 512]), { bytesPerRow: 8 }, [2, 2]);
|
|
425
|
+
const layers = device.createTexture({ size: [1, 1, 4], format: 'rgba8unorm-srgb', usage });
|
|
426
|
+
const colours = [120, 115, 105, 255, 140, 125, 100, 255, 0, 0, 0, 255, 0, 0, 0, 255];
|
|
427
|
+
device.queue.writeTexture({ texture: layers }, new Uint8Array(colours), { bytesPerRow: 4, rowsPerImage: 1 }, [1, 1, 4]);
|
|
428
|
+
const weight = device.createTexture({ size: [1, 1], format: 'rgba8unorm', usage });
|
|
429
|
+
device.queue.writeTexture({ texture: weight }, new Uint8Array([255, 0, 0, 0]), { bytesPerRow: 4 }, [1, 1]);
|
|
430
|
+
// No drainage, a little debris everywhere.
|
|
431
|
+
const structure = device.createTexture({ size: [1, 1], format: 'rgba8unorm', usage });
|
|
432
|
+
device.queue.writeTexture({ texture: structure }, new Uint8Array([0, 40, 0, 255]), { bytesPerRow: 4 }, [1, 1]);
|
|
433
|
+
return { heightmap, layers, weights: [weight, weight], structure };
|
|
434
|
+
},
|
|
435
|
+
});
|
|
436
|
+
```
|
|
437
|
+
|
|
438
|
+
## Sliders for the sand and ground look: `@margoengine/terrain/settings`
|
|
439
|
+
|
|
440
|
+
`TerrainColors` keeps its look (the colours, the height and slope ranges, the wet darkening and the sand surface's wind,
|
|
441
|
+
ripples, streaks, sorting and broad bands) in one small uniform, so any of it changes while the scene runs with
|
|
442
|
+
`colors.setLook(values)`: nothing is rebuilt, the next frame writes 176 bytes. `@margoengine/terrain/settings` lists those
|
|
443
|
+
controls as a table for sliders and panels: `TERRAIN_SETTINGS` has 24 rows (`name`, `group`, `kind`, `default`, `min`,
|
|
444
|
+
`max`, `step`, `unit`, `about` and `live`, which is true for every row), `applyTerrainSettings(colors, values)` writes a
|
|
445
|
+
set of values (a name left out takes its default) with one `setLook` call, and `TERRAIN_LOOKS` names four looks made only
|
|
446
|
+
of row values: `paleDesert`, `redDesert`, `volcanicBeach` and `saltFlat`. An unknown name throws `TypeError`, a value
|
|
447
|
+
outside its row's range `RangeError`, and `null` is accepted only on the rows that say `nullable`: the four height
|
|
448
|
+
ranges (null is the mesh's own range) and `sand.windDirection` (null leaves the wind to the weather drive).
|
|
449
|
+
`detail`, `variation`, `wetness` and whether `sandSurface` is on were compiled in at construction and are not rows; a
|
|
450
|
+
sand row on a `TerrainColors` built with `sandSurface: false` throws `TypeError`. Writing every live row each frame for 60
|
|
451
|
+
frames creates no pipeline, buffer or texture (`test/sand.browser.mjs`, native WebGPU and the WebGL2 layer), and the
|
|
452
|
+
defaults written draw exactly what a plain `TerrainColors` draws.
|
|
453
|
+
|
|
454
|
+
```ts
|
|
455
|
+
import {Engine} from 'margoengine/core';
|
|
456
|
+
import {TerrainColors, heightfield} from 'margoengine/terrain';
|
|
457
|
+
import {TERRAIN_LOOKS, applyTerrainSettings} from 'margoengine/terrain/settings';
|
|
458
|
+
|
|
459
|
+
const engine = await Engine.create(document.querySelector('canvas')!);
|
|
460
|
+
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}));
|
|
461
|
+
const colors = TerrainColors.attach(engine, ground, {shore: [20, 30]});
|
|
462
|
+
applyTerrainSettings(colors, {...TERRAIN_LOOKS.paleDesert, 'sand.windDirection': 45});
|
|
463
|
+
// Key a row over a shot: the sand drifts from fine ripples to long scour bands.
|
|
464
|
+
let time = 0;
|
|
465
|
+
engine.onFrame((_, delta) => {
|
|
466
|
+
time += delta;
|
|
467
|
+
applyTerrainSettings(colors, {...TERRAIN_LOOKS.paleDesert, 'sand.windDirection': 45, 'sand.broad': Math.min(1, time / 10)});
|
|
468
|
+
});
|
|
469
|
+
engine.camera.position = [0, 1.7, -20];
|
|
470
|
+
engine.camera.target = [0, 0, 0];
|
|
471
|
+
```
|
|
472
|
+
|
|
473
|
+
## Relief and far detail: `bump` and `macro`
|
|
474
|
+
|
|
475
|
+
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,
|
|
476
|
+
so rock and snow read as flat grey. Two optional layer settings, each 0 to 1 (`RangeError` outside), keep them
|
|
477
|
+
readable:
|
|
478
|
+
|
|
479
|
+
- `bump` (default 0): the layer's own luma becomes a height of up to half a texture repeat per unit of luma, times
|
|
480
|
+
`bump` (2 m at `scale` 0.25 for luma 0 to 1), and the shading normal follows its slope: derivative bump mapping from
|
|
481
|
+
Mikkelsen's "Bump Mapping Unparametrized Surfaces on the GPU" (2010), screen-space derivatives of the height and the
|
|
482
|
+
position. Where a pixel covers less than 1/128 of a repeat (3 cm at 0.25) the height is not read through the sampler:
|
|
483
|
+
it is the layer's 128-texel mip through a cubic B-spline over exact texel loads, so a magnified layer draws no
|
|
484
|
+
speckle, facets or lines along texel edges. The mips flatten it with distance, as they flatten the colour, and past a footprint
|
|
485
|
+
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
|
|
486
|
+
grazing ground draws no pixel grain.
|
|
487
|
+
- `macro` (default 0): the same layer at 1/24 of its `scale` (a 96 m repeat at 0.25) scales the colour by
|
|
488
|
+
`1 - macro + macro * luma / mean`, where `mean` is the luma of the layer's top mip, so the average colour stays and far
|
|
489
|
+
slopes keep a pattern. A much larger, smooth sample of the layer (about 318 m at 0.25, four mips below the top) adds
|
|
490
|
+
slow variation and picks the repeat's offset, two offsets blended at a time (after Quilez's "Texture Repetition"), so
|
|
491
|
+
the 96 m repeat never lines up into a grid. Give the layers texture a full mip chain for a true mean.
|
|
492
|
+
|
|
493
|
+
```ts
|
|
494
|
+
import {EngineKernel} from 'margoengine/core';
|
|
495
|
+
import {Terrain} from 'margoengine/terrain';
|
|
496
|
+
const engine = await EngineKernel.create(document.querySelector<HTMLCanvasElement>('#viewport')!, {backend:'webgpu'});
|
|
497
|
+
const terrain = Terrain.attach(engine, {
|
|
498
|
+
size:[100,100], origin:[-50,-50], heightScale:20,
|
|
499
|
+
layers:[
|
|
500
|
+
{height:[-20,100],slope:[0,0.3],scale:0.25,bump:0.3,macro:0.35},
|
|
501
|
+
{height:[-20,100],slope:[0.2,1],scale:0.25,bump:1,macro:0.5},
|
|
502
|
+
{height:[-20,2],slope:[0,0.4],scale:0.25,bump:0.25,macro:0.3},
|
|
503
|
+
{height:[10,100],slope:[0,0.5],scale:0.25,bump:0.35,macro:0.15}
|
|
504
|
+
],
|
|
505
|
+
textures:device=>{
|
|
506
|
+
// 6 = TEXTURE_BINDING | COPY_DST. Use real layer textures with full mip chains here.
|
|
507
|
+
const heightmap = device.createTexture({size:[4,4],format:'r32float',usage:6});
|
|
508
|
+
device.queue.writeTexture({texture:heightmap},new Float32Array(16),{bytesPerRow:16},[4,4]);
|
|
509
|
+
const layers = device.createTexture({size:[1,1,4],format:'rgba8unorm-srgb',usage:6});
|
|
510
|
+
device.queue.writeTexture({texture:layers},new Uint8Array([
|
|
511
|
+
60,120,40,255, 110,110,100,255, 120,90,60,255, 240,245,255,255
|
|
512
|
+
]),{bytesPerRow:4,rowsPerImage:1},[1,1,4]);
|
|
513
|
+
return {heightmap,layers};
|
|
514
|
+
}
|
|
515
|
+
});
|
|
516
|
+
engine.start();
|
|
517
|
+
```
|
|
518
|
+
|
|
519
|
+
Leaving both out (or 0 on every layer) keeps the shader text, the 8-float rules and so every GPU call exactly as
|
|
520
|
+
before; when any layer sets one, the rules grow to 12 floats a layer and the shader adds the relief and the macro
|
|
521
|
+
sample for every layer whose value is above 0. This works with painted `weights` and SSR's capture. Cost: `bump`
|
|
522
|
+
adds about 30 ALU operations and four derivatives per pixel, and where a pixel covers less than 1/64 of a repeat, 16
|
|
523
|
+
texel loads for each showing layer and triplanar axis (one axis on most of the ground); `macro` adds, per showing layer, one top-mip sample and
|
|
524
|
+
three texture samples for each triplanar axis that shows (one axis on most of the ground, all three at most). Checked on
|
|
525
|
+
a real GPU by `test/bump.browser.mjs` (in `test:gpu`): on flat ground with one grey noise texture, 0 draws the same pixels
|
|
526
|
+
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
|
|
527
|
+
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
|
|
528
|
+
(RTX A6000).
|
|
529
|
+
Where a crest is seen edge-on, the relief's slope is limited to what the pixel can resolve, so crests draw no dark
|
|
530
|
+
specks: `test/crest.browser.mjs` (in `test:gpu`) draws alpine crests under the noon sun with `bump: 1` and counts
|
|
531
|
+
none more than without it, by rules and by painted weights. Seen from 2 m with a grey value a texel on the noise,
|
|
532
|
+
`bump: 0.35` draws a pixel contrast of 8.5 (28.9 with the height read texel by texel; RTX A6000, `test/bump.browser.mjs`).
|
|
533
|
+
The cubic basis is Sigg and Hadwiger, "Fast Third-Order Texture Filtering", GPU Gems 2, chapter 20, 2005,
|
|
534
|
+
https://developer.nvidia.com/gpugems/gpugems2/part-iii-high-quality-rendering/chapter-20-fast-third-order-texture-filtering
|
|
535
|
+
|
|
536
|
+
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.
|
|
537
|
+
|
|
538
|
+
`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.
|
|
539
|
+
|
|
540
|
+
## Height and ray queries: `@margoengine/terrain/query`
|
|
541
|
+
|
|
542
|
+
`TerrainQuery` answers the height, the normal and a ray's first hit on the surface the clipmap's vertex shader samples
|
|
543
|
+
(bilinear between texels, texel 0 at `origin`, the last at `origin + size`, times `heightScale` plus `heightOffset`),
|
|
544
|
+
on the CPU, so picking, foot placement and game logic need no BVH of the ground. Build it from the heights you upload
|
|
545
|
+
(`new TerrainQuery(heights, columns, rows, terrain.options)`; it keeps the array, no copy), or read a live terrain's
|
|
546
|
+
heightmap back once with `await TerrainQuery.read(engine, terrain, {signal})` (the heightmap needs
|
|
547
|
+
`GPUTextureUsage.COPY_SRC`; `r32float`, `rgba16float` and `rgba8unorm` are read as the shader reads them).
|
|
548
|
+
|
|
549
|
+
```ts
|
|
550
|
+
import {Engine} from 'margoengine/core';
|
|
551
|
+
import {Terrain} from 'margoengine/terrain';
|
|
552
|
+
import {TerrainQuery} from 'margoengine/terrain/query';
|
|
553
|
+
const engine = await Engine.create(document.querySelector('canvas')!);
|
|
554
|
+
const columns = 65, heights = new Float32Array(columns * columns).map((_, i) => Math.sin(i % columns / 6) * 0.1);
|
|
555
|
+
const terrain = Terrain.attach(engine, {
|
|
556
|
+
size: [128, 128], origin: [-64, -64], heightScale: 20,
|
|
557
|
+
layers: Array.from({length: 4}, () => ({height: [-100, 100] as [number, number], slope: [0, 1] as [number, number], scale: 0.25})),
|
|
558
|
+
textures(device) {
|
|
559
|
+
const heightmap = device.createTexture({size: [columns, columns], format: 'r32float', usage: 6});
|
|
560
|
+
device.queue.writeTexture({texture: heightmap}, heights, {bytesPerRow: columns * 4}, [columns, columns]);
|
|
561
|
+
const layers = device.createTexture({size: [1, 1, 4], format: 'rgba8unorm-srgb', usage: 6});
|
|
562
|
+
device.queue.writeTexture({texture: layers}, new Uint8Array(16).fill(128), {bytesPerRow: 4, rowsPerImage: 1}, [1, 1, 4]);
|
|
563
|
+
return {heightmap, layers};
|
|
564
|
+
},
|
|
565
|
+
});
|
|
566
|
+
const ground = new TerrainQuery(heights, columns, columns, terrain.options);
|
|
567
|
+
const y = ground.height(10, -5); // world Y, or undefined outside the map
|
|
568
|
+
const up = ground.normal(10, -5); // unit shading normal, as the vertex shader works it out
|
|
569
|
+
const hit = ground.raycast([0, 50, 0], [0.2, -1, 0.1]); // {distance, position, normal} or null
|
|
570
|
+
console.log(y, up, hit?.position);
|
|
571
|
+
```
|
|
572
|
+
|
|
573
|
+
- `height(x, z)` is the bilinear height; `normal(x, z, out?)` uses the vertex shader's central differences one texel
|
|
574
|
+
either way (a terrain with its own `normalmap` shades with that instead). Both return undefined outside the map's
|
|
575
|
+
rectangle, where the terrain draws nothing.
|
|
576
|
+
- `raycast(origin, direction, maxDistance?, out?)` returns the first point where the ray meets the surface, from above or
|
|
577
|
+
below, inside the map, or null. Each cell's bilinear patch is hit exactly (the height along a ray is quadratic in its
|
|
578
|
+
distance), and an implicit min-max quadtree over the cells (Tevs, Ihrke and Seidel's maximum mipmaps, 2008) skips
|
|
579
|
+
ground the ray passes over. The hit has `@margoengine/animator`'s `GroundHit` shape, so
|
|
580
|
+
`raycast: (o, d) => ground.raycast(o, d)` plants a `FootIK` leg as it is; pass `out` to reuse one hit object.
|
|
581
|
+
- After changing `heights` in place (a sculpt, a crater), call `ground.refresh(x, z, width, depth)` over the changed
|
|
582
|
+
samples; it rebuilds the tree there. Without it a raised cell is skipped.
|
|
583
|
+
- The clipmap draws the surface as triangles at its own cell spacing, morphing between rings, so a drawn point lies
|
|
584
|
+
within that triangulation's error of the query's answer (none at texels the finest ring's vertices sit on).
|
|
585
|
+
- 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).
|
|
586
|
+
- `triangles({ step?, region? })` returns the surface as a world-space triangle mesh, `{ positions, normals, indices }`
|
|
587
|
+
(xyz per vertex, three indices per triangle, counter-clockwise seen from above), for a path tracer
|
|
588
|
+
(`@margoengine/voxel-pathtracer/from-engine` takes it as a `terrain` source), a collider or an export. Vertices sit on
|
|
589
|
+
the height samples, every `step`-th each way (default 1; the last row and column are always kept), with the normals
|
|
590
|
+
`normal` gives; `region` (world XZ `min` and `max`) is widened to whole cells and clipped to the heightmap; a cell whose
|
|
591
|
+
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
|
|
592
|
+
smaller region). Evidence: `test/query-triangles.test.js`.
|
|
593
|
+
|
|
594
|
+
```ts
|
|
595
|
+
import { TerrainQuery } from '@margoengine/terrain/query';
|
|
596
|
+
|
|
597
|
+
const heights = new Float32Array(65 * 65).map((_, i) => Math.sin(i * 0.01));
|
|
598
|
+
const ground = new TerrainQuery(heights, 65, 65, { origin: [-32, -32], size: [64, 64], heightScale: 4 });
|
|
599
|
+
const { positions, normals, indices } = ground.triangles({ step: 2, region: { min: [-16, -16], max: [16, 16] } });
|
|
600
|
+
console.log(positions.length / 3, normals.length / 3, indices.length / 3); // 289 289 512
|
|
601
|
+
```
|
|
602
|
+
|
|
603
|
+
Checked on the CPU by `test/query.test.js` (rays against a brute-force march, heights and normals against the shader's
|
|
604
|
+
formulas) and on a real GPU by `test/query.browser.mjs` (in `test:gpu`), on real elevation (the Mount Rainier tile in
|
|
605
|
+
`packages/shadows/test/fixtures`, 256 x 256 texels, 3.9 km of relief): `TerrainQuery.read` returns every texel as
|
|
606
|
+
uploaded (r32float and rgba8unorm exactly, rgba16float within half precision), the terrain's own WGSL `height` run on
|
|
607
|
+
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
|
|
608
|
+
the shader's height at the hit (Radeon 680M; the bound from float32 rounding is 4.9 mm).
|
|
609
|
+
|
|
610
|
+
## Full PBR layer materials: `@margoengine/terrain/layers-pbr`
|
|
611
|
+
|
|
612
|
+
`TerrainMaterials.attach(engine, terrain, options)` gives every layer its own normal map, ambient occlusion,
|
|
613
|
+
roughness and height, sampled triplanar at the layer's `scale` like its colour, so rock, mud and snow read as
|
|
614
|
+
materials up close. Its `textures` factory returns two 2D array textures with one layer per terrain layer
|
|
615
|
+
(`rgba8unorm` or `rgba16float`), made at attachment and again after device restoration:
|
|
616
|
+
|
|
617
|
+
- `normals`: tangent-space normals, XYZ encoded 0..1 with +Y up (the OpenGL convention, Poly Haven's `nor_gl`; flip
|
|
618
|
+
green for a DirectX map).
|
|
619
|
+
- `surface`: R ambient occlusion, G roughness (glTF's ORM order, Poly Haven's `arm`), B unused, A height 0..1 (a
|
|
620
|
+
`disp` map).
|
|
621
|
+
|
|
622
|
+
```ts
|
|
623
|
+
import {Engine} from 'margoengine/core';
|
|
624
|
+
import {Terrain} from 'margoengine/terrain';
|
|
625
|
+
import {TerrainMaterials} from 'margoengine/terrain/layers-pbr';
|
|
626
|
+
const engine = await Engine.create(document.querySelector('canvas')!);
|
|
627
|
+
// Four 1 x 1 layers here; use your layers' full-size, mipmapped maps.
|
|
628
|
+
function array(device: GPUDevice, rgba: number[]) {
|
|
629
|
+
const texture = device.createTexture({size: [1, 1, 4], format: 'rgba8unorm', usage: 6});
|
|
630
|
+
device.queue.writeTexture({texture}, new Uint8Array([...rgba, ...rgba, ...rgba, ...rgba]), {bytesPerRow: 4, rowsPerImage: 1}, [1, 1, 4]);
|
|
631
|
+
return texture;
|
|
632
|
+
}
|
|
633
|
+
const terrain = Terrain.attach(engine, {
|
|
634
|
+
size: [128, 128], origin: [-64, -64], heightScale: 20,
|
|
635
|
+
layers: [0, 1, 2, 3].map(() => ({height: [-100, 100] as [number, number], slope: [0, 1] as [number, number], scale: 0.25})),
|
|
636
|
+
textures(device) {
|
|
637
|
+
const heightmap = device.createTexture({size: [2, 2], format: 'r32float', usage: 6});
|
|
638
|
+
device.queue.writeTexture({texture: heightmap}, new Float32Array(4), {bytesPerRow: 8}, [2, 2]);
|
|
639
|
+
const layers = device.createTexture({size: [1, 1, 4], format: 'rgba8unorm-srgb', usage: 6});
|
|
640
|
+
device.queue.writeTexture({texture: layers}, new Uint8Array(16).fill(150), {bytesPerRow: 4, rowsPerImage: 1}, [1, 1, 4]);
|
|
641
|
+
return {heightmap, layers};
|
|
642
|
+
},
|
|
643
|
+
});
|
|
644
|
+
TerrainMaterials.attach(engine, terrain, {
|
|
645
|
+
heightBlend: 0.5, // 0 crossfades by weight; 1 lets the higher surface win
|
|
646
|
+
layers: [{normal: 1, occlusion: 1, roughness: 1}], // per layer, the rest take these defaults
|
|
647
|
+
textures: (device) => ({normals: array(device, [128, 128, 255, 255]), surface: array(device, [255, 230, 0, 128])}),
|
|
648
|
+
});
|
|
649
|
+
engine.start();
|
|
650
|
+
```
|
|
651
|
+
|
|
652
|
+
- Normals: each projection's tangent-space normal becomes the slope of a height over that projection's plane; the
|
|
653
|
+
three are blended by the triplanar weights as one gradient and tilt the shading normal as a surface gradient
|
|
654
|
+
(Mikkelsen's "Surface Gradient-Based Bump Mapping Framework", 2020), so cliffs need no tangents and the three
|
|
655
|
+
projections agree. `normal` (0 to 2, default 1) scales the tilt. It stacks with `bump`.
|
|
656
|
+
- Roughness replaces the terrain's `roughness` per pixel, times the layer's `roughness` (0 to 2, default 1), clamped
|
|
657
|
+
to 0.02..1; shadows and clustered lights use it and the tilted normal. AO, times `occlusion` (0 to 1, default 1),
|
|
658
|
+
darkens the terrain's own ambient term only, not image-based light another effect adds.
|
|
659
|
+
- Height blending: where layers' weights overlap (rules or painted weights), each weight is scaled by
|
|
660
|
+
2^(8 x `heightBlend` x (height - 1)), so stones stand out of mud and snow fills the hollows first (after Mishkinis,
|
|
661
|
+
"Advanced Terrain Texture Splatting", 2013). `heightBlend: 0` keeps the terrain's own crossfade.
|
|
662
|
+
- Where no layer's rule applies (the terrain falls back to layer 0's colour) the vertex normal and the terrain's
|
|
663
|
+
roughness are used. SSR's capture (`ssr.add(terrain)`) takes the blended colour but the terrain's own normal and
|
|
664
|
+
roughness.
|
|
665
|
+
- Attach it before any effect that replaces the terrain's lit shader; it patches the layer loop and the fragment.
|
|
666
|
+
- Cost per pixel: each showing layer adds three samples of `surface` and up to three of `normals` (one triplanar axis
|
|
667
|
+
on most ground, all three on cliffs); with height rules every layer's `surface` is sampled, with painted weights
|
|
668
|
+
only those that show. About 40 ALU operations a layer more.
|
|
669
|
+
|
|
670
|
+
Checked on a real GPU by `test/layers-pbr.browser.mjs` (in `test:gpu`), on flat ground seen from above (Radeon 680M):
|
|
671
|
+
flat maps draw exactly the terrain's own pixels (0 of 255 apart) with rules, painted weights and `bump`; a normal tilted
|
|
672
|
+
toward +U lights the ground from +X (luma 146 against 62 from -X, the plain terrain 123 from both), one toward +V (green
|
|
673
|
+
up) from -Z; AO 0 removes the ambient light (151 to 0); roughness 0.1 draws the overhead sun's highlight (254 against
|
|
674
|
+
147); full height blending gives the highest of four equal layers the ground; and Poly Haven's CC0 Aerial Rocks 02 maps
|
|
675
|
+
(`test/fixtures/aerial-rocks-02`) give a low-sun close-up 1.6 times the luminance spread of its colour alone.
|
|
676
|
+
|
|
677
|
+
## Height streaming: `@margoengine/terrain/stream`
|
|
678
|
+
|
|
679
|
+
`TerrainStream.attach(engine, options)` makes a `Terrain` whose heightmap, and painted weights, stream in tiles around
|
|
680
|
+
the camera, so a world can be far bigger than one heightmap. The terrain draws a window of `window` x `window` tiles
|
|
681
|
+
(default 4) centred on the engine camera; `load(x, z, signal)` returns tile (x, z)'s heights (`tileTexels` squared
|
|
682
|
+
float32 samples, rows along +Z) and, with `weights: n`, its n weight byte arrays, or null where there is no data.
|
|
683
|
+
With `normals: true` each tile with data also gives `normals` (RGBA bytes, XYZ encoded `n * 0.5 + 0.5`), which the
|
|
684
|
+
terrain shades with in place of normals from its heights, so lighting keeps detail finer than the height samples; with
|
|
685
|
+
`tint: true` (and weights) a tile may give `tint` (sRGB RGBA bytes), which layers marked `tint: true` move toward by
|
|
686
|
+
its A, a draped photograph or a season map. Both stream, scroll and restore with the heights.
|
|
687
|
+
|
|
688
|
+
```ts
|
|
689
|
+
import {Engine} from 'margoengine/core';
|
|
690
|
+
import {TerrainStream} from 'margoengine/terrain/stream';
|
|
691
|
+
const engine = await Engine.create(document.querySelector('canvas')!);
|
|
692
|
+
const stream = TerrainStream.attach(engine, {
|
|
693
|
+
tileSize: 256, tileTexels: 256, window: 4, heightScale: 1, // 1 m texels; a 1,024 x 1,024 window
|
|
694
|
+
layers: [0, 1, 2, 3].map(() => ({height: [-1e4, 1e4] as [number, number], slope: [0, 1] as [number, number], scale: 0.1})),
|
|
695
|
+
colors(device) {
|
|
696
|
+
const texture = device.createTexture({size: [1, 1, 4], format: 'rgba8unorm-srgb', usage: 6});
|
|
697
|
+
device.queue.writeTexture({texture}, new Uint8Array(16).fill(140), {bytesPerRow: 4, rowsPerImage: 1}, [1, 1, 4]);
|
|
698
|
+
return texture;
|
|
699
|
+
},
|
|
700
|
+
async load(x, z, signal) {
|
|
701
|
+
const response = await fetch(`/tiles/${x}/${z}.f32`, {signal}); // your tile server
|
|
702
|
+
if (response.status === 404) return null; // no data there: the tile keeps `fill`
|
|
703
|
+
if (!response.ok) throw new Error(`tile ${x},${z}: HTTP ${response.status}`); // retried, then failed
|
|
704
|
+
return {heights: new Float32Array(await response.arrayBuffer())};
|
|
705
|
+
},
|
|
706
|
+
retries: 3, // default 2; waits up to 250, 500, 1,000 ms (retryDelay)
|
|
707
|
+
});
|
|
708
|
+
engine.start();
|
|
709
|
+
addEventListener('online', () => stream.retry()); // failed tiles start over when the network comes back
|
|
710
|
+
await stream.ready(); // every tile of the first window is in
|
|
711
|
+
stream.onChange((change) => console.log(change)); // bands uploaded, or the window moved (`shifted`)
|
|
712
|
+
```
|
|
713
|
+
|
|
714
|
+
- The window moves a whole tile when the camera is more than 0.75 of a tile from its centre, so ground at least
|
|
715
|
+
`(window / 2 - 0.75) * tileSize` from the camera on each axis is always in it; the terrain draws nothing past the
|
|
716
|
+
window, as past any heightmap, unless `far` adds a coarser ring there (below). Tiles leaving it have their loads
|
|
717
|
+
aborted (`signal`).
|
|
718
|
+
- No hitches: the kept texels scroll by two GPU texture copies through a scratch texture (no CPU upload), exposed
|
|
719
|
+
tiles show `fill` (default 0) until they load, and loaded tiles go in as bands of rows within `budget` texels a frame
|
|
720
|
+
(default 65,536), the nearest tile first, with `concurrency` loads in flight (default 4). This is the incremental
|
|
721
|
+
clipmap update of Tanner, Migdal and Jones (1998) and Losasso and Hoppe (2004), scrolled instead of wrapped
|
|
722
|
+
toroidally so the terrain's shader is unchanged.
|
|
723
|
+
- A tile's samples sit at the same world positions in every window (sample k of tile x at
|
|
724
|
+
`origin + (x * tileTexels + k) * tileSize / tileTexels`), so the ground does not move when the window does; adjacent
|
|
725
|
+
tiles share no samples and the surface is bilinear across their seam.
|
|
726
|
+
- `heights` and `weights` are the window's CPU copies, kept in place; `origin`, `tile` (the window's minimum tile) and
|
|
727
|
+
`version` follow it. For queries, build `new TerrainQuery(stream.heights, stream.columns, stream.columns,
|
|
728
|
+
stream.terrain.options)` and on each `onChange` refresh it over the band, or rebuild it when `shifted`.
|
|
729
|
+
- `ready(signal?)` resolves once the current window is all in (uploads go in as frames are drawn) and rejects with a
|
|
730
|
+
tile's load error once its retries are spent; a failed tile keeps `fill` until it leaves the window or `retry()`
|
|
731
|
+
starts it over. `options.signal` aborts every load. `dispose()` aborts the loads and disposes the terrain.
|
|
732
|
+
- Retries: a tile whose `load` rejects is loaded again up to `retries` times (0 to 16, default 2), retry k after a
|
|
733
|
+
random wait up to `retryDelay * 2^k` ms (default 250, capped at 30 s): exponential backoff (Metcalfe and Boggs 1976)
|
|
734
|
+
with full jitter (Brooker 2015), so tiles that failed together, or many clients after one outage, do not all ask
|
|
735
|
+
again at once. An aborted load and a tile of the wrong shape (a bug in `load`, which a retry would repeat) are not
|
|
736
|
+
retried. `retry()` starts every failed tile, and every one waiting for a retry, over at once with its full retries,
|
|
737
|
+
and returns how many; a tile leaving the window drops its wait and its count.
|
|
738
|
+
Sources: R. M. Metcalfe and D. R. Boggs, "Ethernet: Distributed Packet Switching for Local Computer Networks",
|
|
739
|
+
Communications of the ACM 19(7), 1976, https://doi.org/10.1145/360248.360253 (binary exponential backoff); M.
|
|
740
|
+
Brooker, "Exponential Backoff And Jitter", AWS Architecture Blog, 2015,
|
|
741
|
+
https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/ (full jitter against synchronised retries).
|
|
742
|
+
- 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
|
|
743
|
+
twice 4 bytes a texel per weight texture, normal map and tint (the GPU texture and the CPU copy; `normals`, `tint`)
|
|
744
|
+
and one shared 4-byte scratch. The window must fit the device's 2D texture limit.
|
|
745
|
+
|
|
746
|
+
Checked on a real GPU by `test/stream.browser.mjs` (in `test:gpu`) on nine adjacent Terrarium tiles around Mount
|
|
747
|
+
Rainier (`test/fixtures/terrarium-10`, Terrain Tiles on AWS), 256 x 256 each with weights made from their heights,
|
|
748
|
+
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,
|
|
749
|
+
the CPU copy, the GPU heightmap read back and the weights hold exactly the mosaic's texels for the expected tiles, the
|
|
750
|
+
streamed terrain draws exactly the pixels of a plain `Terrain` given that window whole, no frame uploads more than the
|
|
751
|
+
budget (16,384 texels: 17 frames for the first four tiles), and a stream disposed mid-load aborts it and rejects
|
|
752
|
+
`ready` with MargoError `'disposed'` (Radeon 680M). Retries (2026-11-27, RTX A6000): tiles failing twice each load on
|
|
753
|
+
their third try with two retries and their third try's heights are uploaded; with one retry `ready` rejects with the
|
|
754
|
+
last error after two tries a tile, `retry()` starts the four over and they load; a tile of the wrong shape is tried
|
|
755
|
+
once. Normals and tint (2026-11-27, RTX A6000): the same stops with a streamed normal map tilted away from the
|
|
756
|
+
heights' own normals and a red tint on every other tile; the CPU copies hold exactly the mosaic's texels and the
|
|
757
|
+
picture equals a plain `Terrain` given both whole, which a stream dropping either fails by 112 and 92 of 255. Cost
|
|
758
|
+
not timed.
|
|
759
|
+
|
|
760
|
+
### Past the window: `@margoengine/terrain/far`
|
|
761
|
+
|
|
762
|
+
`terrainFar(options)` draws coarser ground past the stream's window, out to the horizon you give it. It is a second
|
|
763
|
+
window of tiles, each `scale` times as wide (default 4) with as many samples, loaded by its own `load`, and the
|
|
764
|
+
terrain's heights blend from the near tiles into the far ones with distance from the camera. Pass it as `far`:
|
|
765
|
+
|
|
766
|
+
```ts
|
|
767
|
+
import {Engine} from 'margoengine/core';
|
|
768
|
+
import {terrainFar} from 'margoengine/terrain/far';
|
|
769
|
+
import {TerrainStream} from 'margoengine/terrain/stream';
|
|
770
|
+
const engine = await Engine.create(document.querySelector('canvas')!, {camera: {far: 20_000}});
|
|
771
|
+
// Level "near": 256 m tiles at 1 m. Level "far": 2,048 m tiles at 8 m, from the same server.
|
|
772
|
+
const tiles = (level: string) => async (x: number, z: number, signal: AbortSignal) => {
|
|
773
|
+
const response = await fetch(`/tiles/${level}/${x}/${z}.f32`, {signal});
|
|
774
|
+
if (response.status === 404) return null;
|
|
775
|
+
if (!response.ok) throw new Error(`tile ${level} ${x},${z}: HTTP ${response.status}`);
|
|
776
|
+
return {heights: new Float32Array(await response.arrayBuffer())};
|
|
777
|
+
};
|
|
778
|
+
const far = terrainFar({scale: 8, load: tiles('far')});
|
|
779
|
+
const stream = TerrainStream.attach(engine, {
|
|
780
|
+
tileSize: 256, tileTexels: 256, window: 4, heightScale: 1, load: tiles('near'), far,
|
|
781
|
+
layers: [0, 1, 2, 3].map(() => ({height: [-1e4, 1e4] as [number, number], slope: [0, 1] as [number, number], scale: 0.1})),
|
|
782
|
+
colors(device) {
|
|
783
|
+
const texture = device.createTexture({size: [1, 1, 4], format: 'rgba8unorm-srgb', usage: 6});
|
|
784
|
+
device.queue.writeTexture({texture}, new Uint8Array(16).fill(140), {bytesPerRow: 4, rowsPerImage: 1}, [1, 1, 4]);
|
|
785
|
+
return texture;
|
|
786
|
+
},
|
|
787
|
+
});
|
|
788
|
+
engine.start();
|
|
789
|
+
await stream.ready(); // both windows are in
|
|
790
|
+
console.log(far.detail, far.reach); // 190 m of fine ground, 2544 m in all, each way from the camera
|
|
791
|
+
console.log(far.heightAt(900, -400)); // the height drawn there, near, far or between
|
|
792
|
+
```
|
|
793
|
+
|
|
794
|
+
| Option | Default | Meaning |
|
|
795
|
+
| --- | --- | --- |
|
|
796
|
+
| `load` | required | Loads far tile (x, z), which starts at the stream's `origin + [x, z] * scale * tileSize`; same tile shape as the near `load`. |
|
|
797
|
+
| `scale` | 4 | Far tile width in near tiles, 2 to 64. |
|
|
798
|
+
| `tileTexels` | the stream's | Samples per far tile side, 4 to 1,024. |
|
|
799
|
+
| `window` | the stream's | Far tiles per window side, even, 2 to 16. |
|
|
800
|
+
| `blend` | half a tile | World distance of the transition from near to far heights (at most half the near reach by default). |
|
|
801
|
+
| `fade` | 0.5 | Seconds a near tile takes to fade in over the far ground once uploaded. |
|
|
802
|
+
|
|
803
|
+
- Where each level shows, on each axis from the camera: the near heights alone up to `far.detail` =
|
|
804
|
+
`(window / 2 - 0.75) * tileSize - 2 * tileSize / tileTexels - blend` (190 m above), the mix over the next `blend`
|
|
805
|
+
metres, the far heights from there to `far.reach`, and nothing past it. Both edges are squares that move with the
|
|
806
|
+
camera, not with the tiles, so nothing steps when a window moves; set the camera's `far` to see the whole ring.
|
|
807
|
+
- No cracks and no popping. The blend is part of the height function every vertex reads, so there are not two meshes to
|
|
808
|
+
join: no seam, skirt or stitching. A near window gains and loses tiles only where the ground is already all far, and
|
|
809
|
+
a far window only past `reach`. This is the transition region of a geometry clipmap (Losasso and Hoppe, "Geometry
|
|
810
|
+
Clipmaps", SIGGRAPH 2004, https://hhoppe.com/geomclipmap.pdf; Asirvatham and Hoppe, GPU Gems 2 chapter 2, 2005)
|
|
811
|
+
with two data levels; the mesh rings morph into each other as before (Strugar, CDLOD, Journal of Graphics Tools
|
|
812
|
+
14(4), 2009, https://doi.org/10.1080/2151237X.2009.10129287).
|
|
813
|
+
- A near tile that is late, failed or without data (`null`) shows the far ground, ramped into its neighbours over half
|
|
814
|
+
a tile or less, and fades in when it arrives. So fine data may cover only part of a world the far data covers whole.
|
|
815
|
+
- Far tiles carry what near tiles do: `weights` blend with the heights, as do `tint` and `normals` when streamed.
|
|
816
|
+
Loads share `concurrency` and uploads share `budget`, the far ring first. `ready()` waits for both windows,
|
|
817
|
+
`retry()` restarts both, and `far.tiles` has the far window's CPU copies, `origin`, `tile` and `onChange`.
|
|
818
|
+
- Mesh: `levels` defaults to enough rings to reach `far.reach` (12 at most; raise `cellSize` for a longer view).
|
|
819
|
+
Colour, shadows, occlusion, screen-space reflections and `captureSurfaceHeight` all draw the blended ground.
|
|
820
|
+
`TerrainQuery` over `stream.heights` matches it within `far.detail` over loaded tiles; `far.heightAt(x, z)`
|
|
821
|
+
gives the drawn height anywhere. A far ring serves one stream at a time.
|
|
822
|
+
- Memory and cost: the far window takes what the near one does for its own size, plus one float per near tile; the
|
|
823
|
+
vertex shader reads up to 4 per-tile weights and the far heights in the blend and the far zone. Not timed.
|
|
824
|
+
|
|
825
|
+
Checked on a real GPU by `test/far.browser.mjs` (RTX A6000, WebGPU and the WebGL2 compatibility layer, 2026-11-27),
|
|
826
|
+
with far heights set 40 m under the near ones so the blend shows: the drawn surface read back at every near sample
|
|
827
|
+
equals `far.heightAt` within 0.01 m (3.1e-5 m on WebGPU) when settled, around a missing and a failed tile, mid-fade and
|
|
828
|
+
after window moves; over a 360 m flight with eight window moves and tiles arriving late no point's height changed by
|
|
829
|
+
more than 1.34 m in a 1 m step (2.95 m allowed by the blend and the fade; a hard switch jumps 40 m), also under a
|
|
830
|
+
floating origin 100 km out; painted weights, tint and normals pass from the near tiles' to the far ones', ground is
|
|
831
|
+
drawn up to `reach` and not past it, and shadows and SSR draw it with no validation error, and a runtime virtual texture baked over it draws the same ground.
|
|
832
|
+
|
|
833
|
+
## Sculpt and paint brushes: `@margoengine/terrain/sculpt`
|
|
834
|
+
|
|
835
|
+
`await TerrainSculpt.attach(engine, terrain, options?)` adds GPU brushes to any terrain, for in-game editors and level
|
|
836
|
+
tools: `raise`, `lower`, `smooth`, `flatten` and `paint` (layer weights), with undo and redo. The heightmap must be
|
|
837
|
+
`r32float` and the weight textures (for `paint`) `rgba8unorm`, created with usage 15 (`TEXTURE_BINDING |
|
|
838
|
+
STORAGE_BINDING | COPY_SRC | COPY_DST`); attaching reads them back once into the CPU copies `heights` and `weights`.
|
|
839
|
+
|
|
840
|
+
```ts
|
|
841
|
+
import {Engine} from 'margoengine/core';
|
|
842
|
+
import {Terrain} from 'margoengine/terrain';
|
|
843
|
+
import {TerrainSculpt} from 'margoengine/terrain/sculpt';
|
|
844
|
+
import {TerrainQuery} from 'margoengine/terrain/query';
|
|
845
|
+
const engine = await Engine.create(document.querySelector('canvas')!);
|
|
846
|
+
const n = 257, heights = new Float32Array(n * n);
|
|
847
|
+
const terrain = Terrain.attach(engine, {
|
|
848
|
+
size: [256, 256], origin: [-128, -128], heightScale: 1,
|
|
849
|
+
layers: [0, 1, 2, 3].map(() => ({height: [-100, 100] as [number, number], slope: [0, 1] as [number, number], scale: 0.25})),
|
|
850
|
+
textures(device) {
|
|
851
|
+
const heightmap = device.createTexture({size: [n, n], format: 'r32float', usage: 15});
|
|
852
|
+
device.queue.writeTexture({texture: heightmap}, heights, {bytesPerRow: n * 4}, [n, n]);
|
|
853
|
+
const weight = device.createTexture({size: [n, n], format: 'rgba8unorm', usage: 15});
|
|
854
|
+
device.queue.writeTexture({texture: weight}, new Uint8Array(n * n * 4).map((_, i) => (i % 4 ? 0 : 255)), {bytesPerRow: n * 4}, [n, n]);
|
|
855
|
+
const layers = device.createTexture({size: [1, 1, 4], format: 'rgba8unorm-srgb', usage: 6});
|
|
856
|
+
device.queue.writeTexture({texture: layers}, new Uint8Array(16).fill(140), {bytesPerRow: 4, rowsPerImage: 1}, [1, 1, 4]);
|
|
857
|
+
return {heightmap, layers, weights: [weight, weight]};
|
|
858
|
+
},
|
|
859
|
+
});
|
|
860
|
+
const sculpt = await TerrainSculpt.attach(engine, terrain, {radius: 12, strength: 0.5});
|
|
861
|
+
const ground = new TerrainQuery(sculpt.heights, sculpt.columns, sculpt.rows, terrain.options);
|
|
862
|
+
sculpt.onChange((c) => { if (c.weights === undefined) ground.refresh(c.u, c.v, c.width, c.depth); });
|
|
863
|
+
{
|
|
864
|
+
using stroke = sculpt.stroke({brush: 'raise', amount: 4}); // one undo step
|
|
865
|
+
for (let x = -40; x <= 40; x += 4) sculpt.dab(x, 0);
|
|
866
|
+
}
|
|
867
|
+
sculpt.dab(0, 20, {brush: 'paint', layer: 2, radius: 16}); // a dab is a stroke of its own
|
|
868
|
+
sculpt.dab(10, 10, {brush: 'flatten', height: 2});
|
|
869
|
+
await sculpt.undo(); // the flatten
|
|
870
|
+
await sculpt.flush(); // heights and the query hold every finished stroke
|
|
871
|
+
console.log(ground.height(0, 0));
|
|
872
|
+
engine.start();
|
|
873
|
+
```
|
|
874
|
+
|
|
875
|
+
- Brushes: `raise` and `lower` move heights by `amount` world units (default a tenth of `radius`) times the brush
|
|
876
|
+
weight; `smooth` moves them toward the 5 x 5 binomial blur of the ground under the brush (Burt and Adelson's
|
|
877
|
+
[1 4 6 4 1] filter), `flatten` toward `height` (default the height under the stroke's first dab), `paint` the
|
|
878
|
+
weights toward `layer` (the other layers fall, so the shares still add up). The weight is `strength` (0 to 1,
|
|
879
|
+
default 0.5) times the falloff of the distance over `radius` (world units, default 8): `smooth` (default) is
|
|
880
|
+
Wendland's (1 - t)^4 (4t + 1), `linear` and `constant` as named.
|
|
881
|
+
- Each dab is one compute pass over the texels under the brush (a copy with a 2 texel border is read, the terrain's
|
|
882
|
+
texture written), on the GPU, at once; the terrain's shadow is invalidated.
|
|
883
|
+
- `stroke(options?)` groups dabs into one undo step (`using`, or call `end()`); `undoLimit` strokes are kept (default
|
|
884
|
+
32), each as the changed rectangle's values before and after it, so `undo()` and `redo()` are exact. A new stroke
|
|
885
|
+
clears the redo steps. Await `undo()` before the next dab.
|
|
886
|
+
- `heights` and `weights` follow the GPU when a stroke's rectangle has been read back (`await flush()`); `onChange`
|
|
887
|
+
reports each rectangle they take, for a `TerrainQuery` built on `heights` (refresh it there).
|
|
888
|
+
- After device restoration the CPU copies, edits included, are written into the terrain's new textures.
|
|
889
|
+
- Memory: the CPU copies (4 bytes a texel each), the scratch copy of the largest dab, and per kept stroke its
|
|
890
|
+
rectangle's values twice.
|
|
891
|
+
|
|
892
|
+
Checked on a real GPU by `test/sculpt.browser.mjs` (in `test:gpu`) on the Mount Rainier tile (256 x 256 texels 100 m
|
|
893
|
+
apart) with painted weights (Radeon 680M): raise, lower, smooth and flatten dabs match the brush formulas worked on the
|
|
894
|
+
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
|
|
895
|
+
ground's squared Laplacian there by 96%; full-strength paint sets the layer exactly and soft paint is within one 8-bit
|
|
896
|
+
step of the formula; after every stroke the CPU copy equals the GPU read back and a `TerrainQuery` refreshed from
|
|
897
|
+
`onChange` (height and a ray cast) answers the raised ground; undoing all 8 strokes gives back the original heightmap,
|
|
898
|
+
weights and picture exactly, and redoing them the edited ones; a heightmap without storage usage is refused. Cost not
|
|
899
|
+
timed.
|
|
900
|
+
|
|
901
|
+
## Holes and cutouts: `@margoengine/terrain/holes`
|
|
902
|
+
|
|
903
|
+
`TerrainTextures.holes` takes a mask over the heightmap's bounds (`r8unorm` or `rgba8unorm`, a texel per cell); where
|
|
904
|
+
its R is below 0.5 the terrain draws nothing, in its colour, SSR capture, shadow and occluder passes alike, so caves,
|
|
905
|
+
tunnels, basements and mine entrances pass through the ground and light falls through them. `TerrainHoles` makes and
|
|
906
|
+
edits that mask on the CPU, by cell centre: `circle`, `rect` and `polygon` (even-odd rule) cut, or fill with
|
|
907
|
+
`hole: false`; `texture(device)` makes the texture for the factory and `upload(terrain)` sends later cuts.
|
|
908
|
+
`TerrainQuery` takes the same mask as its `holes` option: no height or normal there, and rays pass through.
|
|
909
|
+
|
|
910
|
+
```ts
|
|
911
|
+
import {Engine} from 'margoengine/core';
|
|
912
|
+
import {Terrain} from 'margoengine/terrain';
|
|
913
|
+
import {TerrainHoles} from 'margoengine/terrain/holes';
|
|
914
|
+
import {TerrainQuery} from 'margoengine/terrain/query';
|
|
915
|
+
const engine = await Engine.create(document.querySelector('canvas')!);
|
|
916
|
+
const n = 129, heights = new Float32Array(n * n).fill(0.05);
|
|
917
|
+
const options = {size: [128, 128] as [number, number], origin: [-64, -64] as [number, number], heightScale: 20};
|
|
918
|
+
const holes = new TerrainHoles(options, n - 1); // one mask cell per heightmap cell
|
|
919
|
+
holes.circle(10, -5, 6).polygon([[-30, 20], [-20, 20], [-25, 30]]);
|
|
920
|
+
const terrain = Terrain.attach(engine, {
|
|
921
|
+
...options,
|
|
922
|
+
layers: [0, 1, 2, 3].map(() => ({height: [-100, 100] as [number, number], slope: [0, 1] as [number, number], scale: 0.25})),
|
|
923
|
+
textures(device) {
|
|
924
|
+
const heightmap = device.createTexture({size: [n, n], format: 'r32float', usage: 6});
|
|
925
|
+
device.queue.writeTexture({texture: heightmap}, heights, {bytesPerRow: n * 4}, [n, n]);
|
|
926
|
+
const layers = device.createTexture({size: [1, 1, 4], format: 'rgba8unorm-srgb', usage: 6});
|
|
927
|
+
device.queue.writeTexture({texture: layers}, new Uint8Array(16).fill(140), {bytesPerRow: 4, rowsPerImage: 1}, [1, 1, 4]);
|
|
928
|
+
return {heightmap, layers, holes: holes.texture(device)};
|
|
929
|
+
},
|
|
930
|
+
});
|
|
931
|
+
const ground = new TerrainQuery(heights, n, n, {...options, holes});
|
|
932
|
+
console.log(ground.height(10, -5)); // undefined: a hole
|
|
933
|
+
holes.rect(30, 30, 40, 36); // a basement, cut later
|
|
934
|
+
holes.upload(terrain);
|
|
935
|
+
engine.start();
|
|
936
|
+
```
|
|
937
|
+
|
|
938
|
+
- A mask cell covers the bounds split evenly into the mask's width by height, so one per heightmap cell
|
|
939
|
+
(`columns - 1` by `rows - 1`) cuts the ground cell by cell; any size works. Hole edges follow the cells, not the
|
|
940
|
+
triangles, so a hole's rim is exact on the drawn surface.
|
|
941
|
+
- `TerrainQuery` reads the mask live (no refresh after a cut). A ray that meets a hole cell passes on to the next
|
|
942
|
+
ground it meets; with a mask finer than the heightmap's cells, a cell hit inside a hole is skipped whole.
|
|
943
|
+
- Without `holes` every shader and binding is as it was. With it, one texel load and a compare a fragment in each
|
|
944
|
+
pass; the mask binds after the weights and tint.
|
|
945
|
+
|
|
946
|
+
Checked on a real GPU by `test/holes.browser.mjs` (in `test:gpu`) on the Mount Rainier tile (Radeon 680M): a mask
|
|
947
|
+
with no hole draws exactly the terrain without one and a mask of all holes exactly no terrain, alone and with SSR on;
|
|
948
|
+
a 3 km crater shows the empty scene's pixels through it; a flat roof 50 m over flat ground, sun overhead, lets the
|
|
949
|
+
ground under its hole be lit exactly as with no roof, while a slanted sun shades the hole's far edge; an all-hole
|
|
950
|
+
occluder writes no depth; a cut sent with `upload` draws as one made before attaching. The node tests check the
|
|
951
|
+
bindings and that the colour, shadow and occluder shaders each declare and test the mask, and that queries skip holes.
|
|
952
|
+
|
|
953
|
+
## Erosion: `erode` from `@margoengine/biomes/erosion`
|
|
954
|
+
|
|
955
|
+
Weathered ground needs no terrain entry of its own: `erode(grid, options)` in `@margoengine/biomes/erosion` erodes
|
|
956
|
+
any height grid (integer millimetres, so the same heights and options give the same bytes on every machine): thermal
|
|
957
|
+
erosion slides material down slopes steeper than the angle of repose (`talus`, default 35 degrees) into scree, and
|
|
958
|
+
hydraulic erosion lets every cell's water run to an outlet, cutting gullies where a flow can carry more than it holds
|
|
959
|
+
and dropping the excess where its slope eases, in fans at the foot of slopes. It is deterministic: noise you generate
|
|
960
|
+
from a seed erodes to the same ground every time. Convert a terrain's heights to millimetres, erode, and upload:
|
|
961
|
+
|
|
962
|
+
```ts
|
|
963
|
+
import {Engine} from 'margoengine/core';
|
|
964
|
+
import {Terrain} from 'margoengine/terrain';
|
|
965
|
+
import {erode} from 'margoengine/biomes/erosion';
|
|
966
|
+
const engine = await Engine.create(document.querySelector('canvas')!);
|
|
967
|
+
const n = 129, size = 1280, heightScale = 400; // 10 m cells, heights 0..1 times 400 m
|
|
968
|
+
let seed = 7;
|
|
969
|
+
const random = () => (seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0) / 2 ** 32;
|
|
970
|
+
const heights = new Float32Array(n * n).map((_, i) =>
|
|
971
|
+
Math.max(0, 1 - Math.hypot(i % n - 64, Math.floor(i / n) - 64) / 50) + random() * 0.01);
|
|
972
|
+
const eroded = erode(
|
|
973
|
+
{height: Int32Array.from(heights, (h) => Math.round(h * heightScale * 1000)), nx: n, nz: n, step: (size / (n - 1)) * 1000},
|
|
974
|
+
{iterations: 64, talus: 35, capacity: 0.05},
|
|
975
|
+
);
|
|
976
|
+
const weathered = Float32Array.from(eroded.height, (mm) => mm / 1000 / heightScale);
|
|
977
|
+
Terrain.attach(engine, {
|
|
978
|
+
size: [size, size], origin: [-size / 2, -size / 2], heightScale, cellSize: 5,
|
|
979
|
+
layers: [0, 1, 2, 3].map(() => ({height: [-1e4, 1e4] as [number, number], slope: [0, 1] as [number, number], scale: 0.05})),
|
|
980
|
+
textures(device) {
|
|
981
|
+
const heightmap = device.createTexture({size: [n, n], format: 'r32float', usage: 6});
|
|
982
|
+
device.queue.writeTexture({texture: heightmap}, weathered, {bytesPerRow: n * 4}, [n, n]);
|
|
983
|
+
const layers = device.createTexture({size: [1, 1, 4], format: 'rgba8unorm-srgb', usage: 6});
|
|
984
|
+
device.queue.writeTexture({texture: layers}, new Uint8Array(16).fill(140), {bytesPerRow: 4, rowsPerImage: 1}, [1, 1, 4]);
|
|
985
|
+
return {heightmap, layers};
|
|
986
|
+
},
|
|
987
|
+
});
|
|
988
|
+
engine.start();
|
|
989
|
+
```
|
|
990
|
+
|
|
991
|
+
`eroded.wear` and `eroded.deposit` (mm a cell) make good painted weights: rock where it wore, gravel or mud where it
|
|
992
|
+
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
|
|
993
|
+
slope from tan 1.19 to 0.89 toward the talus slope's 0.70 (scree), hydraulic erosion alone (`thermal: 0, capacity:
|
|
994
|
+
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
|
|
995
|
+
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
|
|
996
|
+
bytes. It runs on the CPU (in a worker if you like); a GPU port would be a second erosion with float results that
|
|
997
|
+
differ by GPU.
|
|
998
|
+
|
|
999
|
+
## Runtime virtual texture: `@margoengine/terrain/rvt`
|
|
1000
|
+
|
|
1001
|
+
`TerrainVirtualTexture.attach(engine, terrain, options)` bakes the terrain's blended ground colour, with decals and
|
|
1002
|
+
roads on top, into a cache around the camera: clipmap levels of `size` texels, the finest `texel` wide and each next
|
|
1003
|
+
twice as coarse, addressed toroidally, so a camera move bakes only the rows and columns it exposes and a still frame
|
|
1004
|
+
bakes nothing. The terrain's lit shader then reads its ground from the cache, one or two samples a pixel whatever the
|
|
1005
|
+
number of layers and decals, and draws with its own shader only where the cache does not reach or the ground is
|
|
1006
|
+
steeper than `steep` (the cache is baked top down). The coarsest level reaches `(size / 2 - 2) * texel *
|
|
1007
|
+
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
|
|
1008
|
+
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
|
|
1009
|
+
of the coarsest level was baked and never read). `declarations(group, binding)` and `entries(binding)` let any
|
|
1010
|
+
other material read the ground under it (`terrainVirtualColor(position, footprint)`), to blend a rock or a path into
|
|
1011
|
+
the terrain.
|
|
1012
|
+
|
|
1013
|
+
```ts
|
|
1014
|
+
import {Engine} from 'margoengine/core';
|
|
1015
|
+
import {Terrain} from 'margoengine/terrain';
|
|
1016
|
+
import {TerrainVirtualTexture} from 'margoengine/terrain/rvt';
|
|
1017
|
+
const engine = await Engine.create(document.querySelector('canvas')!);
|
|
1018
|
+
const n = 129, heights = new Float32Array(n * n).map((_, i) => 0.02 * Math.sin(i % n / 9) + 0.02 * Math.cos(i / n / 7));
|
|
1019
|
+
const terrain = Terrain.attach(engine, {
|
|
1020
|
+
size: [512, 512], origin: [-256, -256], heightScale: 100,
|
|
1021
|
+
layers: [0, 1, 2, 3].map((i) => ({height: [-100 + i, 100] as [number, number], slope: [0, 1] as [number, number], scale: 0.25})),
|
|
1022
|
+
textures(device) {
|
|
1023
|
+
const heightmap = device.createTexture({size: [n, n], format: 'r32float', usage: 6});
|
|
1024
|
+
device.queue.writeTexture({texture: heightmap}, heights, {bytesPerRow: n * 4}, [n, n]);
|
|
1025
|
+
const layers = device.createTexture({size: [1, 1, 4], format: 'rgba8unorm-srgb', usage: 6});
|
|
1026
|
+
device.queue.writeTexture({texture: layers}, new Uint8Array(16).fill(140), {bytesPerRow: 4, rowsPerImage: 1}, [1, 1, 4]);
|
|
1027
|
+
return {heightmap, layers};
|
|
1028
|
+
},
|
|
1029
|
+
});
|
|
1030
|
+
const ground = TerrainVirtualTexture.attach(engine, terrain, {
|
|
1031
|
+
texel: 0.05, size: 1024, levels: 6,
|
|
1032
|
+
decals(device) { // layer 0 a puddle, layer 1 a road surface
|
|
1033
|
+
const pictures = device.createTexture({size: [1, 1, 2], format: 'rgba8unorm-srgb', usage: 6});
|
|
1034
|
+
device.queue.writeTexture({texture: pictures}, new Uint8Array([40, 50, 60, 200, 70, 70, 70, 255]),
|
|
1035
|
+
{bytesPerRow: 4, rowsPerImage: 1}, [1, 1, 2]);
|
|
1036
|
+
return pictures;
|
|
1037
|
+
},
|
|
1038
|
+
});
|
|
1039
|
+
ground.addDecal({center: [12, 30], size: [6, 4], angle: 0.3, layer: 0});
|
|
1040
|
+
ground.road([[-40, 0], [0, 20], [50, 25]], 5, {layer: 1});
|
|
1041
|
+
ground.invalidate(-20, -20, 20, 20); // after sculpting or painting there
|
|
1042
|
+
engine.start();
|
|
1043
|
+
```
|
|
1044
|
+
|
|
1045
|
+
On a Radeon 680M, on the real Mount Rainier tile under four layers of real rock (levels of 1,024 texels, 7 levels,
|
|
1046
|
+
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
|
|
1047
|
+
(99th percentile 2, worst 5); a camera that moved there over four frames drew exactly what a cache made there drew, a
|
|
1048
|
+
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
|
|
1049
|
+
pixels with no change more than 2 pixels from it, and removing it restored the picture exactly; a compute pass reading
|
|
1050
|
+
through `declarations` and `entries` saw the decal's red at its centre and no coverage past the cache. Cost not timed.
|
|
1051
|
+
|
|
1052
|
+
- Memory: `size * size * levels` texels, 4 bytes each (`rgba8unorm-srgb`) or 8 (`rgba16float`): 24 MiB at the
|
|
1053
|
+
defaults. The first frame bakes every level whole; later frames bake the texels a move exposes plus invalidated
|
|
1054
|
+
areas.
|
|
1055
|
+
- The cache holds colour only: not with `TerrainMaterials` (whose normals and roughness come from the layer loop it
|
|
1056
|
+
replaces); `bump` relief shows only where the terrain's own shader draws. SSR's capture keeps the terrain's own
|
|
1057
|
+
colour. Edits to heights, weights, tint or streamed tiles show after `invalidate(area)`.
|
|
1058
|
+
- Decals (up to 4,096) are baked in the order added, each over its rectangle; a road is a decal a segment, so sharp
|
|
1059
|
+
bends leave a gap on their outer side.
|
|
1060
|
+
|
|
1061
|
+
## Near displacement and parallax: `@margoengine/terrain/displace`
|
|
1062
|
+
|
|
1063
|
+
`TerrainDisplacement.attach(engine, terrain, materials, options)` gives ground near the camera the depth of its layer
|
|
1064
|
+
height maps (the `surface` maps' alpha that `TerrainMaterials` binds): each pixel within `distance` walks its view ray
|
|
1065
|
+
down through the relief (parallax occlusion mapping), and the terrain shades the point the ray hits, so pebbles hide
|
|
1066
|
+
the ground behind them and cracks look deep. With `shadows` (the default) the relief also shadows itself from the sun:
|
|
1067
|
+
a ray from the hit toward the sun runs through a maximum mipmap of the height maps, passing over every square of the
|
|
1068
|
+
map whose highest point stays under it, so no thin ridge is stepped over. A pixel that spans several texels of the
|
|
1069
|
+
finest layer traces up to 4 by 4 such rays over its footprint and takes their mean, so far relief shows the share of
|
|
1070
|
+
its area in sunlight rather than aliasing on whichever texel its centre lands. No geometry moves: the ground's outline
|
|
1071
|
+
against the sky stays the clipmap's.
|
|
1072
|
+
|
|
1073
|
+
```ts
|
|
1074
|
+
import {Engine} from 'margoengine/core';
|
|
1075
|
+
import {Terrain} from 'margoengine/terrain';
|
|
1076
|
+
import {TerrainMaterials} from 'margoengine/terrain/layers-pbr';
|
|
1077
|
+
import {TerrainDisplacement} from 'margoengine/terrain/displace';
|
|
1078
|
+
const engine = await Engine.create(document.querySelector('canvas')!);
|
|
1079
|
+
// Four 2 x 2 layers here; use your layers' full-size maps (square, a power of two in size for shadows).
|
|
1080
|
+
function array(device: GPUDevice, rgba: (i: number) => number[]) {
|
|
1081
|
+
const texture = device.createTexture({size: [2, 2, 4], format: 'rgba8unorm', usage: 6});
|
|
1082
|
+
const data = new Uint8Array(Array.from({length: 16}, (_, i) => rgba(i % 4)).flat());
|
|
1083
|
+
device.queue.writeTexture({texture}, data, {bytesPerRow: 8, rowsPerImage: 2}, [2, 2, 4]);
|
|
1084
|
+
return texture;
|
|
1085
|
+
}
|
|
1086
|
+
const terrain = Terrain.attach(engine, {
|
|
1087
|
+
size: [128, 128], origin: [-64, -64], heightScale: 20,
|
|
1088
|
+
layers: [0, 1, 2, 3].map(() => ({height: [-100, 100] as [number, number], slope: [0, 1] as [number, number], scale: 0.5})),
|
|
1089
|
+
textures(device) {
|
|
1090
|
+
const heightmap = device.createTexture({size: [2, 2], format: 'r32float', usage: 6});
|
|
1091
|
+
device.queue.writeTexture({texture: heightmap}, new Float32Array(4), {bytesPerRow: 8}, [2, 2]);
|
|
1092
|
+
const layers = device.createTexture({size: [1, 1, 4], format: 'rgba8unorm-srgb', usage: 6});
|
|
1093
|
+
device.queue.writeTexture({texture: layers}, new Uint8Array(16).fill(150), {bytesPerRow: 4, rowsPerImage: 1}, [1, 1, 4]);
|
|
1094
|
+
return {heightmap, layers};
|
|
1095
|
+
},
|
|
1096
|
+
});
|
|
1097
|
+
const materials = TerrainMaterials.attach(engine, terrain, {
|
|
1098
|
+
textures: (device) => ({
|
|
1099
|
+
normals: array(device, () => [128, 128, 255, 255]),
|
|
1100
|
+
surface: array(device, (texel) => [255, 230, 0, texel === 0 ? 255 : 40]), // one raised stone in four
|
|
1101
|
+
}),
|
|
1102
|
+
});
|
|
1103
|
+
TerrainDisplacement.attach(engine, terrain, materials, {
|
|
1104
|
+
depth: 0.05, // world depth from height 1 to 0 (per layer: layers: [{depth}])
|
|
1105
|
+
distance: 30, // shown within 30 m, fading over the last quarter
|
|
1106
|
+
steps: 24, // most view-ray steps a pixel takes
|
|
1107
|
+
shadows: true,
|
|
1108
|
+
});
|
|
1109
|
+
engine.start();
|
|
1110
|
+
```
|
|
1111
|
+
|
|
1112
|
+
Checked on a real GPU by `test/displace.browser.mjs` (in `test:gpu`), on Poly Haven's CC0 Aerial Rocks 02 maps (one
|
|
1113
|
+
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
|
|
1114
|
+
picture was 3.07 of 255 from the same rock built as real geometry (a terrain whose heightmap is the displacement map,
|
|
1115
|
+
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
|
|
1116
|
+
weights drew the same rock. Seen from straight above under a 14 degree sun, with white, flat materials and no ambient
|
|
1117
|
+
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
|
|
1118
|
+
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
|
|
1119
|
+
texels finer than a pixel. There a pixel spans about 6.7 texels; against the share of each pixel's area a CPU trace
|
|
1120
|
+
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
|
|
1121
|
+
pixel's centre: 0.176 and 0.024). Cost not timed.
|
|
1122
|
+
|
|
1123
|
+
- Relief: the layers' heights blended by the terrain's weights with the materials' `heightBlend`, from the top
|
|
1124
|
+
projection only, on ground no steeper than about 57 degrees (fading out from about 32); cliffs stay flat. The view
|
|
1125
|
+
ray reads the height maps' mipmaps at the pixel's footprint; the shadow ray reads the full-size map.
|
|
1126
|
+
- Shadows: soft over about 1.1 degrees either side of the relief's horizon; a ray takes at most 160 steps through the
|
|
1127
|
+
mipmap (squares passed over, descended into or tested) and counts what it has not reached as lit. Where layers of
|
|
1128
|
+
different `scale` overlap, the mipmap of the finest decides the squares and the coarser ones are bounded by up to
|
|
1129
|
+
four of their own texels. They need square surface maps a power of two in size (`'unsupported'` otherwise; pass
|
|
1130
|
+
`shadows: false`) and add an `r32float` maximum mipmap: 4 bytes a texel a layer plus a third, about 21 MiB for four
|
|
1131
|
+
1,024-texel layers.
|
|
1132
|
+
- Attach it after `TerrainMaterials`, before any effect that replaces the terrain's lit shader. `shadows` darkens the
|
|
1133
|
+
sun's light only, not ambient or image-based light.
|
|
1134
|
+
- Shadow maps: with `@margoengine/shadows` (`Shadows` or `VirtualShadows`, attached before or after the displacement)
|
|
1135
|
+
objects' sun shadows fall on the relief. The maps hold the clipmap surface, the relief's top, so each point reads
|
|
1136
|
+
them where its ray toward the sun leaves that surface: the relief is not shadowed by its own ground (checked on a
|
|
1137
|
+
real GPU by `test/displace-shadows.browser.mjs`: none of the lit relief darkened; before, 95.2% did), and an object
|
|
1138
|
+
sitting within the relief's depth does not shadow it. The relief casts no shadow onto other objects.
|
|
1139
|
+
|
|
1140
|
+
## Wind-built dunes: `@margoengine/terrain/dunes`
|
|
1141
|
+
|
|
1142
|
+
`duneField(options)` returns the heights of a dune field (a `Float32Array`, `width` heights a row, `depth` rows, in
|
|
1143
|
+
metres) to feed a `Terrain` heightmap or a `BiomeWorld`'s `height.samples`. Each dune has a long gentle windward side
|
|
1144
|
+
whose steepest slope is `stoss` and a short slip face at the angle of repose `lee`, the profile measured on real
|
|
1145
|
+
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.
|
|
1146
|
+
`transverse` lays ridges across the wind every `spacing` metres, their crests wandering and varying in height
|
|
1147
|
+
(`irregularity`); a ridge too high for its spacing is lowered so it fits. `barchan` lays isolated crescents, about 11
|
|
1148
|
+
heights wide, with their horns trailing downwind and some cells left bare where sand is short. `base` builds the dunes on
|
|
1149
|
+
ground you already have (real heights, a beach), and `amount(x, z)` (0 to 1) keeps them off wet sand or a launch flat.
|
|
1150
|
+
|
|
1151
|
+
```ts
|
|
1152
|
+
import {duneField, duneLengths, slopeAt} from 'margoengine/terrain/dunes';
|
|
1153
|
+
const heights = duneField({width: 256, depth: 256, cellSize: 1, type: 'transverse', height: 5, spacing: 70, wind: 90, seed: 2});
|
|
1154
|
+
console.log(heights.length, duneLengths(5).stoss.toFixed(1), slopeAt(heights, 256, 128, 128).toFixed(1)); // 65536 37.0 ...
|
|
1155
|
+
```
|
|
1156
|
+
|
|
1157
|
+
| Option | Default | Meaning |
|
|
1158
|
+
| --- | --- | --- |
|
|
1159
|
+
| `width`, `depth` | required | heights along x and z (2 or more each, at most 67,108,864 in all) |
|
|
1160
|
+
| `cellSize` | 1 | metres between heights |
|
|
1161
|
+
| `origin` | [0, 0] | world x and z of the first height |
|
|
1162
|
+
| `wind` | 90 | degrees from +x toward +z that the wind blows toward; slip faces face downwind |
|
|
1163
|
+
| `type` | `'transverse'` | `'transverse'` ridges (plenty of sand) or `'barchan'` crescents (scarce sand), Werner 1995 |
|
|
1164
|
+
| `height` | 4 | crest height in metres |
|
|
1165
|
+
| `spacing` | 70 | crest-to-crest spacing (transverse) or the cell each barchan stands in, metres |
|
|
1166
|
+
| `stoss` | 12 | steepest windward slope, 3 to 20 degrees |
|
|
1167
|
+
| `lee` | 32 | slip face, the angle of repose of dry sand, 25 to 36 degrees |
|
|
1168
|
+
| `irregularity` | 0.35 | 0 to 1: crest wander, height variation, bare cells and low hummocks between dunes |
|
|
1169
|
+
| `seed` | 1 | the same seed gives the same heights on every machine |
|
|
1170
|
+
| `base` | flat 0 | heights to build on, the grid's layout (not changed) |
|
|
1171
|
+
| `amount` | 1 | `(x, z) => 0..1`, the share of dune height at each point |
|
|
1172
|
+
| `round` | 0 | metres over which each brink is rounded; 0 keeps a sharp brink |
|
|
1173
|
+
|
|
1174
|
+
`duneHill(x, z, {crest, height, wind, halfWidth, stoss, lee, round})` is the height of one big isolated dune, such as
|
|
1175
|
+
a coastal hill built by one main wind: a long windward side at `stoss` (default 12 degrees), a crest rounded over
|
|
1176
|
+
`round` metres (default a third of the height), a lee face at `lee` (default 30 degrees, a settled face) and a crest
|
|
1177
|
+
that falls off as a raised cosine to `halfWidth` across the wind (default 5 heights). Add it to a field or to real
|
|
1178
|
+
heights:
|
|
1179
|
+
|
|
1180
|
+
```ts
|
|
1181
|
+
import {duneHill} from 'margoengine/terrain/dunes';
|
|
1182
|
+
const hill = {crest: [0, 0] as [number, number], height: 30, wind: 90, stoss: 12, lee: 30};
|
|
1183
|
+
console.log(duneHill(0, 0, hill).toFixed(1), duneHill(0, -100, hill).toFixed(1), duneHill(0, 40, hill).toFixed(1)); // crest, windward, lee
|
|
1184
|
+
```
|
|
1185
|
+
|
|
1186
|
+
`duneProfile(p, height, tanStoss, tanLee, toe, round)` is one dune's height `p` metres downwind of its windward toe, `duneLengths`
|
|
1187
|
+
its windward and lee lengths, `barchan(u, v, height, tanStoss, tanLee)` one crescent around its crest, and
|
|
1188
|
+
`slopeAt(heights, width, i, j, cellSize)` the steepest slope at a height in degrees. Aeolian ripples (5 to 20 cm,
|
|
1189
|
+
Anderson 1987) are far finer than a terrain cell and belong in the sand material's relief, not the height field. Plain
|
|
1190
|
+
JavaScript with no GPU and no dependency; the dunes do not move (no saltation or avalanche simulation in v1.0.0,
|
|
1191
|
+
docs/limits.md).
|
|
1192
|
+
|
|
1193
|
+
Sources: Bagnold 1941, *The Physics of Blown Sand and Desert Dunes* (London, 1941), slip faces at the angle of repose;
|
|
1194
|
+
Sauermann, Kroy and Herrmann 2001, "Continuum saltation model for sand dunes", Phys. Rev. E 64, 031305
|
|
1195
|
+
(https://doi.org/10.1103/PhysRevE.64.031305), and Kroy, Sauermann and Herrmann 2002, "Minimal model for sand dunes", Phys.
|
|
1196
|
+
Rev. Lett. 88, 054301 (https://doi.org/10.1103/PhysRevLett.88.054301), the convex windward profile and the brink at the
|
|
1197
|
+
crest; Hersen, Douady and Andreotti 2002, "Relevant length scale of barchan dunes", Phys. Rev. Lett. 89, 264301
|
|
1198
|
+
(https://doi.org/10.1103/PhysRevLett.89.264301), barchan width in proportion to height; Andreotti, Claudin and Douady 2002,
|
|
1199
|
+
"Selection of dune shapes and velocities", Eur. Phys. J. B 28, 321 (https://doi.org/10.1140/epjb/e2002-00236-4), sinuous
|
|
1200
|
+
crests; Werner 1995, "Eolian dunes: computer simulations and attractor interpretation", Geology 23(12), 1107
|
|
1201
|
+
(https://doi.org/10.1130/0091-7613(1995)023<1107:EDCSAA>2.3.CO;2), ridges against crescents by sand supply; Anderson 1987,
|
|
1202
|
+
"A theoretical model for aeolian impact ripples", Sedimentology 34, 943 (https://doi.org/10.1111/j.1365-3091.1987.tb00814.x).
|
|
1203
|
+
|
|
1204
|
+
## Wind scour and shadow dunes: `@margoengine/terrain/scour`
|
|
1205
|
+
|
|
1206
|
+
`windScour(options)` is the change of ground height that wind leaves on sand round obstacles. `change(x, z)` returns
|
|
1207
|
+
metres to add to your ground, and `bounds` the rectangles outside which it is 0:
|
|
1208
|
+
|
|
1209
|
+
- round a **building**, a scour moat along the windward wall and flanks (deepest at the windward corners), a deposit
|
|
1210
|
+
horseshoe whose crest stands 0.65 building heights upwind, and two tails past the flanks that run `tail` times
|
|
1211
|
+
B = w^(2/3) h^(1/3) past the leeward wall (w the width across the wind, h the height);
|
|
1212
|
+
- behind a **plant** or other small porous obstacle, a pyramidal shadow dune: half the obstacle's width times the side
|
|
1213
|
+
slope high, its length shorter in a stronger wind.
|
|
1214
|
+
|
|
1215
|
+
Nothing changes at a building's walls (it stays on the ground it stood on), at or below `threshold`, or far from every
|
|
1216
|
+
obstacle. A shed's moat is about 1.4 m wide, finer than most ground cells, so `refinedHeightfieldGeometry` builds the
|
|
1217
|
+
ground with the cells that touch `regions` split `subdivide` times a side. The split cells lie on the coarse triangles
|
|
1218
|
+
(grass placed on the coarse grid still stands on the mesh) until `add` moves them, and the mesh has no cracks.
|
|
1219
|
+
|
|
1220
|
+
```ts
|
|
1221
|
+
import {refinedHeightfieldGeometry, windScour} from 'margoengine/terrain/scour';
|
|
1222
|
+
const wind = windScour({
|
|
1223
|
+
wind: 90, speed: 11,
|
|
1224
|
+
buildings: [{center: [0, 0], size: [12, 5], height: 3}],
|
|
1225
|
+
plants: [{center: [14, 6], width: 1}],
|
|
1226
|
+
});
|
|
1227
|
+
const data = refinedHeightfieldGeometry((x, z) => 0.02 * x, {size: [200, 200], resolution: 100, regions: wind.bounds, add: wind.change});
|
|
1228
|
+
console.log(wind.change(0, -3.3).toFixed(2), wind.change(0, -4.5).toFixed(2), data.indices.length / 3); // moat, horseshoe, triangles
|
|
1229
|
+
```
|
|
1230
|
+
|
|
1231
|
+
| `windScour` option | Default | Meaning |
|
|
1232
|
+
| --- | --- | --- |
|
|
1233
|
+
| `buildings` | none | `{center, size, height, yaw}`: footprint middle (x, z), its x and z extents, ridge height, turn about +y in radians |
|
|
1234
|
+
| `plants` | none | `{center, width}`: obstacles that grow a shadow dune |
|
|
1235
|
+
| `wind` | 90 | degrees from +x toward +z that the wind blows toward, as `duneField` |
|
|
1236
|
+
| `speed` | 11 | wind speed at 10 m, m/s |
|
|
1237
|
+
| `threshold` | 6.6 | m/s at or below which nothing changes (0.25 mm sand); the forms are full from 1.3 times it |
|
|
1238
|
+
| `scour` | 0.06 | moat depth as a share of the building's height, 0 to 0.075 |
|
|
1239
|
+
| `deposit` | 0.07 | horseshoe and tail height as a share of the building's height, 0 to 0.3 |
|
|
1240
|
+
| `tail` | 3 | tail length past the leeward wall in units of B, 0.5 to 8 |
|
|
1241
|
+
| `slope` | 20 | side slope of a shadow dune, 5 to 32 degrees |
|
|
1242
|
+
|
|
1243
|
+
| `refinedHeightfieldGeometry` option | Default | Meaning |
|
|
1244
|
+
| --- | --- | --- |
|
|
1245
|
+
| `size`, `origin`, `resolution` | as `heightfieldGeometry` | the coarse grid |
|
|
1246
|
+
| `regions` | required | `[minX, minZ, maxX, maxZ]` rectangles whose cells are split |
|
|
1247
|
+
| `subdivide` | 5 | splits per cell side, 1 to 16 |
|
|
1248
|
+
| `add` | none | `(x, z) =>` metres added at every vertex |
|
|
1249
|
+
|
|
1250
|
+
`scourScale(width, height)` is B, and `shadowDuneLength(width, speed)` a shadow dune's length. Plain JavaScript with no
|
|
1251
|
+
GPU. The papers give where the forms stand, how long they are and the shadow dune's shape; the moat and ridge depths and
|
|
1252
|
+
their cross profiles are Margo's choices (the options above). One steady wind direction, no change over time, sand not
|
|
1253
|
+
conserved between moat and deposits, and no scour round open structures such as rails or posts (docs/limits.md).
|
|
1254
|
+
|
|
1255
|
+
Sources: Hunt, Abell, Peterka and Woo 1978, "Kinematical studies of the flows around free or surface-mounted obstacles",
|
|
1256
|
+
J. Fluid Mech. 86, 179 (https://doi.org/10.1017/S0022112078001068), the horseshoe vortex; Tominaga, Okaze and Mochida
|
|
1257
|
+
2018, J. Wind Eng. Ind. Aerodyn. 182, 262 (https://doi.org/10.1016/j.jweia.2018.09.008), erosion at the windward
|
|
1258
|
+
corners; Poppema, Wijnberg, Mulder, Vos and Hulscher 2021, Coastal Engineering 168, 103866
|
|
1259
|
+
(https://doi.org/10.1016/j.coastaleng.2021.103866), the length scale B; the upwind deposit distance of Thiis and Gjessing
|
|
1260
|
+
1999 as reported in D. Poppema, University of Twente report 2020R-001-WEM-001
|
|
1261
|
+
(https://ris.utwente.nl/ws/portalfiles/portal/168667961/2020R_001_WEM_001_Daan_Poppema.pdf); Hesp 1981, "The formation of
|
|
1262
|
+
shadow dunes", J. Sed. Petrology 51, 101 (https://doi.org/10.1306/212F7C1B-2B24-11D7-8648000102C1865D), its height
|
|
1263
|
+
rule as given by Hesp and Smyth 2017, "Nebkha flow dynamics and shadow dune formation", Geomorphology 282, 27
|
|
1264
|
+
(https://doi.org/10.1016/j.geomorph.2016.12.026; accepted manuscript https://hira.hope.ac.uk/1824/), which gives the
|
|
1265
|
+
lengths.
|
|
1266
|
+
|
|
1267
|
+
## Stored height grids: `@margoengine/terrain/height-grid`
|
|
1268
|
+
|
|
1269
|
+
`gridHeightField(options)` turns a height grid you already have (a USGS 3DEP or SRTM tile read from a GeoTIFF, a decoded
|
|
1270
|
+
heightmap, any row-major numbers) into the `(x, z) => height` function that `heightfield`, `heightfieldGeometry` and
|
|
1271
|
+
`TerrainHeightmap` take. It reads bilinearly between texels over the grid's real ground size, holds the edge heights
|
|
1272
|
+
outside the box, and fills missing samples (NaN, or the file's no-data value such as -32768 or -999999) before the first
|
|
1273
|
+
read. The function also carries `min`, `max`, `origin`, `size` and `filled` (how many samples were missing).
|
|
1274
|
+
|
|
1275
|
+
```ts
|
|
1276
|
+
import {heightfield} from 'margoengine/terrain';
|
|
1277
|
+
import {gridHeightField} from 'margoengine/terrain/height-grid';
|
|
1278
|
+
const heights = new Float32Array([0, 1, 0, 1, 2, -999999, 0, 1, 0]); // 3 by 3, one missing sample
|
|
1279
|
+
const ground = gridHeightField({width: 3, height: 3, heights, size: [300, 300], noData: -999999, exaggeration: 1.5});
|
|
1280
|
+
console.log(ground(0, 0), ground.max, ground.filled); // 3 3 1
|
|
1281
|
+
const mesh = heightfield(ground, {size: [300, 300], resolution: 96});
|
|
1282
|
+
```
|
|
1283
|
+
|
|
1284
|
+
| Option | Default | Meaning |
|
|
1285
|
+
| --- | --- | --- |
|
|
1286
|
+
| `width`, `height` | required | texels across x and down z, integers 2 to 65,536 |
|
|
1287
|
+
| `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 |
|
|
1288
|
+
| `size` | required | real ground extent `[x, z]`, each above 0 to 100,000 |
|
|
1289
|
+
| `origin` | centred on 0 | world x and z of the minimum corner |
|
|
1290
|
+
| `exaggeration` | 1 | vertical scale applied to the samples |
|
|
1291
|
+
| `base` | 0 | added to every height after `exaggeration` |
|
|
1292
|
+
| `noData` | none | a sample value that means no data (compared as float32); NaN always does |
|
|
1293
|
+
| `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 |
|
|
1294
|
+
| `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) |
|
|
1295
|
+
| `flipRows` | false | row 0 at the maximum z (a south-up grid) |
|
|
1296
|
+
|
|
1297
|
+
Sources: bilinear interpolation, W. Press and others, Numerical Recipes, 3rd ed., 2007, section 3.6; no-data values,
|
|
1298
|
+
the GDAL raster data model (https://gdal.org/user/raster_data_model.html); PixelIsArea and PixelIsPoint, OGC GeoTIFF
|
|
1299
|
+
standard 1.1 (OGC 19-008r4); the nearest-valid sweep, A. Rosenfeld and J. Pfaltz, "Sequential operations in digital
|
|
1300
|
+
picture processing", Journal of the ACM 13(4), 1966. Our own code from those descriptions.
|
|
1301
|
+
|
|
1302
|
+
## Real elevation and bathymetry: `@margoengine/terrain/elevation`
|
|
1303
|
+
|
|
1304
|
+
A surveyed grid in latitude and longitude (a NOAA bathymetry grid, an SRTM or 3DEP tile in EPSG:4326 or 4269) becomes
|
|
1305
|
+
ground in metres around a site in three calls:
|
|
1306
|
+
|
|
1307
|
+
- `readElevation(page, georeference, options)` takes a decoded GeoTIFF page (`openTIFF(bytes).read(0)` from
|
|
1308
|
+
`@margoengine/decoders/tiff`, which reads strips and tiles, uncompressed, LZW, Deflate and the rest, float32, int16
|
|
1309
|
+
and other sample types) and its georeference (`readGeoTIFF(page)` from `@margoengine/decoders/geotiff`: the model
|
|
1310
|
+
tiepoint and pixel scale, the GeoKeys and GDAL_NODATA). It crops to a `window` in degrees, marks no-data samples NaN,
|
|
1311
|
+
turns feet into metres when the file's VerticalUnits says so, and records the vertical `datum` you name (a GeoTIFF
|
|
1312
|
+
rarely carries it). `at(lat, lon)` reads it bilinearly.
|
|
1313
|
+
- `localFrame(site)` is the local tangent plane at a site on the GRS 80 ellipsoid (or `WGS84`): x east, y up, z south
|
|
1314
|
+
(north is -z, as in `@margoengine/sky`), with `toLocal(lat, lon, height)` and its exact inverse `toGeographic(x, z, y)`.
|
|
1315
|
+
- `elevationField(elevation, {site, spacing})` resamples the window onto that plane as the `(x, z) => height` function
|
|
1316
|
+
that `heightfield`, `Terrain`, `TerrainQuery` and the physics `TerrainBed` (`elevations`) take; it is a
|
|
1317
|
+
`gridHeightField`, so it carries `min`, `max`, `origin`, `size` and `filled`, plus `frame`, `datum`, `surveyed` (the
|
|
1318
|
+
source cell size in metres at the site) and `detailed`.
|
|
1319
|
+
|
|
1320
|
+
```ts
|
|
1321
|
+
import {elevationField, readElevation} from 'margoengine/terrain/elevation';
|
|
1322
|
+
// A 3 by 3 grid of 3 arc-second cells, as openTIFF(bytes).read(0) and readGeoTIFF(page) give it.
|
|
1323
|
+
const page = {width: 3, height: 3, samples: new Float32Array([-30, -20, -30, -20, -12, -20, -30, -20, -9999])};
|
|
1324
|
+
const georeference = {
|
|
1325
|
+
transform: [3 / 3600, 0, -85.8, 0, -3 / 3600, 47.42] as const,
|
|
1326
|
+
raster: 'area' as const,
|
|
1327
|
+
noData: -9999,
|
|
1328
|
+
crs: {model: 'geographic', epsg: 4269, citation: 'NAD83'},
|
|
1329
|
+
verticalUnits: null,
|
|
1330
|
+
};
|
|
1331
|
+
const shoal = readElevation(page, georeference, {datum: 'Lake Superior Low Water Datum, 183.2 m IGLD 1985'});
|
|
1332
|
+
const bed = elevationField(shoal, {site: {lat: 47.41875, lon: -85.79875}, spacing: 10});
|
|
1333
|
+
console.log(shoal.missing, bed(0, 0).toFixed(1), bed.surveyed[1].toFixed(1), bed.datum); // 1 -12.0 92.6 Lake Superior ...
|
|
1334
|
+
```
|
|
1335
|
+
|
|
1336
|
+
| `elevationField` option | Default | Meaning |
|
|
1337
|
+
| --- | --- | --- |
|
|
1338
|
+
| `site` | required | `{lat, lon, height?}` or a `localFrame`: the world origin |
|
|
1339
|
+
| `size` | the largest box centred on the site inside the window | world `[x, z]` metres, each up to 100,000 |
|
|
1340
|
+
| `origin` | `-size / 2` | world x and z of the minimum corner, for a box that is not centred on the site |
|
|
1341
|
+
| `spacing` | the source's north-south cell size at the site | metres between resampled texels |
|
|
1342
|
+
| `fill` | `'nearest'` | what a missing sample becomes, as `gridHeightField` |
|
|
1343
|
+
| `curvature` | false | false: y is the height above the datum, so a level lake at the datum is flat at y = 0 over the whole window; true: y is the tangent plane's up, which falls d^2 / 2R below it (70 m at 30 km) |
|
|
1344
|
+
| `detail` | none | `(x, z) => metres` added to every texel: the engine's own procedural relief below the survey's cell size; `detailed` is then true, so it is never mistaken for survey data |
|
|
1345
|
+
|
|
1346
|
+
Accuracy: the frame matches the ellipsoid's meridian and prime-vertical radii of curvature and inverts to below a
|
|
1347
|
+
millimetre 30 km out (Bowring's iteration). A 3 arc-second grid holds no relief finer than about 90 m north to south;
|
|
1348
|
+
contour-derived lake grids also round shoal tops off, so a charted least depth can be several metres shallower than the
|
|
1349
|
+
grid's. Only `'geographic'` rasters are read; a projected (UTM) raster is refused, and a rotated raster too.
|
|
1350
|
+
|
|
1351
|
+
Sources: OGC GeoTIFF Standard 1.1, OGC 19-008r4 (2019), section 7; H. Moritz, "Geodetic Reference System 1980",
|
|
1352
|
+
Bulletin Geodesique 54(3), 1980; NIMA TR8350.2, "Department of Defense World Geodetic System 1984", 3rd ed., 2000,
|
|
1353
|
+
sections 3 and 4; B. R. Bowring, "Transformation from spatial to geographical coordinates", Survey Review 23(181), 1976;
|
|
1354
|
+
B. Hofmann-Wellenhof, H. Lichtenegger and E. Wasle, GNSS, Springer 2008, section 8.2.2 (the local east, north, up
|
|
1355
|
+
frame); W. Press and others, Numerical Recipes, 3rd ed., 2007, section 3.6. Our own code from those descriptions.
|
|
1356
|
+
|
|
1357
|
+
## Footprints, tracks and trails: `@margoengine/terrain/deform`
|
|
1358
|
+
|
|
1359
|
+
`TerrainDeformation.attach(engine, terrain, options)` presses footprints, tyre tracks and trails into snow, mud and sand.
|
|
1360
|
+
Prints go into a deformation map of `size` texels a side, `texel` wide each, centred on the camera (or on what
|
|
1361
|
+
`follow` returns) and moved with it a texel at a time, so prints stay while they are within half its width; the
|
|
1362
|
+
ground pushed aside rises in a rim around each print; prints fill back in over `fade` seconds. The terrain's lit shader
|
|
1363
|
+
walks each near pixel's view ray down through the prints (parallax occlusion mapping) and shades the ground it meets,
|
|
1364
|
+
with the print's slope as its normal and darkened where it is pressed, so a footprint shows its walls and hides its far
|
|
1365
|
+
floor. No vertex moves: clipmap cells are far wider than a footprint.
|
|
1366
|
+
|
|
1367
|
+
```ts
|
|
1368
|
+
import {Engine} from 'margoengine/core';
|
|
1369
|
+
import {Terrain} from 'margoengine/terrain';
|
|
1370
|
+
import {TerrainDeformation} from 'margoengine/terrain/deform';
|
|
1371
|
+
const engine = await Engine.create(document.querySelector('canvas')!);
|
|
1372
|
+
const terrain = Terrain.attach(engine, {
|
|
1373
|
+
size: [256, 256], origin: [-128, -128], heightScale: 10,
|
|
1374
|
+
layers: [0, 1, 2, 3].map(() => ({height: [-100, 100] as [number, number], slope: [0, 1] as [number, number], scale: 0.5})),
|
|
1375
|
+
textures(device) {
|
|
1376
|
+
const heightmap = device.createTexture({size: [2, 2], format: 'r32float', usage: 6});
|
|
1377
|
+
device.queue.writeTexture({texture: heightmap}, new Float32Array(4), {bytesPerRow: 8}, [2, 2]);
|
|
1378
|
+
const layers = device.createTexture({size: [1, 1, 4], format: 'rgba8unorm-srgb', usage: 6});
|
|
1379
|
+
device.queue.writeTexture({texture: layers}, new Uint8Array(16).fill(230), {bytesPerRow: 4, rowsPerImage: 1}, [1, 1, 4]);
|
|
1380
|
+
return {heightmap, layers};
|
|
1381
|
+
},
|
|
1382
|
+
});
|
|
1383
|
+
const snow = TerrainDeformation.attach(engine, terrain, {
|
|
1384
|
+
depth: 0.15, // deepest print, and a print's depth by default
|
|
1385
|
+
fade: 120, // seconds for a full-depth print to fill back in; 0 keeps prints
|
|
1386
|
+
rim: 0.25, // the rim's height as a share of the print's depth
|
|
1387
|
+
});
|
|
1388
|
+
for (let step = 0; step < 10; step++) // a walk along +X, left and right feet
|
|
1389
|
+
snow.footprint(step * 0.35, step % 2 ? 0.12 : -0.12, {angle: 0, depth: 0.08});
|
|
1390
|
+
snow.track([-5, 2], [5, 2.5], {width: 0.22}); // a tyre
|
|
1391
|
+
snow.trail([[0, -3], [1, -3.5], [2, -3.2]], {width: 0.5, depth: 0.04}); // a sledge
|
|
1392
|
+
engine.start();
|
|
1393
|
+
```
|
|
1394
|
+
|
|
1395
|
+
**Ground meshes, walking and kept prints.** `TerrainDeformation.attach(engine, mesh, options)` shades a ground mesh
|
|
1396
|
+
drawn by core's standard shader the same way, over `TerrainColors` if it has them (attach it after them): the print
|
|
1397
|
+
darkens their colour, takes its own slope as normal and presses their ripples flat. `walk(points, options)` lays the
|
|
1398
|
+
footprints of someone walking through the points: left and right in turn, a heel and a forefoot each, `step` 0.75 m,
|
|
1399
|
+
`straddle` 0.08 m between the feet's lines, `toeOut` 0.12 radians, feet `length` 0.28 by `width` 0.11 m, unevenly by
|
|
1400
|
+
`jitter` 0.5 from `seed` 1 (the means of Murray, Drought and Kory, J. Bone Joint Surg. 46-A, 1964, a little shorter
|
|
1401
|
+
for loose ground). `persist: true` keeps every print: one the map leaves is pressed again when the map returns (needs
|
|
1402
|
+
`fade` 0, its default then; at most 16,384 prints and track pieces). Real-GPU check, WebGPU and the WebGL2 layer:
|
|
1403
|
+
`node packages/terrain/test/deform-mesh.browser.mjs`.
|
|
1404
|
+
|
|
1405
|
+
```ts
|
|
1406
|
+
import {Engine, PbrMaterial} from 'margoengine/core';
|
|
1407
|
+
import {heightfield, TerrainColors} from 'margoengine/terrain';
|
|
1408
|
+
import {TerrainDeformation} from 'margoengine/terrain/deform';
|
|
1409
|
+
|
|
1410
|
+
const engine = await Engine.create(document.querySelector('canvas')!, {
|
|
1411
|
+
camera: {position: [0, 1.6, 4], target: [0, 0, -2]},
|
|
1412
|
+
});
|
|
1413
|
+
const ground = engine
|
|
1414
|
+
.createMesh()
|
|
1415
|
+
.setGeometry(heightfield((x, z) => 0.1 * Math.sin(x / 3) * Math.cos(z / 4), {size: [40, 40]}))
|
|
1416
|
+
.setMaterial(new PbrMaterial({color: [0.52, 0.46, 0.35], roughness: 0.92}));
|
|
1417
|
+
TerrainColors.attach(engine, ground, {sand: [0.52, 0.46, 0.35], shore: [80, 90]});
|
|
1418
|
+
const prints = TerrainDeformation.attach(engine, ground, {depth: 0.045, darken: 0.22, persist: true});
|
|
1419
|
+
prints.walk([[0.5, 3], [-0.5, -2], [1.5, -8]], {seed: 7});
|
|
1420
|
+
engine.start();
|
|
1421
|
+
```
|
|
1422
|
+
|
|
1423
|
+
- A print is pressed on the GPU at the next frame: a footprint is an ellipse (`length` 0.28 and `width` 0.11 by
|
|
1424
|
+
default, turned by `angle`), a track a band of `width` with round ends; the full depth reaches 55% of the way to
|
|
1425
|
+
the edge and falls smoothly to 0 there, and the rim peaks at 1.2 times the half size. Each texel keeps the deepest
|
|
1426
|
+
print over it. With painted `weights`, `layers` gives each layer's softness (rock 0 takes no print).
|
|
1427
|
+
- Defaults: `size` 1,024 texels of 2.5 cm (25.6 m), `depth` 0.15, `rim` 0.25, `fade` 120, `darken` 0.25,
|
|
1428
|
+
`distance` 40 (prints shown within, fading over the last quarter), `steps` 12.
|
|
1429
|
+
- Memory: 16 bytes a texel (the depths and rims, and the `rgba16float` relief `texture`): 16 MiB at the defaults.
|
|
1430
|
+
A frame with a print, a move or `fade` runs a compute pass over the map; a still frame with `fade: 0` runs none.
|
|
1431
|
+
- Prints the window leaves are gone when it comes back; device loss clears every print. The terrain's geometry,
|
|
1432
|
+
shadows and SSR capture do not see prints. Attach it after the terrain's other effects.
|
|
1433
|
+
|
|
1434
|
+
Checked on a real GPU by `test/deform.browser.mjs` (in `test:gpu`, Radeon 680M, 2026-11-08): a footprint and a track
|
|
1435
|
+
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%;
|
|
1436
|
+
nothing pressed draws exactly the picture without deformation; seen from 0.6 m under a slanted sun, the deformed picture
|
|
1437
|
+
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
|
|
1438
|
+
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
|
|
1439
|
+
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
|
|
1440
|
+
softness 0 takes none. Cost not timed.
|
|
1441
|
+
|
|
1442
|
+
## Ground that changes on screen: `@margoengine/terrain/ground-change`
|
|
1443
|
+
|
|
1444
|
+
`GroundChange.attach(engine, mesh, options)` changes a heightfield mesh's ground over film time: gullies cut back from
|
|
1445
|
+
their mouths, river banks retreat, scour holes deepen, slopes fail and run out, a flood leaves mud that dries, ash falls
|
|
1446
|
+
from a vent, lava flows and cools, and fire leaves a burn scar that whitens. Each event is a closed form of film time,
|
|
1447
|
+
so the ground at a time is the same whether a film is rendered in order, seeked to that time or rendered again. Each
|
|
1448
|
+
frame whose time moved recomputes only the vertices the active events can touch, writes their heights and normals into
|
|
1449
|
+
the mesh's own vertex buffer (so shadows and every other pass see the new shape) and lays the covers over the mesh's
|
|
1450
|
+
colour (after `TerrainColors`, if attached), with lava's glow added to its light.
|
|
1451
|
+
|
|
1452
|
+
```ts
|
|
1453
|
+
import {Engine, PbrMaterial} from 'margoengine/core';
|
|
1454
|
+
import {heightfieldGeometry, TerrainColors} from 'margoengine/terrain';
|
|
1455
|
+
import {toGeometry} from 'margoengine/geometry/utils';
|
|
1456
|
+
import {GroundChange} from 'margoengine/terrain/ground-change';
|
|
1457
|
+
import {applyGroundChangeSettings} from 'margoengine/terrain/ground-change-settings';
|
|
1458
|
+
const engine = await Engine.create(document.querySelector('canvas')!);
|
|
1459
|
+
const grid = {size: [400, 400] as [number, number], origin: [-200, -200] as [number, number], resolution: 512};
|
|
1460
|
+
const hills = (x: number, z: number) => 0.05 * z + 4 * Math.sin(x * 0.02) * Math.cos(z * 0.015);
|
|
1461
|
+
const ground = engine.createMesh()
|
|
1462
|
+
.setGeometry(toGeometry(heightfieldGeometry(hills, grid)))
|
|
1463
|
+
.setMaterial(new PbrMaterial({color: [0.3, 0.26, 0.2], roughness: 0.9}));
|
|
1464
|
+
TerrainColors.attach(engine, ground);
|
|
1465
|
+
const change = GroundChange.attach(engine, ground, {
|
|
1466
|
+
grid, // the grid the mesh was built on
|
|
1467
|
+
events: [
|
|
1468
|
+
{kind: 'gully', path: [[-80, -120], [-60, -40], [-70, 30]], width: 6, depth: 2.5, duration: 40},
|
|
1469
|
+
{kind: 'bank', path: [[-200, 120], [200, 140]], river: 'left', retreat: 12, bed: 2, duration: 60},
|
|
1470
|
+
{kind: 'scour', center: [60, -20], radius: 8, depth: 3, flow: [0, 1], start: 10},
|
|
1471
|
+
{kind: 'slide', from: [120, 160], to: [140, 60], width: 30, depth: 4, start: 20},
|
|
1472
|
+
{kind: 'mud', shore: [[-200, -180], [200, -180]], land: 'right', reach: 250, thickness: 0.3, duration: 90},
|
|
1473
|
+
{kind: 'ash', vent: [150, -150], thickness: 0.08, half: 80, wind: [6, 2], start: 30, duration: 60},
|
|
1474
|
+
{kind: 'lava', path: [[150, -150], [100, -60], [40, -40]], width: 14, thickness: 2, start: 30, duration: 120},
|
|
1475
|
+
{kind: 'burn', ignition: [-120, 60], wind: [5, -1], rate: 0.6, start: 5, duration: 240},
|
|
1476
|
+
],
|
|
1477
|
+
});
|
|
1478
|
+
applyGroundChangeSettings(change, {'lava.glow': 16, 'wet.rain': null}); // null: wet with the weather's rain
|
|
1479
|
+
change.setTime(45); // or let frames advance it
|
|
1480
|
+
engine.start();
|
|
1481
|
+
const {height, lava, heat} = change.sample(100, -60); // stand a person or a prop on it
|
|
1482
|
+
console.log(height, lava, heat);
|
|
1483
|
+
```
|
|
1484
|
+
|
|
1485
|
+
On a clipmap `Terrain`, attach it to the terrain instead: the grid is the heightmap's texels, the changed heights are
|
|
1486
|
+
written into the heightmap itself (so every ring, the terrain's shadows and its normals show them), and the covers lie
|
|
1487
|
+
over `terrainColor` as a terrain lighting effect (after the terrain's other effects that replace its shader). The
|
|
1488
|
+
heightmap must be `r32float` with `COPY_SRC | COPY_DST` usage; its base is read back once (`await change.ready`).
|
|
1489
|
+
A terrain takes one GroundChange, which holds any number of events (`add(event)`); a second on the same terrain
|
|
1490
|
+
throws MargoError `'attached'` until the first is disposed.
|
|
1491
|
+
|
|
1492
|
+
```ts
|
|
1493
|
+
import {Engine} from 'margoengine/core';
|
|
1494
|
+
import {Terrain} from 'margoengine/terrain';
|
|
1495
|
+
import {GroundChange} from 'margoengine/terrain/ground-change';
|
|
1496
|
+
const engine = await Engine.create(document.querySelector('canvas')!);
|
|
1497
|
+
const n = 513, heights = new Float32Array(n * n).map((_, k) => 0.02 * Math.floor(k / n));
|
|
1498
|
+
const terrain = Terrain.attach(engine, {
|
|
1499
|
+
size: [512, 512], origin: [-256, -256], heightScale: 1,
|
|
1500
|
+
layers: Array.from({length: 4}, () => ({height: [-1e4, 1e4] as [number, number], slope: [0, 1] as [number, number], scale: 0.1})),
|
|
1501
|
+
textures: (device) => {
|
|
1502
|
+
const heightmap = device.createTexture({size: [n, n], format: 'r32float', usage: 15}); // COPY_SRC | COPY_DST | ...
|
|
1503
|
+
device.queue.writeTexture({texture: heightmap}, heights, {bytesPerRow: n * 4}, [n, n]);
|
|
1504
|
+
const layers = device.createTexture({size: [1, 1, 4], format: 'rgba8unorm-srgb', usage: 6});
|
|
1505
|
+
device.queue.writeTexture({texture: layers}, new Uint8Array(16).fill(128), {bytesPerRow: 4, rowsPerImage: 1}, [1, 1, 4]);
|
|
1506
|
+
return {heightmap, layers};
|
|
1507
|
+
},
|
|
1508
|
+
});
|
|
1509
|
+
const change = GroundChange.attach(engine, terrain, { // grid left out: the heightmap's texels
|
|
1510
|
+
events: [{kind: 'lava', path: [[0, 0], [60, 120]], width: 20, thickness: 3, duration: 90}],
|
|
1511
|
+
});
|
|
1512
|
+
await change.ready; // the base heights are read back
|
|
1513
|
+
engine.start();
|
|
1514
|
+
```
|
|
1515
|
+
|
|
1516
|
+
|
|
1517
|
+
default 0.3) and `seed`:
|
|
1518
|
+
- `gully` (`path` mouth first, `width` 4, `depth` 1.5, `shape` `'v'` or `'u'`, `deposit` 0.6 of the eroded volume
|
|
1519
|
+
left as a fan of radius `fan` below the mouth): the headcut climbs the path at a steady rate and the channel behind
|
|
1520
|
+
it deepens and widens toward its full section.
|
|
1521
|
+
- `bank` (`path`, `river` side, `retreat` 6, `bed` world Y, `face` 60 degrees): the land side retreats at a steady
|
|
1522
|
+
rate, cut down to the bed with its face at the angle.
|
|
1523
|
+
- `scour` (`center`, `radius` 5, `depth` 2, `flow`, `deposit` 0.5): depth grows as 1 - exp(-t / T) to the full depth
|
|
1524
|
+
at the end; with a `flow` the scoured sand forms a mound downstream.
|
|
1525
|
+
- `crater` (`center`, `radius` 30, `depth` 10, `heave` 0.4 depth, `heaveTime` sqrt(2 heave / g), `domeSpread` 1.3,
|
|
1526
|
+
`ejecta` 0.7, `duration` 6 s after the heave): a buried explosion. The ground first heaves into a dome
|
|
1527
|
+
`domeSpread` times the crater's radius, the surface thrown up ballistically to `heave` metres (1.43 s for 10 m);
|
|
1528
|
+
then the dome vents and the crater opens over `duration`, a paraboloid bowl of `radius` and `depth` with a lip at
|
|
1529
|
+
the rim and an ejecta blanket thinning as (r / R)^-3 (McGetchin et al. 1973) out to 5 R, holding `ejecta` of the
|
|
1530
|
+
bowl's volume. Pair it with `BlastCloud` of `margoengine/weather/eruption` for the cloud:
|
|
1531
|
+
`{kind: 'crater', center: [0, 0], radius: 120, depth: 30, heave: 20, start: 2}`.
|
|
1532
|
+
`rays` (3 to 360 weights, one per equal sector from +X toward +Z, such as the mass a crater's blocks landed with
|
|
1533
|
+
in each) shapes the blanket by direction in place of noise rays, keeping its volume; `pits: false` leaves out the
|
|
1534
|
+
noise secondary pits when the real ones are a `craters` event of their own, and `blocks: false` the noise blocks of
|
|
1535
|
+
cap rock when the real blocks are drawn as rocks of their own.
|
|
1536
|
+
- `craters` (`craters`: 1 to 200,000 `{center, start, radius, depth, duration}`, `ejecta` 0.8): a field of small
|
|
1537
|
+
craters, each opening at its own time as a `crater` without its dome (a paraboloid bowl, its lip and a blanket to
|
|
1538
|
+
5 R), such as the secondaries a crater's blocks dig where they land (`impactCrater` of each `blockLanding` in
|
|
1539
|
+
`@margoengine/physics/crater`). Each point reads only the craters near it, so thousands cost little:
|
|
1540
|
+
`{kind: 'craters', craters: [{center: [40, 10], start: 6, radius: 2, depth: 1}]}`.
|
|
1541
|
+
- `fall` (`grid` `{columns, rows, width, depth, centre}`, `mass` kg/m^2 at each of its vertices in the physics bed's
|
|
1542
|
+
layout, row r and column c at r + (rows + 1) c, `density` 1,680 kg/m^3, `duration` 600 s): a deposit laid from a
|
|
1543
|
+
grid, such as the dust a plume drops (ATMO-06's `depositField` of `@margoengine/physics/airborne`). Its thickness is
|
|
1544
|
+
the mass over the bulk density, bilinear between vertices, laid at a steady rate, coloured by `cover` where it is
|
|
1545
|
+
thick (fully covering at 4 mm): `'ash'` (default) grey like fallen ash, or `'soil'` the fresh soil of the earth a
|
|
1546
|
+
crater threw up:
|
|
1547
|
+
`{kind: 'fall', grid: {columns: 2, rows: 2, width: 20, depth: 20, centre: [0, 0]}, mass: [0, 0, 0, 0, 3.36, 0, 0, 0, 0]}`.
|
|
1548
|
+
- `slide` (`from` crown, `to` toe, `width` 20, `depth` 3, `length` 40% of the way, `bulking` 1.15): the scar fails in
|
|
1549
|
+
the first third and the lobe runs out as a block under friction, holding the scar's volume times `bulking`.
|
|
1550
|
+
- `mud` (`shore`, `land` side, `reach` 400, `thickness` 0.25, `decay` reach / 3, `drying` 1,800 s): the front slows
|
|
1551
|
+
inland, the deposit thins by e every `decay` metres and dries by e every `drying` seconds after the water passes.
|
|
1552
|
+
- `ash` (`vent`, `thickness` 0.1, `half` 400, `wind`, `elongation` 1 + 0.25 wind speed): thickness halves every
|
|
1553
|
+
`half` metres of an isopach's crosswind half width, the isopachs stretched downwind; it falls at a steady rate.
|
|
1554
|
+
- `lava` (`path` vent first, `width` 12, `thickness` 2, `levee` 0.35, `cooling` 1, `glowCrust` 0.03): the front
|
|
1555
|
+
advances and slows, the sheet stands between levees, and its glow fades as the crust grows 0.0779 sqrt(hours) m
|
|
1556
|
+
(`cooling` real seconds per film second). With `arrival` (film seconds the front reaches each path point), and
|
|
1557
|
+
optionally `widths`, `thicknesses` and `glows` (one per point), the front follows those times instead and stops
|
|
1558
|
+
where they stop: `LavaFlow.lavaEvent()` of `margoengine/weather/lava` gives all four for a flow that runs down the
|
|
1559
|
+
slope. `pond` (`center`, `start`, `end`, `flux` m^3/s, `viscosity` Pa s, `density` 2,600) fills a pond where the
|
|
1560
|
+
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
|
|
1561
|
+
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
|
|
1562
|
+
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;
|
|
1563
|
+
`lavaEvent()` gives it for a flow that ponds. `roofs` (film seconds, one per point, 1e9 for never) roofs the
|
|
1564
|
+
channel from each point into a lava tube: from the front's arrival to then a crust grows in from the levees
|
|
1565
|
+
(Peterson et al. 1994) until it closes level with their crests, and nothing under it glows; `lavaEvent()` gives
|
|
1566
|
+
them for a flow on gentle ground. `skylights` (metres, default 200, 0 for none) is the mean spacing of skylights
|
|
1567
|
+
in a closed roof (Kauahikaua et al. 1998): a hole 0.8 widths long and half a width across in three of four
|
|
1568
|
+
stretches of that length, at a seeded place, showing the stream half a sheet down, fresh until `drains` (film
|
|
1569
|
+
seconds per point, 1e9 for never) and crusting from then on.
|
|
1570
|
+
- `burn` (`ignition`, `wind`, `rate` 0.3 m/s, `severity` 1, `ashing` 900 s, `consume` 0.03 m): a wind ellipse grows
|
|
1571
|
+
with the head running `rate`, its length to breadth from the wind; char whitens to ash by e every `ashing` seconds.
|
|
1572
|
+
- Look (all live, `setLook` or the rows of `@margoengine/terrain/ground-change-settings`): `soil`, `mud`, `ash`,
|
|
1573
|
+
`char`, `ashen` and `lava` colours, `glow` 12, `cracks` 0.7, `crackSize` 0.8 m, `wetDarkening` 0.55, `wetGloss` 0.5,
|
|
1574
|
+
and `rain` (null: a `WeatherDrive` writes the weather's rain; a number holds it).
|
|
1575
|
+
- Time: frames add their delta, or `clock` returns a shot's time, or `setTime(t)`; `advanceTime(delta)` is the clock
|
|
1576
|
+
step `seek` from `@margoengine/cutscene/seek` replays. Pass `shadows` so a cached still shadow map re-renders when the
|
|
1577
|
+
ground moves.
|
|
1578
|
+
- CPU model alone: `new GroundChange({grid, base, events})`, then `setTime` and `update()`; `change`, `heights` and
|
|
1579
|
+
`covers` hold the grid, `sample(x, z, t)` the exact value anywhere, `onChange` reports each changed rectangle.
|
|
1580
|
+
- Plants follow the ground: spread `change.scatterGround()` into a `Scatter` or `GrassScatter`
|
|
1581
|
+
(`@margoengine/scatter`). Its `heightmap` holds base plus change in metres, so plants rise and sink with the ground;
|
|
1582
|
+
its `densityMap` keeps them where the ground keeps its own cover and clears them under fresh soil, mud, ash, char and
|
|
1583
|
+
lava (255 less the strongest cover byte), so a gully or slide scar is bare, mud, ash and lava bury them and a burn
|
|
1584
|
+
scar is burned clear as its front passes; `bounds` is the rectangle both cover. On a terrain, `await change.ready`
|
|
1585
|
+
before the first frame. Dispose the scatter before the change (the maps go with it). Plants left standing at the edge
|
|
1586
|
+
of a cover take its char, ash and mud through `change.plantCovers()` (`{covers, bounds}`, rgba8 mud, ash, char and
|
|
1587
|
+
wetness per grid vertex) as the `ground` source of a `PlantStates` map (`@margoengine/scatter/states`).
|
|
1588
|
+
|
|
1589
|
+
```ts
|
|
1590
|
+
import {Engine, box} from 'margoengine/core';
|
|
1591
|
+
import {heightfieldGeometry} from 'margoengine/terrain';
|
|
1592
|
+
import {toGeometry} from 'margoengine/geometry/utils';
|
|
1593
|
+
import {GroundChange} from 'margoengine/terrain/ground-change';
|
|
1594
|
+
import {Scatter} from 'margoengine/scatter';
|
|
1595
|
+
const engine = await Engine.create(document.querySelector('canvas')!);
|
|
1596
|
+
const grid = {size: [48, 48] as [number, number], resolution: 96};
|
|
1597
|
+
const ground = engine.createMesh().setGeometry(toGeometry(heightfieldGeometry((x, z) => 0.05 * z, grid)));
|
|
1598
|
+
const change = GroundChange.attach(engine, ground, {
|
|
1599
|
+
grid,
|
|
1600
|
+
events: [{kind: 'burn', ignition: [-12, 0], rate: 0.25, duration: 60}],
|
|
1601
|
+
});
|
|
1602
|
+
Scatter.attach(engine, box(0.2, 0.8, 0.2), {count: 60000, area: [48, 48], ...change.scatterGround()});
|
|
1603
|
+
engine.start();
|
|
1604
|
+
```
|
|
1605
|
+
- A terrain's heightmap must be `r32float` with `COPY_SRC` and `COPY_DST` (the read back and the writes); the grid is
|
|
1606
|
+
its texels over the terrain's `origin` and `size` (`resolution` may differ along X and Z). Each changed frame writes
|
|
1607
|
+
the changed texels (base plus change over `heightScale`) and invalidates the terrain's cached shadows; `dispose()` or
|
|
1608
|
+
`engine.removePlugin(change.name)` writes the read-back texels back exactly. Normals the terrain takes from a
|
|
1609
|
+
`normalmap` are tilted by the change's slope in the fragment shader. The terrain's CPU copies (`TerrainQuery`,
|
|
1610
|
+
`TerrainSculpt.heights`) keep the base: read heights from `change.sample`. Memory on the GPU: 12 bytes a texel.
|
|
1611
|
+
- The mesh must be a `heightfieldGeometry` on the same grid at the identity transform (any vertex order). The mesh's
|
|
1612
|
+
culling sphere grows over any raise past it, so ground lifted at the edge of a small mesh is never culled early.
|
|
1613
|
+
`dispose()` or `engine.removePlugin(change.name)` gives the mesh its base heights, normals and sphere back, on the GPU
|
|
1614
|
+
and in the CPU copy. Memory: 8 bytes of cover textures and 25 bytes of CPU grids a
|
|
1615
|
+
vertex (26 MiB at 1,024 cells a side).
|
|
1616
|
+
|
|
1617
|
+
Checked by `test/ground-change.test.js` against each law (Sumer's scour curve to 1e-9, Pyle's halving, Hon's crust,
|
|
1618
|
+
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
|
|
1619
|
+
real GPU by `test/ground-change.browser.mjs` (in `test:gpu`, WebGPU and `MARGO_COMPAT=1`, 2026-11-17): a gully and a
|
|
1620
|
+
scour drawn through GroundChange are 0.05 of 255 on average from a mesh built from the same final heights, the uncut
|
|
1621
|
+
ground 1.29; fresh lava glows orange (235, 132, 63), cooled lava is dark (33, 28, 25), ash greys and char blackens the
|
|
1622
|
+
ground; time 40 reached directly or in 1,200 steps draws the same pixels; `dispose` and `engine.removePlugin` draw the
|
|
1623
|
+
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
|
|
1624
|
+
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
|
|
1625
|
+
apart, rings of 16 cells, WebGPU and `MARGO_COMPAT=1`): the heightmap holds base plus change exactly; the cut draws
|
|
1626
|
+
0.016 of 255 on average from a terrain whose heightmap is the final heights (the uncut 1.0); lava glows (235, 131, 63)
|
|
1627
|
+
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
|
|
1628
|
+
1.15); `dispose` and `engine.removePlugin` give every texel and pixel back. With a `Scatter` (`test/ground-change-scatter.browser.mjs`, both
|
|
1629
|
+
backends): its heightmap equals the changed heights exactly and its density map the cleared covers exactly; the burn
|
|
1630
|
+
scar and the lava draw no plants, the ground beside them 98 to 100% green.
|
|
1631
|
+
The whole-scene test page `examples/test-pages/ground-change.html` runs all eight kinds on one hillside with a weather
|
|
1632
|
+
drive (`node scripts/test-pages-browser.mjs --page=ground-change`). A changed frame recomputes the box around every
|
|
1633
|
+
active event on the CPU: 31 ms for 148,225 vertices with all eight active, measured once on a loaded dev PC.
|
|
1634
|
+
Sources: Mei, Decaudin and Hu 2007 (Pacific Graphics); Galin et al. 2019 (Computer Graphics Forum 38(2)); Bennett et
|
|
1635
|
+
al. 2000 (Water Resources Research 36(7)); Ikeda, Parker and Sawai 1981 (J. Fluid Mech. 112); Sumer, Fredsoe and
|
|
1636
|
+
Christiansen 1992 (J. Waterway, Port, Coastal and Ocean Eng. 118(1)); Heim 1932; Scheidegger 1973 (Rock Mechanics 5);
|
|
1637
|
+
Goto et al. 2011 (Marine Geology 290); Abe, Goto and Sugawara 2012 (Sedimentary Geology 282); Pyle 1989 (Bulletin of
|
|
1638
|
+
Volcanology 51); Hulme 1974 (Geophys. J. R. Astr. Soc. 39); Hon et al. 1994 (GSA Bulletin 106); Anderson 1983 (USDA
|
|
1639
|
+
INT-305); Alexander 1985 (8th Conf. Fire and Forest Meteorology); Key and Benson 2006 (USDA RMRS-GTR-164-CD).
|
|
1640
|
+
|
|
1641
|
+
## Furrowed fields: `@margoengine/terrain/furrows`
|
|
1642
|
+
|
|
1643
|
+
`FieldFurrows.attach(engine, terrain, { fields })` stripes each field's ground in the direction it was worked, so a field seen from a drone reads as worked ground and not one flat patch (the terrain's own fine detail fades out by 60 m):
|
|
1644
|
+
|
|
1645
|
+
- A field is `{ outline, furrow, spacing, depth }`: its [x, z] outline, the furrows' direction (radians from +x toward +z, as farmland's `Field.furrow` of `margoengine/biomes/farmland` gives it), their spacing (default 0.35 m, a plough's turned slice) and their contrast (default 0.25).
|
|
1646
|
+
- The fields are rasterised once into a small texture (`texel`, default 4 m, over `origin` and `size`, default their extent). Its lighting effect lays a raised cosine across the furrows over the terrain's colour.
|
|
1647
|
+
- The lands a field was ploughed in show as bands of 40 furrows at half that contrast.
|
|
1648
|
+
- Stripes narrower than about four screen pixels fade out, so a far field is its mean colour and never aliases.
|
|
1649
|
+
|
|
1650
|
+
It composes with `GroundChange`, `WetGround`, shadows and lights. `rasterise(fields, origin, size, texels)` gives the texture's bytes, and `furrows.at(x, z)` a texel:
|
|
1651
|
+
|
|
1652
|
+
```ts
|
|
1653
|
+
import {rasterise} from 'margoengine/terrain/furrows';
|
|
1654
|
+
|
|
1655
|
+
// A 40 m field furrowed along z, on 4 m texels over 80 m.
|
|
1656
|
+
const field = {outline: [[0, 0], [40, 0], [40, 40], [0, 40]] as [number, number][], furrow: Math.PI / 2, depth: 0.2};
|
|
1657
|
+
const bytes = rasterise([field], [-20, -20], [80, 80], [20, 20]);
|
|
1658
|
+
console.log(bytes.filter((_, k) => k % 4 === 2 && bytes[k] > 0).length); // 100 texels in the field
|
|
1659
|
+
```
|
|
1660
|
+
|
|
1661
|
+
## Wet ground where a flood has been: `@margoengine/terrain/wet-ground`
|
|
1662
|
+
|
|
1663
|
+
`WetGround.attach(engine, terrain, {record, origin, size})` draws a clipmap `Terrain` darker and glossier wherever a
|
|
1664
|
+
wetting record says the water has been, and dries it back over time. The record is `Flood.wetTexture` of
|
|
1665
|
+
`margoengine/water/flood` (rgba32float, one texel a flood cell: green the seconds since the cell was last wet above
|
|
1666
|
+
1 cm, blue 1 once it has been wet), read every frame, so the wet ground follows each tick, seek and device restore of
|
|
1667
|
+
the flood. A cell's wetness is `exp(-seconds since wet / dryTime)`; fully wet ground has `darkening` of the dry albedo
|
|
1668
|
+
(Lekner and Dorf 1988, https://doi.org/10.1364/AO.27.001278) and `1 - gloss` of the roughness, so the sun's highlight
|
|
1669
|
+
sharpens. It is a terrain lighting effect, so it composes with `GroundChange`, shadows and lights.
|
|
1670
|
+
|
|
1671
|
+
```ts
|
|
1672
|
+
import {Engine} from 'margoengine/core';
|
|
1673
|
+
import {Terrain} from 'margoengine/terrain';
|
|
1674
|
+
import {WetGround, applyWetGroundSettings} from 'margoengine/terrain/wet-ground';
|
|
1675
|
+
import {Water} from 'margoengine/water';
|
|
1676
|
+
import {Flood} from 'margoengine/water/flood';
|
|
1677
|
+
const engine = await Engine.create(document.querySelector('canvas')!, {
|
|
1678
|
+
backend: 'webgpu',
|
|
1679
|
+
camera: {position: [0, 30, 40], target: [0, 0, 0], near: 0.5, far: 1000},
|
|
1680
|
+
});
|
|
1681
|
+
// A street 64 m square falling gently east, and 1 m of water held west of x = -20 m that breaks loose.
|
|
1682
|
+
const n = 129, heights = new Float32Array(n * n).map((_, k) => 1 - 0.01 * (k % n));
|
|
1683
|
+
const terrain = Terrain.attach(engine, {
|
|
1684
|
+
size: [64, 64], origin: [-32, -32], heightScale: 1, cellSize: 0.5,
|
|
1685
|
+
layers: Array.from({length: 4}, () => ({height: [-1e4, 1e4] as [number, number], slope: [0, 1] as [number, number], scale: 0.1})),
|
|
1686
|
+
textures: (device) => {
|
|
1687
|
+
const heightmap = device.createTexture({size: [n, n], format: 'r32float', usage: 15});
|
|
1688
|
+
device.queue.writeTexture({texture: heightmap}, heights, {bytesPerRow: n * 4}, [n, n]);
|
|
1689
|
+
const layers = device.createTexture({size: [1, 1, 4], format: 'rgba8unorm-srgb', usage: 6});
|
|
1690
|
+
device.queue.writeTexture({texture: layers}, new Uint8Array(16).fill(128), {bytesPerRow: 4, rowsPerImage: 1}, [1, 1, 4]);
|
|
1691
|
+
return {heightmap, layers};
|
|
1692
|
+
},
|
|
1693
|
+
});
|
|
1694
|
+
const water = Water.attach(engine, {
|
|
1695
|
+
height: -50,
|
|
1696
|
+
terrain: {heightmap: () => terrain.heightmap, origin: [-32, -32], size: [64, 64]},
|
|
1697
|
+
fill: (x) => (x < -20 ? 2 : undefined),
|
|
1698
|
+
});
|
|
1699
|
+
const flood = Flood.attach(engine, {surface: water, maxDepth: 2, maxSpeed: 6});
|
|
1700
|
+
const wet = WetGround.attach(engine, terrain, {record: () => flood.wetTexture, origin: [-32, -32], size: [64, 64]});
|
|
1701
|
+
applyWetGroundSettings(wet, {'wet.dryTime': 120}); // dries within minutes for this shot (live, keyable)
|
|
1702
|
+
engine.start();
|
|
1703
|
+
```
|
|
1704
|
+
|
|
1705
|
+
- Look (all live, `setLook` or the rows of `WET_GROUND_SETTINGS`, the shared slider row shape): `darkening` 0.55,
|
|
1706
|
+
`gloss` 0.5, `dryTime` 10,800 s (3 hours; a soil surface dries over hours to a day, Idso et al. 1974,
|
|
1707
|
+
https://doi.org/10.2136/sssaj1974.03615995003800050037x). `wetGroundSettingDefaults()` gives a panel's state.
|
|
1708
|
+
- `binding` (default 116) moves its two lighting-group bindings if another effect uses them. `dispose()` gives the
|
|
1709
|
+
terrain its shader back; the record stays the flood's.
|
|
1710
|
+
- Measured on WebGPU and the WebGL2 layer (`test/wet-ground.browser.mjs`): fully wet ground draws as the terrain whose
|
|
1711
|
+
layer is 0.55 of the dry albedo and, under the sun's mirror direction, as the terrain at roughness 0.45 (its highlight
|
|
1712
|
+
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.
|
|
1713
|
+
Limits: one wetness a flood cell, the same darkening for every layer, no evaporation model (docs/limits.md).
|
|
1714
|
+
|
|
1715
|
+
## Soil and contact shade at the feet: `@margoengine/terrain/ground-contact`
|
|
1716
|
+
|
|
1717
|
+
`TerrainGroundContact.attach(engine, terrain)` draws the ground around the feet of the objects standing on it: a ring
|
|
1718
|
+
of soil and litter, and the sky light the object keeps from the ground. Give it footprints by key, flat
|
|
1719
|
+
`[x, z, radius, kind, ...]` in world metres, kind 0 a trunk and 1 a stone; `BiomeView` feeds it every stored trunk and
|
|
1720
|
+
stone by itself (`view.groundContact`).
|
|
1721
|
+
|
|
1722
|
+
```ts
|
|
1723
|
+
import { Engine } from '@margoengine/core';
|
|
1724
|
+
import { Terrain } from '@margoengine/terrain';
|
|
1725
|
+
import { TerrainGroundContact } from '@margoengine/terrain/ground-contact';
|
|
1726
|
+
import { applyGroundContactSettings } from '@margoengine/terrain/ground-contact-settings';
|
|
1727
|
+
const engine = await Engine.create(document.querySelector('canvas')!);
|
|
1728
|
+
// Small demo maps; pass your own heightmap, layers and weights textures.
|
|
1729
|
+
function textures(device: GPUDevice) {
|
|
1730
|
+
const heightmap = device.createTexture({ size: [4, 4], format: 'r32float', usage: 6 });
|
|
1731
|
+
device.queue.writeTexture({ texture: heightmap }, new Float32Array(16), { bytesPerRow: 16 }, [4, 4]);
|
|
1732
|
+
const layers = device.createTexture({ size: [1, 1, 4], format: 'rgba8unorm-srgb', usage: 6 });
|
|
1733
|
+
const colours = [60, 120, 40, 255, 110, 110, 100, 255, 120, 90, 60, 255, 240, 245, 255, 255];
|
|
1734
|
+
device.queue.writeTexture({ texture: layers }, new Uint8Array(colours), { bytesPerRow: 4, rowsPerImage: 1 }, [1, 1, 4]);
|
|
1735
|
+
const weight = device.createTexture({ size: [1, 1], format: 'rgba8unorm', usage: 6 });
|
|
1736
|
+
device.queue.writeTexture({ texture: weight }, new Uint8Array([255, 0, 0, 0]), { bytesPerRow: 4 }, [1, 1]);
|
|
1737
|
+
return { heightmap, layers, weights: [weight, weight] };
|
|
1738
|
+
}
|
|
1739
|
+
const terrain = Terrain.attach(engine, {
|
|
1740
|
+
size: [256, 256],
|
|
1741
|
+
textures,
|
|
1742
|
+
layers: [0, 1, 2, 3].map(() => ({ height: [-1e6, 1e6], slope: [0, 1], scale: 0.25 })),
|
|
1743
|
+
});
|
|
1744
|
+
const contact = TerrainGroundContact.attach(engine, terrain);
|
|
1745
|
+
contact.set('camp', [4, -2, 0.6, 1, 9, 3, 0.25, 0]); // a boulder and a tree trunk
|
|
1746
|
+
contact.setLook({ soil: 0.8 });
|
|
1747
|
+
applyGroundContactSettings(contact, { 'contact.occlusion': 0.8 }); // the same look as slider rows
|
|
1748
|
+
engine.start();
|
|
1749
|
+
```
|
|
1750
|
+
|
|
1751
|
+
- Sky lost at distance d from a footprint of radius r: `(1 + (d / r)^2)^-1.5`, the form factor of a sphere resting
|
|
1752
|
+
there (Quilez, https://iquilezles.org/articles/sphereao/; Evans, "Fast Approximations for Global Illumination on
|
|
1753
|
+
Dynamic Scenes", SIGGRAPH 2006), faded out from 3.5 to 4 radii; a trunk takes 0.6 of it (chosen).
|
|
1754
|
+
- Soil: a trunk's thins as `exp(-s / (1.1 r))` past the bark and ends 3 radii out (duff is deepest at the stem: Ryan
|
|
1755
|
+
and Frandsen 1991, International Journal of Wildland Fire 1(2):107-118,
|
|
1756
|
+
https://www.fs.usda.gov/rm/pubs/rmrs_gtr292/1991_ryan.pdf; the numbers are a chosen fit). A stone's is a narrow ring
|
|
1757
|
+
whose width and 0.75 strength are chosen, with no measurement behind them.
|
|
1758
|
+
- Options (defaults): `color` ([0.1, 0.08, 0.055] linear), `soil` (1), `occlusion` (1), live through `setLook`;
|
|
1759
|
+
`texel` (0.2 m), `resolution` (1024: the mask covers 205 m around the camera, 2 MB), `binding` (124, three bindings).
|
|
1760
|
+
- The mask is baked on the CPU and re-centred as the camera moves; footprints past it draw nothing until it reaches
|
|
1761
|
+
them. A footprint is a circle, and meshes you place yourself get one only from your own `set`.
|
|
1762
|
+
- `contact.mask()` gives the baked `{ texture, bounds }` (red soil, green sky lost), for ground cover that opens around
|
|
1763
|
+
the same feet: `clearingMap` of `@margoengine/scatter/clearing-map`.
|
|
1764
|
+
|
|
1765
|
+
Sliders: `@margoengine/terrain/ground-contact-settings` holds `contact.color`, `contact.soil` and `contact.occlusion`,
|
|
1766
|
+
all live: `applyGroundContactSettings(contact, { 'contact.soil': 0.6 })`, as at the end of the example above.
|
|
1767
|
+
|
|
1768
|
+
## Mesh to terrain blending: `@margoengine/terrain/blend`
|
|
1769
|
+
|
|
1770
|
+
`TerrainBlend.attach(engine, terrain, virtualTexture, options)` blends rocks, cliffs and buildings into the ground they
|
|
1771
|
+
stand on, so a placed asset shows no hard seam line where its surface meets the terrain's. `add(mesh, options)` picks
|
|
1772
|
+
the meshes. On each pixel of an added mesh the ground height under it is read from the heightmap (as the terrain's
|
|
1773
|
+
vertex shader reads it); over the lowest `height` above that ground the mesh fades into the ground: its colour to the
|
|
1774
|
+
terrain's colour there, read from the runtime virtual texture (`@margoengine/terrain/rvt`), its roughness to the
|
|
1775
|
+
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
|
|
1776
|
+
ground. Value noise moves the fade up and down so it never reads as a ruled line.
|
|
1777
|
+
|
|
1778
|
+
```ts
|
|
1779
|
+
import {Engine, PbrMaterial, box} from 'margoengine/core';
|
|
1780
|
+
import {Terrain} from 'margoengine/terrain';
|
|
1781
|
+
import {TerrainVirtualTexture} from 'margoengine/terrain/rvt';
|
|
1782
|
+
import {TerrainBlend} from 'margoengine/terrain/blend';
|
|
1783
|
+
const engine = await Engine.create(document.querySelector('canvas')!, {camera: {position: [0, 1, -6], target: [0, 0.5, 0]}});
|
|
1784
|
+
const terrain = Terrain.attach(engine, {
|
|
1785
|
+
size: [64, 64], origin: [-32, -32], heightScale: 1,
|
|
1786
|
+
layers: [0, 1, 2, 3].map(() => ({height: [-100, 100] as [number, number], slope: [0, 1] as [number, number], scale: 1})),
|
|
1787
|
+
textures(device) {
|
|
1788
|
+
const heightmap = device.createTexture({size: [2, 2], format: 'r32float', usage: 6});
|
|
1789
|
+
device.queue.writeTexture({texture: heightmap}, new Float32Array(4), {bytesPerRow: 8}, [2, 2]);
|
|
1790
|
+
const layers = device.createTexture({size: [1, 1, 4], format: 'rgba8unorm-srgb', usage: 6});
|
|
1791
|
+
device.queue.writeTexture({texture: layers}, new Uint8Array(16).fill(160), {bytesPerRow: 4, rowsPerImage: 1}, [1, 1, 4]);
|
|
1792
|
+
return {heightmap, layers};
|
|
1793
|
+
},
|
|
1794
|
+
});
|
|
1795
|
+
const ground = TerrainVirtualTexture.attach(engine, terrain);
|
|
1796
|
+
const rock = engine.createMesh().setGeometry(box(2, 2, 2)).setPosition([0, 0.5, 0])
|
|
1797
|
+
.setMaterial(new PbrMaterial({color: '#4f6f9f', roughness: 0.5}));
|
|
1798
|
+
const blend = TerrainBlend.attach(engine, terrain, ground, {
|
|
1799
|
+
height: 0.5, // world units above the ground over which a mesh fades into it
|
|
1800
|
+
noise: 0.5, // how far noise moves the fade, as a share of height
|
|
1801
|
+
normal: 1, // how far the shading normal turns to the ground's
|
|
1802
|
+
});
|
|
1803
|
+
blend.add(rock); // or blend.add(rock, {height: 1}) for this mesh alone
|
|
1804
|
+
engine.start();
|
|
1805
|
+
```
|
|
1806
|
+
|
|
1807
|
+
- Defaults: `height` 0.5, `noise` 0.5 (the fade's top and bottom move by up to a quarter of `height` either way),
|
|
1808
|
+
`normal` 1. Each mesh can override them; adding a mesh again changes its settings, `remove(mesh)` stops it, and
|
|
1809
|
+
neither recompiles the shader after the first mesh (the settings are a storage buffer row per mesh id).
|
|
1810
|
+
- It works on meshes drawn with core's standard material, next to `TerrainColors` (they share one varying and one
|
|
1811
|
+
per-pixel block). Meshes on other shaders (glTF PBR, custom materials) draw as they were.
|
|
1812
|
+
- The ground colour is the virtual texture's, so the terrain must use one (`TerrainVirtualTexture` refuses layer
|
|
1813
|
+
materials); past the cache's reach the mesh does not fade. The normal is the heightmap's (a terrain `normalmap` is
|
|
1814
|
+
not read). The fade is in the mesh's colour, roughness and normal only: its shape and shadow stay as they are, and a
|
|
1815
|
+
mesh floating higher than `height` above the ground is not touched.
|
|
1816
|
+
- Cost: five group-0 bindings (from 40, past any taken) and, on an added mesh's pixels, five height reads, one noise
|
|
1817
|
+
and one or two cache samples; other meshes pay one storage read. WebGPU only.
|
|
1818
|
+
|
|
1819
|
+
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
|
|
1820
|
+
flat sandy ground, seen square from 6 m. Without the blend the colour jumps by 126.6 of 255 across the contact line;
|
|
1821
|
+
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
|
|
1822
|
+
without). Every pixel that changes lies on the box's foot (within the fade's reach): the rest of the picture is the
|
|
1823
|
+
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
|
|
1824
|
+
rows. Cost not timed.
|
|
1825
|
+
|
|
1826
|
+
## Cliffs, overhangs and sea rocks: `@margoengine/terrain/rocks`
|
|
1827
|
+
|
|
1828
|
+
A heightfield holds one height per point, so it can draw neither an overhang nor a sea stack with a notch cut at its
|
|
1829
|
+
foot, and its steep slopes stretch into smooth ramps. `findRockSites(ground, options)` finds where rock belongs on a
|
|
1830
|
+
height grid (any grid: a `Terrain`'s heightmap texels, a `@margoengine/biomes` world's heights, a sculpted grid) from
|
|
1831
|
+
its relief and slope; `buildCliff`, `buildSeaRock` and `buildBoulder` build each piece as a closed mesh standing a little
|
|
1832
|
+
proud of the heightfield; `TerrainBlend` fades their feet into the ground and `RockSurface`
|
|
1833
|
+
(`@margoengine/terrain/rock-surface`) shades them as rock that holds up close.
|
|
1834
|
+
|
|
1835
|
+
```ts
|
|
1836
|
+
import {Engine, PbrMaterial} from 'margoengine/core';
|
|
1837
|
+
import {Terrain} from 'margoengine/terrain';
|
|
1838
|
+
import {TerrainVirtualTexture} from 'margoengine/terrain/rvt';
|
|
1839
|
+
import {TerrainBlend} from 'margoengine/terrain/blend';
|
|
1840
|
+
import {findRockSites, buildRocks} from 'margoengine/terrain/rocks';
|
|
1841
|
+
import {RockSurface} from 'margoengine/terrain/rock-surface';
|
|
1842
|
+
// A 30 m cliffed headland falling to the sea (sea level 0), as heights on a 129 x 129 grid over 256 m.
|
|
1843
|
+
const n = 129, heights = new Float32Array(n * n);
|
|
1844
|
+
for (let j = 0; j < n; j++)
|
|
1845
|
+
for (let i = 0; i < n; i++) heights[j * n + i] = 30 / (1 + Math.exp(-(j * 2 - 138) / 2.5)) - 8;
|
|
1846
|
+
const ground = {heights, resolution: [n, n] as [number, number], origin: [-128, -128] as [number, number], size: [256, 256] as [number, number]};
|
|
1847
|
+
const engine = await Engine.create(document.querySelector('canvas')!, {camera: {position: [0, 12, -40], target: [0, 8, 10]}});
|
|
1848
|
+
const terrain = Terrain.attach(engine, {
|
|
1849
|
+
size: [256, 256], origin: [-128, -128], heightScale: 1,
|
|
1850
|
+
layers: [0, 1, 2, 3].map(() => ({height: [-100, 100] as [number, number], slope: [0, 1] as [number, number], scale: 1})),
|
|
1851
|
+
textures(device) {
|
|
1852
|
+
const heightmap = device.createTexture({size: [n, n], format: 'r32float', usage: 6});
|
|
1853
|
+
device.queue.writeTexture({texture: heightmap}, heights, {bytesPerRow: n * 4}, [n, n]);
|
|
1854
|
+
const layers = device.createTexture({size: [1, 1, 4], format: 'rgba8unorm-srgb', usage: 6});
|
|
1855
|
+
device.queue.writeTexture({texture: layers}, new Uint8Array(16).fill(150), {bytesPerRow: 4, rowsPerImage: 1}, [1, 1, 4]);
|
|
1856
|
+
return {heightmap, layers};
|
|
1857
|
+
},
|
|
1858
|
+
});
|
|
1859
|
+
const sites = findRockSites(ground, {
|
|
1860
|
+
seaLevel: 0, // the water the sea rocks stand in
|
|
1861
|
+
cliffSlope: 50, // degrees of slope that can hold a cliff
|
|
1862
|
+
cliffRelief: 8, // metres of local relief a cliff needs, within reliefRadius (16 m)
|
|
1863
|
+
seaRocks: 12, // most stacks and skerries
|
|
1864
|
+
boulders: 3, // fallen blocks at each cliff piece's foot
|
|
1865
|
+
});
|
|
1866
|
+
const blend = TerrainBlend.attach(engine, terrain, TerrainVirtualTexture.attach(engine, terrain), {height: 1});
|
|
1867
|
+
const rock = RockSurface.attach(engine, {moss: 0.3, tideHeight: 1.5});
|
|
1868
|
+
for (const piece of buildRocks(sites, ground, {cliff: {overhang: 3, strata: 1.4}, seaRock: {notchDepth: 0.8}})) {
|
|
1869
|
+
const mesh = engine.createMesh().setGeometry(piece.geometry).setPosition(piece.position)
|
|
1870
|
+
.setMaterial(new PbrMaterial({color: '#888888', roughness: 0.9}));
|
|
1871
|
+
blend.add(mesh);
|
|
1872
|
+
rock.add(mesh, {type: 'sandstone', seaLevel: 0});
|
|
1873
|
+
}
|
|
1874
|
+
engine.start();
|
|
1875
|
+
```
|
|
1876
|
+
|
|
1877
|
+
- Sites. Slope is Horn's 3 x 3 weighted difference (Horn 1981); local relief is the highest less the lowest ground in a
|
|
1878
|
+
square of `reliefRadius` (van Herk 1992, Gil and Werman 1993: linear in the grid whatever the radius). A cliff piece
|
|
1879
|
+
stands where ground at least `cliffSlope` steep (default 50 degrees) has `cliffRelief` of relief (default 8 m); its
|
|
1880
|
+
foot and crest are found by walking down and up the slope until it eases to half the cliff slope, its `position` is
|
|
1881
|
+
mid-face and `facing` points down the slope. Pieces are `cliffWidth` wide (24 m) and 0.75 of that apart at mid-face,
|
|
1882
|
+
so they overlap; none is placed nearer the grid's edge than half a width. Sea rocks stand in water `seaRockDepth`
|
|
1883
|
+
deep (1 to 15 m) within `shoreDistance` (80 m) of land (a two-pass chamfer distance, Borgefors 1986), most often about
|
|
1884
|
+
half that reach out, at least `seaRockSpacing` (14 m) apart: stacks (0.35 to 0.85 of the nearby cliff's height) off
|
|
1885
|
+
cliffed coast as its remnants, skerries (0.4 to 2.5 m above the sea) elsewhere (Sunamura 1992, Trenhaile 1987).
|
|
1886
|
+
Boulders lie in front of each cliff's foot, bigger ones further out (fall sorting, Kirkby and Statham 1975). Sites
|
|
1887
|
+
are a pure function of the ground and options (`seed` picks again); `slope` and `relief` come back as grids too.
|
|
1888
|
+
- Cliff pieces. The face is the ground's own crossing of each height along the facing, so the piece follows the real
|
|
1889
|
+
relief, moved `proud` (0.6 m) out past its deepest crack, soft bed and bump so the smooth slope never shows. It leans
|
|
1890
|
+
`overhang` (2.5 m) out over its top third (a true overhang once that beats the slope's lean back), steps in strata of
|
|
1891
|
+
`strata` (1.4 m) beds whose hard ones stand up to `ledges` (0.5 m) out (tilted by `dip`), is cut by vertical joints
|
|
1892
|
+
every `joints` (3 m), shifted bed by bed, `crackDepth` (0.35 m) deep (jointed blocks after Paris et al. 2020), carries
|
|
1893
|
+
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
|
|
1894
|
+
ends fold back into the hill. Rock volumes over a heightfield after Peytavie et al. 2009 (Arches), Paris et al. 2019
|
|
1895
|
+
and Gamito and Musgrave 2001.
|
|
1896
|
+
- Sea rocks. A lumpy (`lobes` 0.22 of the radius), tapering (`taper` 0.25, a skerry 0.5) column with a wave-cut notch
|
|
1897
|
+
`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
|
|
1898
|
+
the still water, so the rock above overhangs it; strata ledges, `joints` (7) around it and a rounded top. Boulders
|
|
1899
|
+
use `facets` (9) bed, joint and corner cuts through a seeded block. The bed face sits under the ground at the
|
|
1900
|
+
default `embed` (0.3). The upper face has a seeded pitch and each side has its own cut, with `rounding` (0.18)
|
|
1901
|
+
controlling edge wear. These cuts draw on [A. Peytavie, E. Galin, J. Grosjean and S. Mérillou,
|
|
1902
|
+
*Procedural Generation of Rock Piles using Aperiodic Tiling* (2009)](https://perso.liris.cnrs.fr/eric.galin/Articles/2009-aperiodic.pdf)
|
|
1903
|
+
and [A. Paris, A. Peytavie, E. Guérin, J.-M. Dischler and E. Galin, *Modeling Rocky Scenery using Implicit Blocks*
|
|
1904
|
+
(2020)](https://perso.liris.cnrs.fr/aparis/public_html/projects/paris2020_Blocks.html).
|
|
1905
|
+
- Meshes. Each piece is a signed distance field polygonized by Marching Cubes (Lorensen and Cline 1987, `marchingCubes`
|
|
1906
|
+
of `@margoengine/procedural`) at `cell` spacing (cliffs 0.5 m, sea rocks radius / 12, boulders radius / 10) in blocks
|
|
1907
|
+
of up to 127 cells whose shared vertices are welded and whose normals all come from the field's central differences,
|
|
1908
|
+
so every mesh is closed and shows no seam between blocks. Geometry is about `position` (set the mesh there). A 24 m
|
|
1909
|
+
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
|
|
1910
|
+
a long coast in a worker. `cliffField`, `seaRockField` and `boulderField` return the signed distance and its box, for
|
|
1911
|
+
collision or your own polygonizer.
|
|
1912
|
+
- `RockSurface` replaces an added mesh's colour, roughness and metalness, per pixel from the world position (no UVs or
|
|
1913
|
+
textures): six octaves of triplanar relief as a surface gradient on the normal (Mikkelsen 2020, Blinn 1978), each
|
|
1914
|
+
octave fading as its wavelength nears the pixel's footprint so far rock does not shimmer (Norton et al. 1982); the
|
|
1915
|
+
rock type's two bed tones banded by its `strata` with thin bedding lines; broad tone variation; broken joint cracks;
|
|
1916
|
+
moss on faces that look up; a wet, algae-dark band up to `tideHeight` over the rock's `seaLevel`; and rain that
|
|
1917
|
+
darkens and smooths it (Lekner and Dorf 1988, Jensen et al. 1999). Rock types: `sandstone` (default), `limestone`,
|
|
1918
|
+
`chalk`, `granite`, `basalt`, `shale` (`ROCK_TYPES`; give `color`, `color2`, `strata` or `porosity` to override).
|
|
1919
|
+
At close range, granite is a mosaic of 5 mm crystals whatever `scale` is: feldspar (64 percent, light), quartz
|
|
1920
|
+
(30 percent, grey) and dark biotite flecks (6 percent), after the granite field of Streckeisen (Earth-Science
|
|
1921
|
+
Reviews 12(1), 1976, doi:10.1016/0012-8252(76)90052-0) and the coarse Front Range granites (Barker et al.,
|
|
1922
|
+
Precambrian Research 2(2), 1975, doi:10.1016/0301-9268(75)90001-7); averaged they keep granite's measured tone, so a
|
|
1923
|
+
boulder seen from metres away shows no blotches. Basalt has subtle dark pits, and shale has thin laminations between
|
|
1924
|
+
beds. Grain color and relief fade when the screen footprint can no longer resolve them.
|
|
1925
|
+
Granite's two tones are measured: linear (0.2709, 0.224, 0.1869), the mean of ECOSTRESS Spectral Library 1.0 samples
|
|
1926
|
+
Granite_H2, H3 and H5, and (0.1678, 0.171, 0.1512), the grey alkalic Granite_H1 (Meerdink et al., Remote Sensing of
|
|
1927
|
+
Environment 230, 2019, https://doi.org/10.1016/j.rse.2019.05.015), each spectrum integrated under a 6504 K black body.
|
|
1928
|
+
These materials use visual characteristics from the [British Columbia Geological Survey, *Rock Identification
|
|
1929
|
+
Key* (1987)](https://cmscontent.nrs.gov.bc.ca/geoscience/publicationcatalogue/InformationCircular/BCGS_IC1987-05_METC1980.pdf)
|
|
1930
|
+
and [Utah Geological Survey, *Igneous, Sedimentary, & Metamorphic Rocks*](https://geology.utah.gov/map-pub/survey-notes/glad-you-asked/igneous-sedimentary-metamorphic-rocks/).
|
|
1931
|
+
Set `tideHeight: 0` for inland scenes to disable shoreline darkening, including below the assigned sea level. The
|
|
1932
|
+
look (`RockLook`, defaults in `ROCK_LOOK_DEFAULTS`) is live through `setLook`; `look.rain` null follows a
|
|
1933
|
+
`WeatherDrive`, which finds the surface by its name. One group-0 binding (from 40, past any taken); an added mesh's
|
|
1934
|
+
pixels cost about twenty value-noise reads plus three triplanar grain samples in close shots, other meshes one
|
|
1935
|
+
storage read. WebGPU, and WebGPU on the WebGL2 layer.
|
|
1936
|
+
Its patch runs after `TerrainBlend`'s, so the blend's fade into the ground is laid over the rock.
|
|
1937
|
+
- Sliders: `@margoengine/terrain/rock-settings` holds every control on the shared row shape: the live look rows
|
|
1938
|
+
(`detail.*`, `moss.*`, `tide.*`, `wet.*`; `wet.rain` null follows the weather's `rainRate`) for
|
|
1939
|
+
`applyRockSettings(surface, values)`, and the shape rows (`cliff.*`, `sea.*`, `live` false) that `rockShapeOf(values)`
|
|
1940
|
+
turns into the builders' options.
|
|
1941
|
+
|
|
1942
|
+
Checked by `test/rocks.test.js` (CPU): slope exact on a 45 degree plane, relief equal to a brute-force window; on a
|
|
1943
|
+
coast of a 30 m headland beside a beach, cliffs only on the steep high ground and facing down it, sea rocks in their
|
|
1944
|
+
depth band within reach of the shore and spaced, stacks off the cliffs, boulders in front of the feet; 98% of the
|
|
1945
|
+
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
|
|
1946
|
+
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
|
|
1947
|
+
surface and under 0.05 m 2.5 m away; meshes closed (every edge in two triangles) across polygonizer blocks, normals out
|
|
1948
|
+
of the rock, the same input giving the same bytes. On a real GPU by `test/rocks.browser.mjs` (in `test:gpu`, WebGPU and
|
|
1949
|
+
`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
|
|
1950
|
+
luminance; rain darkens it to 0.69 of its light, the tide band to 0.61 with the rock above unchanged; with
|
|
1951
|
+
`TerrainBlend` the changed foot pixels sit 40 of 255 from the bare ground against 96 without; 150 m off, a quarter-pixel
|
|
1952
|
+
camera move changes the picture by 0.17 against the plain mesh's 0.15. Both backends give the same figures.
|
|
1953
|
+
|
|
1954
|
+
## Planet terrain: `@margoengine/terrain/planet`
|
|
1955
|
+
|
|
1956
|
+
`PlanetTerrain.attach(engine, options)` draws a whole planet that can be flown around from orbit down to a metre above
|
|
1957
|
+
the ground. The six faces of a cube are each a quadtree of height patches mapped onto the sphere, so the ground curves
|
|
1958
|
+
and the horizon dips as on a real world. A patch splits into four while its vertices would be more than `screenError`
|
|
1959
|
+
pixels apart on screen (the ground nearest the camera first); patches behind the horizon or outside the view are not
|
|
1960
|
+
drawn, and skirts hung from patch edges close the seams between levels. Each patch keeps its centre in float64 and is
|
|
1961
|
+
drawn relative to the camera, so an Earth-sized planet holds still at any distance with no setting. With a
|
|
1962
|
+
`FloatingOrigin` (`@margoengine/cameras/origin`) the planet's centre follows each rebase, so meshes placed near the
|
|
1963
|
+
camera stay precise too.
|
|
1964
|
+
|
|
1965
|
+
```ts
|
|
1966
|
+
import {Engine} from 'margoengine/core';
|
|
1967
|
+
import {FloatingOrigin} from 'margoengine/cameras/origin';
|
|
1968
|
+
import {PlanetTerrain} from 'margoengine/terrain/planet';
|
|
1969
|
+
const engine = await Engine.create(document.querySelector('canvas')!, {
|
|
1970
|
+
camera: {position: [0, 0, 2e7], target: [0, 0, 0], near: 1, far: 1e9},
|
|
1971
|
+
});
|
|
1972
|
+
const origin = FloatingOrigin.attach(engine);
|
|
1973
|
+
const planet = PlanetTerrain.attach(engine, {
|
|
1974
|
+
radius: 6371000, // metres at height 0 (the Earth's mean radius)
|
|
1975
|
+
relief: 8000, // the default ground spans about -8 km to 8 km
|
|
1976
|
+
seaLevel: 0, // lower ground draws as flat sea; false for none
|
|
1977
|
+
screenError: 4, // pixels between vertices before a patch splits
|
|
1978
|
+
origin, // the planet's centre follows the origin's rebases
|
|
1979
|
+
});
|
|
1980
|
+
engine.start();
|
|
1981
|
+
console.log(planet.altitude(engine.camera.position)); // metres above the ground under the camera
|
|
1982
|
+
```
|
|
1983
|
+
|
|
1984
|
+
- Options and defaults: `radius` 6,371,000 m; `center` [0, 0, 0] (a float64 world position); `height` (default
|
|
1985
|
+
`planetNoise({radius, relief, seed})`, fractal value noise); `relief` 8,000 m; `seed` 1; `seaLevel` 0 (or `false`);
|
|
1986
|
+
`resolution` 32 quads a patch side (even, 4 to 64); `maxLevel` 20 (vertices 0.3 m apart on the Earth); `screenError`
|
|
1987
|
+
4 px; `budget` 4 ms of patch building a frame (at least one patch; `Infinity` builds everything a view needs in one
|
|
1988
|
+
frame); `maxPatches` 2,048 on the GPU at once (about 24 KB each at resolution 32, so 50 MB; when every slot holds a
|
|
1989
|
+
patch the view uses, the planet keeps drawing the coarser parents where it wanted finer ones, never a hole, and
|
|
1990
|
+
`stats.resident` equals `maxPatches`: raise it, up to 16,384, for more detail; the patches share one vertex buffer
|
|
1991
|
+
that must fit the device's `maxBufferSize`, 256 MiB by default, so 10,992 patches at resolution 32 and 2,992 at 64,
|
|
1992
|
+
and `attach` throws `RangeError` past it, batch 132b); `origin` a
|
|
1993
|
+
`FloatingOrigin` to follow. Invalid values throw `RangeError` or `TypeError`.
|
|
1994
|
+
- The same patches on every machine (KB-FILM-CLOCK1): the millisecond `budget` makes a slower machine build fewer patches
|
|
1995
|
+
a frame, so a frame drawn mid-refinement differs. For a film pass `maxBuilds` (patches a frame, 1 or more, `Infinity`
|
|
1996
|
+
until nothing more is wanted): it replaces `budget`, and the patches built and drawn are the same on every run. `clock`
|
|
1997
|
+
(milliseconds, default `performance.now`) is the clock the `budget` reads, for a simulation clock in replay.
|
|
1998
|
+
- Your own ground: `height(x, y, z, detail)` gets a unit direction from the centre (float64) and returns metres above
|
|
1999
|
+
`radius`; `detail` is the spacing of the vertices being built there, so a procedural height can skip finer detail.
|
|
2000
|
+
`cubeSphere(face, s, t)` maps a cube face point to its direction.
|
|
2001
|
+
- `heightAt(direction)` and `altitude(position)` read the ground on the CPU (the drawn surface is that ground sampled at
|
|
2002
|
+
the patch's vertices). `update(camera, [width, height])` plans and builds the patches for a view ahead of time (the
|
|
2003
|
+
frame calls it); `stats` says what the last frame drew and built, `patches` lists the drawn patches.
|
|
2004
|
+
- Shading: the sun (`engine.lighting`) and ambient light over colours by height and slope (sea, sand, grass, dry
|
|
2005
|
+
ground, rock, snow). No shadows, SSR, lighting effects or layer textures yet; one view per frame.
|
|
2006
|
+
|
|
2007
|
+
Checked on a real GPU by `test/planet.browser.mjs` (in `test:gpu`, Radeon 680M, Edge 157, 2026-11-08), an Earth-sized
|
|
2008
|
+
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;
|
|
2009
|
+
on a smooth planet 100 km up, looking level, the horizon dips to the row `acos(R / (R + h))` predicts (157 against
|
|
2010
|
+
156.97 in the middle), within a pixel in every column; 300 m above the default ground, 6,371 km from the world origin,
|
|
2011
|
+
no sky shows through the ground, and the same view with a `FloatingOrigin` (which rebases the camera to near zero) is
|
|
2012
|
+
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
|
|
2013
|
+
frame, reaches level 20 and rebases once, with no validation error. `test/planet.test.js` checks the cube sphere's
|
|
2014
|
+
seams and cell areas, the horizon culling, the screen error, that refining with no budget never leaves a hole, the
|
|
2015
|
+
patch limit, sea level and following an origin. Building a patch costs about 1.3 ms of main-thread time at
|
|
2016
|
+
resolution 32 with the default ground (Node, AMD mini PC, busy machine: diagnostic); the 1,682 patches a view 100 m above
|
|
2017
|
+
the ground at 1280 x 720 needs took 2.2 s, which the `budget` spreads over frames. Frame cost not timed.
|
|
2018
|
+
|
|
2019
|
+
## Far from the origin: `floatingOrigin`
|
|
2020
|
+
|
|
2021
|
+
GPUs draw in float32, which holds about 7 digits: a terrain 10,000 km out has its vertices rounded to a metre and its
|
|
2022
|
+
textures swim. Give the terrain the scene's `FloatingOrigin` (`@margoengine/cameras/origin`) as `floatingOrigin` and it
|
|
2023
|
+
plans everything in float64 world space first: the ring lattice, the layer texture phases, the virtual texture's
|
|
2024
|
+
windows and decals, the deformation window, streamed tiles and imagery views. Only small local numbers (world less the
|
|
2025
|
+
origin) reach the GPU. A terrain 1e7 m out then draws the same vertices, levels, cache texels and pixels as the same
|
|
2026
|
+
terrain at zero, and a rebase moves nothing on screen and bakes nothing again.
|
|
2027
|
+
|
|
2028
|
+
```ts
|
|
2029
|
+
import {Engine} from 'margoengine/core';
|
|
2030
|
+
import {FloatingOrigin} from 'margoengine/cameras/origin';
|
|
2031
|
+
import {Terrain, type TerrainOptions} from 'margoengine/terrain';
|
|
2032
|
+
import {TerrainQuery} from 'margoengine/terrain/query';
|
|
2033
|
+
const engine = await Engine.create(document.querySelector('canvas')!);
|
|
2034
|
+
// ratio 10: rebase once the camera is 10 times its target distance from local zero, so local numbers stay small.
|
|
2035
|
+
const origin = FloatingOrigin.attach(engine, {ratio: 10});
|
|
2036
|
+
const columns = 65, heights = new Float32Array(columns * columns).map((_, i) => Math.sin(i % columns / 6) * 0.1);
|
|
2037
|
+
const options: TerrainOptions = {
|
|
2038
|
+
origin: [1e7 - 64, 1e7 - 64], // world XZ, float64, as without the option
|
|
2039
|
+
size: [128, 128],
|
|
2040
|
+
heightScale: 20,
|
|
2041
|
+
floatingOrigin: origin,
|
|
2042
|
+
layers: Array.from({length: 4}, () => ({height: [-100, 100] as const, slope: [0, 1] as const, scale: 0.25})),
|
|
2043
|
+
textures(device) {
|
|
2044
|
+
const heightmap = device.createTexture({size: [columns, columns], format: 'r32float', usage: 6});
|
|
2045
|
+
device.queue.writeTexture({texture: heightmap}, heights, {bytesPerRow: columns * 4}, [columns, columns]);
|
|
2046
|
+
const layers = device.createTexture({size: [1, 1, 4], format: 'rgba8unorm-srgb', usage: 6});
|
|
2047
|
+
device.queue.writeTexture({texture: layers}, new Uint8Array(16).fill(128), {bytesPerRow: 4, rowsPerImage: 1}, [1, 1, 4]);
|
|
2048
|
+
return {heightmap, layers};
|
|
2049
|
+
},
|
|
2050
|
+
};
|
|
2051
|
+
const terrain = Terrain.attach(engine, options);
|
|
2052
|
+
origin.lookAt([1e7 + 50, 80, 1e7 + 50], [1e7 + 60, 30, 1e7 + 90]); // world points; the camera becomes local
|
|
2053
|
+
engine.start();
|
|
2054
|
+
// CPU calls stay in world coordinates: convert the local camera ray with origin.toWorld.
|
|
2055
|
+
const query = new TerrainQuery(heights, columns, columns, options);
|
|
2056
|
+
console.log(query.height(1e7, 1e7), query.raycast(origin.toWorld(engine.camera.position), [0.2, -1, 0.8]));
|
|
2057
|
+
console.log(terrain.shift); // the float64 world point at local zero, which every terrain entry follows
|
|
2058
|
+
```
|
|
2059
|
+
|
|
2060
|
+
- `floatingOrigin` takes any `{origin, onRebase}` (a `FloatingOrigin` as is). Without it the shaders, uniforms and
|
|
2061
|
+
layer rules are byte for byte what they were. `terrain.shift` is the world point at local zero (zeros without the
|
|
2062
|
+
option); `terrain.anchor` is `origin` at construction.
|
|
2063
|
+
- World in, world out: `origin`, `size`, `TerrainQuery`, holes, sculpt dabs, virtual texture decals, roads and
|
|
2064
|
+
`invalidate` areas, overlays, imagery bounds and deformation prints (and its `follow`) take float64 world
|
|
2065
|
+
coordinates, as without the option.
|
|
2066
|
+
- Why `ratio` 10: core rebases when the camera is `ratio` times its target distance from local zero, so local numbers
|
|
2067
|
+
reach about `ratio` times the view distance before a rebase. float32 is clean to about 1e4 m (0.5 mm steps), so 10
|
|
2068
|
+
keeps a view a few hundred metres across well inside it; `FloatingOrigin`'s default of 1000 lets positions grow to
|
|
2069
|
+
kilometres first and shows float32 noise.
|
|
2070
|
+
- Layer textures repeat on terrain-relative coordinates (world less `anchor`), so moving a terrain and its camera
|
|
2071
|
+
together draws the same picture; a terrain at zero draws as before. A streamed terrain (`/stream`) keeps the anchor
|
|
2072
|
+
where it started, and its overlays and imagery read XZ relative to it in float32: precise within about 1e4 m of the
|
|
2073
|
+
start, as at zero.
|
|
2074
|
+
- The virtual texture addresses its cache by world texel (`floor(world / texel)`, a 32-bit integer): up to 1e8 m from
|
|
2075
|
+
zero at the default 5 cm texel. Its texel and the deformation's are taken as the float32 the GPU holds (a relative
|
|
2076
|
+
change under 1e-7), so the CPU's texel indices and the GPU's coordinates agree at any distance.
|
|
2077
|
+
|
|
2078
|
+
Checked on a real GPU by `test/origin.browser.mjs` (in `test:gpu`, RTX A6000, Edge 157, WebGPU and the WebGL2 layer,
|
|
2079
|
+
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,
|
|
2080
|
+
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,
|
|
2081
|
+
pixel for pixel, with the same draw calls and 1,324,960 texels baked; rebased onto the camera at 1e7, rebased in place
|
|
2082
|
+
(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
|
|
2083
|
+
(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
|
|
2084
|
+
at rest on that origin, with no rebase at all, is 99.83 percent equal: float32 rounding of the frame, not the rebase,
|
|
2085
|
+
which changes 0.004 percent of pixels). Cached imagery with an overlay polygon, layer materials with displacement,
|
|
2086
|
+
footprints, imagery on the lit path, a mesh blended into the ground and a streamed terrain each draw the same picture
|
|
2087
|
+
at 1e7 as at zero, and blend and stream stay within 1 of 255 after a rebase in place. `test/origin.test.js` checks
|
|
2088
|
+
`planRings` and `planWindows` bit for bit at those offsets, the layer wrap and tone, a rebase rewriting the rules once
|
|
2089
|
+
and redrawing shadows once, and `TerrainQuery` at the offsets.
|
|
2090
|
+
|
|
2091
|
+
## Textures after a device restore
|
|
2092
|
+
|
|
2093
|
+
`textures` is a function `(device) => TerrainTextures`, never a plain set, so a device restore needs nothing from you. The terrain calls it once
|
|
2094
|
+
for each device (at attach and again after `engine.rebootDevice()` or core's own recovery), binds the textures it returns, and destroys the old
|
|
2095
|
+
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
|
|
2096
|
+
earlier, and nothing is lost and nothing is reported.
|
|
2097
|
+
|
|
2098
|
+
## On the WebGL2 compatibility layer
|
|
2099
|
+
|
|
2100
|
+
Where the browser has no WebGPU, install the layer (`margoengine/webgl2-compat`) before `Engine.create` and the
|
|
2101
|
+
clipmap terrain draws with nothing else changed: the same options, the same textures factory, the same pixels. The
|
|
2102
|
+
root entry and `rvt` have no compute pass, so they need no route of their own there: this package holds no WebGL2
|
|
2103
|
+
code and a page with WebGPU downloads nothing extra.
|
|
2104
|
+
|
|
2105
|
+
```ts
|
|
2106
|
+
import {Engine} from 'margoengine/core';
|
|
2107
|
+
import {install} from 'margoengine/webgl2-compat';
|
|
2108
|
+
import {Terrain} from 'margoengine/terrain';
|
|
2109
|
+
await install(); // changes nothing where WebGPU has an adapter; else navigator.gpu draws through WebGL2
|
|
2110
|
+
const engine = await Engine.create(document.querySelector('canvas')!, {camera: {position: [0, 20, -40], target: [0, 0, 0]}});
|
|
2111
|
+
Terrain.attach(engine, {
|
|
2112
|
+
size: [64, 64], origin: [-32, -32], heightScale: 4,
|
|
2113
|
+
layers: [0, 1, 2, 3].map(() => ({height: [-100, 100] as [number, number], slope: [0, 1] as [number, number], scale: 1})),
|
|
2114
|
+
textures(device) {
|
|
2115
|
+
const heightmap = device.createTexture({size: [2, 2], format: 'r32float', usage: 6});
|
|
2116
|
+
device.queue.writeTexture({texture: heightmap}, new Float32Array([0, 1, 1, 0]), {bytesPerRow: 8}, [2, 2]);
|
|
2117
|
+
const layers = device.createTexture({size: [1, 1, 4], format: 'rgba8unorm-srgb', usage: 6});
|
|
2118
|
+
device.queue.writeTexture({texture: layers}, new Uint8Array(16).fill(160), {bytesPerRow: 4, rowsPerImage: 1}, [1, 1, 4]);
|
|
2119
|
+
return {heightmap, layers};
|
|
2120
|
+
},
|
|
2121
|
+
});
|
|
2122
|
+
engine.start();
|
|
2123
|
+
```
|
|
2124
|
+
|
|
2125
|
+
Checked on a real GPU by `test/compat.browser.mjs` (in `test:gpu`, Radeon 680M, ANGLE on Direct3D 11, Edge 157,
|
|
2126
|
+
2026-11-08): a 129 x 129 heightmap of hills and a ridge with four checked layers, drawn natively and on the layer
|
|
2127
|
+
(`install({force: true})`) in exact-pixel mode, in three cases: layer rules alone; painted weights with a hole; and a
|
|
2128
|
+
runtime virtual texture (`@margoengine/terrain/rvt`), which bakes the same 1,310,720 texels on both. In every case no
|
|
2129
|
+
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
|
|
2130
|
+
layer, counted, not timed: a frame of six clipmap levels is 6 engine draws, 6 GL draws and 48 GL calls (50 with the
|
|
2131
|
+
virtual texture).
|
|
2132
|
+
|
|
2133
|
+
- Checked on the layer: the root entry (rules, painted weights, holes) and `rvt`. Not run there yet: `layers-pbr`,
|
|
2134
|
+
`stream`, `sculpt`, `deform` and `displace` (the last three have compute passes, which the layer runs on its own
|
|
2135
|
+
tiers), `blend`, the SSR capture, shadows and the occluder pass.
|
|
2136
|
+
- Frame times on the layer are not measured; only one GPU and one ANGLE back end ran it.
|
|
2137
|
+
|
|
2138
|
+
## Screen-space reflections
|
|
2139
|
+
|
|
2140
|
+
`Terrain` takes SSR's capture hook (`@margoengine/post/ssr`): `ssr.add(terrain)` draws its own normal, layer colour and
|
|
2141
|
+
roughness into SSR's material targets (through the hook's `margoSSR`, metal 0), depth tested and written, so wet
|
|
2142
|
+
ground, ice or polished stone reflect what is on screen. `roughness` (GGX, 0-1, default 0.9; `RangeError` outside)
|
|
2143
|
+
sets the terrain's roughness for the sun's highlight and for SSR, whose default `maxRoughness` of 0.6 skips the
|
|
2144
|
+
default 0.9. With an `EnvironmentLighting` on the terrain the IBL specular it added is what SSR replaces where its ray
|
|
2145
|
+
hits; without one the reflection is added (as for core meshes). Leaving out `roughness` and the hook keeps the GPU
|
|
2146
|
+
calls exactly as before (`examples/package-benchmarks/proofs/terrain-ssr.proof.js`, against `6c20076d`).
|
|
2147
|
+
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
|
|
2148
|
+
mirror (24,929 pixels, none outside the projected mirror bounds by more than 6 px) and red at the mirrored centre,
|
|
2149
|
+
at 4x and 1x MSAA. A terrain is reflected only on screen and, being a dielectric, reflects 4-10% at most view angles.
|
|
2150
|
+
|
|
2151
|
+
## Ambient light and the sky
|
|
2152
|
+
|
|
2153
|
+
Without other light, terrain's ambient is `engine.lighting.radiance[3]` times `engine.lighting.ambient` (white by
|
|
2154
|
+
default) times the albedo, the same term core meshes use, so a coloured `lighting.ambient` colours the ground as it
|
|
2155
|
+
colours the meshes on it. `sky.add(terrain)` (`@margoengine/sky` with `lighting.ambient`) puts the sky's own light in
|
|
2156
|
+
its place: diffuse from the sky's nine spherical harmonics (Ramamoorthi and Hanrahan 2001) along the shaded normal and
|
|
2157
|
+
split-sum sky reflections (Karis 2013), so ground in shadow takes the blue of the sky above it. A `HemisphereLight`
|
|
2158
|
+
(`@margoengine/environment`) added to the terrain takes the flat term's place the same way. Checked on WebGPU and the
|
|
2159
|
+
WebGL2 compatibility layer by `test/sky-ambient.browser.mjs` (in `test:gpu`): under no sun, `lighting.ambient`
|
|
2160
|
+
[1, 0.5, 0.25] draws flat grey ground at sRGB (82, 50, 14) against (74, 74, 74) for white; under a clear noon sky the
|
|
2161
|
+
ground with the sky's light reads (20, 22, 31) against (19, 19, 19) without, the same pixels on both backends.
|
|
2162
|
+
|
|
2163
|
+
```ts
|
|
2164
|
+
import {EngineKernel} from 'margoengine/core';
|
|
2165
|
+
import {Terrain} from 'margoengine/terrain';
|
|
2166
|
+
import {Sky} from 'margoengine/sky';
|
|
2167
|
+
const engine = await EngineKernel.create(document.querySelector<HTMLCanvasElement>('#viewport')!, {backend:'webgpu'});
|
|
2168
|
+
const terrain = Terrain.attach(engine, {
|
|
2169
|
+
resolution:64, levels:6, cellSize:1, origin:[-50,-50], size:[100,100], heightScale:20,
|
|
2170
|
+
layers:[0.3,0.2,0.4,0.2].map((scale)=>({height:[-20,100] as [number,number],slope:[0,1] as [number,number],scale})),
|
|
2171
|
+
textures:device=>{
|
|
2172
|
+
// 6 = TEXTURE_BINDING | COPY_DST: flat grey demo ground; replace with your assets.
|
|
2173
|
+
const heightmap = device.createTexture({size:[4,4],format:'r32float',usage:6});
|
|
2174
|
+
device.queue.writeTexture({texture:heightmap},new Float32Array(16),{bytesPerRow:16},[4,4]);
|
|
2175
|
+
const layers = device.createTexture({size:[1,1,4],format:'rgba8unorm-srgb',usage:6});
|
|
2176
|
+
device.queue.writeTexture({texture:layers},new Uint8Array(16).fill(128),{bytesPerRow:4,rowsPerImage:1},[1,1,4]);
|
|
2177
|
+
return {heightmap,layers};
|
|
2178
|
+
}
|
|
2179
|
+
});
|
|
2180
|
+
engine.lighting.ambient.set([1, 0.9, 0.8]); // warm flat ambient on the ground, as on core meshes
|
|
2181
|
+
const sky = new Sky({hours:15, lighting:{ambient:{day:[0.05,0.05,0.06], night:[0.01,0.01,0.02]}}});
|
|
2182
|
+
engine.use(sky);
|
|
2183
|
+
const removeSkyLight = sky.add(terrain); // the sky's light in place of the flat ambient; removeSkyLight() undoes it
|
|
2184
|
+
engine.start();
|
|
2185
|
+
```
|
|
2186
|
+
|
|
2187
|
+
## Shadows
|
|
2188
|
+
|
|
2189
|
+
`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.
|
|
2190
|
+
|
|
2191
|
+
## Terrain as an occluder
|
|
2192
|
+
|
|
2193
|
+
A hill can hide GPU-culled parts: `parts.addOccluder(terrain)` (`CulledParts` from `margoengine/culling/parts`, in
|
|
2194
|
+
`'occlusion'` mode) draws the terrain's depth through `terrain.drawOccluder`, with the rings and uniforms of its main pass.
|
|
2195
|
+
|
|
2196
|
+
## Preview tier contract
|
|
2197
|
+
|
|
2198
|
+
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.
|
|
2199
|
+
|
|
2200
|
+
The renderer now refuses the preview during setup, allowing automatic escalation instead of accepting an attachment that cannot draw.
|
|
2201
|
+
|
|
2202
|
+
`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`.
|
|
2203
|
+
|
|
2204
|
+
## Planet recipes: `@margoengine/terrain/planet-recipes`
|
|
2205
|
+
|
|
2206
|
+
Ground functions for `PlanetTerrain`: impact craters with a real size distribution and profile, ridged noise, domain
|
|
2207
|
+
warp and ready-made moons, Mars-like worlds, asteroids and ice moons. Every function returns a `PlanetHeight`, so it
|
|
2208
|
+
goes straight into `PlanetTerrain`'s `height` and composes with `planetNoise`.
|
|
2209
|
+
|
|
2210
|
+
```ts
|
|
2211
|
+
import {Engine} from 'margoengine/core';
|
|
2212
|
+
import {PlanetTerrain} from 'margoengine/terrain/planet';
|
|
2213
|
+
import {planetPreset, planetPresetBrightness, planetPresetRadius} from 'margoengine/terrain/planet-recipes';
|
|
2214
|
+
const radius = planetPresetRadius('moon'); // 1,737,400 m
|
|
2215
|
+
const engine = await Engine.create(document.querySelector('canvas')!, {
|
|
2216
|
+
camera: {position: [0, 0, 3 * radius], target: [0, 0, 0], near: 1, far: 1e9},
|
|
2217
|
+
});
|
|
2218
|
+
const height = planetPreset('moon', {radius}),
|
|
2219
|
+
brightness = planetPresetBrightness('moon', {radius}); // its crater rays
|
|
2220
|
+
PlanetTerrain.attach(engine, {radius, height, brightness, relief: 4000, seaLevel: false});
|
|
2221
|
+
engine.render({delta: 0});
|
|
2222
|
+
```
|
|
2223
|
+
|
|
2224
|
+
Place a young crater yourself and its rays and secondary chains come with it:
|
|
2225
|
+
|
|
2226
|
+
```ts
|
|
2227
|
+
import {craterField} from 'margoengine/terrain/planet-recipes';
|
|
2228
|
+
const craters = craterField({
|
|
2229
|
+
radius: 1737400,
|
|
2230
|
+
rayed: [{x: 0.6, y: -0.7, z: 0.4, diameter: 85000}],
|
|
2231
|
+
});
|
|
2232
|
+
craters(0.6, -0.7, 0.4, 0); // metres at the central peak, below the undisturbed ground
|
|
2233
|
+
craters.brightness(0.6, -0.7, 0.4, 0); // 1: fresh bright ground
|
|
2234
|
+
```
|
|
2235
|
+
|
|
2236
|
+
- `craterField({radius, density | count, dMin, dMax, exponent, seed, depthRatio, rimRatio, maxDepth, floor, ejecta, blend, transition, peaks, terraces, rayed, rayedSize})`:
|
|
2237
|
+
craters are Poisson placed, uniformly over the sphere, with diameters from a power law (cumulative exponent 2 by
|
|
2238
|
+
default, Neukum et al. 2001) between `dMin` (default `radius / 20,000`) and `dMax` (`radius / 4`). `density` counts
|
|
2239
|
+
craters of `dMin` or more per million square kilometres (default 1,000), or give `count` for the whole planet. Depth,
|
|
2240
|
+
rim crest to floor, is `0.196 D^1.01` and rim height above the ground `0.036 D^1.01` with D in kilometres (Pike 1977);
|
|
2241
|
+
a floor is never more than `maxDepth` 3,400 m below the ground (larger craters are scaled, not clipped). The ejecta blanket is `0.14 R^0.74 (r / R)^-3` metres beyond
|
|
2242
|
+
the rim (McGetchin et al. 1973), the rim uplift falls off as `(r / R)^-4`, both fade to nothing by 3 radii. `floor`
|
|
2243
|
+
is the fraction of the radius that is flat floor (default 0). A younger crater replaces what an older one left inside
|
|
2244
|
+
its rim and fades into it over `blend` radii (0.15). Heights are relative to the undisturbed ground: `combine` it with a base.
|
|
2245
|
+
The result also has `craters(x, y, z, detail)`, the list of craters that reach a point (centre, diameter, age), for decals
|
|
2246
|
+
or labels. A sample reads the 27 lattice cells around it for each octave of diameter; craters under twice `detail`
|
|
2247
|
+
are skipped. A density that puts over 256 craters in one cell throws a `RangeError` that says to raise `dMin`.
|
|
2248
|
+
- Complex craters: past `transition` (default 10,583 m, the Moon's; `Infinity` for none) a crater is shallower for its
|
|
2249
|
+
size, with rim crest to floor `1.044 D^0.301` and rim `0.236 D^0.399` (km, Pike 1977, continuous with the simple laws),
|
|
2250
|
+
a flat floor `0.187 D^1.249` wide from 20 km, a central peak `0.032 D^0.900` high from 27 km (`peaks` scales it,
|
|
2251
|
+
default 1) and terraces on its wall from about 15 km, the outermost about `0.09 D^0.87` wide (Pearce and Melosh 1986;
|
|
2252
|
+
`terraces` 0 to 1, default 1). Another body's `transition` rescales these lunar laws about it.
|
|
2253
|
+
- Rays: `rayed` (default 0) adds young craters, a count of up to 64 sized within `rayedSize`
|
|
2254
|
+
(`[radius / 60, radius / 16]`) or your own `{x, y, z, diameter}` list. Each has 8 to 14 rays of median length
|
|
2255
|
+
`6.59 Rp^1.27` km (Elliott et al. 2018) and chains of secondary craters along them from 1.3 diameters past the rim, the
|
|
2256
|
+
largest 5 percent of the primary and smaller with range (Singer et al. 2020). The result's `rayed` lists them and
|
|
2257
|
+
`brightness(x, y, z, detail)` is 0 to 1; give it to `PlanetTerrain`'s `brightness`.
|
|
2258
|
+
- `PlanetTerrain.attach(engine, {brightness})`: per vertex, 0 leaves the ground's colour, up to 1 turns it to bright
|
|
2259
|
+
fresh rock, down to -1 darkens it to black. Default none.
|
|
2260
|
+
- `ridgeNoise({radius, relief, octaves, gain, frequency, seed})`: ridged multifractal noise between 0 and `relief`
|
|
2261
|
+
(Musgrave et al. 1989); defaults 8,000 m, 6 octaves, gain 2, 2 cycles around the planet.
|
|
2262
|
+
- `domainWarp(height, {radius, amplitude, frequency, levels, seed})`: reads `height` at positions shifted by noise,
|
|
2263
|
+
up to `amplitude` metres (default 100,000) along each axis, so up to sqrt(3) times it in all; `levels: 2` warps by a
|
|
2264
|
+
warped noise, which moves a point no further.
|
|
2265
|
+
- `combine(heights, {mode, smooth})`: `'add'` (default), `'max'` or `'smoothMax'` (rounded joins, `smooth` 100 m).
|
|
2266
|
+
- `planetPreset('moon' | 'mars' | 'asteroid' | 'ice', {radius, seed})` and `planetPresetRadius(name)`: authored looks
|
|
2267
|
+
(numbers in [limits](../../docs/limits.md)), made for the body's own radius; pass the same `radius` to `PlanetTerrain`.
|
|
2268
|
+
The Moon's has 6 rayed craters; `planetPresetBrightness(name, {radius, seed})` gives their brightness (0 everywhere
|
|
2269
|
+
for the other presets).
|
|
2270
|
+
The preset is shaded by `PlanetTerrain` with its height colours, so set `relief` to suit and `seaLevel: false`.
|
|
2271
|
+
|
|
2272
|
+
Complex craters, rays and secondaries are checked in `test/planet-complex-craters.test.js` (depth, rim, floor and peak
|
|
2273
|
+
against the laws within 2%, benches on the wall, no step across the transition, ray count and reach, chains on the rays).
|
|
2274
|
+
The simple craters are checked in `test/planet-recipes.test.js` (an isolated crater's depth and rim over diameter against the Pike ratios and its
|
|
2275
|
+
ejecta against McGetchin within 2%, a flat floor within 1e-6, diameters against the power law with a
|
|
2276
|
+
Kolmogorov-Smirnov statistic under 0.02, determinism, pruning by detail, bounded reads, validation) and on both GPU backends by
|
|
2277
|
+
`test/planet-recipes.browser.mjs` (every preset drawn on `PlanetTerrain`, deterministic, no validation error).
|
|
2278
|
+
|
|
2279
|
+
## Terrain relief lighting
|
|
2280
|
+
|
|
2281
|
+
Use `@margoengine/terrain/relief-lighting` to shade terrain from its measured or generated heightfield. A ridge can
|
|
2282
|
+
block the sun on the floor of a valley, even if the ridge is outside the camera view. The visible sky supplies the
|
|
2283
|
+
remaining diffuse light. The bake keeps sunlight visibility and projected sky visibility separate so layer albedo,
|
|
2284
|
+
roughness and explicit light sources retain their roles.
|
|
2285
|
+
|
|
2286
|
+
```ts
|
|
2287
|
+
import { Engine } from '@margoengine/core';
|
|
2288
|
+
import { Terrain } from '@margoengine/terrain';
|
|
2289
|
+
import { TerrainReliefLighting } from '@margoengine/terrain/relief-lighting';
|
|
2290
|
+
|
|
2291
|
+
const canvas = document.body.appendChild(document.createElement('canvas'));
|
|
2292
|
+
const engine = await Engine.create(canvas, {
|
|
2293
|
+
backend: 'webgpu',
|
|
2294
|
+
camera: { position: [31, 43, 65], target: [31, 0, 25] },
|
|
2295
|
+
});
|
|
2296
|
+
engine.lighting.direction.set([1, 0.28, 0, 3]);
|
|
2297
|
+
const terrain = Terrain.attach(engine, {
|
|
2298
|
+
size: [64, 64],
|
|
2299
|
+
heightScale: 1,
|
|
2300
|
+
layers: Array.from({ length: 4 }, () => ({ height: [-1, 100], slope: [0, 1], scale: 1 })),
|
|
2301
|
+
textures(device) {
|
|
2302
|
+
const heightmap = device.createTexture({ size: [65, 65], format: 'r32float', usage: 6 });
|
|
2303
|
+
const samples = new Float32Array(65 * 65);
|
|
2304
|
+
for (let z = 0; z < 65; z++) samples[z * 65 + 32] = 18;
|
|
2305
|
+
device.queue.writeTexture({ texture: heightmap }, samples, { bytesPerRow: 260 }, [65, 65]);
|
|
2306
|
+
const layers = device.createTexture({ size: [1, 1, 4], format: 'rgba8unorm', usage: 6 });
|
|
2307
|
+
device.queue.writeTexture(
|
|
2308
|
+
{ texture: layers }, new Uint8Array(16).fill(140), { bytesPerRow: 4, rowsPerImage: 1 }, [1, 1, 4],
|
|
2309
|
+
);
|
|
2310
|
+
return { heightmap, layers };
|
|
2311
|
+
},
|
|
2312
|
+
});
|
|
2313
|
+
const relief = TerrainReliefLighting.attach(engine, terrain);
|
|
2314
|
+
engine.start();
|
|
2315
|
+
// After a height or sun change, call relief.rebake(). Call engine.dispose() when leaving the view.
|
|
2316
|
+
```
|
|
2317
|
+
|
|
2318
|
+
- Attach to a live clipmap terrain. On device restore the effect bakes from the heightmap on the restored device.
|
|
2319
|
+
Disposing the effect releases its texture and detaches it from its actual scene.
|
|
2320
|
+
- `direction` defaults to the engine light at the time of the bake. `radius` defaults to one quarter of the
|
|
2321
|
+
shorter extent. The defaults are 12 sky azimuths, 48 samples per ray and a 0.75-degree half-width for the sun.
|
|
2322
|
+
Use 4–32 azimuths, 8–256 samples and a positive half-width of up to 10 degrees.
|
|
2323
|
+
- Height samples must be finite and corner aligned. The effect uses the terrain height scale by default. It
|
|
2324
|
+
works with a single sampled 2D `r32float`, `rgba16float` or `rgba8unorm` height texture at least 2×2.
|
|
2325
|
+
- For Blender meshes and custom terrain draws, `bakeTerrainReliefLighting(device, heightmap, size, options)`
|
|
2326
|
+
returns an owned filterable `rgba16float` texture. Its R channel is sun visibility and its G channel is
|
|
2327
|
+
projected sky visibility. Call `texture.destroy()` when finished. `terrainReliefLightingWGSL` provides
|
|
2328
|
+
`terrainReliefLight(map, sampler, uv)`, with UV coordinates 0 and 1 at the first and last height samples.
|
|
2329
|
+
- Work is bounded by `width × height × (rays + 1) × steps` horizon samples per bake. Draws fetch one texel
|
|
2330
|
+
bilinearly. Radii and sample spacing limit the result. Distant narrow ridges can fall between samples.
|
|
2331
|
+
Overhangs and occluders absent from the heightfield require regular shadow casters.
|
|
2332
|
+
|
|
2333
|
+
Terrain horizons follow Nicolas Max, *Horizon Mapping: Shadows for Bump-Mapped Surfaces* (1988), and
|
|
2334
|
+
A. James Stewart, *Fast Horizon Computation at All Points of a Terrain with Visibility and Shading Applications*
|
|
2335
|
+
(1998). The azimuth-sampled sky view follows Klemen Zakšek, Krištof Oštir and Žiga Kokalj, *Sky-View Factor as
|
|
2336
|
+
a Relief Visualization Technique* (2011).
|
|
2337
|
+
[Max](https://cir.nii.ac.jp/crid/1573387451457112064)
|
|
2338
|
+
[Stewart](https://research.cs.queensu.ca/home/jstewart/papers/tvcg97.html)
|
|
2339
|
+
[Zakšek, Oštir and Kokalj](https://doi.org/10.3390/RS3020398)
|
|
2340
|
+
|
|
2341
|
+
## Terrain bed mesh: `@margoengine/terrain/bed`
|
|
2342
|
+
|
|
2343
|
+
`BedMesh` draws a terrain bed (the physics framework's `TerrainBed`, or any `Bed` from `@margoengine/math/fields`) as
|
|
2344
|
+
a mesh. Its vertices are the bed's vertices and its triangles the kernel's own split, so the drawn ground is the
|
|
2345
|
+
ground bodies, soil solvers and water stand on, heaps included. Normals are area-weighted (Max 1999). `update` takes
|
|
2346
|
+
the bed's current elevations and rewrites only the vertices that changed and the normals around them.
|
|
2347
|
+
|
|
2348
|
+
```ts
|
|
2349
|
+
import { Engine, PbrMaterial } from '@margoengine/core';
|
|
2350
|
+
import { bedSurface } from '@margoengine/physics/earth';
|
|
2351
|
+
import { BedMesh } from '@margoengine/terrain/bed';
|
|
2352
|
+
|
|
2353
|
+
const canvas = document.querySelector('canvas')!;
|
|
2354
|
+
const engine = await Engine.create(canvas);
|
|
2355
|
+
const shape = { columns: 32, rows: 32, width: 40, depth: 40, centre: [0, 0] as [number, number] };
|
|
2356
|
+
const elevations = new Float64Array(33 * 33).fill(-161);
|
|
2357
|
+
const bedMesh = new BedMesh(bedSurface(shape, elevations));
|
|
2358
|
+
const mesh = engine.createMesh().setGeometry(bedMesh.geometry()).setMaterial(new PbrMaterial({ color: '#4a3a2c' }));
|
|
2359
|
+
elevations[16 + 33 * 16] += 0.5; // a heap, as a slide would push up
|
|
2360
|
+
if (bedMesh.update(bedSurface(shape, elevations)).changed) mesh.setGeometry(bedMesh.geometry());
|
|
2361
|
+
```
|
|
2362
|
+
|
|
2363
|
+
| Option or method | Meaning |
|
|
2364
|
+
| --- | --- |
|
|
2365
|
+
| `new BedMesh(bed)` | Builds positions, normals and triangles from the bed; RangeError for a bad grid or a non-finite elevation. |
|
|
2366
|
+
| `geometry()` | The current core `Geometry`; a new one after an update that changed something. |
|
|
2367
|
+
| `update(bed)` | Takes the bed's elevations; returns `{ changed, rewritten }` vertex counts. RangeError for another grid. |
|