Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(terrain): the ground is a CDLOD quadtree of one instanced patch read from height pages, and can go on for ever

yhhf71a54f0c04a
diff --git a/desktop b/desktop
index f277d7fae..1e20c7209 160000
--- a/desktop
+++ b/desktop
@@ -1 +1 @@
-Subproject commit f277d7fae58a82ea1b58e1bcdc7ed10e528aa06a
+Subproject commit 1e20c7209baffab9095825b73865cdea7658777c
diff --git a/docs/astro/src/data/components.generated.json b/docs/astro/src/data/components.generated.json
index 42ddc7466..a18728ec8 100644
--- a/docs/astro/src/data/components.generated.json
+++ b/docs/astro/src/data/components.generated.json
@@ -5235,6 +5235,16 @@
"name": "Terrain",
"source": "ts",
"fields": [
+ {
+ "key": "extent",
+ "type": "enum",
+ "default": "Area",
+ "doc": "An area of its own size, from a heightmap or noise; or ground that goes on for ever, from noise read anywhere (the same seed is the same ground).",
+ "values": [
+ "Area",
+ "Infinite"
+ ]
+ },
{
"key": "heightmap",
"type": "Asset<texture>",
@@ -5257,14 +5267,14 @@
"key": "sizeX",
"type": "number",
"default": "1000",
- "doc": "World size along x.",
+ "doc": "An area's size along x; for ground without end, the span its hills are spread over.",
"range": "≥ 1"
},
{
"key": "sizeZ",
"type": "number",
"default": "1000",
- "doc": "World size along z.",
+ "doc": "An area's size along z.",
"range": "≥ 1"
},
{
@@ -5275,32 +5285,25 @@
"range": "≥ 0"
},
{
- "key": "chunks",
- "type": "number",
- "default": "8",
- "doc": "Chunks along each side; each is drawn and culled on its own.",
- "range": "1–64, step 1"
- },
- {
- "key": "chunkCells",
+ "key": "cellSize",
"type": "number",
- "default": "32",
- "doc": "Cells along a chunk side at its finest level. A power of two keeps the levels clean.",
- "range": "2–128, step 1"
+ "default": "2",
+ "doc": "The finest cell of the ground's mesh, in world units: what it is drawn at near the eye. Further off the cells double, level by level.",
+ "range": "≥ 0.01"
},
{
- "key": "lodLevels",
+ "key": "detail",
"type": "number",
- "default": "4",
- "doc": "Levels of detail per chunk, each half as fine as the one before.",
- "range": "1–4, step 1"
+ "default": "1",
+ "doc": "Above 1 the finest cells reach further out before the ground coarsens.",
+ "range": "0.25–8, step 0.05"
},
{
- "key": "detail",
+ "key": "drawDistance",
"type": "number",
- "default": "1",
- "doc": "Above 1 the finer levels are kept out to a greater distance.",
- "range": "0.1–8, step 0.1"
+ "default": "4000",
+ "doc": "How far ground without end is drawn.",
+ "range": "≥ 1"
},
{
"key": "seed",
@@ -5313,7 +5316,7 @@
"key": "frequency",
"type": "number",
"default": "3",
- "doc": "How many hills across the terrain.",
+ "doc": "How many hills across the terrain (or across sizeX, for ground without end).",
"range": "0.1–32, step 0.1"
},
{
@@ -5341,7 +5344,7 @@
"key": "resolution",
"type": "number",
"default": "257",
- "doc": "Samples along each side of the noise ground.",
+ "doc": "Samples along each side of an area's noise ground.",
"range": "17–2049, step 1"
},
{
@@ -5355,7 +5358,7 @@
"key": "erosion",
"type": "number",
"default": "0",
- "doc": "How much rain wears the ground (a heightmap's too): gullies down the slopes, silt in the valleys, and dirt painted where the water ran. 0 leaves it as made.",
+ "doc": "How much rain wears the ground: an area (a heightmap's too) drop by drop, with dirt where the water ran; ground without end by its noise. 0 leaves it as made.",
"range": "0–4, step 0.05"
},
{
@@ -5401,16 +5404,16 @@
}
],
"animatable": [
+ "extent",
"heightmap",
"splatmap",
"material",
"sizeX",
"sizeZ",
"height",
- "chunks",
- "chunkCells",
- "lodLevels",
+ "cellSize",
"detail",
+ "drawDistance",
"seed",
"frequency",
"octaves",
diff --git a/examples/terrain-water/assets/scenes/main.esscene b/examples/terrain-water/assets/scenes/main.esscene
index 5f50426ea..c6f6d42e0 100644
--- a/examples/terrain-water/assets/scenes/main.esscene
+++ b/examples/terrain-water/assets/scenes/main.esscene
@@ -259,10 +259,8 @@
"sizeX": 28000,
"sizeZ": 28000,
"height": 7400,
- "chunks": 16,
- "chunkCells": 32,
- "lodLevels": 4,
- "detail": 1.5,
+ "cellSize": 30,
+ "detail": 1,
"heightmap": "assets/textures/height.png",
"splatmap": "assets/textures/splat.png",
"material": "assets/materials/ground.esmaterial"
diff --git a/examples/terrain-water/tools/build.mjs b/examples/terrain-water/tools/build.mjs
index 2b839d0f3..b2c5c414a 100644
--- a/examples/terrain-water/tools/build.mjs
+++ b/examples/terrain-water/tools/build.mjs
@@ -494,7 +494,7 @@ function scene() {
add('Ground', [
{ type: 'Transform', data: { position: { x: 0, y: WORLD.base, z: 0 } } },
{ type: 'Terrain', data: {
- sizeX: WORLD.size, sizeZ: WORLD.size, height: WORLD.height, chunks: 16, chunkCells: 32, lodLevels: 4, detail: 1.5,
+ sizeX: WORLD.size, sizeZ: WORLD.size, height: WORLD.height, cellSize: 30, detail: 1,
heightmap: 'assets/textures/height.png', splatmap: 'assets/textures/splat.png', material: 'assets/materials/ground.esmaterial' } },
]);
// The water: one zone over the whole island, which the sea, the lake and the two rivers are baked into and drawn from as one surface.
diff --git a/examples/wilds/assets/materials/grass.esmaterial.meta b/examples/wilds/assets/materials/grass.esmaterial.meta
index 2c2f3781a..5eb9a89e8 100644
--- a/examples/wilds/assets/materials/grass.esmaterial.meta
+++ b/examples/wilds/assets/materials/grass.esmaterial.meta
@@ -1,5 +1,5 @@
{
- "uuid": "94c98077-fb90-4230-a04c-61079e70a7b8",
+ "uuid": "13f81be0-41d8-48be-bc25-96c724ec296d",
"version": "2.0",
"type": "material",
"importer": {}
diff --git a/examples/wilds/assets/materials/pine.esmaterial.meta b/examples/wilds/assets/materials/pine.esmaterial.meta
index 364f97016..c0707c644 100644
--- a/examples/wilds/assets/materials/pine.esmaterial.meta
+++ b/examples/wilds/assets/materials/pine.esmaterial.meta
@@ -1,5 +1,5 @@
{
- "uuid": "7e05d689-8bbf-4a57-98f1-96ba95af9262",
+ "uuid": "5733b915-de02-400f-88fc-524c7be7aba0",
"version": "2.0",
"type": "material",
"importer": {}
diff --git a/examples/wilds/assets/materials/terrain.esmaterial.meta b/examples/wilds/assets/materials/terrain.esmaterial.meta
index b9db28f89..02c37ee31 100644
--- a/examples/wilds/assets/materials/terrain.esmaterial.meta
+++ b/examples/wilds/assets/materials/terrain.esmaterial.meta
@@ -1,5 +1,5 @@
{
- "uuid": "ef7d6778-5201-4d27-8a0a-7546b4da2db3",
+ "uuid": "783121c4-a61a-4921-a800-08fc8a4d473a",
"version": "2.0",
"type": "material",
"importer": {}
diff --git a/examples/wilds/assets/materials/water.esmaterial.meta b/examples/wilds/assets/materials/water.esmaterial.meta
index 3acbf303c..4e33ea7a9 100644
--- a/examples/wilds/assets/materials/water.esmaterial.meta
+++ b/examples/wilds/assets/materials/water.esmaterial.meta
@@ -1,5 +1,5 @@
{
- "uuid": "03a1d0c2-e619-482e-8248-cd2293c578f2",
+ "uuid": "dcdc38bb-9613-4088-a727-47a0eb53e5f1",
"version": "2.0",
"type": "material",
"importer": {}
diff --git a/examples/wilds/assets/models/pine.esmesh.meta b/examples/wilds/assets/models/pine.esmesh.meta
index 1b37e3017..f7194ee9b 100644
--- a/examples/wilds/assets/models/pine.esmesh.meta
+++ b/examples/wilds/assets/models/pine.esmesh.meta
@@ -1,5 +1,5 @@
{
- "uuid": "e5fc7807-fe1c-48d4-b985-331319c686d0",
+ "uuid": "a223e2ba-d1ae-4f05-ba4d-e50cf35b47eb",
"version": "2.0",
"type": "mesh",
"importer": {}
diff --git a/examples/wilds/assets/scenes/main.esscene b/examples/wilds/assets/scenes/main.esscene
index 123958331..ed046dd85 100644
--- a/examples/wilds/assets/scenes/main.esscene
+++ b/examples/wilds/assets/scenes/main.esscene
@@ -251,9 +251,7 @@
"sizeX": 3200,
"sizeZ": 3200,
"height": 560,
- "chunks": 16,
- "chunkCells": 32,
- "lodLevels": 4,
+ "cellSize": 4,
"detail": 1.4,
"heightmap": "assets/textures/height.png",
"rockSlope": 0.34,
diff --git a/examples/wilds/assets/scenes/main.esscene.meta b/examples/wilds/assets/scenes/main.esscene.meta
index d8750fbfe..96ca7295c 100644
--- a/examples/wilds/assets/scenes/main.esscene.meta
+++ b/examples/wilds/assets/scenes/main.esscene.meta
@@ -1,5 +1,5 @@
{
- "uuid": "8ba85cd5-448f-4412-b9f7-501b1daafc28",
+ "uuid": "e9e09271-5946-4625-9a1e-66ddb1bcd7b1",
"version": "2.0",
"type": "scene",
"importer": {}
diff --git a/examples/wilds/assets/textures/dirt.png.meta b/examples/wilds/assets/textures/dirt.png.meta
index e8fd08b12..a1b0fc474 100644
--- a/examples/wilds/assets/textures/dirt.png.meta
+++ b/examples/wilds/assets/textures/dirt.png.meta
@@ -1,5 +1,5 @@
{
- "uuid": "4cb2207f-9288-461c-9ccb-307e0d4097cd",
+ "uuid": "35fc90ae-06b9-4732-87a0-54a1dab01d93",
"version": "2.0",
"type": "texture",
"importer": {
diff --git a/examples/wilds/assets/textures/grass.png.meta b/examples/wilds/assets/textures/grass.png.meta
index d779be4eb..3cc548d60 100644
--- a/examples/wilds/assets/textures/grass.png.meta
+++ b/examples/wilds/assets/textures/grass.png.meta
@@ -1,5 +1,5 @@
{
- "uuid": "6fd01e31-d9ff-4083-901f-182ee813faa3",
+ "uuid": "84f9a3a9-95c2-47da-9a9f-85c71f5bcf1b",
"version": "2.0",
"type": "texture",
"importer": {
diff --git a/examples/wilds/assets/textures/height.png.meta b/examples/wilds/assets/textures/height.png.meta
index 76d5086a3..e438f7f5a 100644
--- a/examples/wilds/assets/textures/height.png.meta
+++ b/examples/wilds/assets/textures/height.png.meta
@@ -1,5 +1,5 @@
{
- "uuid": "dbf3429e-8a64-40e3-b75d-6a58dcd4b695",
+ "uuid": "47ef3399-eb02-4c27-9a86-f01f51dbf890",
"version": "2.0",
"type": "texture",
"importer": {}
diff --git a/examples/wilds/assets/textures/pine.png.meta b/examples/wilds/assets/textures/pine.png.meta
index bd0371e2c..a9014ae4f 100644
--- a/examples/wilds/assets/textures/pine.png.meta
+++ b/examples/wilds/assets/textures/pine.png.meta
@@ -1,5 +1,5 @@
{
- "uuid": "dd06005d-e872-45b9-bca8-e3f6af3ee1b9",
+ "uuid": "2b7f0aa9-e978-44a9-bbc4-a60b771fcb3f",
"version": "2.0",
"type": "texture",
"importer": {}
diff --git a/examples/wilds/assets/textures/rock.png.meta b/examples/wilds/assets/textures/rock.png.meta
index bc0e63d49..2a97fbc61 100644
--- a/examples/wilds/assets/textures/rock.png.meta
+++ b/examples/wilds/assets/textures/rock.png.meta
@@ -1,5 +1,5 @@
{
- "uuid": "e304edee-2b9f-47f0-86a3-604b9315891e",
+ "uuid": "4716058b-e26e-4151-8ac4-a222ee061435",
"version": "2.0",
"type": "texture",
"importer": {
diff --git a/examples/wilds/assets/textures/snow.png.meta b/examples/wilds/assets/textures/snow.png.meta
index f3d51fb23..ab4bf9d2f 100644
--- a/examples/wilds/assets/textures/snow.png.meta
+++ b/examples/wilds/assets/textures/snow.png.meta
@@ -1,5 +1,5 @@
{
- "uuid": "d7b144bf-06ad-41d2-997f-a45bea7ece63",
+ "uuid": "9b5d7702-7c02-41de-a5ce-512ae091e50c",
"version": "2.0",
"type": "texture",
"importer": {
diff --git a/examples/wilds/tools/build.mjs b/examples/wilds/tools/build.mjs
index 845997b9e..61af6c6e3 100644
--- a/examples/wilds/tools/build.mjs
+++ b/examples/wilds/tools/build.mjs
@@ -349,7 +349,7 @@ function scene() {
entity(4, 'Terrain', [
{ type: 'Transform', data: {} },
{ type: 'Terrain', data: {
- sizeX: WORLD.size, sizeZ: WORLD.size, height: WORLD.height, chunks: 16, chunkCells: 32, lodLevels: 4, detail: 1.4,
+ sizeX: WORLD.size, sizeZ: WORLD.size, height: WORLD.height, cellSize: 4, detail: 1.4,
heightmap: 'assets/textures/height.png', rockSlope: 0.34, dirtHeight: 0.5, snowHeight: 0.84, material: 'assets/materials/terrain.esmaterial' } },
]),
entity(5, 'Lake', [
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 106b123d9..a0c0f293b 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 115 public · 159 beta · 1756 experimental · 3 deprecated
+Symbols: 115 public · 159 beta · 1772 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -3930,6 +3930,20 @@ shore: number
swell: number
```
+## FieldSource — class @experimental
+```
+bounds: readonly [number, number, number, number]
+field: Heightfield
+height: (x: number, z: number) => number | null
+infinite: false
+maxHeight: number
+minHeight: 0
+normal: (x: number, z: number) => [number, number, number] | null
+paint: (x: number, z: number, h: number, ny: number) => [number, number, number, number]
+static new (field: Heightfield, data: Pick<TerrainData, "sizeX" | "sizeZ" | "height" | "rockSlope" | "dirtHeight" | "snowHeight">, splat: Splat | null, flow: Float32Array | null): FieldSource
+static prototype: FieldSource
+```
+
## FillMethod — enum @beta
```
Horizontal = 0
@@ -5775,6 +5789,26 @@ output: GraphType | null
params: NodeParamSpec[]
```
+## NoiseParams — type @experimental
+```
+Pick<TerrainData, 'seed' | 'frequency' | 'octaves' | 'persistence' | 'ridged' | 'warp' | 'erosion' | 'sizeX' | 'height'
+ | 'rockSlope' | 'dirtHeight' | 'snowHeight'>
+```
+
+## NoiseSource — class @experimental
+```
+bounds: null
+height: (x: number, z: number) => number
+infinite: true
+maxHeight: number
+minHeight: 0
+normal: (x: number, z: number) => [number, number, number]
+paint: (_x: number, _z: number, h: number, ny: number) => [number, number, number, number]
+sample: (x: number, z: number) => [number, number, number]
+static new (p: NoiseParams): NoiseSource
+static prototype: NoiseSource
+```
+
## Not — function @experimental
```
(filter: FilterExpr): FilterExpr
@@ -5813,6 +5847,21 @@ width: number | undefined
'none' | 'aces' | 'neutral'
```
+## PAGE_SIDE — const @experimental
+```
+number
+```
+
+## PAGE_TEXELS — const @experimental
+```
+number
+```
+
+## PATCH_CELLS — const @experimental
+```
+32
+```
+
## PREFAB_FORMAT_VERSION — const @experimental
```
"2"
@@ -5876,6 +5925,38 @@ worlds: { scene: string; manifest: string; }[] | undefined
ySortLayers: number | undefined
```
+## Page — interface @experimental
+```
+max: number
+min: number
+slot: number
+used: number
+```
+
+## PageImage — interface @experimental
+```
+heights: Uint8Array<ArrayBufferLike>
+max: number
+min: number
+paint: Uint8Array<ArrayBufferLike>
+```
+
+## PageTable — class @experimental
+```
+atlasSize: number
+capacity: number
+claim: (key: string, min: number, max: number) => Page | null
+clear: () => void
+get: (key: string) => Page | undefined
+origin: (slot: number) => [number, number]
+perRow: number
+size: number
+tick: () => void
+touch: (key: string) => void
+static new (atlasSize: number): PageTable
+static prototype: PageTable
+```
+
## Parent — const @public
```
BuiltinComponentDef<ParentData>
@@ -7113,6 +7194,16 @@ fields: readonly PtrFieldDesc[]
ptrFn: string
```
+## QuadtreeParams — interface @experimental
+```
+bounds: readonly [number, number, number, number] | null
+leafSize: number
+levels: number
+maxHeight: number
+minHeight: number
+range0: number
+```
+
## Quality — const @experimental
```
ResourceDef<QualityController | null>
@@ -8861,6 +8952,13 @@ type: "spine"
'2.1' | '3.8' | '4.1' | '4.2' | '4.3'
```
+## Splat — interface @experimental
+```
+height: number
+pixels: Uint8Array<ArrayBufferLike>
+width: number
+```
+
## Spline — const @experimental
```
ComponentDef<SplineData>
@@ -9578,11 +9676,12 @@ ComponentDef<TerrainData>
## TerrainData — interface @experimental
```
-chunkCells: number
-chunks: number
+cellSize: number
detail: number
dirtHeight: number
+drawDistance: number
erosion: number
+extent: number
frequency: number
height: number
heightmap: number
@@ -9590,7 +9689,6 @@ layerColor0: Color
layerColor1: Color
layerColor2: Color
layerColor3: Color
-lodLevels: number
material: number
octaves: number
persistence: number
@@ -9605,11 +9703,19 @@ splatmap: number
warp: number
```
-## TerrainPaint — type @experimental
+## TerrainExtent — const @experimental
```
-(
- u: number, v: number, height01: number, slope: number,
-) => [number, number, number, number]
+{ readonly Area: 0; readonly Infinite: 1; }
+```
+
+## TerrainNode — interface @experimental
+```
+ix: number
+iz: number
+level: number
+size: number
+x0: number
+z0: number
```
## TerrainPlugin — class @experimental
@@ -9621,13 +9727,14 @@ static new (): TerrainPlugin
static prototype: TerrainPlugin
```
-## TerrainShape — interface @experimental
+## TerrainSource — interface @experimental
```
-chunkCells: number
-chunks: number
-height: number
-sizeX: number
-sizeZ: number
+bounds: readonly [number, number, number, number] | null
+height: (x: number, z: number) => number | null
+infinite: boolean
+maxHeight: number
+minHeight: number
+paint: (x: number, z: number, h: number, ny: number) => [number, number, number, number]
```
## Terrains — class @experimental
@@ -12122,6 +12229,11 @@ MotionDriver<AnimatorBlend2DMotion>
(from: number, to: number, progress: number): WeatherState
```
+## boxDistance — function @experimental
+```
+(x0: number, z0: number, size: number, y0: number, y1: number, ex: number, ey: number, ez: number): number
+```
+
## bucketOverridesByEntity — function @experimental
```
(overrides: readonly PrefabOverride[]): Map<PrefabEntityId, PrefabOverride[]>
@@ -12132,11 +12244,6 @@ MotionDriver<AnimatorBlend2DMotion>
(plants: readonly Plant[], width: number, height: number, rect: CardRect, paint?: BladeParams["paint"], triangle?: boolean): MeshData
```
-## buildChunkMesh — function @experimental
-```
-(field: Heightfield, shape: TerrainShape, cx: number, cz: number, lod: number, paint: TerrainPaint): MeshData
-```
-
## buildFrameProfile — function @experimental
```
(input: FrameProfileInput): FrameProfile
@@ -12157,6 +12264,11 @@ MotionDriver<AnimatorBlend2DMotion>
(cells: number, rings: number, cellSize: number): MeshData
```
+## buildPatchMesh — function @experimental
+```
+(cells: number): MeshData
+```
+
## buildText — function @experimental
```
(init?: TextInit): TextData
@@ -12267,21 +12379,11 @@ MotionDriver<AnimatorBlend2DMotion>
(cellX: number, cellZ: number, cellSize: number): { minX: number; minZ: number; maxX: number; maxZ: number; }
```
-## cellsAtLod — function @experimental
-```
-(shape: TerrainShape, lod: number): number
-```
-
## censusProbeIds — function @experimental
```
(): string[]
```
-## chunkCenter — function @experimental
-```
-(shape: TerrainShape, cx: number, cz: number): [number, number]
-```
-
## clearAnimatorControllerStore — function @experimental
```
(): void
@@ -13567,6 +13669,11 @@ InputRouter
(def: AnimatorScope, path: string): AnimatorState | null
```
+## levelRange — function @experimental
+```
+(p: Pick<QuadtreeParams, "range0">, level: number): number
+```
+
## lifecyclePlugin — const @experimental
```
LifecyclePlugin
@@ -13632,11 +13739,6 @@ LifecyclePlugin
LocalizationPlugin
```
-## lodCount — function @experimental
-```
-(shape: TerrainShape, wanted?: number): number
-```
-
## log — const @experimental
```
Logger
@@ -13647,6 +13749,11 @@ Logger
(value: unknown): value is string
```
+## makePage — function @experimental
+```
+(source: TerrainSource, x0: number, z0: number, size: number): PageImage
+```
+
## makeWidgetInteractable — function @experimental
```
(world: World, entity: Entity, init?: WidgetInteractionInit): void
@@ -13757,6 +13864,16 @@ MeshRendererPlugin
() => InputState
```
+## nodeKey — function @experimental
+```
+(level: number, ix: number, iz: number): string
+```
+
+## noised — function @experimental
+```
+(x: number, y: number, seed: number): [number, number, number]
+```
+
## normalizeBundleMode — function @experimental
```
(mode: string | undefined | null): BundleMode
@@ -13832,6 +13949,11 @@ MeshRendererPlugin
(param: ShaderParam): unknown
```
+## parentOf — function @experimental
+```
+(n: TerrainNode, leafSize: number): TerrainNode
+```
+
## parseActionArg — function @experimental
```
(arg: string | undefined, params: readonly AiParamDef[], separator?: string): Record<string, AiParamValue>
@@ -14572,6 +14694,11 @@ Plugin
(blend: AnimatorBlend1DMotion, value: number): AnimatorBlendStop | null
```
+## selectNodes — function @experimental
+```
+(p: QuadtreeParams, ex: number, ey: number, ez: number): TerrainNode[]
+```
+
## selectPluralForm — function @experimental
```
(forms: PluralForms, count: number, selector: PluralSelector): string
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 75731a905..bc46deac5 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.native
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 115 public · 164 beta · 1775 experimental · 3 deprecated
+Symbols: 115 public · 164 beta · 1791 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -3938,6 +3938,20 @@ shore: number
swell: number
```
+## FieldSource — class @experimental
+```
+bounds: readonly [number, number, number, number]
+field: Heightfield
+height: (x: number, z: number) => number | null
+infinite: false
+maxHeight: number
+minHeight: 0
+normal: (x: number, z: number) => [number, number, number] | null
+paint: (x: number, z: number, h: number, ny: number) => [number, number, number, number]
+static new (field: Heightfield, data: Pick<TerrainData, "sizeX" | "sizeZ" | "height" | "rockSlope" | "dirtHeight" | "snowHeight">, splat: Splat | null, flow: Float32Array | null): FieldSource
+static prototype: FieldSource
+```
+
## FillMethod — enum @beta
```
Horizontal = 0
@@ -5973,6 +5987,26 @@ output: GraphType | null
params: NodeParamSpec[]
```
+## NoiseParams — type @experimental
+```
+Pick<TerrainData, 'seed' | 'frequency' | 'octaves' | 'persistence' | 'ridged' | 'warp' | 'erosion' | 'sizeX' | 'height'
+ | 'rockSlope' | 'dirtHeight' | 'snowHeight'>
+```
+
+## NoiseSource — class @experimental
+```
+bounds: null
+height: (x: number, z: number) => number
+infinite: true
+maxHeight: number
+minHeight: 0
+normal: (x: number, z: number) => [number, number, number]
+paint: (_x: number, _z: number, h: number, ny: number) => [number, number, number, number]
+sample: (x: number, z: number) => [number, number, number]
+static new (p: NoiseParams): NoiseSource
+static prototype: NoiseSource
+```
+
## Not — function @experimental
```
(filter: FilterExpr): FilterExpr
@@ -6011,6 +6045,21 @@ width: number | undefined
'none' | 'aces' | 'neutral'
```
+## PAGE_SIDE — const @experimental
+```
+number
+```
+
+## PAGE_TEXELS — const @experimental
+```
+number
+```
+
+## PATCH_CELLS — const @experimental
+```
+32
+```
+
## PLATFORM_BINDINGS — const @experimental
```
{ readonly readAsset: "es_readAsset"; readonly loadImagePixels: "es_loadImagePixels"; readonly utf8Decode: "es_utf8Decode"; }
@@ -6079,6 +6128,38 @@ worlds: { scene: string; manifest: string; }[] | undefined
ySortLayers: number | undefined
```
+## Page — interface @experimental
+```
+max: number
+min: number
+slot: number
+used: number
+```
+
+## PageImage — interface @experimental
+```
+heights: Uint8Array<ArrayBufferLike>
+max: number
+min: number
+paint: Uint8Array<ArrayBufferLike>
+```
+
+## PageTable — class @experimental
+```
+atlasSize: number
+capacity: number
+claim: (key: string, min: number, max: number) => Page | null
+clear: () => void
+get: (key: string) => Page | undefined
+origin: (slot: number) => [number, number]
+perRow: number
+size: number
+tick: () => void
+touch: (key: string) => void
+static new (atlasSize: number): PageTable
+static prototype: PageTable
+```
+
## Parent — const @public
```
BuiltinComponentDef<ParentData>
@@ -7316,6 +7397,16 @@ fields: readonly PtrFieldDesc[]
ptrFn: string
```
+## QuadtreeParams — interface @experimental
+```
+bounds: readonly [number, number, number, number] | null
+leafSize: number
+levels: number
+maxHeight: number
+minHeight: number
+range0: number
+```
+
## Quality — const @experimental
```
ResourceDef<QualityController | null>
@@ -9074,6 +9165,13 @@ type: "spine"
'2.1' | '3.8' | '4.1' | '4.2' | '4.3'
```
+## Splat — interface @experimental
+```
+height: number
+pixels: Uint8Array<ArrayBufferLike>
+width: number
+```
+
## Spline — const @experimental
```
ComponentDef<SplineData>
@@ -9791,11 +9889,12 @@ ComponentDef<TerrainData>
## TerrainData — interface @experimental
```
-chunkCells: number
-chunks: number
+cellSize: number
detail: number
dirtHeight: number
+drawDistance: number
erosion: number
+extent: number
frequency: number
height: number
heightmap: number
@@ -9803,7 +9902,6 @@ layerColor0: Color
layerColor1: Color
layerColor2: Color
layerColor3: Color
-lodLevels: number
material: number
octaves: number
persistence: number
@@ -9818,11 +9916,19 @@ splatmap: number
warp: number
```
-## TerrainPaint — type @experimental
+## TerrainExtent — const @experimental
```
-(
- u: number, v: number, height01: number, slope: number,
-) => [number, number, number, number]
+{ readonly Area: 0; readonly Infinite: 1; }
+```
+
+## TerrainNode — interface @experimental
+```
+ix: number
+iz: number
+level: number
+size: number
+x0: number
+z0: number
```
## TerrainPlugin — class @experimental
@@ -9834,13 +9940,14 @@ static new (): TerrainPlugin
static prototype: TerrainPlugin
```
-## TerrainShape — interface @experimental
+## TerrainSource — interface @experimental
```
-chunkCells: number
-chunks: number
-height: number
-sizeX: number
-sizeZ: number
+bounds: readonly [number, number, number, number] | null
+height: (x: number, z: number) => number | null
+infinite: boolean
+maxHeight: number
+minHeight: number
+paint: (x: number, z: number, h: number, ny: number) => [number, number, number, number]
```
## Terrains — class @experimental
@@ -12350,6 +12457,11 @@ MotionDriver<AnimatorBlend2DMotion>
(from: number, to: number, progress: number): WeatherState
```
+## boxDistance — function @experimental
+```
+(x0: number, z0: number, size: number, y0: number, y1: number, ex: number, ey: number, ez: number): number
+```
+
## bucketOverridesByEntity — function @experimental
```
(overrides: readonly PrefabOverride[]): Map<PrefabEntityId, PrefabOverride[]>
@@ -12360,11 +12472,6 @@ MotionDriver<AnimatorBlend2DMotion>
(plants: readonly Plant[], width: number, height: number, rect: CardRect, paint?: BladeParams["paint"], triangle?: boolean): MeshData
```
-## buildChunkMesh — function @experimental
-```
-(field: Heightfield, shape: TerrainShape, cx: number, cz: number, lod: number, paint: TerrainPaint): MeshData
-```
-
## buildFrameProfile — function @experimental
```
(input: FrameProfileInput): FrameProfile
@@ -12385,6 +12492,11 @@ MotionDriver<AnimatorBlend2DMotion>
(cells: number, rings: number, cellSize: number): MeshData
```
+## buildPatchMesh — function @experimental
+```
+(cells: number): MeshData
+```
+
## buildText — function @experimental
```
(init?: TextInit): TextData
@@ -12495,21 +12607,11 @@ MotionDriver<AnimatorBlend2DMotion>
(cellX: number, cellZ: number, cellSize: number): { minX: number; minZ: number; maxX: number; maxZ: number; }
```
-## cellsAtLod — function @experimental
-```
-(shape: TerrainShape, lod: number): number
-```
-
## censusProbeIds — function @experimental
```
(): string[]
```
-## chunkCenter — function @experimental
-```
-(shape: TerrainShape, cx: number, cz: number): [number, number]
-```
-
## clearAnimatorControllerStore — function @experimental
```
(): void
@@ -13830,6 +13932,11 @@ InputRouter
(def: AnimatorScope, path: string): AnimatorState | null
```
+## levelRange — function @experimental
+```
+(p: Pick<QuadtreeParams, "range0">, level: number): number
+```
+
## lifecyclePlugin — const @experimental
```
LifecyclePlugin
@@ -13895,11 +14002,6 @@ LifecyclePlugin
LocalizationPlugin
```
-## lodCount — function @experimental
-```
-(shape: TerrainShape, wanted?: number): number
-```
-
## log — const @experimental
```
Logger
@@ -13910,6 +14012,11 @@ Logger
(value: unknown): value is string
```
+## makePage — function @experimental
+```
+(source: TerrainSource, x0: number, z0: number, size: number): PageImage
+```
+
## makeWidgetInteractable — function @experimental
```
(world: World, entity: Entity, init?: WidgetInteractionInit): void
@@ -14020,6 +14127,16 @@ MeshRendererPlugin
() => InputState
```
+## nodeKey — function @experimental
+```
+(level: number, ix: number, iz: number): string
+```
+
+## noised — function @experimental
+```
+(x: number, y: number, seed: number): [number, number, number]
+```
+
## normalizeBundleMode — function @experimental
```
(mode: string | undefined | null): BundleMode
@@ -14095,6 +14212,11 @@ MeshRendererPlugin
(param: ShaderParam): unknown
```
+## parentOf — function @experimental
+```
+(n: TerrainNode, leafSize: number): TerrainNode
+```
+
## parseActionArg — function @experimental
```
(arg: string | undefined, params: readonly AiParamDef[], separator?: string): Record<string, AiParamValue>
@@ -14835,6 +14957,11 @@ Plugin
(blend: AnimatorBlend1DMotion, value: number): AnimatorBlendStop | null
```
+## selectNodes — function @experimental
+```
+(p: QuadtreeParams, ex: number, ey: number, ez: number): TerrainNode[]
+```
+
## selectPluralForm — function @experimental
```
(forms: PluralForms, count: number, selector: PluralSelector): string
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index b96f26734..d47b356a5 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.node
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 115 public · 161 beta · 1755 experimental · 3 deprecated
+Symbols: 115 public · 161 beta · 1771 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -3925,6 +3925,20 @@ shore: number
swell: number
```
+## FieldSource — class @experimental
+```
+bounds: readonly [number, number, number, number]
+field: Heightfield
+height: (x: number, z: number) => number | null
+infinite: false
+maxHeight: number
+minHeight: 0
+normal: (x: number, z: number) => [number, number, number] | null
+paint: (x: number, z: number, h: number, ny: number) => [number, number, number, number]
+static new (field: Heightfield, data: Pick<TerrainData, "sizeX" | "sizeZ" | "height" | "rockSlope" | "dirtHeight" | "snowHeight">, splat: Splat | null, flow: Float32Array | null): FieldSource
+static prototype: FieldSource
+```
+
## FillMethod — enum @beta
```
Horizontal = 0
@@ -5770,6 +5784,26 @@ output: GraphType | null
params: NodeParamSpec[]
```
+## NoiseParams — type @experimental
+```
+Pick<TerrainData, 'seed' | 'frequency' | 'octaves' | 'persistence' | 'ridged' | 'warp' | 'erosion' | 'sizeX' | 'height'
+ | 'rockSlope' | 'dirtHeight' | 'snowHeight'>
+```
+
+## NoiseSource — class @experimental
+```
+bounds: null
+height: (x: number, z: number) => number
+infinite: true
+maxHeight: number
+minHeight: 0
+normal: (x: number, z: number) => [number, number, number]
+paint: (_x: number, _z: number, h: number, ny: number) => [number, number, number, number]
+sample: (x: number, z: number) => [number, number, number]
+static new (p: NoiseParams): NoiseSource
+static prototype: NoiseSource
+```
+
## Not — function @experimental
```
(filter: FilterExpr): FilterExpr
@@ -5808,6 +5842,21 @@ width: number | undefined
'none' | 'aces' | 'neutral'
```
+## PAGE_SIDE — const @experimental
+```
+number
+```
+
+## PAGE_TEXELS — const @experimental
+```
+number
+```
+
+## PATCH_CELLS — const @experimental
+```
+32
+```
+
## PREFAB_FORMAT_VERSION — const @experimental
```
"2"
@@ -5871,6 +5920,38 @@ worlds: { scene: string; manifest: string; }[] | undefined
ySortLayers: number | undefined
```
+## Page — interface @experimental
+```
+max: number
+min: number
+slot: number
+used: number
+```
+
+## PageImage — interface @experimental
+```
+heights: Uint8Array<ArrayBufferLike>
+max: number
+min: number
+paint: Uint8Array<ArrayBufferLike>
+```
+
+## PageTable — class @experimental
+```
+atlasSize: number
+capacity: number
+claim: (key: string, min: number, max: number) => Page | null
+clear: () => void
+get: (key: string) => Page | undefined
+origin: (slot: number) => [number, number]
+perRow: number
+size: number
+tick: () => void
+touch: (key: string) => void
+static new (atlasSize: number): PageTable
+static prototype: PageTable
+```
+
## Parent — const @public
```
BuiltinComponentDef<ParentData>
@@ -7108,6 +7189,16 @@ fields: readonly PtrFieldDesc[]
ptrFn: string
```
+## QuadtreeParams — interface @experimental
+```
+bounds: readonly [number, number, number, number] | null
+leafSize: number
+levels: number
+maxHeight: number
+minHeight: number
+range0: number
+```
+
## Quality — const @experimental
```
ResourceDef<QualityController | null>
@@ -8856,6 +8947,13 @@ type: "spine"
'2.1' | '3.8' | '4.1' | '4.2' | '4.3'
```
+## Splat — interface @experimental
+```
+height: number
+pixels: Uint8Array<ArrayBufferLike>
+width: number
+```
+
## Spline — const @experimental
```
ComponentDef<SplineData>
@@ -9573,11 +9671,12 @@ ComponentDef<TerrainData>
## TerrainData — interface @experimental
```
-chunkCells: number
-chunks: number
+cellSize: number
detail: number
dirtHeight: number
+drawDistance: number
erosion: number
+extent: number
frequency: number
height: number
heightmap: number
@@ -9585,7 +9684,6 @@ layerColor0: Color
layerColor1: Color
layerColor2: Color
layerColor3: Color
-lodLevels: number
material: number
octaves: number
persistence: number
@@ -9600,11 +9698,19 @@ splatmap: number
warp: number
```
-## TerrainPaint — type @experimental
+## TerrainExtent — const @experimental
```
-(
- u: number, v: number, height01: number, slope: number,
-) => [number, number, number, number]
+{ readonly Area: 0; readonly Infinite: 1; }
+```
+
+## TerrainNode — interface @experimental
+```
+ix: number
+iz: number
+level: number
+size: number
+x0: number
+z0: number
```
## TerrainPlugin — class @experimental
@@ -9616,13 +9722,14 @@ static new (): TerrainPlugin
static prototype: TerrainPlugin
```
-## TerrainShape — interface @experimental
+## TerrainSource — interface @experimental
```
-chunkCells: number
-chunks: number
-height: number
-sizeX: number
-sizeZ: number
+bounds: readonly [number, number, number, number] | null
+height: (x: number, z: number) => number | null
+infinite: boolean
+maxHeight: number
+minHeight: number
+paint: (x: number, z: number, h: number, ny: number) => [number, number, number, number]
```
## Terrains — class @experimental
@@ -12117,6 +12224,11 @@ MotionDriver<AnimatorBlend2DMotion>
(from: number, to: number, progress: number): WeatherState
```
+## boxDistance — function @experimental
+```
+(x0: number, z0: number, size: number, y0: number, y1: number, ex: number, ey: number, ez: number): number
+```
+
## bucketOverridesByEntity — function @experimental
```
(overrides: readonly PrefabOverride[]): Map<PrefabEntityId, PrefabOverride[]>
@@ -12127,11 +12239,6 @@ MotionDriver<AnimatorBlend2DMotion>
(plants: readonly Plant[], width: number, height: number, rect: CardRect, paint?: BladeParams["paint"], triangle?: boolean): MeshData
```
-## buildChunkMesh — function @experimental
-```
-(field: Heightfield, shape: TerrainShape, cx: number, cz: number, lod: number, paint: TerrainPaint): MeshData
-```
-
## buildFrameProfile — function @experimental
```
(input: FrameProfileInput): FrameProfile
@@ -12152,6 +12259,11 @@ MotionDriver<AnimatorBlend2DMotion>
(cells: number, rings: number, cellSize: number): MeshData
```
+## buildPatchMesh — function @experimental
+```
+(cells: number): MeshData
+```
+
## buildText — function @experimental
```
(init?: TextInit): TextData
@@ -12262,21 +12374,11 @@ MotionDriver<AnimatorBlend2DMotion>
(cellX: number, cellZ: number, cellSize: number): { minX: number; minZ: number; maxX: number; maxZ: number; }
```
-## cellsAtLod — function @experimental
-```
-(shape: TerrainShape, lod: number): number
-```
-
## censusProbeIds — function @experimental
```
(): string[]
```
-## chunkCenter — function @experimental
-```
-(shape: TerrainShape, cx: number, cz: number): [number, number]
-```
-
## clearAnimatorControllerStore — function @experimental
```
(): void
@@ -13562,6 +13664,11 @@ InputRouter
(def: AnimatorScope, path: string): AnimatorState | null
```
+## levelRange — function @experimental
+```
+(p: Pick<QuadtreeParams, "range0">, level: number): number
+```
+
## lifecyclePlugin — const @experimental
```
LifecyclePlugin
@@ -13632,11 +13739,6 @@ LifecyclePlugin
LocalizationPlugin
```
-## lodCount — function @experimental
-```
-(shape: TerrainShape, wanted?: number): number
-```
-
## log — const @experimental
```
Logger
@@ -13647,6 +13749,11 @@ Logger
(value: unknown): value is string
```
+## makePage — function @experimental
+```
+(source: TerrainSource, x0: number, z0: number, size: number): PageImage
+```
+
## makeWidgetInteractable — function @experimental
```
(world: World, entity: Entity, init?: WidgetInteractionInit): void
@@ -13762,6 +13869,16 @@ MeshRendererPlugin
NodePlatformAdapter
```
+## nodeKey — function @experimental
+```
+(level: number, ix: number, iz: number): string
+```
+
+## noised — function @experimental
+```
+(x: number, y: number, seed: number): [number, number, number]
+```
+
## normalizeBundleMode — function @experimental
```
(mode: string | undefined | null): BundleMode
@@ -13837,6 +13954,11 @@ NodePlatformAdapter
(param: ShaderParam): unknown
```
+## parentOf — function @experimental
+```
+(n: TerrainNode, leafSize: number): TerrainNode
+```
+
## parseActionArg — function @experimental
```
(arg: string | undefined, params: readonly AiParamDef[], separator?: string): Record<string, AiParamValue>
@@ -14577,6 +14699,11 @@ Plugin
(blend: AnimatorBlend1DMotion, value: number): AnimatorBlendStop | null
```
+## selectNodes — function @experimental
+```
+(p: QuadtreeParams, ex: number, ey: number, ez: number): TerrainNode[]
+```
+
## selectPluralForm — function @experimental
```
(forms: PluralForms, count: number, selector: PluralSelector): string
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index d64ab6bca..37b54dc9d 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/minigame
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 115 public · 159 beta · 1777 experimental · 3 deprecated
+Symbols: 115 public · 159 beta · 1793 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -3925,6 +3925,20 @@ shore: number
swell: number
```
+## FieldSource — class @experimental
+```
+bounds: readonly [number, number, number, number]
+field: Heightfield
+height: (x: number, z: number) => number | null
+infinite: false
+maxHeight: number
+minHeight: 0
+normal: (x: number, z: number) => [number, number, number] | null
+paint: (x: number, z: number, h: number, ny: number) => [number, number, number, number]
+static new (field: Heightfield, data: Pick<TerrainData, "sizeX" | "sizeZ" | "height" | "rockSlope" | "dirtHeight" | "snowHeight">, splat: Splat | null, flow: Float32Array | null): FieldSource
+static prototype: FieldSource
+```
+
## FillMethod — enum @beta
```
Horizontal = 0
@@ -6063,6 +6077,26 @@ output: GraphType | null
params: NodeParamSpec[]
```
+## NoiseParams — type @experimental
+```
+Pick<TerrainData, 'seed' | 'frequency' | 'octaves' | 'persistence' | 'ridged' | 'warp' | 'erosion' | 'sizeX' | 'height'
+ | 'rockSlope' | 'dirtHeight' | 'snowHeight'>
+```
+
+## NoiseSource — class @experimental
+```
+bounds: null
+height: (x: number, z: number) => number
+infinite: true
+maxHeight: number
+minHeight: 0
+normal: (x: number, z: number) => [number, number, number]
+paint: (_x: number, _z: number, h: number, ny: number) => [number, number, number, number]
+sample: (x: number, z: number) => [number, number, number]
+static new (p: NoiseParams): NoiseSource
+static prototype: NoiseSource
+```
+
## Not — function @experimental
```
(filter: FilterExpr): FilterExpr
@@ -6101,6 +6135,21 @@ width: number | undefined
'none' | 'aces' | 'neutral'
```
+## PAGE_SIDE — const @experimental
+```
+number
+```
+
+## PAGE_TEXELS — const @experimental
+```
+number
+```
+
+## PATCH_CELLS — const @experimental
+```
+32
+```
+
## PREFAB_FORMAT_VERSION — const @experimental
```
"2"
@@ -6164,6 +6213,38 @@ worlds: { scene: string; manifest: string; }[] | undefined
ySortLayers: number | undefined
```
+## Page — interface @experimental
+```
+max: number
+min: number
+slot: number
+used: number
+```
+
+## PageImage — interface @experimental
+```
+heights: Uint8Array<ArrayBufferLike>
+max: number
+min: number
+paint: Uint8Array<ArrayBufferLike>
+```
+
+## PageTable — class @experimental
+```
+atlasSize: number
+capacity: number
+claim: (key: string, min: number, max: number) => Page | null
+clear: () => void
+get: (key: string) => Page | undefined
+origin: (slot: number) => [number, number]
+perRow: number
+size: number
+tick: () => void
+touch: (key: string) => void
+static new (atlasSize: number): PageTable
+static prototype: PageTable
+```
+
## Parent — const @public
```
BuiltinComponentDef<ParentData>
@@ -7401,6 +7482,16 @@ fields: readonly PtrFieldDesc[]
ptrFn: string
```
+## QuadtreeParams — interface @experimental
+```
+bounds: readonly [number, number, number, number] | null
+leafSize: number
+levels: number
+maxHeight: number
+minHeight: number
+range0: number
+```
+
## Quality — const @experimental
```
ResourceDef<QualityController | null>
@@ -9149,6 +9240,13 @@ type: "spine"
'2.1' | '3.8' | '4.1' | '4.2' | '4.3'
```
+## Splat — interface @experimental
+```
+height: number
+pixels: Uint8Array<ArrayBufferLike>
+width: number
+```
+
## Spline — const @experimental
```
ComponentDef<SplineData>
@@ -9866,11 +9964,12 @@ ComponentDef<TerrainData>
## TerrainData — interface @experimental
```
-chunkCells: number
-chunks: number
+cellSize: number
detail: number
dirtHeight: number
+drawDistance: number
erosion: number
+extent: number
frequency: number
height: number
heightmap: number
@@ -9878,7 +9977,6 @@ layerColor0: Color
layerColor1: Color
layerColor2: Color
layerColor3: Color
-lodLevels: number
material: number
octaves: number
persistence: number
@@ -9893,11 +9991,19 @@ splatmap: number
warp: number
```
-## TerrainPaint — type @experimental
+## TerrainExtent — const @experimental
```
-(
- u: number, v: number, height01: number, slope: number,
-) => [number, number, number, number]
+{ readonly Area: 0; readonly Infinite: 1; }
+```
+
+## TerrainNode — interface @experimental
+```
+ix: number
+iz: number
+level: number
+size: number
+x0: number
+z0: number
```
## TerrainPlugin — class @experimental
@@ -9909,13 +10015,14 @@ static new (): TerrainPlugin
static prototype: TerrainPlugin
```
-## TerrainShape — interface @experimental
+## TerrainSource — interface @experimental
```
-chunkCells: number
-chunks: number
-height: number
-sizeX: number
-sizeZ: number
+bounds: readonly [number, number, number, number] | null
+height: (x: number, z: number) => number | null
+infinite: boolean
+maxHeight: number
+minHeight: number
+paint: (x: number, z: number, h: number, ny: number) => [number, number, number, number]
```
## Terrains — class @experimental
@@ -12416,6 +12523,11 @@ MotionDriver<AnimatorBlend2DMotion>
(from: number, to: number, progress: number): WeatherState
```
+## boxDistance — function @experimental
+```
+(x0: number, z0: number, size: number, y0: number, y1: number, ex: number, ey: number, ez: number): number
+```
+
## bucketOverridesByEntity — function @experimental
```
(overrides: readonly PrefabOverride[]): Map<PrefabEntityId, PrefabOverride[]>
@@ -12426,11 +12538,6 @@ MotionDriver<AnimatorBlend2DMotion>
(plants: readonly Plant[], width: number, height: number, rect: CardRect, paint?: BladeParams["paint"], triangle?: boolean): MeshData
```
-## buildChunkMesh — function @experimental
-```
-(field: Heightfield, shape: TerrainShape, cx: number, cz: number, lod: number, paint: TerrainPaint): MeshData
-```
-
## buildFrameProfile — function @experimental
```
(input: FrameProfileInput): FrameProfile
@@ -12451,6 +12558,11 @@ MotionDriver<AnimatorBlend2DMotion>
(cells: number, rings: number, cellSize: number): MeshData
```
+## buildPatchMesh — function @experimental
+```
+(cells: number): MeshData
+```
+
## buildText — function @experimental
```
(init?: TextInit): TextData
@@ -12561,21 +12673,11 @@ MotionDriver<AnimatorBlend2DMotion>
(cellX: number, cellZ: number, cellSize: number): { minX: number; minZ: number; maxX: number; maxZ: number; }
```
-## cellsAtLod — function @experimental
-```
-(shape: TerrainShape, lod: number): number
-```
-
## censusProbeIds — function @experimental
```
(): string[]
```
-## chunkCenter — function @experimental
-```
-(shape: TerrainShape, cx: number, cz: number): [number, number]
-```
-
## clearAnimatorControllerStore — function @experimental
```
(): void
@@ -13876,6 +13978,11 @@ InputRouter
(def: AnimatorScope, path: string): AnimatorState | null
```
+## levelRange — function @experimental
+```
+(p: Pick<QuadtreeParams, "range0">, level: number): number
+```
+
## lifecyclePlugin — const @experimental
```
LifecyclePlugin
@@ -13941,11 +14048,6 @@ LifecyclePlugin
LocalizationPlugin
```
-## lodCount — function @experimental
-```
-(shape: TerrainShape, wanted?: number): number
-```
-
## log — const @experimental
```
Logger
@@ -13956,6 +14058,11 @@ Logger
(value: unknown): value is string
```
+## makePage — function @experimental
+```
+(source: TerrainSource, x0: number, z0: number, size: number): PageImage
+```
+
## makeWidgetInteractable — function @experimental
```
(world: World, entity: Entity, init?: WidgetInteractionInit): void
@@ -14066,6 +14173,16 @@ MeshRendererPlugin
() => InputState
```
+## nodeKey — function @experimental
+```
+(level: number, ix: number, iz: number): string
+```
+
+## noised — function @experimental
+```
+(x: number, y: number, seed: number): [number, number, number]
+```
+
## normalizeBundleMode — function @experimental
```
(mode: string | undefined | null): BundleMode
@@ -14141,6 +14258,11 @@ MeshRendererPlugin
(param: ShaderParam): unknown
```
+## parentOf — function @experimental
+```
+(n: TerrainNode, leafSize: number): TerrainNode
+```
+
## parseActionArg — function @experimental
```
(arg: string | undefined, params: readonly AiParamDef[], separator?: string): Record<string, AiParamValue>
@@ -14881,6 +15003,11 @@ Plugin
(blend: AnimatorBlend1DMotion, value: number): AnimatorBlendStop | null
```
+## selectNodes — function @experimental
+```
+(p: QuadtreeParams, ex: number, ey: number, ez: number): TerrainNode[]
+```
+
## selectPluralForm — function @experimental
```
(forms: PluralForms, count: number, selector: PluralSelector): string
diff --git a/sdk/etc/terrain.api.md b/sdk/etc/terrain.api.md
index df9098432..7e441dbf2 100644
--- a/sdk/etc/terrain.api.md
+++ b/sdk/etc/terrain.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/terrain
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 0 public · 0 beta · 23 experimental · 0 deprecated
+Symbols: 0 public · 0 beta · 39 experimental · 0 deprecated
## Eroded — interface @experimental
```
@@ -18,6 +18,20 @@ sizeX: number
sizeZ: number
```
+## FieldSource — class @experimental
+```
+bounds: readonly [number, number, number, number]
+field: Heightfield
+height: (x: number, z: number) => number | null
+infinite: false
+maxHeight: number
+minHeight: 0
+normal: (x: number, z: number) => [number, number, number] | null
+paint: (x: number, z: number, h: number, ny: number) => [number, number, number, number]
+static new (field: Heightfield, data: Pick<TerrainData, "sizeX" | "sizeZ" | "height" | "rockSlope" | "dirtHeight" | "snowHeight">, splat: Splat | null, flow: Float32Array | null): FieldSource
+static prototype: FieldSource
+```
+
## Heightfield — interface @experimental
```
data: Float32Array<ArrayBufferLike>
@@ -25,6 +39,73 @@ height: number
width: number
```
+## NoiseParams — type @experimental
+```
+Pick<TerrainData, 'seed' | 'frequency' | 'octaves' | 'persistence' | 'ridged' | 'warp' | 'erosion' | 'sizeX' | 'height'
+ | 'rockSlope' | 'dirtHeight' | 'snowHeight'>
+```
+
+## NoiseSource — class @experimental
+```
+bounds: null
+height: (x: number, z: number) => number
+infinite: true
+maxHeight: number
+minHeight: 0
+normal: (x: number, z: number) => [number, number, number]
+paint: (_x: number, _z: number, h: number, ny: number) => [number, number, number, number]
+sample: (x: number, z: number) => [number, number, number]
+static new (p: NoiseParams): NoiseSource
+static prototype: NoiseSource
+```
+
+## PAGE_SIDE — const @experimental
+```
+number
+```
+
+## PAGE_TEXELS — const @experimental
+```
+number
+```
+
+## PATCH_CELLS — const @experimental
+```
+32
+```
+
+## Page — interface @experimental
+```
+max: number
+min: number
+slot: number
+used: number
+```
+
+## PageImage — interface @experimental
+```
+heights: Uint8Array<ArrayBufferLike>
+max: number
+min: number
+paint: Uint8Array<ArrayBufferLike>
+```
+
+## PageTable — class @experimental
+```
+atlasSize: number
+capacity: number
+claim: (key: string, min: number, max: number) => Page | null
+clear: () => void
+get: (key: string) => Page | undefined
+origin: (slot: number) => [number, number]
+perRow: number
+size: number
+tick: () => void
+touch: (key: string) => void
+static new (atlasSize: number): PageTable
+static prototype: PageTable
+```
+
## ProceduralParams — interface @experimental
```
frequency: number
@@ -36,6 +117,23 @@ seed: number
warp: number | undefined
```
+## QuadtreeParams — interface @experimental
+```
+bounds: readonly [number, number, number, number] | null
+leafSize: number
+levels: number
+maxHeight: number
+minHeight: number
+range0: number
+```
+
+## Splat — interface @experimental
+```
+height: number
+pixels: Uint8Array<ArrayBufferLike>
+width: number
+```
+
## Terrain — const @experimental
```
ComponentDef<TerrainData>
@@ -43,11 +141,12 @@ ComponentDef<TerrainData>
## TerrainData — interface @experimental
```
-chunkCells: number
-chunks: number
+cellSize: number
detail: number
dirtHeight: number
+drawDistance: number
erosion: number
+extent: number
frequency: number
height: number
heightmap: number
@@ -55,7 +154,6 @@ layerColor0: Color
layerColor1: Color
layerColor2: Color
layerColor3: Color
-lodLevels: number
material: number
octaves: number
persistence: number
@@ -70,11 +168,19 @@ splatmap: number
warp: number
```
-## TerrainPaint — type @experimental
+## TerrainExtent — const @experimental
+```
+{ readonly Area: 0; readonly Infinite: 1; }
+```
+
+## TerrainNode — interface @experimental
```
-(
- u: number, v: number, height01: number, slope: number,
-) => [number, number, number, number]
+ix: number
+iz: number
+level: number
+size: number
+x0: number
+z0: number
```
## TerrainPlugin — class @experimental
@@ -86,13 +192,14 @@ static new (): TerrainPlugin
static prototype: TerrainPlugin
```
-## TerrainShape — interface @experimental
+## TerrainSource — interface @experimental
```
-chunkCells: number
-chunks: number
-height: number
-sizeX: number
-sizeZ: number
+bounds: readonly [number, number, number, number] | null
+height: (x: number, z: number) => number | null
+infinite: boolean
+maxHeight: number
+minHeight: number
+paint: (x: number, z: number, h: number, ny: number) => [number, number, number, number]
```
## Terrains — class @experimental
@@ -113,19 +220,14 @@ static prototype: Terrains
ResourceDef<Terrains>
```
-## buildChunkMesh — function @experimental
+## boxDistance — function @experimental
```
-(field: Heightfield, shape: TerrainShape, cx: number, cz: number, lod: number, paint: TerrainPaint): MeshData
+(x0: number, z0: number, size: number, y0: number, y1: number, ex: number, ey: number, ez: number): number
```
-## cellsAtLod — function @experimental
+## buildPatchMesh — function @experimental
```
-(shape: TerrainShape, lod: number): number
-```
-
-## chunkCenter — function @experimental
-```
-(shape: TerrainShape, cx: number, cz: number): [number, number]
+(cells: number): MeshData
```
## erodeHeightfield — function @experimental
@@ -143,9 +245,24 @@ ResourceDef<Terrains>
(width: number, height: number, pixels: ArrayLike<number>): Heightfield
```
-## lodCount — function @experimental
+## levelRange — function @experimental
```
-(shape: TerrainShape, wanted?: number): number
+(p: Pick<QuadtreeParams, "range0">, level: number): number
+```
+
+## makePage — function @experimental
+```
+(source: TerrainSource, x0: number, z0: number, size: number): PageImage
+```
+
+## nodeKey — function @experimental
+```
+(level: number, ix: number, iz: number): string
+```
+
+## noised — function @experimental
+```
+(x: number, y: number, seed: number): [number, number, number]
```
## paintWeights — function @experimental
@@ -153,6 +270,11 @@ ResourceDef<Terrains>
(h: number, ny: number, t: Pick<TerrainData, "rockSlope" | "dirtHeight" | "snowHeight">): [number, number, number, number]
```
+## parentOf — function @experimental
+```
+(n: TerrainNode, leafSize: number): TerrainNode
+```
+
## proceduralHeightfield — function @experimental
```
(p: ProceduralParams): Heightfield
@@ -163,6 +285,11 @@ ResourceDef<Terrains>
(field: Heightfield, u: number, v: number): number
```
+## selectNodes — function @experimental
+```
+(p: QuadtreeParams, ex: number, ey: number, ez: number): TerrainNode[]
+```
+
## terrainNormal — function @experimental
```
(field: Heightfield, u: number, v: number, sizeX: number, sizeZ: number, heightScale: number): [number, number, number]
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index b271af70c..da0520d9d 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/wechat
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 115 public · 159 beta · 1768 experimental · 3 deprecated
+Symbols: 115 public · 159 beta · 1784 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -3925,6 +3925,20 @@ shore: number
swell: number
```
+## FieldSource — class @experimental
+```
+bounds: readonly [number, number, number, number]
+field: Heightfield
+height: (x: number, z: number) => number | null
+infinite: false
+maxHeight: number
+minHeight: 0
+normal: (x: number, z: number) => [number, number, number] | null
+paint: (x: number, z: number, h: number, ny: number) => [number, number, number, number]
+static new (field: Heightfield, data: Pick<TerrainData, "sizeX" | "sizeZ" | "height" | "rockSlope" | "dirtHeight" | "snowHeight">, splat: Splat | null, flow: Float32Array | null): FieldSource
+static prototype: FieldSource
+```
+
## FillMethod — enum @beta
```
Horizontal = 0
@@ -5777,6 +5791,26 @@ output: GraphType | null
params: NodeParamSpec[]
```
+## NoiseParams — type @experimental
+```
+Pick<TerrainData, 'seed' | 'frequency' | 'octaves' | 'persistence' | 'ridged' | 'warp' | 'erosion' | 'sizeX' | 'height'
+ | 'rockSlope' | 'dirtHeight' | 'snowHeight'>
+```
+
+## NoiseSource — class @experimental
+```
+bounds: null
+height: (x: number, z: number) => number
+infinite: true
+maxHeight: number
+minHeight: 0
+normal: (x: number, z: number) => [number, number, number]
+paint: (_x: number, _z: number, h: number, ny: number) => [number, number, number, number]
+sample: (x: number, z: number) => [number, number, number]
+static new (p: NoiseParams): NoiseSource
+static prototype: NoiseSource
+```
+
## Not — function @experimental
```
(filter: FilterExpr): FilterExpr
@@ -5815,6 +5849,21 @@ width: number | undefined
'none' | 'aces' | 'neutral'
```
+## PAGE_SIDE — const @experimental
+```
+number
+```
+
+## PAGE_TEXELS — const @experimental
+```
+number
+```
+
+## PATCH_CELLS — const @experimental
+```
+32
+```
+
## PREFAB_FORMAT_VERSION — const @experimental
```
"2"
@@ -5878,6 +5927,38 @@ worlds: { scene: string; manifest: string; }[] | undefined
ySortLayers: number | undefined
```
+## Page — interface @experimental
+```
+max: number
+min: number
+slot: number
+used: number
+```
+
+## PageImage — interface @experimental
+```
+heights: Uint8Array<ArrayBufferLike>
+max: number
+min: number
+paint: Uint8Array<ArrayBufferLike>
+```
+
+## PageTable — class @experimental
+```
+atlasSize: number
+capacity: number
+claim: (key: string, min: number, max: number) => Page | null
+clear: () => void
+get: (key: string) => Page | undefined
+origin: (slot: number) => [number, number]
+perRow: number
+size: number
+tick: () => void
+touch: (key: string) => void
+static new (atlasSize: number): PageTable
+static prototype: PageTable
+```
+
## Parent — const @public
```
BuiltinComponentDef<ParentData>
@@ -7115,6 +7196,16 @@ fields: readonly PtrFieldDesc[]
ptrFn: string
```
+## QuadtreeParams — interface @experimental
+```
+bounds: readonly [number, number, number, number] | null
+leafSize: number
+levels: number
+maxHeight: number
+minHeight: number
+range0: number
+```
+
## Quality — const @experimental
```
ResourceDef<QualityController | null>
@@ -8863,6 +8954,13 @@ type: "spine"
'2.1' | '3.8' | '4.1' | '4.2' | '4.3'
```
+## Splat — interface @experimental
+```
+height: number
+pixels: Uint8Array<ArrayBufferLike>
+width: number
+```
+
## Spline — const @experimental
```
ComponentDef<SplineData>
@@ -9580,11 +9678,12 @@ ComponentDef<TerrainData>
## TerrainData — interface @experimental
```
-chunkCells: number
-chunks: number
+cellSize: number
detail: number
dirtHeight: number
+drawDistance: number
erosion: number
+extent: number
frequency: number
height: number
heightmap: number
@@ -9592,7 +9691,6 @@ layerColor0: Color
layerColor1: Color
layerColor2: Color
layerColor3: Color
-lodLevels: number
material: number
octaves: number
persistence: number
@@ -9607,11 +9705,19 @@ splatmap: number
warp: number
```
-## TerrainPaint — type @experimental
+## TerrainExtent — const @experimental
```
-(
- u: number, v: number, height01: number, slope: number,
-) => [number, number, number, number]
+{ readonly Area: 0; readonly Infinite: 1; }
+```
+
+## TerrainNode — interface @experimental
+```
+ix: number
+iz: number
+level: number
+size: number
+x0: number
+z0: number
```
## TerrainPlugin — class @experimental
@@ -9623,13 +9729,14 @@ static new (): TerrainPlugin
static prototype: TerrainPlugin
```
-## TerrainShape — interface @experimental
+## TerrainSource — interface @experimental
```
-chunkCells: number
-chunks: number
-height: number
-sizeX: number
-sizeZ: number
+bounds: readonly [number, number, number, number] | null
+height: (x: number, z: number) => number | null
+infinite: boolean
+maxHeight: number
+minHeight: number
+paint: (x: number, z: number, h: number, ny: number) => [number, number, number, number]
```
## Terrains — class @experimental
@@ -12148,6 +12255,11 @@ MotionDriver<AnimatorBlend2DMotion>
(from: number, to: number, progress: number): WeatherState
```
+## boxDistance — function @experimental
+```
+(x0: number, z0: number, size: number, y0: number, y1: number, ex: number, ey: number, ez: number): number
+```
+
## bucketOverridesByEntity — function @experimental
```
(overrides: readonly PrefabOverride[]): Map<PrefabEntityId, PrefabOverride[]>
@@ -12158,11 +12270,6 @@ MotionDriver<AnimatorBlend2DMotion>
(plants: readonly Plant[], width: number, height: number, rect: CardRect, paint?: BladeParams["paint"], triangle?: boolean): MeshData
```
-## buildChunkMesh — function @experimental
-```
-(field: Heightfield, shape: TerrainShape, cx: number, cz: number, lod: number, paint: TerrainPaint): MeshData
-```
-
## buildFrameProfile — function @experimental
```
(input: FrameProfileInput): FrameProfile
@@ -12183,6 +12290,11 @@ MotionDriver<AnimatorBlend2DMotion>
(cells: number, rings: number, cellSize: number): MeshData
```
+## buildPatchMesh — function @experimental
+```
+(cells: number): MeshData
+```
+
## buildText — function @experimental
```
(init?: TextInit): TextData
@@ -12293,21 +12405,11 @@ MotionDriver<AnimatorBlend2DMotion>
(cellX: number, cellZ: number, cellSize: number): { minX: number; minZ: number; maxX: number; maxZ: number; }
```
-## cellsAtLod — function @experimental
-```
-(shape: TerrainShape, lod: number): number
-```
-
## censusProbeIds — function @experimental
```
(): string[]
```
-## chunkCenter — function @experimental
-```
-(shape: TerrainShape, cx: number, cz: number): [number, number]
-```
-
## clearAnimatorControllerStore — function @experimental
```
(): void
@@ -13603,6 +13705,11 @@ InputRouter
(def: AnimatorScope, path: string): AnimatorState | null
```
+## levelRange — function @experimental
+```
+(p: Pick<QuadtreeParams, "range0">, level: number): number
+```
+
## lifecyclePlugin — const @experimental
```
LifecyclePlugin
@@ -13668,11 +13775,6 @@ LifecyclePlugin
LocalizationPlugin
```
-## lodCount — function @experimental
-```
-(shape: TerrainShape, wanted?: number): number
-```
-
## log — const @experimental
```
Logger
@@ -13683,6 +13785,11 @@ Logger
(value: unknown): value is string
```
+## makePage — function @experimental
+```
+(source: TerrainSource, x0: number, z0: number, size: number): PageImage
+```
+
## makeWidgetInteractable — function @experimental
```
(world: World, entity: Entity, init?: WidgetInteractionInit): void
@@ -13793,6 +13900,16 @@ MeshRendererPlugin
() => InputState
```
+## nodeKey — function @experimental
+```
+(level: number, ix: number, iz: number): string
+```
+
+## noised — function @experimental
+```
+(x: number, y: number, seed: number): [number, number, number]
+```
+
## normalizeBundleMode — function @experimental
```
(mode: string | undefined | null): BundleMode
@@ -13868,6 +13985,11 @@ MeshRendererPlugin
(param: ShaderParam): unknown
```
+## parentOf — function @experimental
+```
+(n: TerrainNode, leafSize: number): TerrainNode
+```
+
## parseActionArg — function @experimental
```
(arg: string | undefined, params: readonly AiParamDef[], separator?: string): Record<string, AiParamValue>
@@ -14608,6 +14730,11 @@ Plugin
(blend: AnimatorBlend1DMotion, value: number): AnimatorBlendStop | null
```
+## selectNodes — function @experimental
+```
+(p: QuadtreeParams, ex: number, ey: number, ez: number): TerrainNode[]
+```
+
## selectPluralForm — function @experimental
```
(forms: PluralForms, count: number, selector: PluralSelector): string
diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.ts
index e66ffc03c..4604b20d1 100644
--- a/sdk/src/core-content.ts
+++ b/sdk/src/core-content.ts
@@ -794,7 +794,7 @@ export {
// Terrain and Foliage are optional modules (`esengine/terrain`, `esengine/foliage` install them). Their API stays reachable from
// here: a shared chunk is side-effect-free, so what nothing uses is not bundled.
export {
- Terrain, Terrains, TerrainsRes, TerrainPlugin, terrainPlugin, paintWeights, type TerrainData,
+ Terrain, TerrainExtent, Terrains, TerrainsRes, TerrainPlugin, terrainPlugin, paintWeights, type TerrainData,
} from './terrain/terrainPlugin';
export {
Foliage, FoliageField, FoliageRes, FoliagePlugin, foliagePlugin, type FoliageData,
@@ -818,9 +818,10 @@ export {
erodeHeightfield, erosionJob, heightfieldFromPixels, proceduralHeightfield, sampleHeight, terrainNormal,
type Eroded, type ErosionParams, type Heightfield, type ProceduralParams,
} from './terrain/heightfield';
-export {
- buildChunkMesh, cellsAtLod, chunkCenter, lodCount, type TerrainShape, type TerrainPaint,
-} from './terrain/mesh';
+export { FieldSource, NoiseSource, noised, type NoiseParams, type Splat, type TerrainSource } from './terrain/source';
+export { boxDistance, levelRange, nodeKey, parentOf, selectNodes, type QuadtreeParams, type TerrainNode } from './terrain/quadtree';
+export { makePage, PageTable, PAGE_SIDE, PAGE_TEXELS, PATCH_CELLS, type Page, type PageImage } from './terrain/pages';
+export { buildPatchMesh } from './terrain/patch';
export {
mergeMeshes, planStaticBatches, STATIC_BATCH_DEFAULTS,
type StaticBatchGroup, type StaticBatchLimits, type StaticBatchRefusal, type StaticBatchReport,
diff --git a/sdk/src/foliage/foliagePlugin.ts b/sdk/src/foliage/foliagePlugin.ts
index 2c2e038df..61d760201 100644
--- a/sdk/src/foliage/foliagePlugin.ts
+++ b/sdk/src/foliage/foliagePlugin.ts
@@ -188,9 +188,9 @@ export class FoliagePlugin implements Plugin {
continue;
}
if (built.loading) continue;
- // Plants stand on the ground: while a terrain is still being made, growing them would be done again once it is.
+ // Plants stand on the ground: while a terrain's heights are still being made, growing them would be done again once they are.
const terrains = app.hasResource(TerrainsRes) ? app.getResource(TerrainsRes) : null;
- if (terrains && (terrains.loading || terrains.pending > 0)) continue;
+ if (terrains?.loading) continue;
if (water?.baking) continue;
const until = performance.now() + CELL_BUDGET_MS;
while (built.queue.length > 0) {
diff --git a/sdk/src/terrain/index.ts b/sdk/src/terrain/index.ts
index 044914d83..1bf74ad36 100644
--- a/sdk/src/terrain/index.ts
+++ b/sdk/src/terrain/index.ts
@@ -1,15 +1,16 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
export {
- Terrain, Terrains, TerrainsRes, TerrainPlugin, terrainPlugin, paintWeights, type TerrainData,
+ Terrain, TerrainExtent, Terrains, TerrainsRes, TerrainPlugin, terrainPlugin, paintWeights, type TerrainData,
} from './terrainPlugin';
export {
erodeHeightfield, erosionJob, heightfieldFromPixels, proceduralHeightfield, sampleHeight, terrainNormal,
type Eroded, type ErosionParams, type Heightfield, type ProceduralParams,
} from './heightfield';
-export {
- buildChunkMesh, cellsAtLod, chunkCenter, lodCount, type TerrainShape, type TerrainPaint,
-} from './mesh';
+export { FieldSource, NoiseSource, noised, type NoiseParams, type Splat, type TerrainSource } from './source';
+export { boxDistance, levelRange, nodeKey, parentOf, selectNodes, type QuadtreeParams, type TerrainNode } from './quadtree';
+export { makePage, PageTable, PAGE_SIDE, PAGE_TEXELS, PATCH_CELLS, type Page, type PageImage } from './pages';
+export { buildPatchMesh } from './patch';
// Importing this subpath INSTALLS terrain — see tilemap/index.ts.
import { registerTerrainSupport } from './terrainSupport';
diff --git a/sdk/src/terrain/pages.ts b/sdk/src/terrain/pages.ts
new file mode 100644
index 000000000..28ac051f6
--- /dev/null
+++ b/sdk/src/terrain/pages.ts
@@ -0,0 +1,131 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file pages.ts
+ * @brief The ground's height, slope and paint in pages: one per quadtree node, made from the source and kept in two atlas textures.
+ *
+ * @details A page is a node's square sampled `PAGE_TEXELS` times along each side (two samples to a cell of its patch), with one sample
+ * more past each edge so the slope at the edge is known and a filtered read there stays inside the page. Its two images:
+ * - heights: red and green the height over the source's range, high byte then low (read texel by texel and blended in the
+ * shader, as a filtered pair of bytes is no number); blue and alpha the normal's x and z (filtered);
+ * - paint: the weights of the four layers (filtered).
+ * Pages are made as the tree asks for them, coarse ones first, within a time budget a frame, and the least recently drawn give
+ * their slot up when the atlas is full. A node whose page is not made yet is drawn by an ancestor's.
+ */
+import type { TerrainSource } from './source';
+
+/** Cells along a patch's side, and samples along a page's (two to a cell). */
+export const PATCH_CELLS = 32;
+export const PAGE_TEXELS = PATCH_CELLS * 2;
+/** A page's side in the atlas: its samples, the one on its far edge, and one past each edge. */
+export const PAGE_SIDE = PAGE_TEXELS + 3;
+
+/** A page's place and what it found. */
+export interface Page {
+ slot: number;
+ /** The least and most height in it: the node's box. */
+ min: number;
+ max: number;
+ /** When it was last drawn, for choosing which to give up. */
+ used: number;
+}
+
+/** The pixels of one page. */
+export interface PageImage { heights: Uint8Array; paint: Uint8Array; min: number; max: number }
+
+/**
+ * Samples a node's page from `source`: square (x0, z0) to (x0 + size, z0 + size) in the terrain's space. Heights are encoded over
+ * the source's range. Off an area's edge the ground is its nearest edge's, so the pages there are whole.
+ */
+export function makePage(source: TerrainSource, x0: number, z0: number, size: number): PageImage {
+ const n = PAGE_SIDE, step = size / PAGE_TEXELS;
+ const h = new Float32Array(n * n);
+ const [bx0, bz0, bx1, bz1] = source.bounds ?? [-Infinity, -Infinity, Infinity, Infinity];
+ let min = Infinity, max = -Infinity;
+ for (let j = 0; j < n; j++) for (let i = 0; i < n; i++) {
+ const x = Math.min(Math.max(x0 + (i - 1) * step, bx0), bx1), z = Math.min(Math.max(z0 + (j - 1) * step, bz0), bz1);
+ const v = source.height(x, z) ?? source.minHeight;
+ h[j * n + i] = v;
+ if (i >= 1 && i <= n - 2 && j >= 1 && j <= n - 2) { min = Math.min(min, v); max = Math.max(max, v); }
+ }
+ const span = Math.max(source.maxHeight - source.minHeight, 1e-6);
+ const heights = new Uint8Array(n * n * 4), paint = new Uint8Array(n * n * 4);
+ for (let j = 0; j < n; j++) for (let i = 0; i < n; i++) {
+ const k = j * n + i;
+ const enc = Math.round(Math.min(Math.max((h[k]! - source.minHeight) / span, 0), 1) * 65535);
+ const hl = h[j * n + Math.max(i - 1, 0)]!, hr = h[j * n + Math.min(i + 1, n - 1)]!;
+ const hd = h[Math.max(j - 1, 0) * n + i]!, hu = h[Math.min(j + 1, n - 1) * n + i]!;
+ const sx = (hr - hl) / (2 * step), sz = (hu - hd) / (2 * step);
+ const len = Math.hypot(sx, 1, sz);
+ const nx = -sx / len, ny = 1 / len, nz = -sz / len;
+ heights[k * 4] = enc >> 8;
+ heights[k * 4 + 1] = enc & 255;
+ heights[k * 4 + 2] = Math.round((nx * 0.5 + 0.5) * 255);
+ heights[k * 4 + 3] = Math.round((nz * 0.5 + 0.5) * 255);
+ const x = Math.min(Math.max(x0 + (i - 1) * step, bx0), bx1), z = Math.min(Math.max(z0 + (j - 1) * step, bz0), bz1);
+ const w = source.paint(x, z, h[k]!, ny);
+ for (let c = 0; c < 4; c++) paint[k * 4 + c] = Math.round(Math.min(Math.max(w[c]!, 0), 1) * 255);
+ }
+ return { heights, paint, min: Number.isFinite(min) ? min : source.minHeight, max: Number.isFinite(max) ? max : source.maxHeight };
+}
+
+/** Where the pages live: slots in a square atlas, given out and taken back by key. */
+export class PageTable {
+ readonly perRow: number;
+ readonly capacity: number;
+ private readonly pages_ = new Map<string, Page>();
+ private readonly free_: number[] = [];
+ private clock_ = 0;
+
+ constructor(readonly atlasSize: number) {
+ this.perRow = Math.floor(atlasSize / PAGE_SIDE);
+ this.capacity = this.perRow * this.perRow;
+ for (let s = this.capacity - 1; s >= 0; s--) this.free_.push(s);
+ }
+
+ get(key: string): Page | undefined {
+ return this.pages_.get(key);
+ }
+
+ /** Marks pages drawn this frame, so they are the last to be given up. */
+ touch(key: string): void {
+ const p = this.pages_.get(key);
+ if (p) p.used = this.clock_;
+ }
+
+ /** Moves the clock a frame on. */
+ tick(): void {
+ this.clock_++;
+ }
+
+ /** A slot for a new page under `key`: a free one, or the least recently drawn one not drawn this frame. Null when every slot is in use now. */
+ claim(key: string, min: number, max: number): Page | null {
+ let slot = this.free_.pop();
+ if (slot === undefined) {
+ let oldest: string | null = null, at = Infinity;
+ for (const [k, p] of this.pages_) if (p.used < this.clock_ && p.used < at) { at = p.used; oldest = k; }
+ if (oldest === null) return null;
+ slot = this.pages_.get(oldest)!.slot;
+ this.pages_.delete(oldest);
+ }
+ const page: Page = { slot, min, max, used: this.clock_ };
+ this.pages_.set(key, page);
+ return page;
+ }
+
+ /** Forgets every page (the device lost the atlas, or the ground changed). */
+ clear(): void {
+ this.pages_.clear();
+ this.free_.length = 0;
+ for (let s = this.capacity - 1; s >= 0; s--) this.free_.push(s);
+ }
+
+ /** Where a slot's page starts in the atlas, in texels. */
+ origin(slot: number): [number, number] {
+ return [(slot % this.perRow) * PAGE_SIDE, Math.floor(slot / this.perRow) * PAGE_SIDE];
+ }
+
+ get size(): number {
+ return this.pages_.size;
+ }
+}
diff --git a/sdk/src/terrain/patch.ts b/sdk/src/terrain/patch.ts
new file mode 100644
index 000000000..c88bf552d
--- /dev/null
+++ b/sdk/src/terrain/patch.ts
@@ -0,0 +1,43 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file patch.ts
+ * @brief The one patch every quadtree node of the ground is drawn with.
+ *
+ * @details A flat grid of `cells` by `cells` over 0 to 1 in x and z, its uv the same; its box runs 0 to 1 in y as well, because the
+ * Terrain shader lifts it to the node's page and the node's scale.y is its page's height range, so culling sees the ground's true box.
+ */
+import { MeshChannel, MeshChannelType, packChannels, type MeshData } from '../asset/meshFormat';
+
+export function buildPatchMesh(cells: number): MeshData {
+ const n = Math.max(1, Math.floor(cells));
+ const { channels, vertexStride } = packChannels([
+ { semantic: MeshChannel.Position, components: 3, type: MeshChannelType.Float32 },
+ { semantic: MeshChannel.TexCoord0, components: 2, type: MeshChannelType.Float32 },
+ { semantic: MeshChannel.Color, components: 4, type: MeshChannelType.UNorm8 },
+ { semantic: MeshChannel.Normal, components: 3, type: MeshChannelType.Float32 },
+ ]);
+ const count = (n + 1) * (n + 1);
+ const vertices = new Uint8Array(count * vertexStride);
+ const view = new DataView(vertices.buffer);
+ const [pos, uv, color, normal] = channels.map((c) => c.offset) as [number, number, number, number];
+ for (let j = 0; j <= n; j++) for (let i = 0; i <= n; i++) {
+ const base = (j * (n + 1) + i) * vertexStride, x = i / n, z = j / n;
+ view.setFloat32(base + pos, x, true);
+ view.setFloat32(base + pos + 4, 0, true);
+ view.setFloat32(base + pos + 8, z, true);
+ view.setFloat32(base + uv, x, true);
+ view.setFloat32(base + uv + 4, z, true);
+ for (let k = 0; k < 4; k++) view.setUint8(base + color + k, 255);
+ view.setFloat32(base + normal + 4, 1, true);
+ }
+ const indices = new Uint32Array(n * n * 6);
+ let at = 0;
+ for (let j = 0; j < n; j++) for (let i = 0; i < n; i++) {
+ const a = j * (n + 1) + i, b = a + 1, c = a + n + 1, d = c + 1;
+ // Facing up: a, then the next row, then the next column, runs counter-clockwise from above.
+ indices.set([a, c, b, b, c, d], at);
+ at += 6;
+ }
+ return { channels, vertexStride, vertexCount: count, vertices, indices, aabbMin: [0, 0, 0], aabbMax: [1, 1, 1] };
+}
diff --git a/sdk/src/terrain/quadtree.ts b/sdk/src/terrain/quadtree.ts
new file mode 100644
index 000000000..1e80dbc1c
--- /dev/null
+++ b/sdk/src/terrain/quadtree.ts
@@ -0,0 +1,94 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file quadtree.ts
+ * @brief Which squares of ground to draw, and how finely: a CDLOD quadtree round the eye.
+ *
+ * @details Every node is one square drawn with the same patch of `cells` by `cells`, so a node at level L has cells 2^L times the finest.
+ * Each level has a range: a node closer to the eye than the level below's range is split into its four children, so the
+ * ground is finest where it is near and coarsens with distance, level by level. The Terrain shader moves each vertex in the
+ * outer part of its level's range onto the grid of the level above (geomorphing), so where two levels meet their edges are the
+ * same line: no crack, no skirt, and nothing pops as the eye moves.
+ */
+
+/** One square of ground to draw: its level (0 the finest), its place in that level's grid, and its extent in the terrain's space. */
+export interface TerrainNode {
+ level: number;
+ ix: number;
+ iz: number;
+ x0: number;
+ z0: number;
+ size: number;
+}
+
+/** What the tree is cut by. */
+export interface QuadtreeParams {
+ /** The side of a level-0 node, in world units. */
+ leafSize: number;
+ /** How many levels there are: the top one's nodes are `leafSize * 2^(levels - 1)` across. */
+ levels: number;
+ /** The distance within which level 0 is drawn; each level's is twice the one below's. */
+ range0: number;
+ /** The area to draw, [minX, minZ, maxX, maxZ]; null draws the top level's nodes round the eye out to its range (an infinite ground). */
+ bounds: readonly [number, number, number, number] | null;
+ /** The least and most height the ground has: the vertical extent every node's box is measured with. */
+ minHeight: number;
+ maxHeight: number;
+}
+
+/** The range of level `level`: where its nodes end and the next level's begin. */
+export function levelRange(p: Pick<QuadtreeParams, 'range0'>, level: number): number {
+ return p.range0 * 2 ** level;
+}
+
+/**
+ * The nodes to draw for an eye at (ex, ey, ez), coarse to fine. Every place in the area (or within the top range of the eye, for an
+ * infinite ground) is covered by exactly one node.
+ */
+export function selectNodes(p: QuadtreeParams, ex: number, ey: number, ez: number): TerrainNode[] {
+ const out: TerrainNode[] = [];
+ const top = p.levels - 1;
+ const topSize = p.leafSize * 2 ** top;
+ let minX: number, minZ: number, maxX: number, maxZ: number;
+ if (p.bounds) {
+ [minX, minZ, maxX, maxZ] = p.bounds;
+ } else {
+ const reach = levelRange(p, top);
+ minX = ex - reach; maxX = ex + reach; minZ = ez - reach; maxZ = ez + reach;
+ }
+ const i0 = Math.floor(minX / topSize), i1 = Math.ceil(maxX / topSize) - 1;
+ const k0 = Math.floor(minZ / topSize), k1 = Math.ceil(maxZ / topSize) - 1;
+ for (let k = k0; k <= k1; k++) for (let i = i0; i <= i1; i++) visit(p, top, i, k, ex, ey, ez, out);
+ return out;
+}
+
+function visit(p: QuadtreeParams, level: number, ix: number, iz: number, ex: number, ey: number, ez: number, out: TerrainNode[]): void {
+ const size = p.leafSize * 2 ** level;
+ const x0 = ix * size, z0 = iz * size;
+ if (p.bounds && (x0 >= p.bounds[2] || z0 >= p.bounds[3] || x0 + size <= p.bounds[0] || z0 + size <= p.bounds[1])) return;
+ if (level === 0 || boxDistance(x0, z0, size, p.minHeight, p.maxHeight, ex, ey, ez) > levelRange(p, level - 1)) {
+ out.push({ level, ix, iz, x0, z0, size });
+ return;
+ }
+ for (let dz = 0; dz < 2; dz++) for (let dx = 0; dx < 2; dx++) visit(p, level - 1, ix * 2 + dx, iz * 2 + dz, ex, ey, ez, out);
+}
+
+/** How far the eye is from a node's box (its square, from the least to the most height). */
+export function boxDistance(x0: number, z0: number, size: number, y0: number, y1: number, ex: number, ey: number, ez: number): number {
+ const dx = Math.max(x0 - ex, 0, ex - (x0 + size));
+ const dz = Math.max(z0 - ez, 0, ez - (z0 + size));
+ const dy = Math.max(y0 - ey, 0, ey - y1);
+ return Math.hypot(dx, dy, dz);
+}
+
+/** The node one level up that holds this one. */
+export function parentOf(n: TerrainNode, leafSize: number): TerrainNode {
+ const level = n.level + 1, size = leafSize * 2 ** level;
+ const ix = Math.floor(n.ix / 2), iz = Math.floor(n.iz / 2);
+ return { level, ix, iz, x0: ix * size, z0: iz * size, size };
+}
+
+/** A node's key, for the pages and the pool. */
+export function nodeKey(level: number, ix: number, iz: number): string {
+ return `${level}:${ix}:${iz}`;
+}
diff --git a/sdk/src/terrain/source.ts b/sdk/src/terrain/source.ts
new file mode 100644
index 000000000..536204d86
--- /dev/null
+++ b/sdk/src/terrain/source.ts
@@ -0,0 +1,183 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file source.ts
+ * @brief Where the ground's height and paint come from: a field over an area, or noise that goes on for ever.
+ *
+ * @details The terrain draws from height pages (pages.ts) and answers the CPU (what stands on it, what floats over it) from the same
+ * numbers, so both ask one source. Positions are in the terrain's own space (its entity at the origin), heights in world units
+ * above it.
+ * - An area is a heightfield (a heightmap, or noise made once and worn by rain) over `sizeX` by `sizeZ`, painted by its splatmap
+ * or by height and slope, with dirt where the rain ran.
+ * - An infinite ground is noise read at any (x, z), so it never ends and the same seed is the same ground everywhere. Rain cannot
+ * be run over ground that has no edge, so its wear is the noise's own: each octave is damped where the octaves under it are
+ * already steep, which leaves smooth valleys between sharp ridges and gullies down the slopes.
+ */
+import { paintWeights, type TerrainData } from './terrainPlugin';
+import { sampleHeight, terrainNormal, type Heightfield } from './heightfield';
+
+/** The ground a terrain draws, as the pages and the CPU read it. */
+export interface TerrainSource {
+ /** Whether the ground goes on for ever (no edge to clip, no area to bake). */
+ readonly infinite: boolean;
+ /** The area the ground covers, [minX, minZ, maxX, maxZ] in the terrain's space; null for an infinite one. */
+ readonly bounds: readonly [number, number, number, number] | null;
+ /** The least and the most the height can be: what the pages encode their heights over. */
+ readonly minHeight: number;
+ readonly maxHeight: number;
+ /** The height at (x, z), or null off the area. */
+ height(x: number, z: number): number | null;
+ /** The weights of the four layers (grass, dirt, snow, rock) at (x, z), where the ground there is `h` high and faces `ny` up. */
+ paint(x: number, z: number, h: number, ny: number): [number, number, number, number];
+}
+
+/** The pixels of a splatmap, as the terrain read them. */
+export interface Splat { width: number; height: number; pixels: Uint8Array }
+
+/** An area's ground: a field of heights `height` tall, centred on the terrain, with its splatmap and where its rain ran. */
+export class FieldSource implements TerrainSource {
+ readonly infinite = false;
+ readonly bounds: readonly [number, number, number, number];
+ readonly minHeight = 0;
+ readonly maxHeight: number;
+
+ constructor(
+ readonly field: Heightfield,
+ private readonly data: Pick<TerrainData, 'sizeX' | 'sizeZ' | 'height' | 'rockSlope' | 'dirtHeight' | 'snowHeight'>,
+ private readonly splat: Splat | null,
+ private readonly flow: Float32Array | null,
+ ) {
+ this.bounds = [-data.sizeX / 2, -data.sizeZ / 2, data.sizeX / 2, data.sizeZ / 2];
+ this.maxHeight = data.height;
+ }
+
+ height(x: number, z: number): number | null {
+ const u = x / this.data.sizeX + 0.5, v = z / this.data.sizeZ + 0.5;
+ if (u < 0 || u > 1 || v < 0 || v > 1) return null;
+ return sampleHeight(this.field, u, v) * this.data.height;
+ }
+
+ /** The ground's normal at (x, z), or null off the area. */
+ normal(x: number, z: number): [number, number, number] | null {
+ const u = x / this.data.sizeX + 0.5, v = z / this.data.sizeZ + 0.5;
+ if (u < 0 || u > 1 || v < 0 || v > 1) return null;
+ return terrainNormal(this.field, u, v, this.data.sizeX, this.data.sizeZ, this.data.height);
+ }
+
+ paint(x: number, z: number, h: number, ny: number): [number, number, number, number] {
+ const u = Math.min(Math.max(x / this.data.sizeX + 0.5, 0), 1), v = Math.min(Math.max(z / this.data.sizeZ + 0.5, 0), 1);
+ let w = paintWeights(h / Math.max(this.data.height, 1e-6), ny, this.data);
+ const splat = this.splat;
+ if (splat) {
+ const sx = Math.round(u * (splat.width - 1)), sy = Math.round(v * (splat.height - 1));
+ const at = (sy * splat.width + sx) * 4;
+ const s: [number, number, number, number] = [splat.pixels[at]! / 255, splat.pixels[at + 1]! / 255, splat.pixels[at + 2]! / 255, splat.pixels[at + 3]! / 255];
+ const sum = s[0] + s[1] + s[2] + s[3];
+ if (sum > 0.001) w = [s[0] / sum, s[1] / sum, s[2] / sum, s[3] / sum];
+ }
+ if (this.flow) {
+ // Where the rain ran it took the grass and left dirt; snow and rock stay as they are.
+ const fx = Math.round(u * (this.field.width - 1)), fy = Math.round(v * (this.field.height - 1));
+ const channel = smooth(0.45, 0.85, this.flow[fy * this.field.width + fx]!) * 0.8 * w[0];
+ w = [w[0] - channel, w[1] + channel, w[2], w[3]];
+ }
+ return w;
+ }
+}
+
+/** What shapes an infinite ground: the noise's seed and scale, and how worn and how ridged it is. */
+export type NoiseParams = Pick<TerrainData, 'seed' | 'frequency' | 'octaves' | 'persistence' | 'ridged' | 'warp' | 'erosion' | 'sizeX' | 'height'
+ | 'rockSlope' | 'dirtHeight' | 'snowHeight'>;
+
+/**
+ * Ground that goes on for ever: fractal noise read at any point, `frequency` hills to every `sizeX` world units, `height` tall at most.
+ * `erosion` damps each octave by how steep the ones under it already are, which is what rain does to real ground.
+ */
+export class NoiseSource implements TerrainSource {
+ readonly infinite = true;
+ readonly bounds = null;
+ readonly minHeight = 0;
+ readonly maxHeight: number;
+
+ constructor(private readonly p: NoiseParams) {
+ this.maxHeight = p.height;
+ }
+
+ height(x: number, z: number): number {
+ return this.sample(x, z)[0] * this.p.height;
+ }
+
+ /** The normal at (x, z), from the noise's own slope. */
+ normal(x: number, z: number): [number, number, number] {
+ const [, dx, dz] = this.sample(x, z);
+ const sx = dx * this.p.height, sz = dz * this.p.height;
+ const len = Math.hypot(sx, 1, sz);
+ return [-sx / len, 1 / len, -sz / len];
+ }
+
+ paint(_x: number, _z: number, h: number, ny: number): [number, number, number, number] {
+ return paintWeights(h / Math.max(this.p.height, 1e-6), ny, this.p);
+ }
+
+ /** The height (0 to 1) at (x, z) and its slope along x and z, per world unit. */
+ sample(x: number, z: number): [number, number, number] {
+ const p = this.p;
+ const scale = Math.max(p.frequency, 1e-6) / Math.max(p.sizeX, 1e-6);
+ let u = x * scale, v = z * scale;
+ const warp = Math.min(Math.max(p.warp, 0), 1);
+ if (warp > 0) {
+ // Pushed about by noise of its own, up to half a hill: valleys wind and ridges bend.
+ u += (noised(u + 5.2, v + 1.3, p.seed + 7001)[0] * 2 - 1) * warp * 0.5;
+ v += (noised(u + 8.3, v + 2.8, p.seed + 7003)[0] * 2 - 1) * warp * 0.5;
+ }
+ const octaves = Math.max(1, Math.min(8, Math.floor(p.octaves)));
+ const wear = Math.min(Math.max(p.erosion, 0), 4);
+ let amp = 1, freq = 1, sum = 0, norm = 0, dx = 0, dz = 0;
+ // The slope the octaves so far have built up, which damps the ones that follow.
+ let gx = 0, gz = 0;
+ for (let o = 0; o < octaves; o++) {
+ const [n, nx, nz] = noised(u * freq, v * freq, p.seed + o * 101);
+ let value = n, ddx = nx * freq, ddz = nz * freq;
+ if (p.ridged > 0) {
+ // Folded about its middle, a sharp crest where it turns.
+ const s = n * 2 - 1, sign = s >= 0 ? 1 : -1;
+ value = n * (1 - p.ridged) + (1 - Math.abs(s)) * p.ridged;
+ ddx = ddx * (1 - p.ridged) - 2 * sign * ddx * p.ridged;
+ ddz = ddz * (1 - p.ridged) - 2 * sign * ddz * p.ridged;
+ }
+ gx += ddx * amp; gz += ddz * amp;
+ const damp = wear > 0 ? 1 / (1 + wear * (gx * gx + gz * gz) * 0.25) : 1;
+ sum += value * amp * damp;
+ dx += ddx * amp * damp; dz += ddz * amp * damp;
+ norm += amp;
+ amp *= p.persistence;
+ freq *= 2;
+ }
+ return [sum / norm, (dx / norm) * scale, (dz / norm) * scale];
+ }
+}
+
+/** A 32-bit integer hash, stable across hosts, so a seed makes the same ground everywhere. */
+function hash2(x: number, y: number, seed: number): number {
+ let h = (Math.imul(x, 374761393) + Math.imul(y, 668265263) + Math.imul(seed | 0, 2147483647)) | 0;
+ h = Math.imul(h ^ (h >>> 13), 1274126177);
+ h = (h ^ (h >>> 16)) >>> 0;
+ return h / 4294967295;
+}
+
+/** Value noise at (x, y), 0 to 1, and its derivatives along x and y. */
+export function noised(x: number, y: number, seed: number): [number, number, number] {
+ const ix = Math.floor(x), iy = Math.floor(y);
+ const fx = x - ix, fy = y - iy;
+ const sx = fx * fx * (3 - 2 * fx), sy = fy * fy * (3 - 2 * fy);
+ const dsx = 6 * fx * (1 - fx), dsy = 6 * fy * (1 - fy);
+ const a = hash2(ix, iy, seed), b = hash2(ix + 1, iy, seed);
+ const c = hash2(ix, iy + 1, seed), d = hash2(ix + 1, iy + 1, seed);
+ const k1 = b - a, k2 = c - a, k3 = a - b - c + d;
+ return [a + k1 * sx + k2 * sy + k3 * sx * sy, (k1 + k3 * sy) * dsx, (k2 + k3 * sx) * dsy];
+}
+
+function smooth(a: number, b: number, x: number): number {
+ const t = Math.min(Math.max((x - a) / (b - a || 1e-6), 0), 1);
+ return t * t * (3 - 2 * t);
+}
diff --git a/sdk/src/terrain/terrainPlugin.ts b/sdk/src/terrain/terrainPlugin.ts
index d7b189b64..c8535d2cf 100644
--- a/sdk/src/terrain/terrainPlugin.ts
+++ b/sdk/src/terrain/terrainPlugin.ts
@@ -2,58 +2,67 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
* @file terrainPlugin.ts
- * @brief Ground: a heightmap (or noise) cut into chunks that draw themselves at the detail their size on screen deserves.
+ * @brief Ground: a source of heights drawn as a CDLOD quadtree of one shared patch, its heights read from pages on the GPU.
*
- * @details The `Terrain` component says what the ground is; this builds it. The entity stays as authored and
- * the chunks are its children, spawned here and rebuilt whenever the component changes, so there is
- * nothing to bake and nothing to keep in step: edit a field and the ground follows.
- *
- * Each chunk is an ordinary MeshRenderer with an ordinary LODGroup (see mesh.ts for how a chunk and
- * its coarser levels are made), so culling, shadows, picking and the level-of-detail choice are the
- * engine's and need to know nothing about terrain. The chunks are built a few a frame, so a large
- * terrain appears over a moment instead of stalling one.
+ * @details The `Terrain` component says what the ground is: an area (a heightmap, or noise worn by rain) or ground without end (noise
+ * read anywhere). Its source (source.ts) answers the CPU, and the GPU draws it in pages (pages.ts): each quadtree node
+ * (quadtree.ts) round the eye is the same small patch, placed and sized by its instance, whose vertices the Terrain shader
+ * lifts from the node's page and slides onto the coarser grid toward the end of their level's range, so neighbouring levels
+ * meet without a crack. The nodes are ordinary MeshRenderers of one mesh and one material, which the renderer draws as instanced
+ * runs; pages are made a few a frame, coarse first, and a node whose page is not ready is drawn by an ancestor's.
*/
import type { App, Plugin } from '../app/app';
import { defineSystem, Schedule } from '../ecs/system';
import { defineResource } from '../ecs/resource';
import {
- defineComponent, getComponent, MeshRenderer, Transform,
- type ComponentDef, type MeshRendererData, type TransformData,
+ defineComponent, Camera, MeshRenderer, Transform,
+ type ComponentDef, type CameraData, type MeshRendererData, type TransformData,
} from '../ecs/component';
import { Assets } from '../asset/AssetPlugin';
+import type { MaterialShaderSource } from '../asset/loaders/MaterialShaderAssetLoader';
import { platformLoadImagePixels } from '../platform/base';
import { decodeImagePixels } from '../asset/imageDecode';
import { decodePngData } from '../asset/pngData';
+import { Material, MATERIAL_FORMAT_VERSION } from '../render/material';
+import { BlendMode } from '../render/blend';
+import { createTextureFromPixels, updateTextureSubregion } from '../runtime/runtimeAssets';
+import { getResourceManager, provideTextureContent, withdrawTextureContent } from '../wasm/resourceManager';
+import { TextureContent } from '../wasm';
+import { EditorView, editorViewEye } from '../camera/EditorView';
import { log } from '../util/logger';
import { bakesOf } from '../runtime/bakes';
import type { Color, Entity } from '../types';
-import {
- erosionJob, heightfieldFromPixels, proceduralHeightfield, sampleHeight, terrainNormal, type Heightfield,
-} from './heightfield';
-import { buildChunkMesh, chunkCenter, lodCount, type TerrainPaint, type TerrainShape } from './mesh';
+import { erosionJob, heightfieldFromPixels, proceduralHeightfield } from './heightfield';
+import { FieldSource, NoiseSource, type TerrainSource } from './source';
+import { levelRange, nodeKey, parentOf, selectNodes, type QuadtreeParams, type TerrainNode } from './quadtree';
+import { makePage, PageTable, PAGE_SIDE, PAGE_TEXELS, PATCH_CELLS } from './pages';
+import { buildPatchMesh } from './patch';
+
+/** How far the ground goes: an area of its own size, or for ever. */
+export const TerrainExtent = { Area: 0, Infinite: 1 } as const;
/** The fields of the `Terrain` component. @experimental */
export interface TerrainData {
+ /** {@link TerrainExtent}: an area `sizeX` by `sizeZ`, or ground that goes on for ever (noise read anywhere, the same for a seed). */
+ extent: number;
/** A heightmap image: red is the height (green, if it is not just grey, its low byte). Empty makes the ground from noise. */
heightmap: number;
/** An image whose four channels are the weights of the four layers; empty paints by height and slope. */
splatmap: number;
- /** A material on the Terrain shader. Empty draws the layer colours straight onto the ground. */
+ /** A material on the Terrain shader. Empty draws the layer colours onto the ground. */
material: number;
- /** World size along x and z; the terrain is centred on its entity. */
+ /** An area's size along x and z, centred on its entity; for ground without end, the span `frequency` hills are spread over. */
sizeX: number;
sizeZ: number;
/** World height of the highest ground. */
height: number;
- /** Chunks along each side. */
- chunks: number;
- /** Cells along a chunk's side at its finest level. */
- chunkCells: number;
- /** How many levels of detail each chunk has, 1 to 4. */
- lodLevels: number;
- /** Above 1, chunks keep their finer levels out to a greater distance. */
+ /** The finest cell of the ground's mesh, in world units: what it is drawn at near the eye. */
+ cellSize: number;
+ /** Above 1 the finest cells reach further out before the ground coarsens. */
detail: number;
- /** Noise ground: the seed, how many hills across, how many octaves, how rough, how ridged, and how many samples. */
+ /** How far ground without end is drawn. */
+ drawDistance: number;
+ /** Noise ground: the seed, how many hills across, how many octaves, how rough, how ridged, and (an area's) how many samples. */
seed: number;
frequency: number;
octaves: number;
@@ -62,7 +71,7 @@ export interface TerrainData {
resolution: number;
/** How far the noise is bent by noise of its own, 0 to 1: winding valleys and bent ridges instead of round hills. */
warp: number;
- /** How much rain wears the ground, 0 to 4 (a heightmap's too): gullies down the slopes, silt in the valleys, and dirt where the water ran. */
+ /** How much rain wears the ground, 0 to 4: an area is worn drop by drop (dirt where the water ran), ground without end by its noise. */
erosion: number;
/** Painting: how steep ground must be to turn to rock (0 flat, 1 sheer), and the heights, 0 to 1, where dirt and snow start. */
rockSlope: number;
@@ -78,38 +87,37 @@ export interface TerrainData {
const rgb = (r: number, g: number, b: number): Color => ({ r, g, b, a: 1 });
/**
- * The ground. Presence is the opt-in; its children are drawn at the detail their size on screen deserves.
+ * The ground. Presence is the opt-in; its children are the quadtree's nodes, drawn as instances of one patch.
*
* @experimental
*/
export const Terrain: ComponentDef<TerrainData> = defineComponent<TerrainData>('Terrain', {
- heightmap: 0, splatmap: 0, material: 0,
- sizeX: 1000, sizeZ: 1000, height: 150,
- chunks: 8, chunkCells: 32, lodLevels: 4, detail: 1,
+ extent: TerrainExtent.Area, heightmap: 0, splatmap: 0, material: 0,
+ sizeX: 1000, sizeZ: 1000, height: 150, cellSize: 2, detail: 1, drawDistance: 4000,
seed: 1, frequency: 3, octaves: 5, persistence: 0.5, ridged: 0.35, resolution: 257, warp: 0, erosion: 0,
rockSlope: 0.35, dirtHeight: 0.62, snowHeight: 0.88,
layerColor0: rgb(0.28, 0.46, 0.2), layerColor1: rgb(0.45, 0.36, 0.24), layerColor2: rgb(0.93, 0.95, 0.98), layerColor3: rgb(0.4, 0.38, 0.36),
}, {
assetFields: [{ field: 'heightmap', type: 'texture' }, { field: 'splatmap', type: 'texture' }, { field: 'material', type: 'material' }],
fields: {
- heightmap: { tooltip: 'A heightmap image: red is the height. Empty makes the ground from noise.', category: 'Shape' },
- splatmap: { tooltip: 'An image whose red, green, blue and alpha are the weights of grass, dirt, snow and rock.', category: 'Layers' },
+ extent: { enum: [{ label: 'Area', value: TerrainExtent.Area }, { label: 'Infinite', value: TerrainExtent.Infinite }], category: 'Shape', tooltip: 'An area of its own size, from a heightmap or noise; or ground that goes on for ever, from noise read anywhere (the same seed is the same ground).' },
+ heightmap: { tooltip: 'A heightmap image: red is the height. Empty makes the ground from noise.', category: 'Shape', shownWhen: { field: 'extent', values: [TerrainExtent.Area] } },
+ splatmap: { tooltip: 'An image whose red, green, blue and alpha are the weights of grass, dirt, snow and rock.', category: 'Layers', shownWhen: { field: 'extent', values: [TerrainExtent.Area] } },
material: { tooltip: 'A material on the Terrain shader. Empty draws the layer colours onto the ground.', category: 'Layers' },
- sizeX: { min: 1, category: 'Shape', tooltip: 'World size along x.' },
- sizeZ: { min: 1, category: 'Shape', tooltip: 'World size along z.' },
+ sizeX: { min: 1, category: 'Shape', tooltip: 'An area\'s size along x; for ground without end, the span its hills are spread over.' },
+ sizeZ: { min: 1, category: 'Shape', tooltip: 'An area\'s size along z.', shownWhen: { field: 'extent', values: [TerrainExtent.Area] } },
height: { min: 0, category: 'Shape', tooltip: 'World height of the highest ground.' },
- chunks: { min: 1, max: 64, step: 1, category: 'Detail', tooltip: 'Chunks along each side; each is drawn and culled on its own.' },
- chunkCells: { min: 2, max: 128, step: 1, category: 'Detail', tooltip: 'Cells along a chunk side at its finest level. A power of two keeps the levels clean.' },
- lodLevels: { min: 1, max: 4, step: 1, category: 'Detail', tooltip: 'Levels of detail per chunk, each half as fine as the one before.' },
- detail: { min: 0.1, max: 8, step: 0.1, category: 'Detail', tooltip: 'Above 1 the finer levels are kept out to a greater distance.' },
+ cellSize: { min: 0.01, category: 'Detail', tooltip: 'The finest cell of the ground\'s mesh, in world units: what it is drawn at near the eye. Further off the cells double, level by level.' },
+ detail: { min: 0.25, max: 8, step: 0.05, category: 'Detail', tooltip: 'Above 1 the finest cells reach further out before the ground coarsens.' },
+ drawDistance: { min: 1, category: 'Detail', tooltip: 'How far ground without end is drawn.', shownWhen: { field: 'extent', values: [TerrainExtent.Infinite] } },
seed: { step: 1, category: 'Noise', tooltip: 'Another seed is another ground.' },
- frequency: { min: 0.1, max: 32, step: 0.1, category: 'Noise', tooltip: 'How many hills across the terrain.' },
+ frequency: { min: 0.1, max: 32, step: 0.1, category: 'Noise', tooltip: 'How many hills across the terrain (or across sizeX, for ground without end).' },
octaves: { min: 1, max: 8, step: 1, category: 'Noise', tooltip: 'Layers of detail in the noise.' },
persistence: { min: 0, max: 1, step: 0.01, category: 'Noise', tooltip: 'How much of its height each finer layer keeps. Lower is smoother.' },
ridged: { min: 0, max: 1, step: 0.01, category: 'Noise', tooltip: '0 is rolling hills; 1 is sharp ridges.' },
- resolution: { min: 17, max: 2049, step: 1, category: 'Noise', tooltip: 'Samples along each side of the noise ground.' },
+ resolution: { min: 17, max: 2049, step: 1, category: 'Noise', tooltip: 'Samples along each side of an area\'s noise ground.', shownWhen: { field: 'extent', values: [TerrainExtent.Area] } },
warp: { min: 0, max: 1, step: 0.01, category: 'Noise', tooltip: 'How far the noise is bent by noise of its own: winding valleys and bent ridges instead of round hills.' },
- erosion: { min: 0, max: 4, step: 0.05, category: 'Shape', tooltip: 'How much rain wears the ground (a heightmap\'s too): gullies down the slopes, silt in the valleys, and dirt painted where the water ran. 0 leaves it as made.' },
+ erosion: { min: 0, max: 4, step: 0.05, category: 'Shape', tooltip: 'How much rain wears the ground: an area (a heightmap\'s too) drop by drop, with dirt where the water ran; ground without end by its noise. 0 leaves it as made.' },
rockSlope: { min: 0, max: 1, step: 0.01, category: 'Layers', tooltip: 'How steep ground must be to turn to rock. 0 is flat, 1 is sheer.' },
dirtHeight: { min: 0, max: 1, step: 0.01, category: 'Layers', tooltip: 'The height, as a share of the terrain, where grass gives way to dirt.' },
snowHeight: { min: 0, max: 1, step: 0.01, category: 'Layers', tooltip: 'The height, as a share of the terrain, where snow begins.' },
@@ -125,7 +133,7 @@ const smooth = (a: number, b: number, x: number): number => {
return t * t * (3 - 2 * t);
};
-/** The weights of grass, dirt, snow and rock at a point of ground, by how high and how steep it is. */
+/** The weights of grass, dirt, snow and rock at a point of ground, by how high (0 to 1 of the terrain) and how steep it is. */
export function paintWeights(h: number, ny: number, t: Pick<TerrainData, 'rockSlope' | 'dirtHeight' | 'snowHeight'>): [number, number, number, number] {
const rock = smooth(t.rockSlope - 0.08, t.rockSlope + 0.08, 1 - ny);
const snow = smooth(t.snowHeight - 0.06, t.snowHeight + 0.06, h) * (1 - rock * 0.85);
@@ -135,50 +143,52 @@ export function paintWeights(h: number, ny: number, t: Pick<TerrainData, 'rockSl
return [grass / sum, dirt / sum, snow / sum, rock / sum];
}
+/** The side of the atlases the pages are kept in, in texels: 900 pages of 67 by 67. */
+const ATLAS_SIZE = 2048;
+/** How long a frame may spend making pages, in milliseconds; at least one is made a frame while any is wanted. */
+const PAGE_BUDGET_MS = 5;
+
/** What the plugin knows about one terrain it has built. */
interface Built {
signature: string;
- field: Heightfield | null;
data: TerrainData;
- handles: number[];
- chunks: Entity[];
- queue: [number, number][];
- splat: { width: number; height: number; pixels: Uint8Array } | null;
- /** Where the rain ran when the ground was worn (erodeHeightfield), 0 to 1 per sample of the field; null when it was not. */
- flow: Float32Array | null;
- materialHandle: number;
+ source: TerrainSource | null;
/** Bumped on every rebuild so an answer that arrives for an older one is thrown away. */
epoch: number;
loading: boolean;
- /** The chunks to build in all, for the progress shown while they are; and the erosion in hand, to stop if the terrain is rebuilt. */
- total: number;
+ /** The erosion in hand, to stop if the terrain is rebuilt. */
cancel: (() => void) | null;
+ table: PageTable;
+ heights: number;
+ paint: number;
+ mesh: number;
+ instance: number;
+ /** The nodes drawn now, by key, and spare ones to place again. */
+ nodes: Map<string, Entity>;
+ spare: Entity[];
+ /** Pages wanted and not made yet, by key. */
+ wanted: Map<string, TerrainNode>;
+ pending: boolean;
}
-/** How long a frame may spend building chunks, in milliseconds: a terrain appears quickly, and no frame is a stall. At least one is built a frame. */
-const CHUNK_BUDGET_MS = 6;
-
/** Run-time access to the ground: how high it is anywhere, for putting things on it. */
export class Terrains {
/** @internal */ readonly built_ = new Map<Entity, Built>();
/** @internal */ app_: App | null = null;
/**
- * The world height of the ground at (x, z), or null where no terrain is. The terrain's own position and
- * uniform scale are taken into account; a rotation about y is not.
+ * The world height of the ground at (x, z), or null where no terrain is. The terrain's own position is taken into account; its
+ * rotation and scale are not (a terrain is laid flat at its own size).
*/
heightAt(x: number, z: number): number | null {
const world = this.app_?.world;
if (!world) return null;
for (const [entity, built] of this.built_) {
- if (!built.field || !world.valid(entity)) continue;
+ if (!built.source || !world.valid(entity)) continue;
const t = world.tryGet(entity, Transform) as TransformData | null;
if (!t) continue;
- const sx = t.worldScale.x || 1, sz = t.worldScale.z || 1, sy = t.worldScale.y || 1;
- const u = (x - t.worldPosition.x) / (built.data.sizeX * sx) + 0.5;
- const v = (z - t.worldPosition.z) / (built.data.sizeZ * sz) + 0.5;
- if (u < 0 || u > 1 || v < 0 || v > 1) continue;
- return t.worldPosition.y + sampleHeight(built.field, u, v) * built.data.height * sy;
+ const h = built.source.height(x - t.worldPosition.x, z - t.worldPosition.z);
+ if (h !== null) return t.worldPosition.y + h;
}
return null;
}
@@ -188,14 +198,15 @@ export class Terrains {
const world = this.app_?.world;
if (!world) return null;
for (const [entity, built] of this.built_) {
- if (!built.field || !world.valid(entity)) continue;
+ const source = built.source;
+ if (!source || !world.valid(entity)) continue;
const t = world.tryGet(entity, Transform) as TransformData | null;
if (!t) continue;
- const sx = t.worldScale.x || 1, sz = t.worldScale.z || 1, sy = t.worldScale.y || 1;
- const u = (x - t.worldPosition.x) / (built.data.sizeX * sx) + 0.5;
- const v = (z - t.worldPosition.z) / (built.data.sizeZ * sz) + 0.5;
- if (u < 0 || u > 1 || v < 0 || v > 1) continue;
- return terrainNormal(built.field, u, v, built.data.sizeX * sx, built.data.sizeZ * sz, built.data.height * sy);
+ const lx = x - t.worldPosition.x, lz = z - t.worldPosition.z;
+ if (source instanceof FieldSource || source instanceof NoiseSource) {
+ const n = source.normal(lx, lz);
+ if (n) return n;
+ }
}
return null;
}
@@ -203,16 +214,16 @@ export class Terrains {
/** @internal Bumped whenever a terrain's ground changes, so what stands on it knows to stand again. */
revision_ = 0;
- /** Whether any terrain is still reading its images: its ground is not known yet. */
+ /** Whether any terrain is still reading its images or wearing its ground: its heights are not known yet. */
get loading(): boolean {
for (const b of this.built_.values()) if (b.loading) return true;
return false;
}
- /** How many chunks across every terrain are still waiting to be built. */
+ /** How many pages every terrain still wants made for what is in view. */
get pending(): number {
let n = 0;
- for (const b of this.built_.values()) n += b.queue.length + (b.loading ? 1 : 0);
+ for (const b of this.built_.values()) n += b.wanted.size + (b.loading ? 1 : 0);
return n;
}
}
@@ -220,20 +231,18 @@ export class Terrains {
/** The resource the plugin installs. @experimental */
export const TerrainsRes = defineResource<Terrains>(new Terrains(), 'Terrains');
+/** What, changed, rebuilds the ground: everything but the colours and the detail, which are written each frame. */
function signatureOf(data: TerrainData): string {
- return JSON.stringify(data);
-}
-
-function shapeOf(data: TerrainData): TerrainShape {
- return {
- sizeX: Math.max(1, data.sizeX), sizeZ: Math.max(1, data.sizeZ), height: Math.max(0, data.height),
- chunks: Math.min(64, Math.max(1, Math.floor(data.chunks))), chunkCells: Math.min(128, Math.max(2, Math.floor(data.chunkCells))),
- };
+ const { layerColor0: _a, layerColor1: _b, layerColor2: _c, layerColor3: _d, detail: _e, drawDistance: _f, ...shape } = data;
+ return JSON.stringify(shape);
}
export class TerrainPlugin implements Plugin {
name = 'terrain';
+ /** The stock material a terrain with none of its own is an instance of. */
+ private stock_ = 0;
+
build(app: App): void {
const terrains = new Terrains();
terrains.app_ = app;
@@ -249,21 +258,21 @@ export class TerrainPlugin implements Plugin {
if (!built || built.signature !== signature) {
if (built) this.destroy(app, built);
built = {
- signature, field: null, data: { ...data }, handles: [], chunks: [], queue: [], splat: null, flow: null,
- materialHandle: data.material, epoch: (built?.epoch ?? 0) + 1, loading: true, total: 0, cancel: null,
+ signature, data: { ...data }, source: null, epoch: (built?.epoch ?? 0) + 1, loading: true, cancel: null,
+ table: new PageTable(ATLAS_SIZE), heights: 0, paint: 0, mesh: 0, instance: 0,
+ nodes: new Map(), spare: [], wanted: new Map(), pending: false,
};
terrains.built_.set(entity, built);
void this.load(app, entity, built);
continue;
}
- if (built.loading) continue;
- const until = performance.now() + CHUNK_BUDGET_MS;
- while (built.queue.length > 0) {
- const [cx, cz] = built.queue.shift()!;
- this.buildChunk(app, entity, built, cx, cz);
- if (performance.now() >= until) break;
+ built.data = { ...data };
+ if (built.loading || !built.source) continue;
+ if (!built.instance) {
+ if (!built.pending) void this.prepare(app, built);
+ continue;
}
- bakesOf(app).mark(built, 'Building the terrain', built.total ? 1 - built.queue.length / built.total : 1);
+ this.draw(app, entity, built);
}
}, { name: 'TerrainSystem' }));
}
@@ -273,59 +282,42 @@ export class TerrainPlugin implements Plugin {
const terrains = app.getResource(TerrainsRes);
for (const built of terrains.built_.values()) this.destroy(app, built);
terrains.built_.clear();
+ if (this.stock_) Material.release(this.stock_);
+ this.stock_ = 0;
}
- /** Reads the images the terrain names (or makes the noise), then queues its chunks. */
+ /** Reads the images the terrain names (or makes its noise, and wears it), and makes its source. */
private async load(app: App, entity: Entity, built: Built): Promise<void> {
const epoch = built.epoch;
- const assets = app.getResource(Assets);
const data = built.data;
- const pixelsOf = async (handle: number): Promise<{ width: number; height: number; pixels: Uint8Array } | null> => {
- if (!handle) return null;
- const path = assets.pathForHandle('texture', handle);
- if (!path) { log.warn('terrain', `no source image is known for texture ${handle}; the terrain falls back to its noise`); return null; }
- try {
- // The bytes the asset layer would load, decoded unmodified (no premultiply, no colour conversion): a height is data.
- // A PNG is read as stored first: through a canvas, a splatmap's zero alpha erased the other three weights.
- if (typeof createImageBitmap === 'function' && typeof Blob !== 'undefined') {
- const bytes = new Uint8Array(await assets.fetchBinary(path));
- return await decodePngData(bytes) ?? await decodeImagePixels(new Blob([bytes]));
- }
- const image = await platformLoadImagePixels(assets.resolveLoadPath(path));
- return { width: image.width, height: image.height, pixels: image.pixels };
- } catch (e) {
- log.warn('terrain', `reading ${path} failed`, e);
- return null;
- }
- };
try {
- const height = await pixelsOf(data.heightmap);
- const splat = await pixelsOf(data.splatmap);
- if (built.epoch !== epoch || !app.world.valid(entity)) return;
- const made = height
- ? heightfieldFromPixels(height.width, height.height, height.pixels)
- : proceduralHeightfield({
- resolution: Math.min(2049, Math.max(17, Math.floor(data.resolution))), seed: data.seed, frequency: data.frequency,
- octaves: data.octaves, persistence: data.persistence, ridged: data.ridged, warp: data.warp,
- });
- if (data.erosion > 0) {
- // Rain over a big field is seconds of work: it is spread over frames, and shown while it runs.
- const job = bakesOf(app).run('Eroding the terrain',
- erosionJob(made, { amount: data.erosion, seed: data.seed, sizeX: data.sizeX, sizeZ: data.sizeZ, height: data.height }));
- built.cancel = job.cancel;
- const worn = await job.done;
- built.cancel = null;
- if (built.epoch !== epoch || !app.world.valid(entity)) return;
- built.field = worn.field;
- built.flow = worn.flow;
+ if (data.extent === TerrainExtent.Infinite) {
+ built.source = new NoiseSource(data);
} else {
- built.field = made;
+ const height = await this.pixelsOf(app, data.heightmap);
+ const splat = await this.pixelsOf(app, data.splatmap);
+ if (built.epoch !== epoch || !app.world.valid(entity)) return;
+ const made = height
+ ? heightfieldFromPixels(height.width, height.height, height.pixels)
+ : proceduralHeightfield({
+ resolution: Math.min(2049, Math.max(17, Math.floor(data.resolution))), seed: data.seed, frequency: data.frequency,
+ octaves: data.octaves, persistence: data.persistence, ridged: data.ridged, warp: data.warp,
+ });
+ let field = made, flow: Float32Array | null = null;
+ if (data.erosion > 0) {
+ // Rain over a big field is seconds of work: it is spread over frames, and shown while it runs.
+ const job = bakesOf(app).run('Eroding the terrain',
+ erosionJob(made, { amount: data.erosion, seed: data.seed, sizeX: data.sizeX, sizeZ: data.sizeZ, height: data.height }));
+ built.cancel = job.cancel;
+ const worn = await job.done;
+ built.cancel = null;
+ if (built.epoch !== epoch || !app.world.valid(entity)) return;
+ field = worn.field;
+ flow = worn.flow;
+ }
+ built.source = new FieldSource(field, data, splat, flow);
}
- built.splat = splat;
app.getResource(TerrainsRes).revision_++;
- const shape = shapeOf(data);
- for (let cz = 0; cz < shape.chunks; cz++) for (let cx = 0; cx < shape.chunks; cx++) built.queue.push([cx, cz]);
- built.total = built.queue.length;
} catch (e) {
log.error('terrain', 'building the terrain failed', e);
} finally {
@@ -333,91 +325,242 @@ export class TerrainPlugin implements Plugin {
}
}
- private paintFor(built: Built): TerrainPaint {
- const data = built.data;
- const colors = [data.layerColor0, data.layerColor1, data.layerColor2, data.layerColor3];
- const splat = built.splat;
- const flow = built.flow, field = built.field;
- const textured = built.materialHandle !== 0;
- return (u, v, h, ny) => {
- let w = paintWeights(h, ny, data);
- if (splat) {
- const x = Math.min(splat.width - 1, Math.max(0, Math.round(u * (splat.width - 1))));
- const y = Math.min(splat.height - 1, Math.max(0, Math.round(v * (splat.height - 1))));
- const at = (y * splat.width + x) * 4;
- const s: [number, number, number, number] = [splat.pixels[at]! / 255, splat.pixels[at + 1]! / 255, splat.pixels[at + 2]! / 255, splat.pixels[at + 3]! / 255];
- const sum = s[0] + s[1] + s[2] + s[3];
- if (sum > 0.001) w = [s[0] / sum, s[1] / sum, s[2] / sum, s[3] / sum];
- }
- if (flow && field) {
- // Where the rain ran it took the grass and left dirt; snow and rock stay as they are.
- const x = Math.min(field.width - 1, Math.max(0, Math.round(u * (field.width - 1))));
- const y = Math.min(field.height - 1, Math.max(0, Math.round(v * (field.height - 1))));
- const channel = smooth(0.45, 0.85, flow[y * field.width + x]!) * 0.8 * w[0];
- w = [w[0] - channel, w[1] + channel, w[2], w[3]];
+ private async pixelsOf(app: App, handle: number): Promise<{ width: number; height: number; pixels: Uint8Array } | null> {
+ if (!handle) return null;
+ const assets = app.getResource(Assets);
+ const path = assets.pathForHandle('texture', handle);
+ if (!path) { log.warn('terrain', `no source image is known for texture ${handle}; the terrain falls back to its noise`); return null; }
+ try {
+ // The bytes the asset layer would load, decoded unmodified (no premultiply, no colour conversion): a height is data.
+ if (typeof createImageBitmap === 'function' && typeof Blob !== 'undefined') {
+ const bytes = new Uint8Array(await assets.fetchBinary(path));
+ return await decodePngData(bytes) ?? await decodeImagePixels(new Blob([bytes]));
}
- // A material reads the weights; with none the colours are mixed here and the ground is drawn in them.
- if (textured) return w;
- return [
- w[0] * colors[0]!.r + w[1] * colors[1]!.r + w[2] * colors[2]!.r + w[3] * colors[3]!.r,
- w[0] * colors[0]!.g + w[1] * colors[1]!.g + w[2] * colors[2]!.g + w[3] * colors[3]!.g,
- w[0] * colors[0]!.b + w[1] * colors[1]!.b + w[2] * colors[2]!.b + w[3] * colors[3]!.b,
- 1,
- ];
- };
+ const image = await platformLoadImagePixels(assets.resolveLoadPath(path));
+ return { width: image.width, height: image.height, pixels: image.pixels };
+ } catch (e) {
+ log.warn('terrain', `reading ${path} failed`, e);
+ return null;
+ }
}
- private buildChunk(app: App, parent: Entity, built: Built, cx: number, cz: number): void {
- const world = app.world;
- if (!built.field || !world.valid(parent)) return;
- const assets = app.getResource(Assets);
- const shape = shapeOf(built.data);
- const levels = lodCount(shape, Math.min(4, Math.max(1, Math.floor(built.data.lodLevels))));
- const paint = this.paintFor(built);
- const handles: number[] = [];
- for (let lod = 0; lod < levels; lod++) {
- const handle = assets.createMesh(buildChunkMesh(built.field, shape, cx, cz, lod, paint));
- if (handle === 0) {
- log.warn('terrain', `the engine refused the geometry of chunk ${cx},${cz} at level ${lod}`);
- for (const h of handles) assets.releaseBuiltMesh(h);
+ /** The stock material: the Terrain shader, compiled once. */
+ private async stock(app: App): Promise<number> {
+ if (this.stock_) return this.stock_;
+ const source = await app.getResource(Assets).load<MaterialShaderSource>('material-shader', 'builtin:terrain');
+ const shader = source.compile([]);
+ if (this.stock_) return this.stock_;
+ this.stock_ = Material.createFromAsset({
+ version: MATERIAL_FORMAT_VERSION, type: 'material', shader: 'builtin:terrain', blendMode: BlendMode.None,
+ depthTest: true, depthWrite: true, cull: 0, properties: {},
+ }, shader);
+ return this.stock_;
+ }
+
+ /** Makes what the ground is drawn with: the patch, the atlases and an instance of its material. */
+ private async prepare(app: App, built: Built): Promise<void> {
+ built.pending = true;
+ const epoch = built.epoch;
+ try {
+ const material = built.data.material || await this.stock(app);
+ if (built.epoch !== epoch) return;
+ const assets = app.getResource(Assets);
+ built.mesh = assets.createMesh(buildPatchMesh(PATCH_CELLS));
+ const blank = new Uint8Array(ATLAS_SIZE * ATLAS_SIZE * 4);
+ const params = { filterMode: 'linear', wrapMode: 'clamp', srgb: false } as const;
+ built.heights = createTextureFromPixels(app.wasmModule, { width: ATLAS_SIZE, height: ATLAS_SIZE, pixels: blank }, TextureContent.Transient, false, params);
+ built.paint = createTextureFromPixels(app.wasmModule, { width: ATLAS_SIZE, height: ATLAS_SIZE, pixels: blank }, TextureContent.Transient, false, params);
+ // A device that lost the atlases has lost every page in them: they are made again as they are wanted.
+ for (const handle of [built.heights, built.paint]) {
+ provideTextureContent(handle, () => { built.table.clear(); return true; });
+ }
+ built.instance = Material.createInstance(material);
+ if (!built.mesh || !built.heights || !built.paint || !built.instance) {
+ log.warn('terrain', 'the engine refused the terrain\'s mesh, atlases or material');
return;
}
- handles.push(handle);
+ const set = (name: string, value: Parameters<typeof Material.setUniform>[2]): void => { Material.setUniform(built.instance, name, value); };
+ set('u_heightPages', Material.tex(built.heights));
+ set('u_paintPages', Material.tex(built.paint));
+ set('u_terrainPages', 1);
+ set('u_atlasTexels', ATLAS_SIZE);
+ set('u_pageTexels', PAGE_TEXELS);
+ set('u_patchCells', PATCH_CELLS);
+ } catch (e) {
+ log.error('terrain', 'preparing the terrain failed', e);
+ } finally {
+ built.pending = false;
+ }
+ }
+
+ /** Where the eye is, in the terrain's space: the active camera, or the editor's own eye while it looks at the scene in 3D. */
+ private eye(app: App, t: TransformData): [number, number, number] | null {
+ if (app.hasResource(EditorView)) {
+ const view = app.getResource(EditorView);
+ if (view.active && view.perspective) {
+ const e = editorViewEye(view);
+ return [e.x - t.worldPosition.x, e.y - t.worldPosition.y, e.z - t.worldPosition.z];
+ }
+ }
+ for (const entity of app.world.getEntitiesWithComponents([Camera, Transform])) {
+ if (!(app.world.get(entity, Camera) as CameraData).isActive) continue;
+ const c = app.world.get(entity, Transform) as TransformData;
+ return [c.worldPosition.x - t.worldPosition.x, c.worldPosition.y - t.worldPosition.y, c.worldPosition.z - t.worldPosition.z];
+ }
+ return null;
+ }
+
+ /** The quadtree's cut for this terrain: leaf nodes a patch of the finest cells, ranges doubling, enough levels to cover it. */
+ private treeOf(built: Built, source: TerrainSource): QuadtreeParams {
+ const d = built.data;
+ const leafSize = PATCH_CELLS * Math.max(d.cellSize, 1e-3);
+ const range0 = leafSize * 2.5 * Math.max(d.detail, 0.25);
+ const reach = source.bounds ? Math.max(source.bounds[2] - source.bounds[0], source.bounds[3] - source.bounds[1]) : Math.max(d.drawDistance, leafSize);
+ let levels = 1;
+ while (levels < 16 && (source.bounds ? leafSize * 2 ** (levels - 1) < reach : levelRange({ range0 }, levels - 1) < reach)) levels++;
+ return { leafSize, levels, range0, bounds: source.bounds, minHeight: source.minHeight, maxHeight: source.maxHeight };
+ }
+
+ /** Chooses the nodes for the eye, makes the pages they want within the budget, and places the nodes. */
+ private draw(app: App, entity: Entity, built: Built): void {
+ const source = built.source!;
+ const t = app.world.get(entity, Transform) as TransformData;
+ const eye = this.eye(app, t);
+ const tree = this.treeOf(built, source);
+ const eyeAt = eye ?? [0, source.maxHeight, 0];
+ const chosen = selectNodes(tree, eyeAt[0], eyeAt[1], eyeAt[2]);
+ const table = built.table;
+ table.tick();
+
+ // Each node is drawn by its own page, or by its nearest ancestor that has one; a node under an ancestor drawn instead is not.
+ built.wanted.clear();
+ const drawn = new Map<string, TerrainNode>();
+ const covered = new Set<string>();
+ for (const node of chosen) {
+ let n: TerrainNode | null = node;
+ const own = nodeKey(node.level, node.ix, node.iz);
+ if (!table.get(own)) built.wanted.set(own, node);
+ while (n && !table.get(nodeKey(n.level, n.ix, n.iz))) {
+ n = n.level + 1 < tree.levels ? parentOf(n, tree.leafSize) : null;
+ if (n && !table.get(nodeKey(n.level, n.ix, n.iz))) built.wanted.set(nodeKey(n.level, n.ix, n.iz), n);
+ }
+ if (!n) continue;
+ const key = nodeKey(n.level, n.ix, n.iz);
+ if (n !== node) covered.add(key);
+ drawn.set(key, n);
+ }
+ for (const [key, n] of drawn) {
+ // A node whose ancestor is drawn in its place is left out: the ancestor covers it.
+ for (let up = n; up.level + 1 < tree.levels;) {
+ up = parentOf(up, tree.leafSize);
+ if (covered.has(nodeKey(up.level, up.ix, up.iz))) { drawn.delete(key); break; }
+ }
+ }
+ this.makePages(app, built, source, tree, eyeAt);
+
+ const set = (name: string, value: Parameters<typeof Material.setUniform>[2]): void => { Material.setUniform(built.instance, name, value); };
+ set('u_heightRange', { x: source.minHeight, y: Math.max(source.maxHeight - source.minHeight, 1e-6) });
+ set('u_lodRange0', tree.range0);
+ set('u_terrainOrigin', { x: t.worldPosition.x, y: t.worldPosition.y, z: t.worldPosition.z, w: 0 });
+ const b = source.bounds;
+ set('u_terrainBounds', b ? { x: b[0], y: b[1], z: b[2], w: b[3] } : { x: -1e9, y: -1e9, z: 1e9, w: 1e9 });
+ if (!built.data.material) {
+ const d = built.data;
+ for (const [i, c] of [d.layerColor0, d.layerColor1, d.layerColor2, d.layerColor3].entries()) set(`u_tint${i}`, { x: c.r, y: c.g, z: c.b, w: c.a });
}
- built.handles.push(...handles);
- const [x, z] = chunkCenter(shape, cx, cz);
- const chunk = world.spawn(`TerrainChunk ${cx},${cz}`);
- world.insert(chunk, Transform, { position: { x, y: 0, z } });
- world.insert(chunk, MeshRenderer, {
- mesh: handles[0]!, material: built.materialHandle, lit: true, opaque: true, cullBackfaces: false,
- color: { r: 1, g: 1, b: 1, a: 1 },
- } as Partial<MeshRendererData>);
- const lodDef = getComponent('LODGroup');
- if (lodDef && handles.length > 1) {
- const k = 1 / Math.max(0.1, built.data.detail);
- world.insert(chunk, lodDef, {
- lod1: handles[1] ?? 0, lod2: handles[2] ?? 0, lod3: handles[3] ?? 0,
- lod1Size: 0.2 * k, lod2Size: 0.09 * k, lod3Size: 0.04 * k, cullSize: 0, hysteresis: 0.1, enabled: true,
- });
+ this.place(app, entity, built, drawn);
+ }
+
+ /** Makes the wanted pages, coarse and near first, for as long as the frame can spare. */
+ private makePages(app: App, built: Built, source: TerrainSource, tree: QuadtreeParams, eye: [number, number, number]): void {
+ const bakes = bakesOf(app);
+ if (built.wanted.size === 0) { bakes.mark(built, 'Building the terrain', 1); return; }
+ const order = [...built.wanted.values()].sort((a, b) => b.level - a.level
+ || Math.hypot(a.x0 + a.size / 2 - eye[0], a.z0 + a.size / 2 - eye[2]) - Math.hypot(b.x0 + b.size / 2 - eye[0], b.z0 + b.size / 2 - eye[2]));
+ const until = performance.now() + PAGE_BUDGET_MS;
+ let made = 0;
+ for (const node of order) {
+ const key = nodeKey(node.level, node.ix, node.iz);
+ const image = makePage(source, node.x0, node.z0, node.size);
+ const page = built.table.claim(key, image.min, image.max);
+ if (!page) break;
+ const [ox, oy] = built.table.origin(page.slot);
+ updateTextureSubregion(app.wasmModule, built.heights, ox, oy, PAGE_SIDE, PAGE_SIDE, image.heights);
+ updateTextureSubregion(app.wasmModule, built.paint, ox, oy, PAGE_SIDE, PAGE_SIDE, image.paint);
+ built.wanted.delete(key);
+ made++;
+ if (performance.now() >= until) break;
+ }
+ bakes.mark(built, 'Building the terrain', made === 0 ? 0 : 1 - built.wanted.size / (built.wanted.size + made));
+ void tree;
+ }
+
+ /** Puts a node entity on each node drawn (reusing the ones it had), and takes the rest away. */
+ private place(app: App, entity: Entity, built: Built, drawn: Map<string, TerrainNode>): void {
+ const world = app.world;
+ for (const [key, e] of built.nodes) {
+ if (drawn.has(key)) continue;
+ built.nodes.delete(key);
+ if (!world.valid(e)) continue;
+ const mr = world.get(e, MeshRenderer) as MeshRendererData;
+ if (mr.enabled) world.insert(e, MeshRenderer, { ...mr, enabled: false });
+ built.spare.push(e);
+ }
+ for (const [key, n] of drawn) {
+ const page = built.table.get(key)!;
+ built.table.touch(key);
+ let e = built.nodes.get(key);
+ if (e === undefined || !world.valid(e)) {
+ e = built.spare.pop();
+ if (e === undefined || !world.valid(e)) {
+ e = world.spawn('TerrainNode');
+ world.insert(e, Transform, {});
+ world.setParent(e, entity);
+ }
+ built.nodes.set(key, e);
+ }
+ const [ox, oy] = built.table.origin(page.slot);
+ // The tint names the page and the level (see the Terrain shader's hook): every channel above zero, as the hook divides by it.
+ const color = { r: (ox + 0.5) / ATLAS_SIZE, g: (oy + 0.5) / ATLAS_SIZE, b: (n.level + 1) / 64, a: 1 };
+ const position = { x: n.x0, y: page.min, z: n.z0 };
+ const scale = { x: n.size, y: Math.max(page.max - page.min, 1e-3), z: n.size };
+ const t = world.get(e, Transform) as TransformData;
+ if (t.position.x !== position.x || t.position.y !== position.y || t.position.z !== position.z || t.scale.x !== scale.x || t.scale.y !== scale.y) {
+ world.insert(e, Transform, { ...t, position, scale });
+ }
+ const mr = world.tryGet(e, MeshRenderer) as MeshRendererData | null;
+ if (!mr || !mr.enabled || mr.color.r !== color.r || mr.color.g !== color.g || mr.color.b !== color.b || mr.material !== built.instance) {
+ world.insert(e, MeshRenderer, {
+ ...(mr ?? {}), mesh: built.mesh, material: built.instance, lit: true, opaque: true, cullBackfaces: true, color, enabled: true,
+ } as Partial<MeshRendererData>);
+ }
}
- world.setParent(chunk, parent);
- built.chunks.push(chunk);
}
private destroy(app: App, built: Built): void {
built.epoch++;
- built.queue.length = 0;
built.cancel?.();
built.cancel = null;
bakesOf(app).clear(built);
- const assets = app.hasResource(Assets) ? app.getResource(Assets) : null;
- for (const chunk of built.chunks) if (app.world.valid(chunk)) app.world.despawn(chunk);
- for (const handle of built.handles) assets?.releaseBuiltMesh(handle);
- built.chunks.length = 0;
- built.handles.length = 0;
+ for (const e of [...built.nodes.values(), ...built.spare]) if (app.world.valid(e)) app.world.despawn(e);
+ built.nodes.clear();
+ built.spare.length = 0;
+ built.wanted.clear();
+ const rm = getResourceManager();
+ for (const handle of [built.heights, built.paint]) {
+ if (!handle) continue;
+ withdrawTextureContent(handle);
+ rm?.releaseTexture(handle);
+ }
+ built.heights = built.paint = 0;
+ if (built.instance) Material.release(built.instance);
+ built.instance = 0;
+ if (built.mesh && app.hasResource(Assets)) app.getResource(Assets).releaseBuiltMesh(built.mesh);
+ built.mesh = 0;
+ built.source = null;
}
- /** Releases the chunks of a terrain whose entity is gone. */
+ /** Releases the nodes of a terrain whose entity is gone. */
private sweep(app: App, terrains: Terrains): void {
for (const [entity, built] of terrains.built_) {
if (app.world.valid(entity) && app.world.has(entity, Terrain)) continue;
diff --git a/sdk/src/terrain/terrainShader.ts b/sdk/src/terrain/terrainShader.ts
index 5c91eb01e..e0704bbc1 100644
--- a/sdk/src/terrain/terrainShader.ts
+++ b/sdk/src/terrain/terrainShader.ts
@@ -43,6 +43,98 @@ const TERRAIN = `#pragma shader "Terrain"
#pragma param u_wetLevel float default(0) range(-100000,100000) ui(slider)
#pragma param u_wetBand float default(0) range(0,100000) ui(slider)
#pragma param u_roughness float default(0.92) range(0,1) ui(slider)
+// The ground in pages (pages.ts; the Terrain component writes these): heights and normals, and the paint, in two atlases; heights over
+// u_heightRange above u_terrainOrigin; level 0 drawn out to u_lodRange0, each level twice as far; nothing off u_terrainBounds.
+#pragma param u_terrainPages float default(0) range(0,1) ui(slider)
+#pragma param u_heightPages texture default(white) texel(data)
+#pragma param u_paintPages texture default(white) texel(data)
+#pragma param u_atlasTexels float default(2048) range(1,16384) ui(slider)
+#pragma param u_pageTexels float default(64) range(1,1024) ui(slider)
+#pragma param u_patchCells float default(32) range(1,512) ui(slider)
+#pragma param u_heightRange vec2 default(0,1)
+#pragma param u_lodRange0 float default(100) range(0,1000000) ui(slider)
+#pragma param u_terrainOrigin vec4 default(0,0,0,0)
+#pragma param u_terrainBounds vec4 default(-1000000000,-1000000000,1000000000,1000000000)
+
+#pragma vertexoffset
+// The node's page (pages.ts): its height decoded texel by texel and blended (a filtered pair of bytes is no number).
+float tnPageHeight(vec2 texel) {
+ vec2 f = texel - 0.5;
+ ivec2 i = ivec2(floor(f));
+ vec2 t = f - vec2(i);
+ vec4 a = texelFetch(u_heightPages, i, 0), b = texelFetch(u_heightPages, i + ivec2(1, 0), 0);
+ vec4 c = texelFetch(u_heightPages, i + ivec2(0, 1), 0), d = texelFetch(u_heightPages, i + ivec2(1, 1), 0);
+ vec4 hs = vec4(a.r * 65280.0 + a.g * 255.0, b.r * 65280.0 + b.g * 255.0, c.r * 65280.0 + c.g * 255.0, d.r * 65280.0 + d.g * 255.0) / 65535.0;
+ return u_terrainOrigin.y + u_heightRange.x + mix(mix(hs.x, hs.y, t.x), mix(hs.z, hs.w, t.x), t.y) * u_heightRange.y;
+}
+// A node is the shared patch (0 to 1 in x and z) placed and sized by its instance: its model is its square (x and z) and its box
+// (y, from its page's least height to its most), and its tint names its page (x and y, the page's corner in the atlas) and level (z).
+void esMaterialVertex(inout vec3 local, inout vec3 localNormal, in vec2 uv) {
+ if (u_terrainPages < 0.5) return;
+ vec4 tint = esInstanceTint();
+ mat4 model = esInstanceModel();
+ float size = model[0][0], rise = max(model[1][1], 1e-6);
+ vec3 corner = model[3].xyz;
+ float level = floor(tint.z * 64.0 + 0.5) - 1.0;
+ // The tint holds the page's corner plus half a texel (so it is never zero); its first sample is one texel in, past the border.
+ vec2 page = tint.xy * u_atlasTexels + 0.5;
+ // Toward the end of its level's range a vertex slides onto the grid of the level above, so where two levels meet they share an edge.
+ vec2 g = uv * u_patchCells;
+ float h0 = tnPageHeight(page + uv * u_pageTexels + 0.5);
+ float range = u_lodRange0 * exp2(level);
+ float dist = distance(u_camera.xyz, vec3(corner.x + uv.x * size, h0, corner.z + uv.y * size));
+ float k = clamp((dist - range * 0.7) / (range * 0.3), 0.0, 1.0);
+ g -= fract(g * 0.5) * 2.0 * k;
+ vec2 at = g / u_patchCells;
+ vec2 texel = page + at * u_pageTexels + 0.5;
+ float h = tnPageHeight(texel);
+ local = vec3(at.x, (h - corner.y) / rise, at.y);
+ vec2 nxz = textureLod(u_heightPages, texel / u_atlasTexels, 0.0).ba * 2.0 - 1.0;
+ vec3 n = vec3(nxz.x, sqrt(max(1.0 - dot(nxz, nxz), 0.0)), nxz.y);
+ // The normal goes through the inverse transpose of the node's scale: put in what comes out as n.
+ localNormal = vec3(n.x * size, n.y * rise, n.z * size);
+ // The fragment reads the page where the vertex is: the colour carries it, divided by the tint it is multiplied by on the way.
+ es_vertexColor = vec4(texel / u_atlasTexels, 1.0, 1.0) / tint;
+}
+#pragma end
+
+#pragma vertexoffset wgsl
+fn tnPageHeight(texel : vec2f) -> f32 {
+ let f = texel - vec2f(0.5);
+ let i = vec2i(floor(f));
+ let t = f - vec2f(i);
+ let a = textureLoad(u_heightPages, i, 0);
+ let b = textureLoad(u_heightPages, i + vec2i(1, 0), 0);
+ let c = textureLoad(u_heightPages, i + vec2i(0, 1), 0);
+ let d = textureLoad(u_heightPages, i + vec2i(1, 1), 0);
+ let hs = vec4f(a.r * 65280.0 + a.g * 255.0, b.r * 65280.0 + b.g * 255.0, c.r * 65280.0 + c.g * 255.0, d.r * 65280.0 + d.g * 255.0) / 65535.0;
+ return mc.u_terrainOrigin.y + mc.u_heightRange.x + mix(mix(hs.x, hs.y, t.x), mix(hs.z, hs.w, t.x), t.y) * mc.u_heightRange.y;
+}
+fn esMaterialVertex(local : ptr<function, vec3f>, localNormal : ptr<function, vec3f>, uv : vec2f) {
+ if (mc.u_terrainPages < 0.5) { return; }
+ let tint = esInstanceTint();
+ let model = esInstanceModel();
+ let size = model[0][0];
+ let rise = max(model[1][1], 1e-6);
+ let corner = model[3].xyz;
+ let level = floor(tint.z * 64.0 + 0.5) - 1.0;
+ let page = tint.xy * mc.u_atlasTexels + vec2f(0.5);
+ var g = uv * mc.u_patchCells;
+ let h0 = tnPageHeight(page + uv * mc.u_pageTexels + vec2f(0.5));
+ let range = mc.u_lodRange0 * exp2(level);
+ let dist = distance(frame.camera.xyz, vec3f(corner.x + uv.x * size, h0, corner.z + uv.y * size));
+ let k = clamp((dist - range * 0.7) / (range * 0.3), 0.0, 1.0);
+ g = g - fract(g * 0.5) * 2.0 * k;
+ let at = g / mc.u_patchCells;
+ let texel = page + at * mc.u_pageTexels + vec2f(0.5);
+ let h = tnPageHeight(texel);
+ *local = vec3f(at.x, (h - corner.y) / rise, at.y);
+ let nxz = textureSampleLevel(u_heightPages, u_heightPages_s, texel / mc.u_atlasTexels, 0.0).ba * 2.0 - vec2f(1.0);
+ let n = vec3f(nxz.x, sqrt(max(1.0 - dot(nxz, nxz), 0.0)), nxz.y);
+ *localNormal = vec3f(n.x * size, n.y * rise, n.z * size);
+ es_vertexColor = vec4f(texel / mc.u_atlasTexels, 1.0, 1.0) / tint;
+}
+#pragma end
#pragma fragment
precision highp float;
@@ -102,7 +194,16 @@ void main() {
highp vec3 P = vec3(v_worldPos.x, 0.0, v_worldPos.y);
highp vec3 N = vec3(0.0, 1.0, 0.0);
#endif
- vec4 w = max(v_color, vec4(0.0));
+ // A paged ground reads its paint and its normal where the vertex said it lies in the page, filtered; off its area there is none.
+ vec4 paint = v_color;
+ if (u_terrainPages > 0.5) {
+ vec2 lp = P.xz - u_terrainOrigin.xz;
+ if (lp.x < u_terrainBounds.x || lp.y < u_terrainBounds.y || lp.x > u_terrainBounds.z || lp.y > u_terrainBounds.w) discard;
+ paint = texture(u_paintPages, v_color.xy);
+ vec2 nxz = texture(u_heightPages, v_color.xy).ba * 2.0 - 1.0;
+ N = normalize(vec3(nxz.x, sqrt(max(1.0 - dot(nxz, nxz), 0.0)), nxz.y));
+ }
+ vec4 w = max(paint, vec4(0.0));
w /= max(dot(w, vec4(1.0)), 1e-4);
// The strongest layer wins its seam more cleanly the higher the sharpness.
w = pow(w, vec4(u_sharpness));
@@ -214,12 +315,21 @@ fn packNormal(n : vec3f) -> vec2f {
#endif
#ifdef MESH_NORMALS
let P = v.v_worldXYZ;
- let N = normalize(v.v_worldNormal);
+ var N = normalize(v.v_worldNormal);
#else
let P = vec3f(v.v_worldPos.x, 0.0, v.v_worldPos.y);
- let N = vec3f(0.0, 1.0, 0.0);
+ var N = vec3f(0.0, 1.0, 0.0);
#endif
- var w = max(v.v_color, vec4f(0.0));
+ let pagePaint = textureSample(u_paintPages, u_paintPages_s, v.v_color.xy);
+ let pageNormal = textureSample(u_heightPages, u_heightPages_s, v.v_color.xy).ba * 2.0 - vec2f(1.0);
+ var paint = v.v_color;
+ if (mc.u_terrainPages > 0.5) {
+ let lp = P.xz - mc.u_terrainOrigin.xz;
+ if (lp.x < mc.u_terrainBounds.x || lp.y < mc.u_terrainBounds.y || lp.x > mc.u_terrainBounds.z || lp.y > mc.u_terrainBounds.w) { discard; }
+ paint = pagePaint;
+ N = normalize(vec3f(pageNormal.x, sqrt(max(1.0 - dot(pageNormal, pageNormal), 0.0)), pageNormal.y));
+ }
+ var w = max(paint, vec4f(0.0));
w = w / max(dot(w, vec4f(1.0)), 1e-4);
w = pow(w, vec4f(mc.u_sharpness));
w = w / max(dot(w, vec4f(1.0)), 1e-4);
diff --git a/sdk/tests/terrain-quadtree.test.ts b/sdk/tests/terrain-quadtree.test.ts
new file mode 100644
index 000000000..4cabaec73
--- /dev/null
+++ b/sdk/tests/terrain-quadtree.test.ts
@@ -0,0 +1,92 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { describe, expect, it } from 'vitest';
+import { levelRange, parentOf, selectNodes, type QuadtreeParams, type TerrainNode } from '../src/terrain/quadtree';
+import { makePage, PageTable, PAGE_SIDE } from '../src/terrain/pages';
+import { NoiseSource, noised } from '../src/terrain/source';
+
+const area: QuadtreeParams = { leafSize: 32, levels: 5, range0: 80, bounds: [-256, -256, 256, 256], minHeight: 0, maxHeight: 50 };
+const covers = (nodes: TerrainNode[], x: number, z: number): number =>
+ nodes.filter((n) => x >= n.x0 && x < n.x0 + n.size && z >= n.z0 && z < n.z0 + n.size).length;
+
+describe('the ground\'s quadtree', () => {
+ it('covers every place in the area exactly once', () => {
+ const nodes = selectNodes(area, 10, 20, -30);
+ for (let x = -250; x < 256; x += 17) for (let z = -250; z < 256; z += 19) expect(covers(nodes, x, z)).toBe(1);
+ });
+
+ it('is finest at the eye and coarsens with distance', () => {
+ const nodes = selectNodes(area, 0, 5, 0);
+ const at = (x: number, z: number) => nodes.find((n) => x >= n.x0 && x < n.x0 + n.size && z >= n.z0 && z < n.z0 + n.size)!;
+ expect(at(1, 1).level).toBe(0);
+ expect(at(250, 250).level).toBeGreaterThan(at(60, 60).level);
+ });
+
+ it('never puts two nodes more than a level apart side by side, so the morph closes every seam', () => {
+ const nodes = selectNodes(area, 40, 10, 70);
+ for (const a of nodes) for (const b of nodes) {
+ const touch = a.x0 <= b.x0 + b.size && b.x0 <= a.x0 + a.size && a.z0 <= b.z0 + b.size && b.z0 <= a.z0 + a.size;
+ if (touch) expect(Math.abs(a.level - b.level)).toBeLessThanOrEqual(1);
+ }
+ });
+
+ it('goes on round the eye for ground without end, as far as its top range', () => {
+ const nodes = selectNodes({ ...area, bounds: null }, 5000, 10, -9000);
+ expect(covers(nodes, 5000, -9000)).toBe(1);
+ expect(covers(nodes, 5000 + levelRange(area, 4) * 0.9, -9000)).toBe(1);
+ expect(nodes.every((n) => n.size === 32 * 2 ** n.level)).toBe(true);
+ });
+
+ it('finds a node\'s parent', () => {
+ expect(parentOf({ level: 0, ix: 3, iz: -1, x0: 96, z0: -32, size: 32 }, 32)).toEqual({ level: 1, ix: 1, iz: -1, x0: 64, z0: -64, size: 64 });
+ });
+});
+
+describe('ground without end', () => {
+ const ground = new NoiseSource({ seed: 4, frequency: 3, octaves: 5, persistence: 0.5, ridged: 0.3, warp: 0.3, erosion: 1, sizeX: 1000, height: 200,
+ rockSlope: 0.35, dirtHeight: 0.62, snowHeight: 0.88 });
+
+ it('is the same ground for the same seed anywhere, as far out as it is asked', () => {
+ const a = ground.height(123456.5, -98765.25), b = new NoiseSource({ ...(ground as unknown as { p: never }).p }).height(123456.5, -98765.25);
+ expect(a).toBe(b);
+ expect(a).toBeGreaterThanOrEqual(0);
+ expect(a).toBeLessThanOrEqual(200);
+ });
+
+ it('has a slope that is the derivative of its noise', () => {
+ const e = 1e-4;
+ for (const [x, y] of [[0.3, 0.7], [5.5, -3.2], [-12.1, 9.9]] as const) {
+ const [, dx, dy] = noised(x, y, 7);
+ expect(dx).toBeCloseTo((noised(x + e, y, 7)[0] - noised(x - e, y, 7)[0]) / (2 * e), 4);
+ expect(dy).toBeCloseTo((noised(x, y + e, 7)[0] - noised(x, y - e, 7)[0]) / (2 * e), 4);
+ }
+ });
+});
+
+describe('the pages', () => {
+ const ground = new NoiseSource({ seed: 2, frequency: 2, octaves: 4, persistence: 0.5, ridged: 0, warp: 0, erosion: 0, sizeX: 500, height: 100,
+ rockSlope: 0.35, dirtHeight: 0.62, snowHeight: 0.88 });
+
+ it('hold a node\'s heights to a 65535th of the ground\'s range, with a border, and its box', () => {
+ const page = makePage(ground, 64, -32, 32);
+ const n = PAGE_SIDE;
+ // The first sample past the border is the node's corner.
+ const k = (1 * n + 1) * 4;
+ const h = ((page.heights[k]! * 256 + page.heights[k + 1]!) / 65535) * 100;
+ expect(h).toBeCloseTo(ground.height(64, -32), 1);
+ expect(page.min).toBeLessThanOrEqual(page.max);
+ expect(page.heights.length).toBe(n * n * 4);
+ });
+
+ it('give a full atlas\'s oldest page up for a new one, but not one drawn this frame', () => {
+ const table = new PageTable(PAGE_SIDE * 2);
+ expect(table.capacity).toBe(4);
+ for (let i = 0; i < 4; i++) expect(table.claim(`p${i}`, 0, 1)).not.toBeNull();
+ expect(table.claim('fresh', 0, 1)).toBeNull();
+ table.tick();
+ table.touch('p1'); table.touch('p2'); table.touch('p3');
+ const page = table.claim('fresh', 0, 1)!;
+ expect(table.get('p0')).toBeUndefined();
+ expect(page.slot).toBeGreaterThanOrEqual(0);
+ });
+});
diff --git a/tools/check-gizmo-coverage.mjs b/tools/check-gizmo-coverage.mjs
index d9d8cb9c9..b0f070974 100644
--- a/tools/check-gizmo-coverage.mjs
+++ b/tools/check-gizmo-coverage.mjs
@@ -117,6 +117,8 @@ const DISPOSITION = {
'Terrain.snowHeight': ['not-world', 'a share of the height of the terrain, 0 to 1'],
'Foliage.sizeX': ['owed', 'the area plants grow in is not outlined in the viewport yet'],
'Foliage.sizeZ': ['owed', 'the area plants grow in is not outlined in the viewport yet'],
+ 'Terrain.cellSize': ['no-place', 'the finest cell of the ground\'s mesh near the eye, not a region of the entity'],
+ 'Terrain.drawDistance': ['no-place', 'how far from the eye ground without end is drawn, not a region of the entity'],
'Foliage.cellSize': ['no-place', 'the square the area is cut into for drawing, not a region of the entity'],
'Foliage.bladeWidth': ['renders', 'the blades drawn at it are the picture'],
'Foliage.bladeHeight': ['renders', 'the blades drawn at it are the picture'],