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): ground without end comes from a versioned provider the game names, and a terrain that cannot get its ground fails

yhhe4937e1483aa
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ff92e08eb..3e13bfbfc 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -22,6 +22,7 @@ published separately; it ships inside the editor.
- **Surf on the shore.** Waves run in toward every shore of a water zone, stand up as the water shoals, break white and run up the ground past the waterline before falling back. `WaterZone.surf` sets how high a breaker stands against its body's waves and `surfLength` the length of the surf's waves; a current carries none, and `Waters.sample` rides the same surf. The zone now measures the distance to the shore across the ground for every body, an ocean over a beach included, where an ocean used to measure its depth.
- **Terrain without cracks, and without end.** The ground is now a CDLOD quadtree round the eye: every node is the same small patch drawn as instances of one mesh, its heights and normals read on the GPU from pages of a height atlas, and its vertices slide onto the coarser grid toward the end of their level's range, so levels meet without cracks or skirts and nothing pops as the camera moves. `Terrain.extent` Infinite makes ground that goes on for ever from seeded noise read anywhere (worn by the noise's own erosion), drawn out to `drawDistance`; `cellSize` is the finest cell near the eye. Pages are made a few a frame, coarse and near first, and shown as progress.
+- **Terrain from a generator the game names, versioned.** Infinite ground is now made by a terrain provider: a function of the world position that samples whole regions (heights, and paint if it has its own), the same on every machine, and that may answer later from a worker or a server. `Terrain.provider`, `world` and `generatorVersion` name it; `registerTerrainProvider` adds a game's own, and the engine's noise is `estella:noise` version 1. A terrain whose provider is missing, whose version its provider no longer has, or whose heightmap cannot be read fails with a reason in `Terrains.status` and answers nothing, instead of growing noise in its place.
- **A vertex hook can hand the fragment a colour.** What a material's vertex hook leaves in `es_vertexColor` is now the colour its fragment receives (times the instance's tint), on both backends.
- **Bakes run over frames, with progress.** Work that used to hold a frame until it was done (a terrain worn by rain, a water zone baked, terrain chunks built, plants grown) is now spread over frames within a budget, and listed with its progress in the new `Bakes` resource (`bakesOf(app).active`). The editor's status bar shows it as a bar, for the edit world and for the game running in Play, and a game can show it on a loading screen. Plants wait for the ground and the water they stand on instead of being grown twice.
- **Eroded and warped terrain.** `Terrain.erosion` wears the ground with rain (a heightmap's as well as the noise's): gullies down the slopes, sharper ridges, silt in the valleys, and dirt painted where the water ran; the same seed wears the same ground. `Terrain.warp` bends the noise by noise of its own for winding valleys and bent ridges. `erodeHeightfield` and `erosionJob` do the same for a tool.
diff --git a/docs/astro/src/content/docs/graphics/terrain.mdx b/docs/astro/src/content/docs/graphics/terrain.mdx
index b7d3cb6ab..5faff4bf9 100644
--- a/docs/astro/src/content/docs/graphics/terrain.mdx
+++ b/docs/astro/src/content/docs/graphics/terrain.mdx
@@ -16,8 +16,9 @@ The ground is one of two kinds, chosen by `extent`:
- **Area**: ground `sizeX` by `sizeZ`, centred on the entity, from a heightmap or from noise made once. It may be worn by rain and
painted by a splatmap.
-- **Infinite**: noise read at any point in the world, so the ground has no edge. The same seed is the same ground everywhere, in the
- editor, in a game and on a server. It is drawn round the eye out to `drawDistance`.
+- **Infinite**: ground made by a provider (below) read at any point in the world, so it has no edge. The same provider, world, seed
+ and version are the same ground everywhere, in the editor, in a game and on a server. It is drawn round the eye out to
+ `drawDistance`.
| Field | What it does |
|---|---|
@@ -27,6 +28,7 @@ The ground is one of two kinds, chosen by `extent`:
| `cellSize` | The finest cell of the ground's mesh, in world units: what the ground is drawn at near the eye. Further off the cells double, level by level. |
| `detail` | A multiplier on how far the finest cells reach before the ground coarsens. Above 1 is finer at a distance and costs more triangles. |
| `drawDistance` | Infinite only. How far from the eye the ground is drawn. |
+| `provider`, `world`, `generatorVersion` | Infinite only. The generator the ground is made by (`estella:noise`, the engine's noise, or one the game registers), the world it belongs to as the game names it, and the generator version that world was made with. |
| `seed`, `frequency`, `octaves`, `persistence`, `ridged` | The noise: another seed is another ground; `frequency` is how many hills across; `ridged` goes from rolling hills to sharp ridges. |
| `resolution` | Area only. Samples along each side of an area's noise ground. |
| `warp` | 0 to 1: how far the noise is bent by noise of its own, which gives winding valleys and bent ridges instead of round hills. |
@@ -120,9 +122,41 @@ const y = terrains.heightAt(x, z); // world height, or null where there is
const n = terrains.normalAt(x, z); // the unit normal there, or null
```
-These read the same source the pages are made from (the area's field, or the infinite noise), so they agree with what is drawn, and
-they answer at once for any point, whether or not its page has been made. Infinite ground has a height everywhere. Until an area's
-images are read and its erosion is done, `heightAt` returns null and `terrains.loading` is true.
+These read the same source the pages are made from (the area's field, or the provider), so they agree with what is drawn, and they
+answer for any point whether or not its page has been made. Until an area's images are read and its erosion is done, `heightAt`
+returns null and `terrains.loading` is true. A provider that answers later leaves a point null until the samples round it come in.
+
+`terrains.status(entity)` says where a terrain stands: `loading`, `ready`, or `failed` with a `reason`. A terrain whose heightmap
+cannot be read, whose provider is not registered, or whose version its provider no longer has fails: it draws nothing and answers
+null, rather than growing noise where the game expected its own ground.
+
+### Providers and versions
+
+Ground without end is made by a provider: one function of the world position, the same on every machine. It is asked for a region
+(the world, seed and version, a corner in world units, a spacing and a count of samples a side) and answers the heights there, and,
+if it paints the ground, four layer weights a sample. Every region is the same function read at other points, so neighbouring pages
+share their edge's samples, a coarse page and a fine one agree where their samples meet, and the order pages are made in changes
+nothing. Positions are the world's, not the terrain's: two terrains placed apart over one world are the same ground.
+
+```ts
+import { registerTerrainProvider, type TerrainProvider } from 'esengine/terrain';
+
+const planet: TerrainProvider = {
+ id: 'mygame:planet',
+ versions: [1, 2], // every version a saved world may still name
+ range: (seed, version) => [-200, 900], // the least and most height, which the GPU encodes over
+ sample({ world, seed, version, x0, z0, spacing, count }) {
+ const heights = new Float32Array(count * count);
+ // ... heights[j * count + i] at (x0 + i * spacing, z0 + j * spacing)
+ return { heights }; // or a Promise, from a worker or a server
+ },
+};
+registerTerrainProvider(planet);
+```
+
+A version names an algorithm for good. A saved world keeps `generatorVersion`; when the algorithm changes, add a version and keep
+the old one, so what was built on the old ground still stands on it. The engine's noise is `estella:noise`, version 1. A provider
+with `heightAt` answers a point at once; without it a point is answered from small sampled tiles at the finest cell size.
## Limits
diff --git a/docs/astro/src/content/docs/zh-cn/graphics/terrain.mdx b/docs/astro/src/content/docs/zh-cn/graphics/terrain.mdx
index dc2eff8c5..73f3a9e4b 100644
--- a/docs/astro/src/content/docs/zh-cn/graphics/terrain.mdx
+++ b/docs/astro/src/content/docs/zh-cn/graphics/terrain.mdx
@@ -12,7 +12,7 @@ description: 一个 Terrain 组件,用高度图或噪声生成地面,可以是
地面有两种,由 `extent` 选择:
- **Area(区域)**:以实体为中心、`sizeX` 乘 `sizeZ` 的一片地面,来自高度图或一次性生成的噪声。可以被雨水侵蚀,也可以用 splatmap 上色。
-- **Infinite(无限)**:在世界中任意一点读取的噪声,所以地面没有边缘。同一个种子在任何地方都是同一片地面,编辑器里、游戏里、服务器上都一样。它围绕视点绘制到 `drawDistance` 为止。
+- **Infinite(无限)**:由一个生成器(provider,见下)在世界中任意一点读取的地面,所以没有边缘。同一个生成器、世界、种子和版本在任何地方都是同一片地面,编辑器里、游戏里、服务器上都一样。它围绕视点绘制到 `drawDistance` 为止。
| 字段 | 作用 |
|---|---|
@@ -22,6 +22,7 @@ description: 一个 Terrain 组件,用高度图或噪声生成地面,可以是
| `cellSize` | 地面网格最细的格子,以世界单位计:视点近处地面按它绘制。再远一些,格子逐级加倍。 |
| `detail` | 最细格子在地面变粗之前能延伸多远的倍率。大于 1 时远处更细,三角形也更多。 |
| `drawDistance` | 仅无限地面。地面从视点向外绘制多远。 |
+| `provider`、`world`、`generatorVersion` | 仅无限。生成地面的生成器(`estella:noise` 为引擎自带噪声,或游戏注册的生成器)、游戏给这个世界起的名字,以及这个世界生成时用的生成器版本。 |
| `seed`、`frequency`、`octaves`、`persistence`、`ridged` | 噪声:换一个种子就是另一片地面;`frequency` 是横跨有几座山丘;`ridged` 从起伏的丘陵到尖锐的山脊。 |
| `resolution` | 仅区域。区域噪声地面每边的采样数。 |
| `warp` | 0 到 1:噪声被它自己的另一层噪声扭曲多远,得到蜿蜒的山谷和弯折的山脊,而不是圆圆的山丘。 |
@@ -90,7 +91,31 @@ const y = terrains.heightAt(x, z); // 世界高度,没有地形的地方
const n = terrains.normalAt(x, z); // 那里的单位法线,或 null
```
-它们读的是生成页所用的同一个来源(区域的场,或无限的噪声),所以和画出来的一致,而且任何一点都能立刻回答,不管那里的页做没做好。无限地面处处都有高度。区域的图读完、侵蚀做完之前,`heightAt` 返回 null,`terrains.loading` 为 true。
+它们读的是生成页所用的同一个来源(区域的场,或生成器),所以和画出来的一致,而且任何一点都能回答,不管那里的页做没做好。区域的图读完、侵蚀做完之前,`heightAt` 返回 null,`terrains.loading` 为 true。稍后才应答的生成器,在某点周围的样本到达之前,该点返回 null。
+
+`terrains.status(entity)` 说明地形所处的状态:`loading`、`ready`,或带 `reason` 的 `failed`。高度图读不到、生成器没注册、或生成器已没有所要的版本时,地形失败:什么都不画,查询返回 null,而不是在游戏期待自己地面的地方长出噪声。
+
+### 生成器与版本
+
+无限地面由生成器生成:一个关于世界位置的函数,在每台机器上都一样。它被要求采样一个区域(世界、种子和版本、以世界单位计的起点、间距和每边样本数),返回那里的高度;如果它自己给地面上色,还返回每个样本四个图层权重。每个区域都是同一个函数在不同点上的读数,所以相邻页共享边上的样本,粗页和细页在样本重合处一致,页生成的先后不改变任何东西。位置是世界的,不是地形的:同一个世界上分开摆放的两个地形是同一片地面。
+
+```ts
+import { registerTerrainProvider, type TerrainProvider } from 'esengine/terrain';
+
+const planet: TerrainProvider = {
+ id: 'mygame:planet',
+ versions: [1, 2], // 存档里的世界可能仍会指名的每个版本
+ range: (seed, version) => [-200, 900], // 最低与最高高度,GPU 按它编码高度
+ sample({ world, seed, version, x0, z0, spacing, count }) {
+ const heights = new Float32Array(count * count);
+ // ... heights[j * count + i] 位于 (x0 + i * spacing, z0 + j * spacing)
+ return { heights }; // 也可以是 Promise,来自 worker 或服务器
+ },
+};
+registerTerrainProvider(planet);
+```
+
+一个版本永久对应一种算法。存档的世界保留 `generatorVersion`;算法改变时新增一个版本并保留旧版本,这样建在旧地面上的东西仍立在原处。引擎的噪声是 `estella:noise` 版本 1。带 `heightAt` 的生成器能立刻回答单点;没有它时,单点从按最细格子采样的小块里回答。
## 限制
diff --git a/docs/astro/src/data/components.generated.json b/docs/astro/src/data/components.generated.json
index a18728ec8..54626126d 100644
--- a/docs/astro/src/data/components.generated.json
+++ b/docs/astro/src/data/components.generated.json
@@ -5245,11 +5245,30 @@
"Infinite"
]
},
+ {
+ "key": "provider",
+ "type": "string",
+ "default": "\"estella:noise\"",
+ "doc": "The generator ground without end is made by: estella:noise, or one the game registers. The same provider, world, seed and version are the same ground on every machine."
+ },
+ {
+ "key": "world",
+ "type": "string",
+ "default": "empty",
+ "doc": "The world (a planet, a level) the ground belongs to, as the game names it; handed to the provider."
+ },
+ {
+ "key": "generatorVersion",
+ "type": "number",
+ "default": "1",
+ "doc": "The generator version the world was made with. A version the provider no longer has fails the terrain rather than growing other ground under what was built.",
+ "range": "≥ 1, step 1"
+ },
{
"key": "heightmap",
"type": "Asset<texture>",
"default": "none",
- "doc": "A heightmap image: red is the height. Empty makes the ground from noise."
+ "doc": "A heightmap image: red is the height. Empty makes the ground from noise; a heightmap that cannot be read fails the terrain instead."
},
{
"key": "splatmap",
@@ -5405,6 +5424,7 @@
],
"animatable": [
"extent",
+ "generatorVersion",
"heightmap",
"splatmap",
"material",
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index a0c0f293b..06dfeca39 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 · 1772 experimental · 3 deprecated
+Symbols: 115 public · 159 beta · 1782 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -5740,6 +5740,11 @@ ComponentDef<MotorJoint2DData>
Record<GraphNodeType, NodeSpec>
```
+## NOISE_PROVIDER — const @experimental
+```
+"estella:noise"
+```
+
## Name — const @public
```
ComponentDef<NameData>
@@ -7182,6 +7187,24 @@ name: string
type: "property"
```
+## ProviderSource — class @experimental
+```
+bounds: null
+height: (x: number, z: number) => number | null
+infinite: true
+maxHeight: number
+minHeight: number
+normal: (x: number, z: number) => [number, number, number] | null
+paint: (_x: number, _z: number, h: number, ny: number) => [number, number, number, number]
+provider: TerrainProvider
+region: (x0: number, z0: number, spacing: number, count: number) => TerrainSamples | Promise<TerrainSamples>
+seed: number
+version: number
+world: string
+static new (provider: TerrainProvider, world: string, seed: number, version: number, originX: number, originZ: number, pointSpacing: number, paintRules: (h: number, ny: number) => [number, number, number, number]): ProviderSource
+static prototype: ProviderSource
+```
+
## PseudoLocalizationOptions — interface @experimental
```
accents: boolean | undefined
@@ -9683,6 +9706,7 @@ drawDistance: number
erosion: number
extent: number
frequency: number
+generatorVersion: number
height: number
heightmap: number
layerColor0: Color
@@ -9692,6 +9716,7 @@ layerColor3: Color
material: number
octaves: number
persistence: number
+provider: string
resolution: number
ridged: number
rockSlope: number
@@ -9701,6 +9726,7 @@ sizeZ: number
snowHeight: number
splatmap: number
warp: number
+world: string
```
## TerrainExtent — const @experimental
@@ -9727,6 +9753,32 @@ static new (): TerrainPlugin
static prototype: TerrainPlugin
```
+## TerrainProvider — interface @experimental
+```
+heightAt: ((world: string, seed: number, version: number, x: number, z: number) => number) | undefined
+id: string
+range: (seed: number, version: number) => [number, number]
+sample: (region: TerrainRegion) => TerrainSamples | Promise<TerrainSamples>
+versions: readonly number[]
+```
+
+## TerrainRegion — interface @experimental
+```
+count: number
+seed: number
+spacing: number
+version: number
+world: string
+x0: number
+z0: number
+```
+
+## TerrainSamples — interface @experimental
+```
+heights: Float32Array<ArrayBufferLike>
+paint: Float32Array<ArrayBufferLike> | undefined
+```
+
## TerrainSource — interface @experimental
```
bounds: readonly [number, number, number, number] | null
@@ -9734,7 +9786,21 @@ height: (x: number, z: number) => number | null
infinite: boolean
maxHeight: number
minHeight: number
+normal: (x: number, z: number) => [number, number, number] | null
paint: (x: number, z: number, h: number, ny: number) => [number, number, number, number]
+region: ((x0: number, z0: number, spacing: number, count: number) => { heights: Float32Array; paint?: Float32Array; } | Promise<{ heights: Float32Array; paint?: Float32Array; }>) | undefined
+```
+
+## TerrainStatus — interface @experimental
+```
+reason: string | undefined
+state: "failed" | "ready" | "loading"
+```
+
+## TerrainUnavailable — class @experimental
+```
+static new (message?: string): TerrainUnavailable
+static prototype: TerrainUnavailable
```
## Terrains — class @experimental
@@ -9746,6 +9812,7 @@ heightAt: (x: number, z: number) => number | null
loading: boolean
normalAt: (x: number, z: number) => [number, number, number] | null
pending: number
+status: (entity: Entity) => TerrainStatus | null
static new (): Terrains
static prototype: Terrains
```
@@ -13751,7 +13818,7 @@ Logger
## makePage — function @experimental
```
-(source: TerrainSource, x0: number, z0: number, size: number): PageImage
+(source: TerrainSource, x0: number, z0: number, size: number): PageImage | Promise<PageImage>
```
## makeWidgetInteractable — function @experimental
@@ -13869,6 +13936,11 @@ MeshRendererPlugin
(level: number, ix: number, iz: number): string
```
+## noiseProvider — function @experimental
+```
+(params: (seed: number) => NoiseParams): TerrainProvider
+```
+
## noised — function @experimental
```
(x: number, y: number, seed: number): [number, number, number]
@@ -14394,6 +14466,11 @@ PrefabsPlugin
(id: string, descriptor: SideModuleDescriptor): void
```
+## registerTerrainProvider — function @experimental
+```
+(provider: TerrainProvider): void
+```
+
## registerValue — function @experimental
```
(name: string, spec: AiValueSpec<AiContext>): void
@@ -15099,6 +15176,11 @@ StatsPlugin
Plugin
```
+## terrainProvider — function @experimental
+```
+(id: string): TerrainProvider | undefined
+```
+
## textInputPlugin — const @experimental
```
TextInputPlugin
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index bc46deac5..ae0a4bc49 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 · 1791 experimental · 3 deprecated
+Symbols: 115 public · 164 beta · 1801 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -5753,6 +5753,11 @@ ComponentDef<MotorJoint2DData>
Record<GraphNodeType, NodeSpec>
```
+## NOISE_PROVIDER — const @experimental
+```
+"estella:noise"
+```
+
## Name — const @public
```
ComponentDef<NameData>
@@ -7385,6 +7390,24 @@ name: string
type: "property"
```
+## ProviderSource — class @experimental
+```
+bounds: null
+height: (x: number, z: number) => number | null
+infinite: true
+maxHeight: number
+minHeight: number
+normal: (x: number, z: number) => [number, number, number] | null
+paint: (_x: number, _z: number, h: number, ny: number) => [number, number, number, number]
+provider: TerrainProvider
+region: (x0: number, z0: number, spacing: number, count: number) => TerrainSamples | Promise<TerrainSamples>
+seed: number
+version: number
+world: string
+static new (provider: TerrainProvider, world: string, seed: number, version: number, originX: number, originZ: number, pointSpacing: number, paintRules: (h: number, ny: number) => [number, number, number, number]): ProviderSource
+static prototype: ProviderSource
+```
+
## PseudoLocalizationOptions — interface @experimental
```
accents: boolean | undefined
@@ -9896,6 +9919,7 @@ drawDistance: number
erosion: number
extent: number
frequency: number
+generatorVersion: number
height: number
heightmap: number
layerColor0: Color
@@ -9905,6 +9929,7 @@ layerColor3: Color
material: number
octaves: number
persistence: number
+provider: string
resolution: number
ridged: number
rockSlope: number
@@ -9914,6 +9939,7 @@ sizeZ: number
snowHeight: number
splatmap: number
warp: number
+world: string
```
## TerrainExtent — const @experimental
@@ -9940,6 +9966,32 @@ static new (): TerrainPlugin
static prototype: TerrainPlugin
```
+## TerrainProvider — interface @experimental
+```
+heightAt: ((world: string, seed: number, version: number, x: number, z: number) => number) | undefined
+id: string
+range: (seed: number, version: number) => [number, number]
+sample: (region: TerrainRegion) => TerrainSamples | Promise<TerrainSamples>
+versions: readonly number[]
+```
+
+## TerrainRegion — interface @experimental
+```
+count: number
+seed: number
+spacing: number
+version: number
+world: string
+x0: number
+z0: number
+```
+
+## TerrainSamples — interface @experimental
+```
+heights: Float32Array<ArrayBufferLike>
+paint: Float32Array<ArrayBufferLike> | undefined
+```
+
## TerrainSource — interface @experimental
```
bounds: readonly [number, number, number, number] | null
@@ -9947,7 +9999,21 @@ height: (x: number, z: number) => number | null
infinite: boolean
maxHeight: number
minHeight: number
+normal: (x: number, z: number) => [number, number, number] | null
paint: (x: number, z: number, h: number, ny: number) => [number, number, number, number]
+region: ((x0: number, z0: number, spacing: number, count: number) => { heights: Float32Array; paint?: Float32Array; } | Promise<{ heights: Float32Array; paint?: Float32Array; }>) | undefined
+```
+
+## TerrainStatus — interface @experimental
+```
+reason: string | undefined
+state: "failed" | "ready" | "loading"
+```
+
+## TerrainUnavailable — class @experimental
+```
+static new (message?: string): TerrainUnavailable
+static prototype: TerrainUnavailable
```
## Terrains — class @experimental
@@ -9959,6 +10025,7 @@ heightAt: (x: number, z: number) => number | null
loading: boolean
normalAt: (x: number, z: number) => [number, number, number] | null
pending: number
+status: (entity: Entity) => TerrainStatus | null
static new (): Terrains
static prototype: Terrains
```
@@ -14014,7 +14081,7 @@ Logger
## makePage — function @experimental
```
-(source: TerrainSource, x0: number, z0: number, size: number): PageImage
+(source: TerrainSource, x0: number, z0: number, size: number): PageImage | Promise<PageImage>
```
## makeWidgetInteractable — function @experimental
@@ -14132,6 +14199,11 @@ MeshRendererPlugin
(level: number, ix: number, iz: number): string
```
+## noiseProvider — function @experimental
+```
+(params: (seed: number) => NoiseParams): TerrainProvider
+```
+
## noised — function @experimental
```
(x: number, y: number, seed: number): [number, number, number]
@@ -14657,6 +14729,11 @@ PrefabsPlugin
(id: string, descriptor: SideModuleDescriptor): void
```
+## registerTerrainProvider — function @experimental
+```
+(provider: TerrainProvider): void
+```
+
## registerValue — function @experimental
```
(name: string, spec: AiValueSpec<AiContext>): void
@@ -15362,6 +15439,11 @@ StatsPlugin
Plugin
```
+## terrainProvider — function @experimental
+```
+(id: string): TerrainProvider | undefined
+```
+
## textInputPlugin — const @experimental
```
TextInputPlugin
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index d47b356a5..4291374f6 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 · 1771 experimental · 3 deprecated
+Symbols: 115 public · 161 beta · 1781 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -5735,6 +5735,11 @@ ComponentDef<MotorJoint2DData>
Record<GraphNodeType, NodeSpec>
```
+## NOISE_PROVIDER — const @experimental
+```
+"estella:noise"
+```
+
## Name — const @public
```
ComponentDef<NameData>
@@ -7177,6 +7182,24 @@ name: string
type: "property"
```
+## ProviderSource — class @experimental
+```
+bounds: null
+height: (x: number, z: number) => number | null
+infinite: true
+maxHeight: number
+minHeight: number
+normal: (x: number, z: number) => [number, number, number] | null
+paint: (_x: number, _z: number, h: number, ny: number) => [number, number, number, number]
+provider: TerrainProvider
+region: (x0: number, z0: number, spacing: number, count: number) => TerrainSamples | Promise<TerrainSamples>
+seed: number
+version: number
+world: string
+static new (provider: TerrainProvider, world: string, seed: number, version: number, originX: number, originZ: number, pointSpacing: number, paintRules: (h: number, ny: number) => [number, number, number, number]): ProviderSource
+static prototype: ProviderSource
+```
+
## PseudoLocalizationOptions — interface @experimental
```
accents: boolean | undefined
@@ -9678,6 +9701,7 @@ drawDistance: number
erosion: number
extent: number
frequency: number
+generatorVersion: number
height: number
heightmap: number
layerColor0: Color
@@ -9687,6 +9711,7 @@ layerColor3: Color
material: number
octaves: number
persistence: number
+provider: string
resolution: number
ridged: number
rockSlope: number
@@ -9696,6 +9721,7 @@ sizeZ: number
snowHeight: number
splatmap: number
warp: number
+world: string
```
## TerrainExtent — const @experimental
@@ -9722,6 +9748,32 @@ static new (): TerrainPlugin
static prototype: TerrainPlugin
```
+## TerrainProvider — interface @experimental
+```
+heightAt: ((world: string, seed: number, version: number, x: number, z: number) => number) | undefined
+id: string
+range: (seed: number, version: number) => [number, number]
+sample: (region: TerrainRegion) => TerrainSamples | Promise<TerrainSamples>
+versions: readonly number[]
+```
+
+## TerrainRegion — interface @experimental
+```
+count: number
+seed: number
+spacing: number
+version: number
+world: string
+x0: number
+z0: number
+```
+
+## TerrainSamples — interface @experimental
+```
+heights: Float32Array<ArrayBufferLike>
+paint: Float32Array<ArrayBufferLike> | undefined
+```
+
## TerrainSource — interface @experimental
```
bounds: readonly [number, number, number, number] | null
@@ -9729,7 +9781,21 @@ height: (x: number, z: number) => number | null
infinite: boolean
maxHeight: number
minHeight: number
+normal: (x: number, z: number) => [number, number, number] | null
paint: (x: number, z: number, h: number, ny: number) => [number, number, number, number]
+region: ((x0: number, z0: number, spacing: number, count: number) => { heights: Float32Array; paint?: Float32Array; } | Promise<{ heights: Float32Array; paint?: Float32Array; }>) | undefined
+```
+
+## TerrainStatus — interface @experimental
+```
+reason: string | undefined
+state: "failed" | "ready" | "loading"
+```
+
+## TerrainUnavailable — class @experimental
+```
+static new (message?: string): TerrainUnavailable
+static prototype: TerrainUnavailable
```
## Terrains — class @experimental
@@ -9741,6 +9807,7 @@ heightAt: (x: number, z: number) => number | null
loading: boolean
normalAt: (x: number, z: number) => [number, number, number] | null
pending: number
+status: (entity: Entity) => TerrainStatus | null
static new (): Terrains
static prototype: Terrains
```
@@ -13751,7 +13818,7 @@ Logger
## makePage — function @experimental
```
-(source: TerrainSource, x0: number, z0: number, size: number): PageImage
+(source: TerrainSource, x0: number, z0: number, size: number): PageImage | Promise<PageImage>
```
## makeWidgetInteractable — function @experimental
@@ -13874,6 +13941,11 @@ NodePlatformAdapter
(level: number, ix: number, iz: number): string
```
+## noiseProvider — function @experimental
+```
+(params: (seed: number) => NoiseParams): TerrainProvider
+```
+
## noised — function @experimental
```
(x: number, y: number, seed: number): [number, number, number]
@@ -14399,6 +14471,11 @@ PrefabsPlugin
(id: string, descriptor: SideModuleDescriptor): void
```
+## registerTerrainProvider — function @experimental
+```
+(provider: TerrainProvider): void
+```
+
## registerValue — function @experimental
```
(name: string, spec: AiValueSpec<AiContext>): void
@@ -15104,6 +15181,11 @@ StatsPlugin
Plugin
```
+## terrainProvider — function @experimental
+```
+(id: string): TerrainProvider | undefined
+```
+
## textInputPlugin — const @experimental
```
TextInputPlugin
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 37b54dc9d..b64b13ea9 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 · 1793 experimental · 3 deprecated
+Symbols: 115 public · 159 beta · 1803 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -6028,6 +6028,11 @@ ComponentDef<MotorJoint2DData>
Record<GraphNodeType, NodeSpec>
```
+## NOISE_PROVIDER — const @experimental
+```
+"estella:noise"
+```
+
## Name — const @public
```
ComponentDef<NameData>
@@ -7470,6 +7475,24 @@ name: string
type: "property"
```
+## ProviderSource — class @experimental
+```
+bounds: null
+height: (x: number, z: number) => number | null
+infinite: true
+maxHeight: number
+minHeight: number
+normal: (x: number, z: number) => [number, number, number] | null
+paint: (_x: number, _z: number, h: number, ny: number) => [number, number, number, number]
+provider: TerrainProvider
+region: (x0: number, z0: number, spacing: number, count: number) => TerrainSamples | Promise<TerrainSamples>
+seed: number
+version: number
+world: string
+static new (provider: TerrainProvider, world: string, seed: number, version: number, originX: number, originZ: number, pointSpacing: number, paintRules: (h: number, ny: number) => [number, number, number, number]): ProviderSource
+static prototype: ProviderSource
+```
+
## PseudoLocalizationOptions — interface @experimental
```
accents: boolean | undefined
@@ -9971,6 +9994,7 @@ drawDistance: number
erosion: number
extent: number
frequency: number
+generatorVersion: number
height: number
heightmap: number
layerColor0: Color
@@ -9980,6 +10004,7 @@ layerColor3: Color
material: number
octaves: number
persistence: number
+provider: string
resolution: number
ridged: number
rockSlope: number
@@ -9989,6 +10014,7 @@ sizeZ: number
snowHeight: number
splatmap: number
warp: number
+world: string
```
## TerrainExtent — const @experimental
@@ -10015,6 +10041,32 @@ static new (): TerrainPlugin
static prototype: TerrainPlugin
```
+## TerrainProvider — interface @experimental
+```
+heightAt: ((world: string, seed: number, version: number, x: number, z: number) => number) | undefined
+id: string
+range: (seed: number, version: number) => [number, number]
+sample: (region: TerrainRegion) => TerrainSamples | Promise<TerrainSamples>
+versions: readonly number[]
+```
+
+## TerrainRegion — interface @experimental
+```
+count: number
+seed: number
+spacing: number
+version: number
+world: string
+x0: number
+z0: number
+```
+
+## TerrainSamples — interface @experimental
+```
+heights: Float32Array<ArrayBufferLike>
+paint: Float32Array<ArrayBufferLike> | undefined
+```
+
## TerrainSource — interface @experimental
```
bounds: readonly [number, number, number, number] | null
@@ -10022,7 +10074,21 @@ height: (x: number, z: number) => number | null
infinite: boolean
maxHeight: number
minHeight: number
+normal: (x: number, z: number) => [number, number, number] | null
paint: (x: number, z: number, h: number, ny: number) => [number, number, number, number]
+region: ((x0: number, z0: number, spacing: number, count: number) => { heights: Float32Array; paint?: Float32Array; } | Promise<{ heights: Float32Array; paint?: Float32Array; }>) | undefined
+```
+
+## TerrainStatus — interface @experimental
+```
+reason: string | undefined
+state: "failed" | "ready" | "loading"
+```
+
+## TerrainUnavailable — class @experimental
+```
+static new (message?: string): TerrainUnavailable
+static prototype: TerrainUnavailable
```
## Terrains — class @experimental
@@ -10034,6 +10100,7 @@ heightAt: (x: number, z: number) => number | null
loading: boolean
normalAt: (x: number, z: number) => [number, number, number] | null
pending: number
+status: (entity: Entity) => TerrainStatus | null
static new (): Terrains
static prototype: Terrains
```
@@ -14060,7 +14127,7 @@ Logger
## makePage — function @experimental
```
-(source: TerrainSource, x0: number, z0: number, size: number): PageImage
+(source: TerrainSource, x0: number, z0: number, size: number): PageImage | Promise<PageImage>
```
## makeWidgetInteractable — function @experimental
@@ -14178,6 +14245,11 @@ MeshRendererPlugin
(level: number, ix: number, iz: number): string
```
+## noiseProvider — function @experimental
+```
+(params: (seed: number) => NoiseParams): TerrainProvider
+```
+
## noised — function @experimental
```
(x: number, y: number, seed: number): [number, number, number]
@@ -14703,6 +14775,11 @@ PrefabsPlugin
(id: string, descriptor: SideModuleDescriptor): void
```
+## registerTerrainProvider — function @experimental
+```
+(provider: TerrainProvider): void
+```
+
## registerValue — function @experimental
```
(name: string, spec: AiValueSpec<AiContext>): void
@@ -15408,6 +15485,11 @@ StatsPlugin
Plugin
```
+## terrainProvider — function @experimental
+```
+(id: string): TerrainProvider | undefined
+```
+
## textInputPlugin — const @experimental
```
TextInputPlugin
diff --git a/sdk/etc/terrain.api.md b/sdk/etc/terrain.api.md
index 7e441dbf2..40f7ee653 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 · 39 experimental · 0 deprecated
+Symbols: 0 public · 0 beta · 49 experimental · 0 deprecated
## Eroded — interface @experimental
```
@@ -39,6 +39,11 @@ height: number
width: number
```
+## NOISE_PROVIDER — const @experimental
+```
+"estella:noise"
+```
+
## NoiseParams — type @experimental
```
Pick<TerrainData, 'seed' | 'frequency' | 'octaves' | 'persistence' | 'ridged' | 'warp' | 'erosion' | 'sizeX' | 'height'
@@ -117,6 +122,24 @@ seed: number
warp: number | undefined
```
+## ProviderSource — class @experimental
+```
+bounds: null
+height: (x: number, z: number) => number | null
+infinite: true
+maxHeight: number
+minHeight: number
+normal: (x: number, z: number) => [number, number, number] | null
+paint: (_x: number, _z: number, h: number, ny: number) => [number, number, number, number]
+provider: TerrainProvider
+region: (x0: number, z0: number, spacing: number, count: number) => TerrainSamples | Promise<TerrainSamples>
+seed: number
+version: number
+world: string
+static new (provider: TerrainProvider, world: string, seed: number, version: number, originX: number, originZ: number, pointSpacing: number, paintRules: (h: number, ny: number) => [number, number, number, number]): ProviderSource
+static prototype: ProviderSource
+```
+
## QuadtreeParams — interface @experimental
```
bounds: readonly [number, number, number, number] | null
@@ -148,6 +171,7 @@ drawDistance: number
erosion: number
extent: number
frequency: number
+generatorVersion: number
height: number
heightmap: number
layerColor0: Color
@@ -157,6 +181,7 @@ layerColor3: Color
material: number
octaves: number
persistence: number
+provider: string
resolution: number
ridged: number
rockSlope: number
@@ -166,6 +191,7 @@ sizeZ: number
snowHeight: number
splatmap: number
warp: number
+world: string
```
## TerrainExtent — const @experimental
@@ -192,6 +218,32 @@ static new (): TerrainPlugin
static prototype: TerrainPlugin
```
+## TerrainProvider — interface @experimental
+```
+heightAt: ((world: string, seed: number, version: number, x: number, z: number) => number) | undefined
+id: string
+range: (seed: number, version: number) => [number, number]
+sample: (region: TerrainRegion) => TerrainSamples | Promise<TerrainSamples>
+versions: readonly number[]
+```
+
+## TerrainRegion — interface @experimental
+```
+count: number
+seed: number
+spacing: number
+version: number
+world: string
+x0: number
+z0: number
+```
+
+## TerrainSamples — interface @experimental
+```
+heights: Float32Array<ArrayBufferLike>
+paint: Float32Array<ArrayBufferLike> | undefined
+```
+
## TerrainSource — interface @experimental
```
bounds: readonly [number, number, number, number] | null
@@ -199,7 +251,21 @@ height: (x: number, z: number) => number | null
infinite: boolean
maxHeight: number
minHeight: number
+normal: (x: number, z: number) => [number, number, number] | null
paint: (x: number, z: number, h: number, ny: number) => [number, number, number, number]
+region: ((x0: number, z0: number, spacing: number, count: number) => { heights: Float32Array; paint?: Float32Array; } | Promise<{ heights: Float32Array; paint?: Float32Array; }>) | undefined
+```
+
+## TerrainStatus — interface @experimental
+```
+reason: string | undefined
+state: "failed" | "ready" | "loading"
+```
+
+## TerrainUnavailable — class @experimental
+```
+static new (message?: string): TerrainUnavailable
+static prototype: TerrainUnavailable
```
## Terrains — class @experimental
@@ -211,6 +277,7 @@ heightAt: (x: number, z: number) => number | null
loading: boolean
normalAt: (x: number, z: number) => [number, number, number] | null
pending: number
+status: (entity: Entity) => TerrainStatus | null
static new (): Terrains
static prototype: Terrains
```
@@ -252,7 +319,7 @@ ResourceDef<Terrains>
## makePage — function @experimental
```
-(source: TerrainSource, x0: number, z0: number, size: number): PageImage
+(source: TerrainSource, x0: number, z0: number, size: number): PageImage | Promise<PageImage>
```
## nodeKey — function @experimental
@@ -260,6 +327,11 @@ ResourceDef<Terrains>
(level: number, ix: number, iz: number): string
```
+## noiseProvider — function @experimental
+```
+(params: (seed: number) => NoiseParams): TerrainProvider
+```
+
## noised — function @experimental
```
(x: number, y: number, seed: number): [number, number, number]
@@ -280,6 +352,11 @@ ResourceDef<Terrains>
(p: ProceduralParams): Heightfield
```
+## registerTerrainProvider — function @experimental
+```
+(provider: TerrainProvider): void
+```
+
## sampleHeight — function @experimental
```
(field: Heightfield, u: number, v: number): number
@@ -300,3 +377,8 @@ ResourceDef<Terrains>
Plugin
```
+## terrainProvider — function @experimental
+```
+(id: string): TerrainProvider | undefined
+```
+
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index da0520d9d..006c18707 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 · 1784 experimental · 3 deprecated
+Symbols: 115 public · 159 beta · 1794 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -5742,6 +5742,11 @@ ComponentDef<MotorJoint2DData>
Record<GraphNodeType, NodeSpec>
```
+## NOISE_PROVIDER — const @experimental
+```
+"estella:noise"
+```
+
## Name — const @public
```
ComponentDef<NameData>
@@ -7184,6 +7189,24 @@ name: string
type: "property"
```
+## ProviderSource — class @experimental
+```
+bounds: null
+height: (x: number, z: number) => number | null
+infinite: true
+maxHeight: number
+minHeight: number
+normal: (x: number, z: number) => [number, number, number] | null
+paint: (_x: number, _z: number, h: number, ny: number) => [number, number, number, number]
+provider: TerrainProvider
+region: (x0: number, z0: number, spacing: number, count: number) => TerrainSamples | Promise<TerrainSamples>
+seed: number
+version: number
+world: string
+static new (provider: TerrainProvider, world: string, seed: number, version: number, originX: number, originZ: number, pointSpacing: number, paintRules: (h: number, ny: number) => [number, number, number, number]): ProviderSource
+static prototype: ProviderSource
+```
+
## PseudoLocalizationOptions — interface @experimental
```
accents: boolean | undefined
@@ -9685,6 +9708,7 @@ drawDistance: number
erosion: number
extent: number
frequency: number
+generatorVersion: number
height: number
heightmap: number
layerColor0: Color
@@ -9694,6 +9718,7 @@ layerColor3: Color
material: number
octaves: number
persistence: number
+provider: string
resolution: number
ridged: number
rockSlope: number
@@ -9703,6 +9728,7 @@ sizeZ: number
snowHeight: number
splatmap: number
warp: number
+world: string
```
## TerrainExtent — const @experimental
@@ -9729,6 +9755,32 @@ static new (): TerrainPlugin
static prototype: TerrainPlugin
```
+## TerrainProvider — interface @experimental
+```
+heightAt: ((world: string, seed: number, version: number, x: number, z: number) => number) | undefined
+id: string
+range: (seed: number, version: number) => [number, number]
+sample: (region: TerrainRegion) => TerrainSamples | Promise<TerrainSamples>
+versions: readonly number[]
+```
+
+## TerrainRegion — interface @experimental
+```
+count: number
+seed: number
+spacing: number
+version: number
+world: string
+x0: number
+z0: number
+```
+
+## TerrainSamples — interface @experimental
+```
+heights: Float32Array<ArrayBufferLike>
+paint: Float32Array<ArrayBufferLike> | undefined
+```
+
## TerrainSource — interface @experimental
```
bounds: readonly [number, number, number, number] | null
@@ -9736,7 +9788,21 @@ height: (x: number, z: number) => number | null
infinite: boolean
maxHeight: number
minHeight: number
+normal: (x: number, z: number) => [number, number, number] | null
paint: (x: number, z: number, h: number, ny: number) => [number, number, number, number]
+region: ((x0: number, z0: number, spacing: number, count: number) => { heights: Float32Array; paint?: Float32Array; } | Promise<{ heights: Float32Array; paint?: Float32Array; }>) | undefined
+```
+
+## TerrainStatus — interface @experimental
+```
+reason: string | undefined
+state: "failed" | "ready" | "loading"
+```
+
+## TerrainUnavailable — class @experimental
+```
+static new (message?: string): TerrainUnavailable
+static prototype: TerrainUnavailable
```
## Terrains — class @experimental
@@ -9748,6 +9814,7 @@ heightAt: (x: number, z: number) => number | null
loading: boolean
normalAt: (x: number, z: number) => [number, number, number] | null
pending: number
+status: (entity: Entity) => TerrainStatus | null
static new (): Terrains
static prototype: Terrains
```
@@ -13787,7 +13854,7 @@ Logger
## makePage — function @experimental
```
-(source: TerrainSource, x0: number, z0: number, size: number): PageImage
+(source: TerrainSource, x0: number, z0: number, size: number): PageImage | Promise<PageImage>
```
## makeWidgetInteractable — function @experimental
@@ -13905,6 +13972,11 @@ MeshRendererPlugin
(level: number, ix: number, iz: number): string
```
+## noiseProvider — function @experimental
+```
+(params: (seed: number) => NoiseParams): TerrainProvider
+```
+
## noised — function @experimental
```
(x: number, y: number, seed: number): [number, number, number]
@@ -14430,6 +14502,11 @@ PrefabsPlugin
(id: string, descriptor: SideModuleDescriptor): void
```
+## registerTerrainProvider — function @experimental
+```
+(provider: TerrainProvider): void
+```
+
## registerValue — function @experimental
```
(name: string, spec: AiValueSpec<AiContext>): void
@@ -15135,6 +15212,11 @@ StatsPlugin
Plugin
```
+## terrainProvider — function @experimental
+```
+(id: string): TerrainProvider | undefined
+```
+
## textInputPlugin — const @experimental
```
TextInputPlugin
diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.ts
index 4604b20d1..eac6c5c9d 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, TerrainExtent, Terrains, TerrainsRes, TerrainPlugin, terrainPlugin, paintWeights, type TerrainData,
+ Terrain, TerrainExtent, Terrains, TerrainsRes, TerrainPlugin, terrainPlugin, paintWeights, NOISE_PROVIDER, type TerrainData, type TerrainStatus,
} from './terrain/terrainPlugin';
export {
Foliage, FoliageField, FoliageRes, FoliagePlugin, foliagePlugin, type FoliageData,
@@ -822,6 +822,10 @@ export { FieldSource, NoiseSource, noised, type NoiseParams, type Splat, type Te
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 {
+ noiseProvider, ProviderSource, registerTerrainProvider, terrainProvider, TerrainUnavailable,
+ type TerrainProvider, type TerrainRegion, type TerrainSamples,
+} from './terrain/provider';
export {
mergeMeshes, planStaticBatches, STATIC_BATCH_DEFAULTS,
type StaticBatchGroup, type StaticBatchLimits, type StaticBatchRefusal, type StaticBatchReport,
diff --git a/sdk/src/terrain/index.ts b/sdk/src/terrain/index.ts
index 1bf74ad36..34c011ecf 100644
--- a/sdk/src/terrain/index.ts
+++ b/sdk/src/terrain/index.ts
@@ -1,7 +1,7 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
export {
- Terrain, TerrainExtent, Terrains, TerrainsRes, TerrainPlugin, terrainPlugin, paintWeights, type TerrainData,
+ Terrain, TerrainExtent, Terrains, TerrainsRes, TerrainPlugin, terrainPlugin, paintWeights, NOISE_PROVIDER, type TerrainData, type TerrainStatus,
} from './terrainPlugin';
export {
erodeHeightfield, erosionJob, heightfieldFromPixels, proceduralHeightfield, sampleHeight, terrainNormal,
@@ -11,6 +11,10 @@ export { FieldSource, NoiseSource, noised, type NoiseParams, type Splat, type Te
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';
+export {
+ noiseProvider, ProviderSource, registerTerrainProvider, terrainProvider, TerrainUnavailable,
+ type TerrainProvider, type TerrainRegion, type TerrainSamples,
+} from './provider';
// 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
index 28ac051f6..173c5d4c2 100644
--- a/sdk/src/terrain/pages.ts
+++ b/sdk/src/terrain/pages.ts
@@ -35,19 +35,30 @@ export interface PageImage { heights: Uint8Array; paint: Uint8Array; min: 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.
+ * the source's range. Off an area's edge the ground is its nearest edge's, so the pages there are whole. A source that samples regions
+ * (a provider) is asked for the page's whole grid at once, and may answer later.
*/
-export function makePage(source: TerrainSource, x0: number, z0: number, size: number): PageImage {
+export function makePage(source: TerrainSource, x0: number, z0: number, size: number): PageImage | Promise<PageImage> {
const n = PAGE_SIDE, step = size / PAGE_TEXELS;
+ if (source.region) {
+ const got = source.region(x0 - step, z0 - step, step, n);
+ return got instanceof Promise ? got.then((r) => encodePage(source, x0, z0, step, r.heights, r.paint)) : encodePage(source, x0, z0, step, got.heights, got.paint);
+ }
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); }
+ h[j * n + i] = source.height(x, z) ?? source.minHeight;
}
+ return encodePage(source, x0, z0, step, h);
+}
+
+/** Encodes a page's samples (row by row, one past each edge): heights and normals into one image, the paint into the other. */
+function encodePage(source: TerrainSource, x0: number, z0: number, step: number, h: Float32Array, given?: Float32Array): PageImage {
+ const n = PAGE_SIDE;
+ const [bx0, bz0, bx1, bz1] = source.bounds ?? [-Infinity, -Infinity, Infinity, Infinity];
+ let min = Infinity, max = -Infinity;
+ for (let j = 1; j <= n - 2; j++) for (let i = 1; i <= n - 2; i++) { const v = h[j * n + i]!; 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++) {
@@ -63,7 +74,7 @@ export function makePage(source: TerrainSource, x0: number, z0: number, size: nu
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);
+ const w = given ? [given[k * 4]!, given[k * 4 + 1]!, given[k * 4 + 2]!, given[k * 4 + 3]!] : 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 };
diff --git a/sdk/src/terrain/provider.ts b/sdk/src/terrain/provider.ts
new file mode 100644
index 000000000..8785ebaf0
--- /dev/null
+++ b/sdk/src/terrain/provider.ts
@@ -0,0 +1,161 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file provider.ts
+ * @brief Ground made by a generator a game names: one function of the world's position, versioned, the same on every machine.
+ *
+ * @details A provider samples the ground over a region it is handed: a world, a seed, a generator version, a corner in world units, a
+ * spacing and a count. Every region is the same function read at other points, so two regions that share an edge share its
+ * samples, a coarse page and a fine one agree where their samples coincide, and the order regions are asked in changes nothing.
+ * The client draws from it, the server answers from it, and what stands on the ground is placed by it: one source.
+ *
+ * A version names an algorithm for good. A saved world keeps the version it was made with; a provider that changes its algorithm
+ * adds a version and keeps the old one, and a terrain asking for a version its provider does not have fails, loudly, rather than
+ * growing other ground under what was built on it. The engine's own noise is the provider `estella:noise`, version 1.
+ */
+import type { TerrainSource } from './source';
+import { NoiseSource, type NoiseParams } from './source';
+
+/** Where and how finely a provider is asked to sample. */
+export interface TerrainRegion {
+ /** The world (a planet, a level) the ground belongs to, as the game names it. */
+ world: string;
+ seed: number;
+ /** The generator version the world was made with. */
+ version: number;
+ /** The world position of the first sample, and the distance between samples along x and z. */
+ x0: number;
+ z0: number;
+ spacing: number;
+ /** Samples along each side: `count * count` of them, row by row from z0, each row from x0. */
+ count: number;
+}
+
+/** What a provider answers for a region: heights in world units and, if it paints the ground, four layer weights a sample. */
+export interface TerrainSamples {
+ heights: Float32Array;
+ /** Grass, dirt, snow, rock, 0 to 1, four a sample; absent leaves the terrain to paint by height and slope. */
+ paint?: Float32Array;
+}
+
+/** A generator of ground. */
+export interface TerrainProvider {
+ /** The name a Terrain asks for it by. */
+ readonly id: string;
+ /** The generator versions it can still make. */
+ readonly versions: readonly number[];
+ /** The least and most height its ground can have for this seed and version: what the GPU encodes heights over. */
+ range(seed: number, version: number): [number, number];
+ /** The ground over a region. May answer later (a worker, a server); must answer the same for the same region every time. */
+ sample(region: TerrainRegion): TerrainSamples | Promise<TerrainSamples>;
+ /** The height at one point, for a provider that can answer one at once; without it a point is answered from sampled regions. */
+ heightAt?(world: string, seed: number, version: number, x: number, z: number): number;
+}
+
+const providers_ = new Map<string, TerrainProvider>();
+
+/** Makes `provider` available to every Terrain that names it. A second provider under the same id replaces the first. */
+export function registerTerrainProvider(provider: TerrainProvider): void {
+ providers_.set(provider.id, provider);
+}
+
+/** The provider registered under `id`, if any. */
+export function terrainProvider(id: string): TerrainProvider | undefined {
+ return providers_.get(id);
+}
+
+/** Why a terrain's ground could not be made. */
+export class TerrainUnavailable extends Error {}
+
+/** The size of the tiles a point is answered from when its provider has no `heightAt`: this many samples a side. */
+const POINT_TILE = 33;
+
+/** Ground from a provider, as a terrain draws and answers it. Positions are world positions less the terrain's own. */
+export class ProviderSource implements TerrainSource {
+ readonly infinite = true;
+ readonly bounds = null;
+ readonly minHeight: number;
+ readonly maxHeight: number;
+ /** Tiles of samples a point is answered from, by key; a tile asked for and not yet answered is a promise. */
+ private readonly tiles_ = new Map<string, TerrainSamples | Promise<TerrainSamples>>();
+
+ constructor(
+ readonly provider: TerrainProvider,
+ readonly world: string,
+ readonly seed: number,
+ readonly version: number,
+ /** The terrain's own position, which the provider's world positions are offset by. */
+ private readonly originX: number,
+ private readonly originZ: number,
+ /** The spacing a point's tile is sampled at: the finest the terrain is drawn at. */
+ private readonly pointSpacing: number,
+ private readonly paintRules: (h: number, ny: number) => [number, number, number, number],
+ ) {
+ if (!provider.versions.includes(version)) {
+ throw new TerrainUnavailable(`the terrain provider ${provider.id} has no version ${version} (it has ${provider.versions.join(', ') || 'none'})`);
+ }
+ [this.minHeight, this.maxHeight] = provider.range(seed, version);
+ }
+
+ /** The ground over a region of the terrain's space, from the provider. */
+ region(x0: number, z0: number, spacing: number, count: number): TerrainSamples | Promise<TerrainSamples> {
+ return this.provider.sample({ world: this.world, seed: this.seed, version: this.version, x0: x0 + this.originX, z0: z0 + this.originZ, spacing, count });
+ }
+
+ height(x: number, z: number): number | null {
+ const p = this.provider;
+ if (p.heightAt) return p.heightAt(this.world, this.seed, this.version, x + this.originX, z + this.originZ);
+ // From the tile the point falls in, bilinear between its samples (the same samples the pages hold at the finest level).
+ const span = this.pointSpacing * (POINT_TILE - 1);
+ const tx = Math.floor(x / span), tz = Math.floor(z / span);
+ const key = `${tx}:${tz}`;
+ let tile = this.tiles_.get(key);
+ if (!tile) {
+ tile = this.region(tx * span, tz * span, this.pointSpacing, POINT_TILE);
+ this.tiles_.set(key, tile);
+ if (tile instanceof Promise) void tile.then((t) => this.tiles_.set(key, t), () => this.tiles_.delete(key));
+ }
+ if (tile instanceof Promise) return null;
+ const fx = (x - tx * span) / this.pointSpacing, fz = (z - tz * span) / this.pointSpacing;
+ const i = Math.min(Math.floor(fx), POINT_TILE - 2), j = Math.min(Math.floor(fz), POINT_TILE - 2);
+ const u = fx - i, v = fz - j, h = tile.heights, n = POINT_TILE;
+ const a = h[j * n + i]!, b = h[j * n + i + 1]!, c = h[(j + 1) * n + i]!, d = h[(j + 1) * n + i + 1]!;
+ return a + (b - a) * u + (c - a) * v + (a - b - c + d) * u * v;
+ }
+
+ /** The normal at (x, z), from the heights a spacing either side; null where they are not known yet. */
+ normal(x: number, z: number): [number, number, number] | null {
+ const e = this.pointSpacing;
+ const l = this.height(x - e, z), r = this.height(x + e, z), d = this.height(x, z - e), u = this.height(x, z + e);
+ if (l === null || r === null || d === null || u === null) return null;
+ const sx = (r - l) / (2 * e), sz = (u - d) / (2 * e);
+ 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 this.paintRules(h, ny);
+ }
+}
+
+/** The engine's own ground without end: seeded noise of the world's position, as `estella:noise` version 1. */
+export function noiseProvider(params: (seed: number) => NoiseParams): TerrainProvider {
+ const sources = new Map<number, NoiseSource>();
+ const source = (seed: number): NoiseSource => {
+ let s = sources.get(seed);
+ if (!s) { s = new NoiseSource(params(seed)); sources.set(seed, s); }
+ return s;
+ };
+ return {
+ id: 'estella:noise',
+ versions: [1],
+ range: (seed) => [0, source(seed).maxHeight],
+ sample(r) {
+ const s = source(r.seed);
+ const heights = new Float32Array(r.count * r.count);
+ for (let j = 0; j < r.count; j++) for (let i = 0; i < r.count; i++) heights[j * r.count + i] = s.height(r.x0 + i * r.spacing, r.z0 + j * r.spacing);
+ return { heights };
+ },
+ heightAt: (_world, seed, _version, x, z) => source(seed).height(x, z),
+ };
+}
diff --git a/sdk/src/terrain/source.ts b/sdk/src/terrain/source.ts
index 536204d86..8d01eb7da 100644
--- a/sdk/src/terrain/source.ts
+++ b/sdk/src/terrain/source.ts
@@ -25,10 +25,17 @@ export interface TerrainSource {
/** 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. */
+ /** The height at (x, z), or null off the area (or where a provider has not answered yet). */
height(x: number, z: number): number | null;
+ /** The ground's unit normal at (x, z), or null where the height is not known. */
+ normal(x: number, z: number): [number, 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 ground over a grid of `count` by `count` samples `spacing` apart from (x0, z0), when the source samples whole regions (a
+ * provider, which may answer later); without it the pages read `height` and `paint` point by point.
+ */
+ region?(x0: number, z0: number, spacing: number, count: number): { heights: Float32Array; paint?: Float32Array } | Promise<{ heights: Float32Array; paint?: Float32Array }>;
}
/** The pixels of a splatmap, as the terrain read them. */
diff --git a/sdk/src/terrain/terrainPlugin.ts b/sdk/src/terrain/terrainPlugin.ts
index 45596544f..7a875f22d 100644
--- a/sdk/src/terrain/terrainPlugin.ts
+++ b/sdk/src/terrain/terrainPlugin.ts
@@ -33,18 +33,29 @@ import { log } from '../util/logger';
import { bakesOf } from '../runtime/bakes';
import type { Color, Entity } from '../types';
import { erosionJob, heightfieldFromPixels, proceduralHeightfield } from './heightfield';
-import { FieldSource, NoiseSource, type TerrainSource } from './source';
+import { FieldSource, 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 { makePage, PageTable, PAGE_SIDE, PAGE_TEXELS, PATCH_CELLS, type PageImage } from './pages';
+import { noiseProvider, ProviderSource, terrainProvider, TerrainUnavailable } from './provider';
import { buildPatchMesh } from './patch';
+/** The engine's own provider of ground without end: seeded noise of the world's position. */
+export const NOISE_PROVIDER = 'estella:noise';
+
/** 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). */
+ /** {@link TerrainExtent}: an area `sizeX` by `sizeZ`, or ground that goes on for ever (from a provider, read anywhere). */
extent: number;
+ /**
+ * Ground without end: the provider it is made by (`estella:noise`, the engine's noise, or one a game registers with
+ * registerTerrainProvider), the world it belongs to as the game names it, and the generator version that world was made with.
+ */
+ provider: string;
+ world: string;
+ generatorVersion: 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. */
@@ -92,7 +103,7 @@ const rgb = (r: number, g: number, b: number): Color => ({ r, g, b, a: 1 });
* @experimental
*/
export const Terrain: ComponentDef<TerrainData> = defineComponent<TerrainData>('Terrain', {
- extent: TerrainExtent.Area, heightmap: 0, splatmap: 0, material: 0,
+ extent: TerrainExtent.Area, provider: NOISE_PROVIDER, world: '', generatorVersion: 1, 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,
@@ -101,7 +112,10 @@ export const Terrain: ComponentDef<TerrainData> = defineComponent<TerrainData>('
assetFields: [{ field: 'heightmap', type: 'texture' }, { field: 'splatmap', type: 'texture' }, { field: 'material', type: 'material' }],
fields: {
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] } },
+ provider: { category: 'Shape', tooltip: 'The generator ground without end is made by: estella:noise, or one the game registers. The same provider, world, seed and version are the same ground on every machine.', shownWhen: { field: 'extent', values: [TerrainExtent.Infinite] } },
+ world: { category: 'Shape', tooltip: 'The world (a planet, a level) the ground belongs to, as the game names it; handed to the provider.', shownWhen: { field: 'extent', values: [TerrainExtent.Infinite] } },
+ generatorVersion: { min: 1, step: 1, category: 'Shape', tooltip: 'The generator version the world was made with. A version the provider no longer has fails the terrain rather than growing other ground under what was built.', shownWhen: { field: 'extent', values: [TerrainExtent.Infinite] } },
+ heightmap: { tooltip: 'A heightmap image: red is the height. Empty makes the ground from noise; a heightmap that cannot be read fails the terrain instead.', 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: 'An area\'s size along x; for ground without end, the span its hills are spread over.' },
@@ -168,9 +182,16 @@ interface Built {
spare: Entity[];
/** Pages wanted and not made yet, by key. */
wanted: Map<string, TerrainNode>;
+ /** Pages asked of a provider that answers later, by key: the frame's budget is not spent waiting for them. */
+ asked: Set<string>;
pending: boolean;
+ /** Why the ground could not be made, once it could not: nothing is drawn or answered for it. */
+ failure: string | null;
}
+/** Where a terrain's ground stands: still being made, ready, or failed (with why). */
+export interface TerrainStatus { state: 'loading' | 'ready' | 'failed'; reason?: string }
+
/** 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>();
@@ -203,14 +224,20 @@ export class Terrains {
const t = world.tryGet(entity, Transform) as TransformData | null;
if (!t) continue;
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;
- }
+ const n = source.normal(lx, lz);
+ if (n) return n;
}
return null;
}
+ /** Where a terrain's ground stands. A failed one draws and answers nothing, and says why. */
+ status(entity: Entity): TerrainStatus | null {
+ const built = this.built_.get(entity);
+ if (!built) return null;
+ if (built.failure) return { state: 'failed', reason: built.failure };
+ return { state: built.loading || !built.source ? 'loading' : 'ready' };
+ }
+
/** @internal Bumped whenever a terrain's ground changes, so what stands on it knows to stand again. */
revision_ = 0;
@@ -249,7 +276,8 @@ export class TerrainPlugin implements Plugin {
app.insertResource(TerrainsRes, terrains);
app.addSystemToSchedule(Schedule.Update, defineSystem([], () => {
- if (!app.hasResource(Assets)) return;
+ // What the ground IS needs no renderer: a server or a test without one still makes the source and answers from it.
+ const rendering = app.hasResource(Assets);
this.sweep(app, terrains);
for (const entity of app.world.getEntitiesWithComponents([Terrain, Transform])) {
const data = app.world.get(entity, Terrain) as TerrainData;
@@ -260,14 +288,14 @@ export class TerrainPlugin implements Plugin {
built = {
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,
+ nodes: new Map(), spare: [], wanted: new Map(), asked: new Set(), pending: false, failure: null,
};
terrains.built_.set(entity, built);
void this.load(app, entity, built);
continue;
}
built.data = { ...data };
- if (built.loading || !built.source) continue;
+ if (built.loading || !built.source || !rendering) continue;
if (!built.instance) {
if (!built.pending) void this.prepare(app, built);
continue;
@@ -292,9 +320,15 @@ export class TerrainPlugin implements Plugin {
const data = built.data;
try {
if (data.extent === TerrainExtent.Infinite) {
- built.source = new NoiseSource(data);
+ const t = app.world.get(entity, Transform) as TransformData;
+ const provider = data.provider === NOISE_PROVIDER ? noiseProvider(() => data) : terrainProvider(data.provider);
+ if (!provider) throw new TerrainUnavailable(`no terrain provider ${data.provider} is registered`);
+ built.source = new ProviderSource(provider, data.world, data.seed, data.generatorVersion, t.worldPosition.x, t.worldPosition.z,
+ Math.max(data.cellSize, 1e-3) / 2, (h, ny) => paintWeights(h / Math.max(provider.range(data.seed, data.generatorVersion)[1], 1e-6), ny, data));
} else {
+ // A heightmap named and not read is a failure: a world built on that ground must not quietly get other ground.
const height = await this.pixelsOf(app, data.heightmap);
+ if (data.heightmap && !height) throw new TerrainUnavailable(`the heightmap (texture ${data.heightmap}) could not be read`);
const splat = await this.pixelsOf(app, data.splatmap);
if (built.epoch !== epoch || !app.world.valid(entity)) return;
const made = height
@@ -319,6 +353,7 @@ export class TerrainPlugin implements Plugin {
}
app.getResource(TerrainsRes).revision_++;
} catch (e) {
+ if (built.epoch === epoch) built.failure = e instanceof Error ? e.message : String(e);
log.error('terrain', 'building the terrain failed', e);
} finally {
if (built.epoch === epoch) built.loading = false;
@@ -326,10 +361,10 @@ export class TerrainPlugin implements Plugin {
}
private async pixelsOf(app: App, handle: number): Promise<{ width: number; height: number; pixels: Uint8Array } | null> {
- if (!handle) return null;
+ if (!handle || !app.hasResource(Assets)) 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; }
+ if (!path) { log.warn('terrain', `no source image is known for texture ${handle}`); 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') {
@@ -479,14 +514,32 @@ export class TerrainPlugin implements Plugin {
|| 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 store = (key: string, image: PageImage): boolean => {
const page = built.table.claim(key, image.min, image.max);
- if (!page) break;
+ if (!page) return false;
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);
+ return true;
+ };
+ const epoch = built.epoch;
+ for (const node of order) {
+ const key = nodeKey(node.level, node.ix, node.iz);
+ if (built.asked.has(key)) continue;
+ const image = makePage(source, node.x0, node.z0, node.size);
+ if (image instanceof Promise) {
+ // A provider answering later: its page is stored when it lands, if the terrain is still the one that asked.
+ built.asked.add(key);
+ void image.then((img) => {
+ built.asked.delete(key);
+ if (built.epoch === epoch && built.heights) store(key, img);
+ }, (e) => {
+ built.asked.delete(key);
+ log.warn('terrain', `the provider failed a page (${key})`, e);
+ });
+ continue;
+ }
+ if (!store(key, image)) break;
built.wanted.delete(key);
made++;
if (performance.now() >= until) break;
diff --git a/sdk/tests/terrain-provider.test.ts b/sdk/tests/terrain-provider.test.ts
new file mode 100644
index 000000000..1b861d75b
--- /dev/null
+++ b/sdk/tests/terrain-provider.test.ts
@@ -0,0 +1,144 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { describe, expect, it } from 'vitest';
+import { App } from '../src/app/app';
+import { AppContext, setDefaultContext } from '../src/ecs/context';
+import { setEditorMode, setPlayMode } from '../src/ecs/env';
+import { Transform } from '../src/ecs/component';
+import { createMockModule } from './mocks/wasm';
+import { Terrain, TerrainExtent, TerrainPlugin, TerrainsRes, paintWeights } from '../src/terrain/terrainPlugin';
+import {
+ noiseProvider, ProviderSource, registerTerrainProvider, TerrainUnavailable, type TerrainProvider, type TerrainRegion,
+} from '../src/terrain/provider';
+import { makePage, PAGE_SIDE, PAGE_TEXELS, type PageImage } from '../src/terrain/pages';
+import type { NoiseParams } from '../src/terrain/source';
+
+const params: NoiseParams = { seed: 7, frequency: 3, octaves: 5, persistence: 0.5, ridged: 0.35, warp: 0.3, erosion: 1, sizeX: 2000, height: 300,
+ rockSlope: 0.35, dirtHeight: 0.62, snowHeight: 0.88 };
+const paint = (h: number, ny: number) => paintWeights(h / 300, ny, params);
+const ground = (provider: TerrainProvider, ox = 0, oz = 0, version = 1) => new ProviderSource(provider, 'planet-a', 7, version, ox, oz, 1, paint);
+
+/** A provider of its own, as a game's generator would be: a function of the world position and the version, answering later. */
+const terraced: TerrainProvider = {
+ id: 'test:terraces',
+ versions: [1, 2],
+ range: () => [0, 100],
+ sample(r: TerrainRegion) {
+ const heights = new Float32Array(r.count * r.count);
+ for (let j = 0; j < r.count; j++) for (let i = 0; i < r.count; i++) {
+ const x = r.x0 + i * r.spacing, z = r.z0 + j * r.spacing;
+ heights[j * r.count + i] = r.version === 1 ? 50 + 20 * Math.sin(x * 0.01) * Math.cos(z * 0.013) : 10;
+ }
+ return Promise.resolve({ heights });
+ },
+};
+
+const heightOf = (page: PageImage, i: number, j: number): number => {
+ const k = (j * PAGE_SIDE + i) * 4;
+ return page.heights[k]! * 256 + page.heights[k + 1]!;
+};
+
+describe('ground from a provider', () => {
+ it('is the same for the same world, seed, version and position', () => {
+ const a = ground(noiseProvider(() => params)), b = ground(noiseProvider(() => params));
+ for (const [x, z] of [[0, 0], [12345.5, -9876.25], [-77777, 31415]] as const) expect(a.height(x, z)).toBe(b.height(x, z));
+ });
+
+ it('is the same ground under two terrains placed apart: positions are the world\'s, not the terrain\'s', () => {
+ const here = ground(noiseProvider(() => params), 0, 0), there = ground(noiseProvider(() => params), 5000, -3000);
+ expect(there.height(100, 200)).toBe(here.height(5100, -2800));
+ });
+
+ it('fails, rather than growing other ground, for a version its provider does not have', () => {
+ expect(() => ground(noiseProvider(() => params), 0, 0, 2)).toThrow(TerrainUnavailable);
+ });
+
+ it('shares every sample of an edge between two neighbouring pages, whichever is made first', () => {
+ const src = ground(noiseProvider(() => params));
+ const size = 64;
+ const west = makePage(src, 0, 0, size) as PageImage, east = makePage(src, size, 0, size) as PageImage;
+ const eastFirst = makePage(src, size, 0, size) as PageImage, westAfter = makePage(src, 0, 0, size) as PageImage;
+ for (let j = 0; j < PAGE_SIDE; j++) {
+ // The west page's far edge (its sample PAGE_TEXELS past the border) is the east page's near edge (its first past the border).
+ expect(heightOf(west, PAGE_TEXELS + 1, j)).toBe(heightOf(east, 1, j));
+ // The normals there are made from the same samples on both sides.
+ const kw = (j * PAGE_SIDE + PAGE_TEXELS + 1) * 4, ke = (j * PAGE_SIDE + 1) * 4;
+ expect(west.heights[kw + 2]).toBe(east.heights[ke + 2]);
+ expect(west.heights[kw + 3]).toBe(east.heights[ke + 3]);
+ }
+ expect(Array.from(eastFirst.heights)).toEqual(Array.from(east.heights));
+ expect(Array.from(westAfter.heights)).toEqual(Array.from(west.heights));
+ });
+
+ it('agrees between a coarse page and a fine one where their samples meet', () => {
+ const src = ground(noiseProvider(() => params));
+ const coarse = makePage(src, 0, 0, 128) as PageImage, fine = makePage(src, 0, 0, 64) as PageImage;
+ // Every second sample of the fine page is a sample of the coarse one.
+ for (let k = 0; k <= PAGE_TEXELS; k += 2) expect(heightOf(fine, 1 + k, 1)).toBe(heightOf(coarse, 1 + k / 2, 1));
+ });
+
+ it('takes a game\'s own provider, which may answer later, and keeps its versions apart', async () => {
+ registerTerrainProvider(terraced);
+ const v1 = new ProviderSource(terraced, 'planet-b', 1, 1, 0, 0, 1, paint);
+ const v2 = new ProviderSource(terraced, 'planet-b', 1, 2, 0, 0, 1, paint);
+ const p1 = makePage(v1, 0, 0, 64), p2 = makePage(v2, 0, 0, 64);
+ expect(p1).toBeInstanceOf(Promise);
+ const [a, b] = await Promise.all([p1, p2]);
+ expect(a.max).toBeGreaterThan(b.max);
+ // A point is answered once its tile has come in.
+ expect(v1.height(10, 10)).toBeNull();
+ await new Promise((r) => setTimeout(r, 0));
+ expect(v1.height(10, 10)).toBeCloseTo(50 + 20 * Math.sin(0.1) * Math.cos(0.13), 3);
+ });
+});
+
+describe('a Terrain with no renderer (a server)', () => {
+ const boot = (): App => {
+ setDefaultContext(new AppContext());
+ setEditorMode(false);
+ setPlayMode(false);
+ const app = App.new();
+ const module = createMockModule();
+ app.connectCpp(module.getRegistry(), module);
+ app.addPlugin(new TerrainPlugin());
+ return app;
+ };
+ const settle = async (app: App) => { for (let i = 0; i < 4; i++) { app.tick(1 / 60); await new Promise((r) => setTimeout(r, 0)); } };
+
+ it('answers the height of ground without end, the same as the provider', async () => {
+ const app = boot();
+ const e = app.world.spawn();
+ app.world.insert(e, Transform, {});
+ app.world.insert(e, Terrain, { ...Terrain._default, extent: TerrainExtent.Infinite, ...params });
+ await settle(app);
+ const terrains = app.getResource(TerrainsRes);
+ expect(terrains.status(e)).toEqual({ state: 'ready' });
+ expect(terrains.heightAt(321, -654)).toBeCloseTo(ground(noiseProvider(() => params)).height(321, -654)!, 6);
+ });
+
+ it('fails, and answers nothing, when its provider is not registered or its version is gone', async () => {
+ const app = boot();
+ const missing = app.world.spawn(), old = app.world.spawn();
+ for (const e of [missing, old]) app.world.insert(e, Transform, {});
+ app.world.insert(missing, Terrain, { ...Terrain._default, extent: TerrainExtent.Infinite, provider: 'test:nowhere' });
+ app.world.insert(old, Terrain, { ...Terrain._default, extent: TerrainExtent.Infinite, generatorVersion: 9 });
+ await settle(app);
+ const terrains = app.getResource(TerrainsRes);
+ expect(terrains.status(missing)!.state).toBe('failed');
+ expect(terrains.status(old)!.state).toBe('failed');
+ expect(terrains.status(old)!.reason).toMatch(/version 9/);
+ expect(terrains.heightAt(0, 0)).toBeNull();
+ });
+
+ it('fails when its heightmap cannot be read, instead of growing noise in its place', async () => {
+ const app = boot();
+ const e = app.world.spawn();
+ app.world.insert(e, Transform, {});
+ app.world.insert(e, Terrain, { ...Terrain._default, heightmap: 42 });
+ await settle(app);
+ const terrains = app.getResource(TerrainsRes);
+ expect(terrains.status(e)!.state).toBe('failed');
+ expect(terrains.status(e)!.reason).toMatch(/heightmap/);
+ expect(terrains.heightAt(0, 0)).toBeNull();
+ });
+});
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index 7622882c1..e19244756 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -2762,4 +2762,6 @@ export const NOTED = {
{"internal":"The generated embed of a shader change that has its own note."},
"docs: the procedural world plan records what the engine owes, where each part stands and how it is accepted":
{"internal":"A planning document; nothing a creator can use yet."},
+ "feat(terrain): ground without end comes from a versioned provider the game names, and a terrain that cannot get its ground fails":
+ {"note":"Terrain from a generator the game names, versioned."},
};