@threenative/terrain 0.1.9 → 0.1.12
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/README.md +40 -59
- package/THIRD_PARTY_NOTICES.md +2 -1
- package/dist/bake-DJ5cxg0C.d.ts +82 -0
- package/dist/editor/index.d.ts +4 -4
- package/dist/editor/index.js +130 -128
- package/dist/editor/server.d.ts +2 -2
- package/dist/editor/server.js +38 -35
- package/dist/editor/worker.d.ts +1 -1
- package/dist/editor/worker.js +101 -101
- package/dist/export.d.ts +1 -1
- package/dist/index.d.ts +156 -273
- package/dist/index.js +562 -378
- package/dist/kit-world.d.ts +107 -0
- package/dist/kit-world.js +5134 -0
- package/dist/kit.d.ts +21 -4
- package/dist/kit.js +337 -223
- package/dist/mcp/cook-child.js +1963 -1543
- package/dist/mcp/server.js +716 -429
- package/dist/prop-package-Dwz0EWoB.d.ts +141 -0
- package/dist/{server-B5RdvEAC.d.ts → server-LnFwY8sr.d.ts} +1 -1
- package/dist/starter.d.ts +1142 -7
- package/dist/starter.js +2102 -120
- package/dist/{terrain-CAEaW0mQ.d.ts → terrain-DYCyAOCJ.d.ts} +1 -1
- package/dist/three.d.ts +1 -1
- package/dist/three.js +1 -1
- package/dist/{types-BpH00qsx.d.ts → types-kpI0C4hW.d.ts} +1 -1
- package/dist/{world-package-B8QgHjAQ.d.ts → world-package-DqJC3-Nn.d.ts} +2 -2
- package/docs/authoring/editor.md +73 -0
- package/docs/authoring/new-environment.md +97 -0
- package/docs/authoring/recipes.md +97 -0
- package/docs/authoring/world-export.md +66 -0
- package/package.json +24 -8
- package/starter/alpine/README.md +22 -12
- package/starter/alpine/bake.mjs +14 -1
- package/starter/alpine/biome.data.json +187 -25
- package/starter/alpine/heightmap.r16 +0 -0
- package/starter/alpine/playerRig.ts +89 -0
- package/starter/alpine/recipe.json +169 -15
- package/starter/alpine/render/bakedFile.ts +17 -0
- package/starter/alpine/render/benchmark.ts +77 -0
- package/starter/alpine/render/biomeData.ts +14 -0
- package/starter/alpine/render/biomes.ts +687 -0
- package/starter/alpine/render/ground/cover.ts +565 -0
- package/starter/alpine/render/ground/horizon.ts +219 -0
- package/starter/alpine/render/ground/palette.d.ts +1 -0
- package/starter/alpine/render/ground/palette.js +11 -0
- package/starter/alpine/render/ground/scatter.ts +104 -0
- package/starter/alpine/render/ground/terrain.ts +1860 -0
- package/starter/alpine/render/kitAssets.ts +28 -0
- package/starter/alpine/render/loading.ts +354 -0
- package/starter/alpine/render/lookKnobs.ts +37 -0
- package/starter/alpine/render/orbitCamera.ts +155 -0
- package/starter/alpine/render/props/farForest.ts +94 -0
- package/starter/alpine/render/props/pack.ts +1114 -0
- package/starter/alpine/render/props/prepared.ts +225 -0
- package/starter/alpine/render/props/propMaterials.ts +1239 -0
- package/starter/alpine/render/props/propProgress.ts +2 -0
- package/starter/alpine/render/props/propWorld.ts +105 -0
- package/starter/alpine/render/props/props.ts +633 -0
- package/starter/alpine/render/props/spruce.ts +440 -0
- package/starter/alpine/render/sky/atmosphere.ts +329 -0
- package/starter/alpine/render/sky/sky.ts +382 -0
- package/starter/alpine/render/texturePreparation.ts +135 -0
- package/starter/alpine/render/water/river.ts +1132 -0
- package/starter/alpine/render/worldNames.ts +6 -0
- package/starter/alpine/scene.ts +715 -0
- package/starter/alpine/sceneProps.ts +561 -0
- package/starter/alpine/sceneState.ts +33 -0
- package/starter/alpine/world/terrainAssets.ts +145 -0
- package/starter/alpine/world/walkBand.ts +47 -0
- package/starter/alpine/world/water.ts +74 -0
- package/starter/alpine/worlds.ts +13 -0
- package/starter/arbor/wind.ts +84 -0
- package/starter/coastal/README.md +26 -25
- package/starter/coastal/assets.json +10 -0
- package/starter/coastal/bake.mjs +14 -1
- package/starter/coastal/biome.data.json +18 -3
- package/starter/coastal/playerRig.ts +89 -0
- package/starter/coastal/recipe.json +220 -18
- package/starter/coastal/render/bakedFile.ts +17 -0
- package/starter/coastal/render/benchmark.ts +81 -0
- package/starter/coastal/render/biomeData.ts +14 -0
- package/starter/coastal/render/biomes.ts +678 -0
- package/starter/coastal/render/ground/cover.ts +565 -0
- package/starter/coastal/render/ground/horizon.ts +219 -0
- package/starter/coastal/render/ground/palette.d.ts +1 -0
- package/starter/coastal/render/ground/palette.js +11 -0
- package/starter/coastal/render/ground/scatter.ts +104 -0
- package/starter/coastal/render/ground/terrain.ts +1829 -0
- package/starter/coastal/render/kitAssets.ts +28 -0
- package/starter/coastal/render/loading.ts +354 -0
- package/starter/coastal/render/lookKnobs.ts +37 -0
- package/starter/coastal/render/orbitCamera.ts +155 -0
- package/starter/coastal/render/props/farForest.ts +94 -0
- package/starter/coastal/render/props/pack.ts +1109 -0
- package/starter/coastal/render/props/prepared.ts +225 -0
- package/starter/coastal/render/props/propMaterials.ts +1239 -0
- package/starter/coastal/render/props/propProgress.ts +2 -0
- package/starter/coastal/render/props/propWorld.ts +105 -0
- package/starter/coastal/render/props/props.ts +633 -0
- package/starter/coastal/render/props/spruce.ts +440 -0
- package/starter/coastal/render/sky/atmosphere.ts +329 -0
- package/starter/coastal/render/sky/sky.ts +382 -0
- package/starter/coastal/render/texturePreparation.ts +135 -0
- package/starter/coastal/render/water/ocean.ts +284 -0
- package/starter/coastal/render/water/river.ts +1132 -0
- package/starter/coastal/render/worldNames.ts +6 -0
- package/starter/coastal/scene.ts +740 -0
- package/starter/coastal/sceneProps.ts +559 -0
- package/starter/coastal/sceneState.ts +33 -0
- package/starter/coastal/world/terrainAssets.ts +151 -0
- package/starter/coastal/world/walkBand.ts +47 -0
- package/starter/coastal/world/water.ts +74 -0
- package/starter/coastal/worlds.ts +13 -0
- package/starter/desert/README.md +51 -23
- package/starter/desert/bake-flora.mjs +142 -0
- package/starter/desert/bake-rocks.mjs +291 -0
- package/starter/desert/bake.mjs +14 -1
- package/starter/desert/biome.data.json +24 -12
- package/starter/desert/playerRig.ts +89 -0
- package/starter/desert/recipe.json +63 -16
- package/starter/desert/render/bakedFile.ts +17 -0
- package/starter/desert/render/benchmark.ts +79 -0
- package/starter/desert/render/biomeData.ts +14 -0
- package/starter/desert/render/biomes.ts +660 -0
- package/starter/desert/render/ground/cover.ts +565 -0
- package/starter/desert/render/ground/debris.ts +136 -0
- package/starter/desert/render/ground/horizon.ts +219 -0
- package/starter/desert/render/ground/palette.d.ts +1 -0
- package/starter/desert/render/ground/palette.js +11 -0
- package/starter/desert/render/ground/scatter.ts +104 -0
- package/starter/desert/render/ground/terrain.ts +1854 -0
- package/starter/desert/render/kitAssets.ts +28 -0
- package/starter/desert/render/loading.ts +354 -0
- package/starter/desert/render/lookKnobs.ts +37 -0
- package/starter/desert/render/orbitCamera.ts +155 -0
- package/starter/desert/render/props/farForest.ts +96 -0
- package/starter/desert/render/props/formations.ts +630 -0
- package/starter/desert/render/props/pack.ts +1195 -0
- package/starter/desert/render/props/prepared.ts +225 -0
- package/starter/desert/render/props/propMaterials.ts +1255 -0
- package/starter/desert/render/props/propProgress.ts +2 -0
- package/starter/desert/render/props/propWorld.ts +105 -0
- package/starter/desert/render/props/props.ts +624 -0
- package/starter/desert/render/props/spruce.ts +440 -0
- package/starter/desert/render/sand.ts +581 -0
- package/starter/desert/render/sky/atmosphere.ts +329 -0
- package/starter/desert/render/sky/sky.ts +382 -0
- package/starter/desert/render/texturePreparation.ts +135 -0
- package/starter/desert/render/water/river.ts +1132 -0
- package/starter/desert/render/worldNames.ts +6 -0
- package/starter/desert/scene.ts +748 -0
- package/starter/desert/sceneProps.ts +562 -0
- package/starter/desert/sceneState.ts +33 -0
- package/starter/desert/world/terrainAssets.ts +162 -0
- package/starter/desert/world/walkBand.ts +47 -0
- package/starter/desert/world/water.ts +74 -0
- package/starter/desert/worlds.ts +13 -0
- package/starter/forest/README.md +59 -116
- package/starter/forest/assets.json +14 -14
- package/starter/forest/bake.mjs +26 -4
- package/starter/forest/playerRig.ts +89 -0
- package/starter/forest/recipe.json +233 -43
- package/starter/forest/render/bakedFile.ts +17 -0
- package/starter/forest/render/benchmark.ts +77 -0
- package/starter/forest/render/biomeData.ts +14 -0
- package/starter/forest/render/biomes.ts +637 -0
- package/starter/forest/render/ground/cover.ts +565 -0
- package/starter/forest/render/ground/horizon.ts +219 -0
- package/starter/forest/render/ground/palette.d.ts +1 -0
- package/starter/forest/render/ground/palette.js +11 -0
- package/starter/forest/render/ground/scatter.ts +104 -0
- package/starter/forest/render/ground/terrain.ts +1796 -0
- package/starter/forest/render/kitAssets.ts +28 -0
- package/starter/forest/render/loading.ts +354 -0
- package/starter/forest/render/lookKnobs.ts +37 -0
- package/starter/forest/render/orbitCamera.ts +155 -0
- package/starter/forest/render/props/farForest.ts +94 -0
- package/starter/forest/render/props/pack.ts +1078 -0
- package/starter/forest/render/props/prepared.ts +226 -0
- package/starter/forest/render/props/propMaterials.ts +1247 -0
- package/starter/forest/render/props/propProgress.ts +2 -0
- package/starter/forest/render/props/propWorld.ts +105 -0
- package/starter/forest/render/props/props.ts +624 -0
- package/starter/forest/render/props/spruce.ts +440 -0
- package/starter/forest/render/sky/atmosphere.ts +329 -0
- package/starter/forest/render/sky/sky.ts +382 -0
- package/starter/forest/render/texturePreparation.ts +135 -0
- package/starter/forest/render/water/river.ts +1132 -0
- package/starter/forest/render/worldNames.ts +6 -0
- package/starter/forest/scene.ts +715 -0
- package/starter/forest/sceneProps.ts +559 -0
- package/starter/forest/sceneState.ts +33 -0
- package/starter/forest/surface.json +2 -2
- package/starter/forest/world/terrainAssets.ts +158 -0
- package/starter/forest/world/walkBand.ts +47 -0
- package/starter/forest/world/water.ts +74 -0
- package/starter/forest/worlds.ts +13 -0
- package/starter/tundra/README.md +35 -14
- package/starter/tundra/bake.mjs +14 -1
- package/starter/tundra/biome.data.json +6 -6
- package/starter/tundra/playerRig.ts +89 -0
- package/starter/tundra/recipe.json +111 -110
- package/starter/tundra/render/bakedFile.ts +17 -0
- package/starter/tundra/render/benchmark.ts +79 -0
- package/starter/tundra/render/biomeData.ts +14 -0
- package/starter/tundra/render/biomes.ts +714 -0
- package/starter/tundra/render/ground/cover.ts +565 -0
- package/starter/tundra/render/ground/horizon.ts +219 -0
- package/starter/tundra/render/ground/palette.d.ts +1 -0
- package/starter/tundra/render/ground/palette.js +11 -0
- package/starter/tundra/render/ground/scatter.ts +104 -0
- package/starter/tundra/render/ground/terrain.ts +1874 -0
- package/starter/tundra/render/kitAssets.ts +28 -0
- package/starter/tundra/render/loading.ts +354 -0
- package/starter/tundra/render/lookKnobs.ts +37 -0
- package/starter/tundra/render/orbitCamera.ts +155 -0
- package/starter/tundra/render/props/farForest.ts +96 -0
- package/starter/tundra/render/props/pack.ts +1088 -0
- package/starter/tundra/render/props/prepared.ts +225 -0
- package/starter/tundra/render/props/propMaterials.ts +1247 -0
- package/starter/tundra/render/props/propProgress.ts +2 -0
- package/starter/tundra/render/props/propWorld.ts +105 -0
- package/starter/tundra/render/props/props.ts +624 -0
- package/starter/tundra/render/props/spruce.ts +440 -0
- package/starter/tundra/render/sky/atmosphere.ts +329 -0
- package/starter/tundra/render/sky/sky.ts +382 -0
- package/starter/tundra/render/texturePreparation.ts +135 -0
- package/starter/tundra/render/water/river.ts +1132 -0
- package/starter/tundra/render/worldNames.ts +6 -0
- package/starter/tundra/scene.ts +715 -0
- package/starter/tundra/sceneProps.ts +559 -0
- package/starter/tundra/sceneState.ts +33 -0
- package/starter/tundra/world/terrainAssets.ts +159 -0
- package/starter/tundra/world/walkBand.ts +47 -0
- package/starter/tundra/world/water.ts +74 -0
- package/starter/tundra/worlds.ts +13 -0
- package/starter-assets.json +4 -4
- package/starter-credits.json +901 -15
- package/AGENT_GUIDE.md +0 -209
- package/starter/forest/sky.ts +0 -38
- package/starter/forest/water.ts +0 -257
- package/starter/forest/world.ts +0 -182
package/AGENT_GUIDE.md
DELETED
|
@@ -1,209 +0,0 @@
|
|
|
1
|
-
# Strata: instructions for a coding agent
|
|
2
|
-
|
|
3
|
-
## Read this first
|
|
4
|
-
|
|
5
|
-
Use the typed public `@threenative/terrain` imports to author terrain. The headless implementation is recovered from the owner-supplied Strata source. An operation records intent; `evaluate()` produces disposable data. Never modify an evaluated height array expecting to edit the recipe.
|
|
6
|
-
|
|
7
|
-
World units are metres. Y is up. X and Z range from `-size/2` to `+size/2`. Brush centres and masks use `[x,z]`; spline points use `[x,y,z]`. Rotation and slope thresholds use degrees. **Placement output yaw uses radians.** Heights are absolute world elevations, not normalized texture values.
|
|
8
|
-
|
|
9
|
-
Prefer stable semantic IDs: `base`, `north-peak`, `camp-pad`, `access-road`, `river-main`, `forest`. Repeating an operation with an existing ID replaces it **in place**. It does not append another layer. Use `label` for a human-readable name in fluent calls; the saved layer uses `name`. In `biome()` the `name` parameter is the biome key, not the display name.
|
|
10
|
-
|
|
11
|
-
## Workflow
|
|
12
|
-
|
|
13
|
-
1. Establish world size, seed, and a low preview resolution. Add base noise and large landforms.
|
|
14
|
-
2. Add erosion before fine roads/building pads. Roads and pads take their elevation from the ground they cross unless you pin one.
|
|
15
|
-
3. Add surface/biome rules and population. Put rules after the geometry changes whose slopes they should see. Road painting can override earlier surface rules; a later reset-material pass can also erase a road's paint.
|
|
16
|
-
4. Inspect the result and diagnostics. Modify known IDs, keeping the source stack small.
|
|
17
|
-
5. Export the recipe and derived runtime data at an explicit resolution. Verify the high-resolution result; resolution-dependent simulation is not guaranteed to match the preview exactly.
|
|
18
|
-
|
|
19
|
-
Use `transaction()` for a synchronous semantic edit that should undo as a unit. Validation failure rolls back the entire batch. `applyPatch()` accepts JSON-only atomic commands, useful for a tool-calling agent:
|
|
20
|
-
|
|
21
|
-
```js
|
|
22
|
-
terrain.applyPatch([
|
|
23
|
-
{ op: 'update', id: 'north-peak', patch: { params: { amplitude: 120 } } },
|
|
24
|
-
{ op: 'update', id: 'river-main', patch: { params: { width: 22 } } },
|
|
25
|
-
{ op: 'toggle', id: 'erosion', enabled: true },
|
|
26
|
-
]);
|
|
27
|
-
```
|
|
28
|
-
|
|
29
|
-
Allowed patch commands: `upsert` with `layer`, `update` with `id` and `patch`, `remove` with `id`, `move` with `id` and zero-based `index`, `toggle` with `id` and optional `enabled`. Do not invent methods such as `terrain.generate()`, `terrain.bake()` or `terrain.saveGLB()`. Use `evaluate()`, `bakeTerrain()` and `makeExport()`.
|
|
30
|
-
|
|
31
|
-
## API patterns
|
|
32
|
-
|
|
33
|
-
```js
|
|
34
|
-
import { Terrain, Mask, bakeMesh, bakeTerrain, makeExport } from '@threenative/terrain';
|
|
35
|
-
const t = new Terrain({ size: 512, resolution: 129, seed: 73 });
|
|
36
|
-
|
|
37
|
-
t.noise({ id: 'base', base: 15, amplitude: 20, scale: 140, octaves: 5, warp: 30 });
|
|
38
|
-
t.sculpt({ id: 'hill', at: [0,0], radius: 45, strength: 12, falloff: .7 });
|
|
39
|
-
t.sculpt({ id: 'ditch', points: [[-40,10],[0,30],[40,35]], radius: 10, strength: -5 });
|
|
40
|
-
t.smooth({ id: 'soften', at: [0,0], radius: 65, strength: .6, iterations: 4 });
|
|
41
|
-
t.flatten({ id: 'pad', at: [-70,50], radius: 28, height: 22, strength: 1 });
|
|
42
|
-
t.ramp({ id: 'ramp', from: [-70,22,50], to: [-20,38,50], width: 15, shoulder: 10 });
|
|
43
|
-
t.stamp({ id: 'cliff-mass', shape: 'mesa', at: [90,-70], radius: [70,40], amplitude: 50, rotation: 30 });
|
|
44
|
-
t.erode({ id: 'thermal', method: 'thermal', iterations: 15, talus: 32, rate: .22 });
|
|
45
|
-
t.erode({ id: 'hydraulic', method: 'hydraulic', droplets: 5000, maxSteps: 40 });
|
|
46
|
-
t.terrace({ id: 'strata', step: 8, softness: .22, strength: .7 });
|
|
47
|
-
```
|
|
48
|
-
|
|
49
|
-
A `flatten` with no `height` levels the pad to the ground already under it and lets the blend reach as far as its deepest cut or fill, so it is a bench rather than a mesa.
|
|
50
|
-
|
|
51
|
-
Stroke tools accept `at` or a polyline `points`. Brush radius is a **radius**, not diameter. Strength is signed metres for sculpt; `0..1` for smoothing, flattening and paint. Stroke coverage uses maximum falloff coverage, not repeated accumulation at every mouse event. Holding a brush stationary does not keep adding height. Points are interpolated at `2 * radius * spacing`; jitter is seeded. Procedural stamps use `amplitude` in metres. `opacity` is available on every layer.
|
|
52
|
-
|
|
53
|
-
Masks are serializable expressions, never callbacks:
|
|
54
|
-
|
|
55
|
-
```js
|
|
56
|
-
const forest = Mask.and(
|
|
57
|
-
Mask.height(8, 85, 10), // altitude band, feathered boundaries
|
|
58
|
-
Mask.slope(0, 34, 6), // slope degrees
|
|
59
|
-
Mask.not(Mask.material('road')),
|
|
60
|
-
Mask.not(Mask.circle([-70, 50], 38, .3)),
|
|
61
|
-
);
|
|
62
|
-
|
|
63
|
-
t.biome({ id: 'forest-zone', label: 'Conifer biome', name: 'forest', mask: forest });
|
|
64
|
-
t.scatter({ id: 'trees', asset: 'pine', count: 900, minDistance: 5,
|
|
65
|
-
scale: [.75,1.25], maxSlope: 35, mask: Mask.biome('forest') });
|
|
66
|
-
t.clear({ id: 'clear-camp', target: 'scatter', mask: Mask.circle([-70,50],35) });
|
|
67
|
-
```
|
|
68
|
-
|
|
69
|
-
Additional masks: `Mask.rectangle(at, size, rotation, falloff)`, `Mask.noise(scale, threshold, seed, fade)`, `Mask.or(...)`, `Mask.all()`, `Mask.none()`. Slope/height masks are evaluated against the terrain at that operation's stage. Population is deferred: scatter rules sample the **final** heights/materials/biomes and re-evaluate their mask there, so later height edits do not leave trees floating. Clear-scatter masks affect preceding rules only. Minimum distance is guaranteed **within each rule**, not across different scatter rules. The bounded rejection sampler may place fewer than requested; inspect diagnostics rather than assuming an exact count.
|
|
70
|
-
|
|
71
|
-
Materials are exactly `grass`, `dirt`, `rock`, `snow`, `sand`, `mud`, `road`, `moss`. Splat arrays are sample-major: `splat[sampleIndex * 8 + channel]`. Weights sum to one. `paint()` blends and renormalizes; `materials()` applies ordered rules. A later rule can override an earlier one.
|
|
72
|
-
|
|
73
|
-
```js
|
|
74
|
-
t.materials({ id: 'surfaces', base: 'grass', rules: [
|
|
75
|
-
{ material: 'sand', mask: Mask.height(-100, 5, 3) },
|
|
76
|
-
{ material: 'rock', mask: Mask.slope(42, 90, 8) },
|
|
77
|
-
{ material: 'snow', mask: Mask.height(95, 1000, 15) },
|
|
78
|
-
] });
|
|
79
|
-
t.paint({ id: 'camp-dirt', at: [-70,50], radius: 27, material: 'dirt', strength: .9 });
|
|
80
|
-
```
|
|
81
|
-
|
|
82
|
-
## Realistic mountains and environments
|
|
83
|
-
|
|
84
|
-
Start from a kind, not from noise. `landform(kind, { size, resolution, seed, relief })` returns an ordinary `Terrain` with a calibrated recipe: `alpine`, `temperateMountains`, `rollingHills`, `desertMesa`, `coastalCliffs`, `tundra`, `volcanic`. `LANDFORMS[kind]` names the real reference landscape and the measured targets. It decides shape only, never material or colour. Calibrated at size 5000, resolution 513; other sizes keep slopes and scale relief with `size`. `relief` (metres, highest minus lowest) defaults to the kind's real ratio times `size`.
|
|
85
|
-
|
|
86
|
-
```js
|
|
87
|
-
import { landform, terrainStats } from '@threenative/terrain';
|
|
88
|
-
const state = landform('alpine', { seed: 4 }).evaluate(); // build script, about 1.5 s at 513
|
|
89
|
-
terrainStats(state.height, state.resolution, state.size); // relief, slopes, hypsometry, curvature kurtosis
|
|
90
|
-
```
|
|
91
|
-
|
|
92
|
-
`erode({ method: 'fluvial' })` is the engine behind it: stream-power incision with uplift (Braun & Willett 2013, Cordonnier et al. 2016). The earlier layers are the uplift envelope; it cuts dendritic valleys and sharp divides that droplet erosion at game resolution does not. Params: `iterations` (default 40), `uplift` m/yr, `erodibility` K, `timeStep` yr, `talus` landslide threshold, `relief` metres. Follow it with a short `thermal` pass and `smooth` to remove the 8-neighbour grain. Bake a backdrop: `node packages/terrain/scripts/bake-horizon.mjs alpine --seed 4 --out alpine-horizon.json`.
|
|
93
|
-
|
|
94
|
-
## Roads, rivers and water
|
|
95
|
-
|
|
96
|
-
A road, river or ramp **grades itself to the ground it crosses** when a control point leaves its elevation out (`null`, or `NaN` in code) or when it sets `followTerrain: true`. The elevation is sampled along the centreline, low-passed along arc length, then held inside `maxGrade` (default 0.12) and `maxCut`/`maxFill` (default 2.5 m / 1.5 m); the shoulder widens into a batter with the cut or fill, so a corridor never stands on a retaining step. Leaving the ground is the hard limit: where the ground itself is steeper than `maxGrade`, the road is steep too. Absolute elevations are still honoured exactly, so existing documents keep their meaning. Horizontal spline interpolation is Catmull–Rom; vertical interpolation is linear between controls to avoid vertical overshoot. Use `smooth:false` for a polyline.
|
|
97
|
-
|
|
98
|
-
```js
|
|
99
|
-
t.road({ id: 'access-road', points: [[-220,null,100],[-150,null,70],[-70,null,50]], width: 12, shoulder: 8 });
|
|
100
|
-
t.river({ id: 'river-main', points: [[20,14,-240],[35,8,0],[80,3,240]], width: 18, depth: 4, enforceDownhill: true });
|
|
101
|
-
t.water({ id: 'lake', kind: 'lake', at: [80,210], radius: 75, level: 4 });
|
|
102
|
-
```
|
|
103
|
-
|
|
104
|
-
`enforceDownhill:true` validates non-increasing Y, rather than silently changing elevations in the API. River carving only lowers terrain. The water surface is a ribbon, not a flow simulation. Keep profiles sensible and avoid self-intersecting splines.
|
|
105
|
-
|
|
106
|
-
Lake flood fill starts at the supplied location, follows connected samples below `level`, and is limited by `radius`/mask. A seed above water level produces an empty mask and a diagnostic. Oceans flood from map boundaries. Water placement does not itself excavate a basin: lower the basin first. Scatter avoids flooded lake/ocean samples and submerged river ribbons by default.
|
|
107
|
-
|
|
108
|
-
## Copy/paste and external heightfields
|
|
109
|
-
|
|
110
|
-
```js
|
|
111
|
-
const heights = t.copyRegion({ at: [90,-70], size: 110, resolution: 65 });
|
|
112
|
-
t.paste({ id: 'copied-mass', data: heights, at: [-120,-90], size: 110,
|
|
113
|
-
rotation: 90, mirrorX: true, blend: 'replace', falloff: .2 });
|
|
114
|
-
```
|
|
115
|
-
|
|
116
|
-
The copy contains heights only. Paste/stamp data is `{width,height,values}` in world metres. Fluent `heightmap()` / `paste()` / `stamp()` normalize typed arrays to plain arrays; raw recipe JSON must already contain plain arrays. RAW files have no self-describing dimensions/range. Preserve sidecars. PNG import accepts non-interlaced grayscale 8/16-bit images only, not RGB/palette images, and reports `hasEmbeddedRange`.
|
|
117
|
-
|
|
118
|
-
Stamp and paste footprints use `at: [x,z]`, `radius: [halfWidth,halfDepth]` or
|
|
119
|
-
`size: [width,depth]`, and `rotation` in degrees (positive turns +X towards +Z).
|
|
120
|
-
Existing `radius` takes precedence over `size`. All three landform operations use
|
|
121
|
-
positive `scale` for vertical gain and `offset` in metres after that gain;
|
|
122
|
-
additive blends add both the scaled height and offset. Heightmap accepts optional
|
|
123
|
-
`at`, `size`, `rotation` and `falloff` to place a bounded rectangular footprint.
|
|
124
|
-
Without these footprint fields it retains the supplied full-world sampling.
|
|
125
|
-
Outside a bounded footprint, existing terrain remains unchanged. Samples must
|
|
126
|
-
all be finite numbers. X/Z rotations that create overhangs have no heightfield
|
|
127
|
-
representation. These transforms change recipe parameters, not an independent
|
|
128
|
-
solid hidden inside the evaluated terrain.
|
|
129
|
-
|
|
130
|
-
## Inspect and export
|
|
131
|
-
|
|
132
|
-
```js
|
|
133
|
-
console.log(t.inspect({ resolution: 129 }));
|
|
134
|
-
const recipe = t.toJSON();
|
|
135
|
-
const same = Terrain.fromJSON(recipe);
|
|
136
|
-
const result = same.evaluate({ resolution: 257 });
|
|
137
|
-
const runtime = bakeTerrain(result, { chunkCells: 64, lodSteps: [1,2,4], skirtDepth: 6 });
|
|
138
|
-
const archive = await makeExport(result, recipe, 'runtime');
|
|
139
|
-
// Node: await writeFile(archive.name, archive.bytes)
|
|
140
|
-
```
|
|
141
|
-
|
|
142
|
-
`makeExport` kinds are `project`, `png`, `raw`, `splat`, `glb`, `runtime`; all return `{name,type,bytes}`. Exporting does not mutate the authoring recipe. Collision height samples are row-major from Z=-size/2 to Z=+size/2, with X increasing along each row. Grid vertices are `(x/(N-1)-.5)*size, height[z*N+x], (z/(N-1)-.5)*size`.
|
|
143
|
-
|
|
144
|
-
Do not promise navmesh, physics registration, EXR, seamless mixed-LOD stitching, procedural caves, true water simulation, or production art from this version. GLB exports terrain only; load placement assets separately. Native-engine integration is via arrays/manifests and still needs an engine-specific adapter.
|
|
145
|
-
|
|
146
|
-
## Bounds and operational safety
|
|
147
|
-
|
|
148
|
-
Valid grid resolutions: 17, 33, 65, 129, 257, 513, 1025 **vertices per side**. Use 129 or 257 while iterating, and inspect before moving to 513/1025. Changing resolution can change erosion and population. No cross-resolution exactness guarantee exists.
|
|
149
|
-
|
|
150
|
-
Maximum recipe layers: 512; maximum requested instances per scatter rule: 20,000; hydraulic droplets: 200,000; steps per droplet: 128; thermal/smooth iterations: 200; noise octaves: 10; spline/brush input points: 8192; interpolated brush centres per stroke: 65,536. These are input safeguards, not real-time performance targets. Do not choose all maximums together.
|
|
151
|
-
|
|
152
|
-
The evaluator is synchronous. An AbortSignal is checked between operations, not inside a long erosion pass. For real cancellation of a headless job, isolate it in a Node worker/process and terminate the worker. A prefix cache stores private snapshots, up to 48 MiB of counted height/splat/biome arrays by default; JavaScript metadata and output arrays are additional memory.
|
|
153
|
-
|
|
154
|
-
Never execute untrusted JavaScript from a recipe. The editor parses data only. Surface validation errors and preserve the previous valid recipe. Save the recipe, not just the baked mesh, before destructive project housekeeping.
|
|
155
|
-
|
|
156
|
-
Splatmaps are linear data, not color images: use a non-sRGB/NoColorSpace texture setting and renormalize sampled weights in the consuming shader. Do not use an 8-bit canvas conversion to read a PNG16 heightfield; the supplied decoder preserves its 16-bit samples.
|
|
157
|
-
|
|
158
|
-
## Live editor: environment, assets and surfaces
|
|
159
|
-
|
|
160
|
-
The running editor exposes three revision-checked operations beside the document, each also behind a GUI
|
|
161
|
-
panel that calls the same code. A write names `baseRevision`; a stale one is a 409 and nothing changes.
|
|
162
|
-
|
|
163
|
-
- `controller.environment({ op: "get" | "patch" | "reset" }, revision)`: sun azimuth/elevation/intensity/colour,
|
|
164
|
-
sky fill, sky colour or image, `exp2` haze, exposure, sea colours, and an independent `lighting` image.
|
|
165
|
-
`null` returns a field to the project's own value; an unsupported fog mode is refused by name. The
|
|
166
|
-
project's `src/render/` decides what each value does. Nothing here evaluates the terrain.
|
|
167
|
-
- `controller.asset({ op: "register" | "upload" | "adjust" | "remove" | "list" | "map" | "unmap" }, revision)`:
|
|
168
|
-
`register` takes an absolute local path (an asset-MCP download result), `upload` takes base64 bytes. Files
|
|
169
|
-
are stored as `<kind>/<sha12>-<id>.<ext>` so a replacement is a new URL; GLB, PNG, JPEG, WebP, HDR and EXR are
|
|
170
|
-
recognised by their bytes, measured, and refused by name when damaged, over the project's limits, or when a
|
|
171
|
-
GLB points outside itself. Same id with other bytes needs `replace: true`. `remove` drops the entry, never
|
|
172
|
-
the file, and is refused while a surface or an environment still uses it.
|
|
173
|
-
- `map` binds an image to a `<surface>.<channel>` input the project exposes (`bark.albedo`, `stone.normal`);
|
|
174
|
-
albedo is read as sRGB, every other channel as linear data. Placing a model is a `scatter` layer whose
|
|
175
|
-
`asset` is its id; `adjust` sets the file's unit scale and pivot without editing it.
|
|
176
|
-
|
|
177
|
-
## Three.js ownership
|
|
178
|
-
|
|
179
|
-
`@threenative/terrain/three` exports `toGeometry(bakeMesh(state))`. It creates only ordinary indexed geometry using your installed Three.js. Create the mesh/material in your own `src/render/`, register collision through the existing engine API, and dispose the geometry yourself. Baked vertex colours are absent by default; pass an explicit eight-channel sRGB `palette` to `bakeMesh` or `bakeTerrain` when wanted. The addon supplies no palette or material. The legacy `makeExport(..., "glb")` contains terrain only; use the separate static-world encoder below for resolved models and baked surfaces. The default GUI full-world action, chosen-resolution material/deformation baking and five final starter exports remain pending.
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
## Resolved static-world GLB
|
|
183
|
-
|
|
184
|
-
Import `prepareWorldGLTF` from `@threenative/terrain/export` in browser authoring source. Its import is DOM-free; scene preparation requires FileReader and canvas. Root and `/three` remain headless. This entry uses the installed Three.js GLTFExporter to prepare glTF JSON; the Node assets cook owns GLB encoding.
|
|
185
|
-
|
|
186
|
-
```ts
|
|
187
|
-
import { prepareWorldGLTF } from '@threenative/terrain/export';
|
|
188
|
-
const prepared = await prepareWorldGLTF({
|
|
189
|
-
revision, // accepted document's 64-character content hash
|
|
190
|
-
snapshotTime, // finite seconds, pinned across all baked deformations
|
|
191
|
-
state, // evaluated committed recipe with applied override records
|
|
192
|
-
terrain, // canonical metre-frame Mesh with UVs and prepared PBR maps
|
|
193
|
-
assets, // Map<assetId, Object3D>: actual static models
|
|
194
|
-
transforms, // Map<placementId, Matrix4>: actual final grounded root matrices
|
|
195
|
-
water, // [{ id, object, time: snapshotTime, staleFrames: 0 }]
|
|
196
|
-
});
|
|
197
|
-
// Send prepared.json to your Node authoring process, then:
|
|
198
|
-
// import { cookTerrainWorld } from '@threenative/assets';
|
|
199
|
-
// const { worldGlb } = await cookTerrainWorld({ preparedWorld: prepared.json });
|
|
200
|
-
// worldGlb is the self-contained world.glb; persist only after success.
|
|
201
|
-
```
|
|
202
|
-
|
|
203
|
-
Game source owns all geometry, materials and images. The terrain needs albedo `map`, `normalMap`, `roughnessMap` and `aoMap`; vertex colours alone are insufficient. MeshStandardMaterial metallic/roughness surfaces are supported. Colour/emissive images are sRGB, data maps are NoColorSpace. Supply decoded byte images (at most 16 megapixels); DataTexture images need complete RGBA bytes. Bake alpha into the colour image. Bake displacement, bump/light maps, node shaders, skinning/morphing and wind into the supplied static geometry/material first. Use tangent-space normal maps with equal X/Y scale magnitudes; bake object-space/anisotropic maps first. MeshPhysicalMaterial extensions are outside this bounded encoder's contract.
|
|
204
|
-
|
|
205
|
-
All final matrices use metres, Y-up, positive scale and no shear. Keys are durable placement IDs, never instance indices; unmatched matrices fail. Ordinary glTF nodes share model mesh data without requiring EXT_mesh_gpu_instancing. Source geometry, images and material values are copied before asynchronous encoding, so later source edits cannot mix the export snapshot. Input objects remain owned by the caller.
|
|
206
|
-
|
|
207
|
-
Every evaluated water body/river needs its actual baked object at exactly `snapshotTime` with `staleFrames: 0`. A low-resolution or stale ocean CPU height sample does not satisfy this contract. Missing/unbaked content rejects before producing a download; preserve the previous valid export and document. Encoding does not perform the project's material bake, chosen-resolution re-evaluation or ocean readback for you.
|
|
208
|
-
|
|
209
|
-
`output.report` records revision, resolution, time and placement/water IDs. Model cameras/lights and source userData are excluded. The receiving game supplies its own lighting, sky/environment, fog, exposure, post and live water/wind; GLB does not carry those running systems. A vanilla Three.js GLTFLoader or a normal game model loader can consume the bytes without this addon.
|
package/starter/forest/sky.ts
DELETED
|
@@ -1,38 +0,0 @@
|
|
|
1
|
-
// The forest's daylight: the engine's sun, sky, fill, haze and tone curve, every value this world's.
|
|
2
|
-
// Edit any number here to change the look; nothing in a package decides it.
|
|
3
|
-
import { Daylight } from "@threenative/core";
|
|
4
|
-
import { ACESFilmicToneMapping, Color, type Object3D, Vector3 } from "three";
|
|
5
|
-
import { color, mix, normalize, positionLocal, smoothstep, vec3 } from "three/tsl";
|
|
6
|
-
import type { Node } from "three/webgpu";
|
|
7
|
-
import { SKY_REFLECTION_LAYER } from "./water.js";
|
|
8
|
-
|
|
9
|
-
export function forestDaylight(follow: Object3D): Daylight {
|
|
10
|
-
const daylight = new Daylight({
|
|
11
|
-
follow,
|
|
12
|
-
// Mid-morning sun from the south-east, high enough for short readable shadows under the firs.
|
|
13
|
-
sunDirection: new Vector3(0.55, 0.62, 0.56),
|
|
14
|
-
sunColor: new Color(0xfff1dc),
|
|
15
|
-
sunIntensity: 2.6,
|
|
16
|
-
shadowExtents: [24, 96, 320],
|
|
17
|
-
sky: { turbidity: 1.2, rayleigh: 2.4, mieCoefficient: 0.0015, mieDirectionalG: 0.78 },
|
|
18
|
-
fill: { sky: new Color(0xa8c8e8), ground: new Color(0x7a7e5c), intensity: 1.5 },
|
|
19
|
-
// Enough air that the 512 m world's far edge fades instead of ending on a hard line.
|
|
20
|
-
haze: { color: new Color(0x9fb4c2), density: 0.0012 },
|
|
21
|
-
exposure: 2 ** -0.38,
|
|
22
|
-
toneMapping: ACESFilmicToneMapping,
|
|
23
|
-
// The box's corners must stay inside the camera's far plane (5000 m in the kit's example scene).
|
|
24
|
-
skySize: 5000,
|
|
25
|
-
});
|
|
26
|
-
// Compress the bright lower dome without dimming the blue sky the lake reflects.
|
|
27
|
-
const elevation = normalize(positionLocal).y;
|
|
28
|
-
daylight.sky.material.colorNode = mix(
|
|
29
|
-
color(daylight.haze.color).mul(mix(2.4, 3.2, smoothstep(-0.6, 0, elevation))),
|
|
30
|
-
vec3(daylight.sky.material.colorNode as Node<"vec4">).mul(
|
|
31
|
-
mix(0.3, 1, smoothstep(-0.05, 0.45, elevation)),
|
|
32
|
-
),
|
|
33
|
-
smoothstep(-0.08, 0.08, elevation),
|
|
34
|
-
);
|
|
35
|
-
// The lake mirrors the sky: its mirror draws only the layer the sky sits on (see water.ts).
|
|
36
|
-
daylight.sky.layers.enable(SKY_REFLECTION_LAYER);
|
|
37
|
-
return daylight;
|
|
38
|
-
}
|
package/starter/forest/water.ts
DELETED
|
@@ -1,257 +0,0 @@
|
|
|
1
|
-
// The forest's lake and river, drawn from the water the bake wrote to `world/water.json`. The lake covers
|
|
2
|
-
// the ground that its level floods from the lake's centre, read from the same heightfield the physics
|
|
3
|
-
// stands on, so the water sits where the bake floods it. WaterSurface3D mirrors the sky in the lake and
|
|
4
|
-
// shows the bed through it, and the water thins to nothing where the ground rises through the level: that
|
|
5
|
-
// is the shore. A river follows the ground, so it is a ribbon the game shades itself. Colours, depths and
|
|
6
|
-
// the shore are this file's to change: the kit owns its look.
|
|
7
|
-
import type { ICtx } from "@threenative/core";
|
|
8
|
-
import { WaterSurface3D } from "@threenative/core";
|
|
9
|
-
import { type Heightfield, riverRibbonGeometry } from "@threenative/core/world";
|
|
10
|
-
import type { IPhysicsContext } from "@threenative/physics";
|
|
11
|
-
import {
|
|
12
|
-
BufferAttribute,
|
|
13
|
-
BufferGeometry,
|
|
14
|
-
Color,
|
|
15
|
-
DoubleSide,
|
|
16
|
-
type Material,
|
|
17
|
-
Mesh,
|
|
18
|
-
MeshStandardMaterial,
|
|
19
|
-
} from "three";
|
|
20
|
-
import {
|
|
21
|
-
attribute,
|
|
22
|
-
cameraPosition,
|
|
23
|
-
clamp,
|
|
24
|
-
dot,
|
|
25
|
-
float,
|
|
26
|
-
mix,
|
|
27
|
-
normalize,
|
|
28
|
-
positionWorld,
|
|
29
|
-
pow,
|
|
30
|
-
smoothstep,
|
|
31
|
-
vec3,
|
|
32
|
-
} from "three/tsl";
|
|
33
|
-
import { MeshBasicNodeMaterial } from "three/webgpu";
|
|
34
|
-
|
|
35
|
-
/** The generator's own water, written beside the world by `bake.mjs`. */
|
|
36
|
-
export interface IForestWaterFile {
|
|
37
|
-
readonly lakes: readonly ILake[];
|
|
38
|
-
readonly rivers: readonly IRiver[];
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
interface ILake {
|
|
42
|
-
readonly id: string;
|
|
43
|
-
readonly at: readonly [number, number];
|
|
44
|
-
readonly radius: number;
|
|
45
|
-
readonly level: number;
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
interface IRiver {
|
|
49
|
-
readonly id: string;
|
|
50
|
-
readonly width: number;
|
|
51
|
-
readonly points: readonly (readonly [number, number, number])[];
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
export interface IForestWater {
|
|
55
|
-
readonly lakes: number;
|
|
56
|
-
readonly rivers: number;
|
|
57
|
-
dispose(): void;
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
/** The layer the sky sits on, so the lake's mirror can show it (see `sky.ts`). */
|
|
61
|
-
export const SKY_REFLECTION_LAYER = 3;
|
|
62
|
-
/** The ribbon sits this far above its profile, clear of the carved bed. */
|
|
63
|
-
const RIVER_LIFT = 0.05;
|
|
64
|
-
/** Metres of water over the bed at which the lake is fully opaque; thinner water fades into the shore. */
|
|
65
|
-
const SHORE_DEPTH = 1.8;
|
|
66
|
-
/**
|
|
67
|
-
* The colour the mirrored sky takes at grazing angles, in linear light. The sky's horizon is near-neutral,
|
|
68
|
-
* so the tint carries the lake's teal; the mirror keeps the sky's gradient.
|
|
69
|
-
*/
|
|
70
|
-
const SHEEN = new Color(0x94b9bf);
|
|
71
|
-
/** Deep water's own colour; the bed shows through where the lake is shallow. */
|
|
72
|
-
const BODY = new Color(0x285b59);
|
|
73
|
-
const RIVER = new Color(0x2a4b4c);
|
|
74
|
-
/** Shallow water stays teal, gently darkening with the measured depth of the bed. */
|
|
75
|
-
const SHALLOW = new Color(0x3c746e);
|
|
76
|
-
|
|
77
|
-
/** The heightfield's sample grid in world metres: one node per column and row, the first at (x0, z0). */
|
|
78
|
-
function gridOf(field: Heightfield): { stepX: number; stepZ: number; x0: number; z0: number } {
|
|
79
|
-
return {
|
|
80
|
-
stepX: field.width / (field.columns - 1),
|
|
81
|
-
stepZ: field.depth / (field.rows - 1),
|
|
82
|
-
x0: field.origin.x - field.width / 2,
|
|
83
|
-
z0: field.origin.z - field.depth / 2,
|
|
84
|
-
};
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
/**
|
|
88
|
-
* The grid nodes the lake covers: the nodes below its level that a flood from its centre reaches inside
|
|
89
|
-
* its radius. This reproduces the generator's own flood on the heightfield the physics stands on.
|
|
90
|
-
*/
|
|
91
|
-
function floodedNodes(field: Heightfield, lake: ILake): Uint8Array {
|
|
92
|
-
const { columns, rows } = field;
|
|
93
|
-
const { stepX, stepZ, x0, z0 } = gridOf(field);
|
|
94
|
-
const [cx, cz] = lake.at;
|
|
95
|
-
const worldX = (node: number): number => x0 + (node % columns) * stepX;
|
|
96
|
-
const worldZ = (node: number): number => z0 + Math.floor(node / columns) * stepZ;
|
|
97
|
-
const below = (node: number): boolean => field.heightAt(worldX(node), worldZ(node)) < lake.level;
|
|
98
|
-
const within = (node: number): boolean =>
|
|
99
|
-
Math.hypot(worldX(node) - cx, worldZ(node) - cz) <= lake.radius;
|
|
100
|
-
const start = Math.round((cz - z0) / stepZ) * columns + Math.round((cx - x0) / stepX);
|
|
101
|
-
const flooded = new Uint8Array(columns * rows);
|
|
102
|
-
const seen = new Uint8Array(columns * rows);
|
|
103
|
-
const queue: number[] = [start];
|
|
104
|
-
seen[start] = 1;
|
|
105
|
-
for (let head = 0; head < queue.length; head += 1) {
|
|
106
|
-
const node = queue[head];
|
|
107
|
-
if (node === undefined || !below(node)) continue;
|
|
108
|
-
flooded[node] = 1;
|
|
109
|
-
const i = node % columns;
|
|
110
|
-
const j = Math.floor(node / columns);
|
|
111
|
-
const neighbours = [
|
|
112
|
-
i > 0 ? node - 1 : -1,
|
|
113
|
-
i < columns - 1 ? node + 1 : -1,
|
|
114
|
-
j > 0 ? node - columns : -1,
|
|
115
|
-
j < rows - 1 ? node + columns : -1,
|
|
116
|
-
];
|
|
117
|
-
for (const next of neighbours) {
|
|
118
|
-
if (next < 0 || seen[next] === 1 || !within(next)) continue;
|
|
119
|
-
seen[next] = 1;
|
|
120
|
-
queue.push(next);
|
|
121
|
-
}
|
|
122
|
-
}
|
|
123
|
-
return flooded;
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
/**
|
|
127
|
-
* The lake's surface: a level sheet over every grid cell that touches a flooded node. The sheet runs a
|
|
128
|
-
* cell past the flood, so the shore is where `lakeMaterial` thins the water, not the sheet's edge.
|
|
129
|
-
*/
|
|
130
|
-
function lakeGeometry(field: Heightfield, lake: ILake, flooded: Uint8Array): BufferGeometry {
|
|
131
|
-
const { columns, rows } = field;
|
|
132
|
-
const { stepX, stepZ, x0, z0 } = gridOf(field);
|
|
133
|
-
const positions: number[] = [];
|
|
134
|
-
const indices: number[] = [];
|
|
135
|
-
const depths: number[] = [];
|
|
136
|
-
const vertexOf = new Map<number, number>();
|
|
137
|
-
const vertex = (node: number): number => {
|
|
138
|
-
const known = vertexOf.get(node);
|
|
139
|
-
if (known !== undefined) return known;
|
|
140
|
-
const index = positions.length / 3;
|
|
141
|
-
const x = x0 + (node % columns) * stepX;
|
|
142
|
-
const z = z0 + Math.floor(node / columns) * stepZ;
|
|
143
|
-
positions.push(x, lake.level, z);
|
|
144
|
-
depths.push(lake.level - field.heightAt(x, z));
|
|
145
|
-
vertexOf.set(node, index);
|
|
146
|
-
return index;
|
|
147
|
-
};
|
|
148
|
-
for (let j = 0; j < rows - 1; j += 1)
|
|
149
|
-
for (let i = 0; i < columns - 1; i += 1) {
|
|
150
|
-
const a = j * columns + i;
|
|
151
|
-
const b = a + 1;
|
|
152
|
-
const c = a + columns;
|
|
153
|
-
const d = c + 1;
|
|
154
|
-
if (!(flooded[a] || flooded[b] || flooded[c] || flooded[d])) continue;
|
|
155
|
-
const va = vertex(a);
|
|
156
|
-
const vb = vertex(b);
|
|
157
|
-
const vc = vertex(c);
|
|
158
|
-
const vd = vertex(d);
|
|
159
|
-
indices.push(va, vc, vb, vb, vc, vd);
|
|
160
|
-
}
|
|
161
|
-
const geometry = new BufferGeometry();
|
|
162
|
-
geometry.setAttribute("position", new BufferAttribute(new Float32Array(positions), 3));
|
|
163
|
-
geometry.setAttribute("waterDepth", new BufferAttribute(new Float32Array(depths), 1));
|
|
164
|
-
geometry.setIndex(indices);
|
|
165
|
-
return geometry;
|
|
166
|
-
}
|
|
167
|
-
|
|
168
|
-
/**
|
|
169
|
-
* The lake's surface: the sky mirrored in it at grazing angles, the bed seen through it where it is
|
|
170
|
-
* shallow, and the body's own colour where it is deep. Capped Schlick at water's 1.333 index keeps
|
|
171
|
-
* the far bank's reflection subdued. Where the water is thinner than SHORE_DEPTH it fades
|
|
172
|
-
* to nothing, because the ground has risen through the level there.
|
|
173
|
-
*/
|
|
174
|
-
function lakeMaterial(surface: WaterSurface3D): MeshBasicNodeMaterial {
|
|
175
|
-
const view = normalize(cameraPosition.sub(positionWorld));
|
|
176
|
-
const facing = clamp(dot(vec3(0, 1, 0), view), float(0), float(1));
|
|
177
|
-
const fresnel = float(0.02).add(pow(float(1).sub(facing), 5).mul(0.98));
|
|
178
|
-
const thickness = surface.thicknessAt();
|
|
179
|
-
// Bed depth shades the shore consistently; screen depth still preserves the bed and its shadows.
|
|
180
|
-
const bedDepth = attribute<"float">("waterDepth", "float");
|
|
181
|
-
const body = mix(
|
|
182
|
-
vec3(SHALLOW.r, SHALLOW.g, SHALLOW.b),
|
|
183
|
-
vec3(BODY.r, BODY.g, BODY.b),
|
|
184
|
-
smoothstep(float(0), float(3), bedDepth),
|
|
185
|
-
);
|
|
186
|
-
const submerged = mix(surface.refractionAt(), body, smoothstep(float(0.4), float(3), thickness));
|
|
187
|
-
const material = new MeshBasicNodeMaterial({ transparent: true, side: DoubleSide });
|
|
188
|
-
// The HDR mirror is compressed, then tinted: its horizon is neutral, the water should not be.
|
|
189
|
-
const mirror = surface.reflectionAt();
|
|
190
|
-
const compressed = mirror.div(mirror.add(vec3(1, 1, 1)));
|
|
191
|
-
// A small sky floor reveals the mirror; the cap keeps grazing water from becoming an ice sheet.
|
|
192
|
-
const reflection = clamp(float(0.16).add(fresnel.mul(0.3)), float(0), float(0.46));
|
|
193
|
-
const open = mix(submerged, compressed.mul(vec3(SHEEN.r, SHEEN.g, SHEEN.b)), reflection);
|
|
194
|
-
// Cap linear radiance before the scene tone curve, including the glancing shoreline.
|
|
195
|
-
material.colorNode = clamp(open, vec3(0, 0, 0), vec3(0.22, 0.22, 0.22));
|
|
196
|
-
material.opacityNode = smoothstep(float(0), float(SHORE_DEPTH), bedDepth).mul(
|
|
197
|
-
smoothstep(float(0), float(0.3), thickness),
|
|
198
|
-
);
|
|
199
|
-
return material;
|
|
200
|
-
}
|
|
201
|
-
|
|
202
|
-
/**
|
|
203
|
-
* Adds the lake and river the bake wrote. `field` is the ground the props and the colliders stand on.
|
|
204
|
-
* The caller owns the returned handle: its `dispose` removes both meshes and releases each surface.
|
|
205
|
-
*/
|
|
206
|
-
export function addForestWater(
|
|
207
|
-
ctx: ICtx<Record<string, unknown>, IPhysicsContext>,
|
|
208
|
-
water: IForestWaterFile,
|
|
209
|
-
field: Heightfield,
|
|
210
|
-
): IForestWater {
|
|
211
|
-
const surfaces: WaterSurface3D[] = [];
|
|
212
|
-
const meshes: Mesh[] = [];
|
|
213
|
-
for (const lake of water.lakes) {
|
|
214
|
-
const surface = new WaterSurface3D({
|
|
215
|
-
level: lake.level,
|
|
216
|
-
maxThickness: 4,
|
|
217
|
-
// The mirror holds only the sky, which barely changes: redrawing it every fourth frame keeps the
|
|
218
|
-
// water's look and takes the second world draw off most frames (the lake's cost in the ground view).
|
|
219
|
-
reflection: { resolutionScale: 0.5, layers: 1 << SKY_REFLECTION_LAYER, refreshInterval: 4 },
|
|
220
|
-
});
|
|
221
|
-
surfaces.push(surface);
|
|
222
|
-
meshes.push(
|
|
223
|
-
new Mesh(lakeGeometry(field, lake, floodedNodes(field, lake)), lakeMaterial(surface)),
|
|
224
|
-
);
|
|
225
|
-
}
|
|
226
|
-
for (const river of water.rivers) {
|
|
227
|
-
const material = new MeshStandardMaterial({
|
|
228
|
-
color: RIVER,
|
|
229
|
-
roughness: 0.18,
|
|
230
|
-
metalness: 0,
|
|
231
|
-
transparent: true,
|
|
232
|
-
opacity: 0.9,
|
|
233
|
-
side: DoubleSide,
|
|
234
|
-
});
|
|
235
|
-
// One channel width across, out a half width past each end where the bed is carved; dry
|
|
236
|
-
// quads drop, so the water ends at the bank (core `riverRibbonGeometry`).
|
|
237
|
-
const mesh = new Mesh(
|
|
238
|
-
riverRibbonGeometry([river], field, { reach: 0.5, columns: 3 }),
|
|
239
|
-
material,
|
|
240
|
-
);
|
|
241
|
-
mesh.position.y = RIVER_LIFT;
|
|
242
|
-
meshes.push(mesh);
|
|
243
|
-
}
|
|
244
|
-
for (const mesh of meshes) ctx.add(mesh);
|
|
245
|
-
return {
|
|
246
|
-
lakes: water.lakes.length,
|
|
247
|
-
rivers: water.rivers.length,
|
|
248
|
-
dispose() {
|
|
249
|
-
for (const mesh of meshes) {
|
|
250
|
-
mesh.removeFromParent();
|
|
251
|
-
mesh.geometry.dispose();
|
|
252
|
-
(mesh.material as Material).dispose();
|
|
253
|
-
}
|
|
254
|
-
for (const surface of surfaces) surface.dispose();
|
|
255
|
-
},
|
|
256
|
-
};
|
|
257
|
-
}
|