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(render): Terrain and Foliage components with heightmaps, painted layers, wind and level of detail

yhh8f4869063c13
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c0e1544f1..ecc68de97 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -17,6 +17,9 @@ published separately; it ships inside the editor.
### Added
- **Contact shadows and screen-space bounce light.** Contact Shadows and Screen Space GI effects add small sharp shadows at contacts and one bounce of colour between surfaces, and the weather softens the sun's shadows. `contactShadows` marches a short ray toward the scene's sun in the depth buffer; `ssgi` gathers eight rays a pixel over the G-buffer's normals at half size into a float target and averages the neighbours on the same surface before laying the light, times the receiver's colour, over the picture. The Weather component raises the sun's `sourceAngle` and lowers its `shadowStrength` as the sky clouds over.
+- **Wilds example.** Wilds is a new 3D example: a lake under mountains at dusk, made from a generated heightmap with the Terrain, Water and Foliage features and the sky's cloud shadows. Everything in it is made from numbers by `examples/wilds/tools/build.mjs`, so there is no art to credit.
+- **Foliage.** A Foliage component scatters grass or a mesh across an area and over a Terrain, swaying in the wind and thinning out with distance. Each cell of the area is one mesh with all its plants in it, built twice (near, and a far version: fewer broader blades, or two crossed cards a mesh), so a field is a few hundred draws. The **Foliage** shader bends vertices by weights painted in the vertex colour, which a vertex hook of your own can read as `es_vertexColor`. Plants do not collide and do not bend away from a character.
+- **Terrain.** A Terrain component makes ground from a heightmap or noise, paints it with grass, dirt, snow and rock layers, and draws it in chunks that coarsen with distance. Add a `Terrain` component to an entity: its heightmap (or a seed, for noise) sets the shape, and each chunk is built at up to four levels of detail with a skirt that hides the cracks between levels, so the engine's level-of-detail choice needs no knowledge of its neighbours. A **Terrain** material shader draws four texture layers by world position, with the rock projected from three sides. `TerrainsRes.heightAt(x, z)` answers how high the ground is. The ground is drawn, not simulated: it has no collider, and no holes or overhangs.
- **Water.** A Water material: waves that travel, the scene seen through it bent and tinted by how deep the water is, reflections, and foam at the shore and on the crests. Give a horizontal plane a material on the built-in **Water** shader. The depth is measured, not guessed: the frame takes a copy of how far each pixel of the opaque scene is from the eye, so water over a shelf goes from the shore's pale teal to deep blue, with red absorbed first. It needs the same engine-copied scene as glass (a post-process chain running) and a float target for the depth; the waves are drawn in the surface's shading, not as displaced geometry, and the surface is taken to lie flat.
- **Cloud shadows.** The Sky Atmosphere's clouds can now cast shadows on the scene. **Cloud Shadows** marches the sun's ray up through the same cloud slab the sky draws, so the ground is darker and patchier under cloud; it also pins the clouds to the world instead of the camera, and **World Units per km** says how large a kilometre of sky is in the scene. The default is 0, which leaves every existing scene as it was. Ambient light is not shadowed, and the clouds are still only drawn where there is sky.
- **Voxel GI on WebGL2.** Voxel GI now runs on WebGL2: the world-space bounce light is built with fragment passes where there is no compute stage. The result matches the WebGPU one in the editor check; the gather is fixed at half size, grazing surfaces are thinner in the cache, a 32 MB half-float atlas is used, and the `low` quality tier leaves the effect out. Its cost on real GPUs has not been measured.
diff --git a/desktop b/desktop
index 02fc76368..e5a0834e2 160000
--- a/desktop
+++ b/desktop
@@ -1 +1 @@
-Subproject commit 02fc76368d7e8840e52dfdc3e9bfa8293c9838d5
+Subproject commit e5a0834e23d5d38ec49d99dc8b0ef07dad9c1abf
diff --git a/docs/astro/astro.config.mjs b/docs/astro/astro.config.mjs
index 3d916c747..e339c3315 100644
--- a/docs/astro/astro.config.mjs
+++ b/docs/astro/astro.config.mjs
@@ -223,6 +223,8 @@ export default defineConfig({
{ label: 'Materials & Shaders', translations: { 'zh-CN': '材质与着色器' }, slug: 'graphics/materials' },
{ label: '2D Lighting & Shadows', translations: { 'zh-CN': '2D 光照与阴影' }, slug: 'graphics/lighting' },
{ label: 'Post-processing', translations: { 'zh-CN': '后处理' }, slug: 'graphics/post-processing' },
+ { label: 'Terrain', translations: { 'zh-CN': '地形' }, slug: 'graphics/terrain' },
+ { label: 'Foliage', translations: { 'zh-CN': '植被' }, slug: 'graphics/foliage' },
{ label: 'Weather', translations: { 'zh-CN': '天气' }, slug: 'graphics/weather' },
{ label: 'Time of Day', translations: { 'zh-CN': '昼夜' }, slug: 'graphics/time-of-day' },
{ label: 'Custom Drawing', translations: { 'zh-CN': '自定义绘制' }, slug: 'graphics/drawing' },
diff --git a/docs/astro/src/content/docs/graphics/foliage.mdx b/docs/astro/src/content/docs/graphics/foliage.mdx
new file mode 100644
index 000000000..f513dfaae
--- /dev/null
+++ b/docs/astro/src/content/docs/graphics/foliage.mdx
@@ -0,0 +1,52 @@
+---
+title: Foliage
+description: A Foliage component that scatters grass or a mesh across an area and over a terrain, draws it a cell at a time, sways it in the wind and thins it out with distance.
+---
+
+A field of grass is tens of thousands of blades and a forest is thousands of trees, which no engine draws one entity at a time. The `Foliage`
+component grows them as **cells**: the area is cut into squares and each square is one mesh with all its plants in it, so a field is a few
+hundred draws that culling can drop whole, and each cell is built at the detail its distance deserves.
+
+## The component
+
+Add a `Foliage` component to an entity. The area is centred on it, and its children are the cells, made when the scene runs (and in the
+editor's scene view) and made again when a field changes. Nothing is baked.
+
+| Field | What it does |
+|---|---|
+| `mesh` | The plant to scatter. Empty grows grass, with blades made here. |
+| `material` | A material on the **Foliage** shader, which makes the wind (below). Empty draws the plants still, in their own colours. |
+| `sizeX`, `sizeZ`, `cellSize` | The area, and the side of the cells it is cut into. |
+| `count`, `seed` | Plants per cell, and the seed: another seed grows the same plants in other places. |
+| `minScale`, `maxScale` | Each plant is given a size between these. |
+| `minUp`, `heightMin`, `heightMax` | Where plants grow: the least a place may face up (lower lets them onto slopes), and a band of world heights. |
+| `bladeHeight`, `bladeWidth` | Grass only: the size of a blade at scale 1. |
+| `lodDistance`, `drawDistance` | Past the first a cell is drawn as its far version; past the second it is not drawn. |
+| `cardU0`, `cardV0`, `cardU1`, `cardV1` | A mesh's far version is two crossed cards showing this rectangle of its texture. |
+
+If the scene has a [Terrain](/docs/graphics/terrain/), plants stand on it, keep off what is too steep, and wait for it to be built; with none, the
+area is flat at the entity's height.
+
+## Wind
+
+The **Foliage** shader (`builtin:foliage`) bends each vertex by a weight painted in its colour (red is how far up the plant it is, so the root
+stays and the tip moves; green is a phase of the plant's own, so a meadow does not sway as one), with a gust that travels across the world and
+a flutter on top. Its parameters are in the material: `u_windStrength`, `u_windSpeed`, `u_windDirection` (degrees), `u_gustScale` (the lower, the
+longer a gust) and `u_flutter`. Plants are two-sided and let light through them (`u_translucency`); a leaf texture with an alpha channel
+(`u_albedo`, `u_useTexture`, `u_alphaCutoff`) cuts the outline of a leaf out of a card.
+
+A shader of your own can read the same weights: a vertex hook (`#pragma vertexoffset`) sees the vertex colour as `es_vertexColor`.
+
+## Levels of detail
+
+Each cell is built twice. Near, grass is a bent, tapered blade for every plant; far, a third of the blades, broader and flat. A mesh is
+copied in full near, and far is two crossed cards a plant. The engine's own [level of detail](/docs/performance/level-of-detail/) picks between
+them by how much of the screen the cell covers, and drops the cell past `drawDistance`.
+
+## Limits
+
+- **Position only.** The area is taken to be unrotated and unscaled; the terrain's position and uniform scale are followed, a rotation is not.
+- **No collision and no interaction.** Plants do not bend away from a character; the wind is the only thing that moves them.
+- **The far version of a mesh is a card, not an impostor.** It shows the rectangle of the plant's texture you name, from every side the same; a
+ tree whose texture has no such picture shows its texture there.
+- **Cells are built a few a frame**, so a large field appears over a moment.
diff --git a/docs/astro/src/content/docs/graphics/materials.mdx b/docs/astro/src/content/docs/graphics/materials.mdx
index 59848c8b9..7050033fd 100644
--- a/docs/astro/src/content/docs/graphics/materials.mdx
+++ b/docs/astro/src/content/docs/graphics/materials.mdx
@@ -34,6 +34,8 @@ creates a material from a built-in template — the same list ships in code as
| **UV Scroll** | `sprite-uv-scroll` | Scrolls the texture by `u_scrollSpeed` × time. |
| **Model** | `model` | What a glTF material says beyond base color: `u_normalMap`, `u_emissive`(`Map`), `u_occlusionMap` + `u_occlusionStrength`, `u_alphaCutoff`, `u_metallic` / `u_roughness` (+ `u_metallicRoughnessMap`), and the [shading layers](#shading-layers) — clear coat, sheen, anisotropy, translucency, thin film, index of refraction, transmission. Written by model import. |
+| **Terrain** | `terrain` | Four texture layers (grass, dirt, snow, rock) weighted by the [Terrain](/docs/graphics/terrain/) component and tiled by world position. |
+| **Foliage** | `foliage` | Plants that sway in the wind: a vertex bend by weights painted in the vertex colour, two-sided and translucent, with an optional cutout texture. See [Foliage](/docs/graphics/foliage/). |
| **Water** | `water` | A horizontal body of water: travelling waves and ripples, the scene behind it bent and tinted by how deep the water is, reflections, and foam. See [Water](#water). |
A new material **references** its template by id — it stores `shader: "builtin:sprite-unlit"`
diff --git a/docs/astro/src/content/docs/graphics/terrain.mdx b/docs/astro/src/content/docs/graphics/terrain.mdx
new file mode 100644
index 000000000..991a589c6
--- /dev/null
+++ b/docs/astro/src/content/docs/graphics/terrain.mdx
@@ -0,0 +1,63 @@
+---
+title: Terrain
+description: A Terrain component that makes ground from a heightmap or noise, paints it by height and slope, and draws it in chunks that coarsen with distance.
+---
+
+Ground is the largest thing most 3D scenes draw and the thing a mesh is worst at: too many triangles near the camera
+and too few where it matters. The `Terrain` component makes it from a grid of heights and cuts it into chunks, each built at
+several levels of detail, so a hill underfoot is drawn finely and the same hill on the horizon is a few hundred triangles.
+
+## The component
+
+Add a `Terrain` component to an entity. It is centred on that entity; its children are the chunks, made when the scene runs
+(and in the editor's scene view) and rebuilt when a field changes. Nothing is baked and nothing is saved besides the component.
+
+| Field | What it does |
+|---|---|
+| `heightmap` | An image: the red channel is the height. If the green channel is not just grey it is taken as the low byte of a 16-bit height, so a 16-bit map exported into an 8-bit-per-channel PNG keeps its precision. Empty makes the ground from noise. |
+| `sizeX`, `sizeZ`, `height` | World size of the terrain and the world height of its highest ground. |
+| `chunks` | Chunks along each side. Each is culled and drawn on its own, so more chunks cull better and cost more draws. |
+| `chunkCells` | Cells along a chunk's side at its finest level. |
+| `lodLevels`, `detail` | How many levels each chunk has (each half as fine as the one before) and a multiplier on how far the finer levels reach. |
+| `seed`, `frequency`, `octaves`, `persistence`, `ridged`, `resolution` | The noise ground: another seed is another ground; `ridged` goes from rolling hills to sharp ridges. |
+| `splatmap` | An image whose four channels are the weights of the four layers. Empty paints by height and slope. |
+| `rockSlope`, `dirtHeight`, `snowHeight` | How steep ground must be to turn to rock, and the heights where grass gives way to dirt and where snow begins. |
+| `layerColor0`–`3` | Grass, dirt, snow, rock: the colours the ground is drawn in when it has no material. |
+| `material` | A material on the **Terrain** shader (below). Empty draws the layer colours straight onto the ground. |
+
+## Layers and the Terrain material
+
+The four layers are grass, dirt, snow and rock. Each vertex is given its weight of every layer, from the splatmap or from how high
+and how steep the ground is there, and the **Terrain** shader (`builtin:terrain`) draws them: `u_layer0`–`3` are the textures,
+`u_tint0`–`3` their colours and `u_tile0`–`3` how many world units one repeat covers. The textures are tiled by *world position*, so a
+layer runs unbroken from one chunk to the next, and the rock is projected from three sides so a cliff is not a smear. `u_sharpness`
+hardens the seams and `u_macroVariation` lays a slow variation over the grass so a meadow is not one repeated tile.
+
+## How the levels of detail work
+
+Each chunk is a grid of `chunkCells` cells a side, built again at half that, a quarter, and so on down to two cells. The engine's own
+[level of detail](/docs/performance/level-of-detail/) picks among them by how large the chunk is on screen. Two neighbours at different levels
+have different numbers of vertices along their shared edge, which would leave a crack; each chunk therefore has a **skirt**, a wall let
+down from its edges, so a chunk is built alone and may change level without rebuilding anyone else. Heights and normals are read from the one field
+at every level, so a chunk keeps its lighting as it coarsens and only its silhouette changes.
+
+## From code
+
+The ground can be asked how high it is, for putting things on it:
+
+```ts
+import { TerrainsRes } from 'esengine';
+
+const terrains = app.getResource(TerrainsRes);
+const y = terrains.heightAt(x, z); // world height, or null where there is no terrain
+const n = terrains.normalAt(x, z); // the unit normal there, or null
+```
+
+## Limits
+
+- **No collision.** The ground is drawn, not simulated: `heightAt` is the way to stand something on it, and a physics body falls through it
+ unless the project adds its own collider.
+- **Heights are one field.** Splat weights are per vertex, at the finest level's resolution, so they are as fine as the grid is.
+- **No holes, caves or overhangs.** A heightfield has one height at each place. Caves and bridges are meshes placed with it.
+- **No rotation in `heightAt`.** The terrain's position and uniform scale are taken into account, a rotation about y is not.
+- **Chunks are built a few a frame**, so a large terrain appears over a moment rather than stalling one frame.
diff --git a/docs/astro/src/content/docs/zh-cn/graphics/foliage.mdx b/docs/astro/src/content/docs/zh-cn/graphics/foliage.mdx
new file mode 100644
index 000000000..5fa35cb8e
--- /dev/null
+++ b/docs/astro/src/content/docs/zh-cn/graphics/foliage.mdx
@@ -0,0 +1,41 @@
+---
+title: 植被
+description: 一个 Foliage 组件,把草或网格散布到一片区域或地形上,按格子绘制,在风里摆动,并随距离变稀。
+---
+
+一片草地是几万根草叶,一片森林是几千棵树,没有哪个引擎会一个实体一个实体地画它们。`Foliage` 组件把它们按**格子**长出来:区域被切成方块,每个方块是一个包含全部植物的网格,所以一片草地是几百次绘制,剔除可以整块丢掉,每个格子又按它的距离该有的细节来构建。
+
+## 组件
+
+给某个实体加一个 `Foliage` 组件。区域以它为中心,它的子实体就是这些格子,在场景运行时(以及编辑器的场景视图里)生成,字段一变就重新生成。没有任何东西被烘焙。
+
+| 字段 | 作用 |
+|---|---|
+| `mesh` | 要散布的植物。为空则长草,草叶在这里生成。 |
+| `material` | 用 **Foliage** 着色器的材质,它负责风(见下)。为空则植物静止,用自己的颜色绘制。 |
+| `sizeX`、`sizeZ`、`cellSize` | 区域,以及它被切成的格子的边长。 |
+| `count`、`seed` | 每格的植物数,以及种子:换一个种子就在别处长出同样的植物。 |
+| `minScale`、`maxScale` | 每棵植物的大小在这两者之间。 |
+| `minUp`、`heightMin`、`heightMax` | 植物在哪里生长:一个地方最少要朝上多少(调低能让植物长上斜坡),以及一段世界高度范围。 |
+| `bladeHeight`、`bladeWidth` | 只对草:缩放为 1 时一根草叶的大小。 |
+| `lodDistance`、`drawDistance` | 超过前者,格子用它的远景版本绘制;超过后者就不画。 |
+| `cardU0`、`cardV0`、`cardU1`、`cardV1` | 网格的远景版本是两张交叉的卡片,显示它纹理的这个矩形。 |
+
+如果场景里有 [Terrain](/docs/zh-cn/graphics/terrain/),植物就站在它上面,避开太陡的地方,并等它构建完;没有地形时,区域是实体所在高度的平地。
+
+## 风
+
+**Foliage** 着色器(`builtin:foliage`)按顶点颜色里画好的权重弯曲每个顶点(红色是它在植物上多高,所以根不动、尖端动;绿色是植物自己的相位,所以一片草地不会整体一起摆),再加一阵在世界上传播的阵风和叠在上面的颤动。参数在材质里:`u_windStrength`、`u_windSpeed`、`u_windDirection`(度)、`u_gustScale`(越小阵风越长)和 `u_flutter`。植物是双面的,并且让光透过(`u_translucency`);带 alpha 通道的叶子纹理(`u_albedo`、`u_useTexture`、`u_alphaCutoff`)能从一张卡片里抠出叶子的轮廓。
+
+你自己的着色器也能读到同样的权重:顶点钩子(`#pragma vertexoffset`)里,顶点颜色是 `es_vertexColor`。
+
+## 细节层级
+
+每个格子构建两次。近处,草是每棵植物一根弯曲、渐细的草叶;远处,是三分之一的草叶,更宽而且更平。网格近处是完整的拷贝,远处是每棵植物两张交叉的卡片。引擎自己的[细节层级](/docs/zh-cn/performance/level-of-detail/)按格子覆盖多少屏幕在它们之间选择,超过 `drawDistance` 就把格子丢掉。
+
+## 限制
+
+- **只有位置。** 区域被当作不旋转、不缩放;地形的位置和均匀缩放会被跟随,旋转不会。
+- **没有碰撞,也没有交互。** 植物不会被角色压弯;风是唯一能让它们动的东西。
+- **网格的远景版本是卡片,不是 impostor。** 它显示你指定的那个纹理矩形,从各个方向看都一样;纹理里没有这样一张图的树,卡片上就是它的纹理。
+- **格子每帧构建几个**,所以大片区域会在一小会儿内出现。
diff --git a/docs/astro/src/content/docs/zh-cn/graphics/materials.mdx b/docs/astro/src/content/docs/zh-cn/graphics/materials.mdx
index 120cb1a1c..8a1de2e64 100644
--- a/docs/astro/src/content/docs/zh-cn/graphics/materials.mdx
+++ b/docs/astro/src/content/docs/zh-cn/graphics/materials.mdx
@@ -30,6 +30,8 @@ std140 uniform 块,于是 CPU 能按名字设置、并安全地送到 GPU。一
| **UV Scroll** | `sprite-uv-scroll` | 按 `u_scrollSpeed` × 时间滚动纹理。 |
| **Model** | `model` | glTF 材质在 base color 之外说的东西:`u_normalMap`、`u_emissive`(`Map`)、`u_occlusionMap` + `u_occlusionStrength`、`u_alphaCutoff`、`u_metallic` / `u_roughness`(以及 `u_metallicRoughnessMap`),还有[着色层](#着色层)——清漆、绒面、各向异性、半透、薄膜干涉、折射率、透射。模型导入会写出它。 |
+| **Terrain** | `terrain` | 四个纹理图层(草、泥土、雪、岩石),由 [Terrain](/docs/zh-cn/graphics/terrain/) 组件加权并按世界位置平铺。 |
+| **Foliage** | `foliage` | 在风里摆动的植物:按顶点颜色里画好的权重做顶点弯曲,双面、半透光,可选镂空纹理。见[植被](/docs/zh-cn/graphics/foliage/)。 |
| **Water** | `water` | 水平的水体:传播的波浪和涟漪、被折射并按水深染色的背后场景、反射与泡沫。见[水](#水)。 |
新建材质是**按 id 引用**其模板的——它存的是 `shader: "builtin:sprite-unlit"`,并**不会**在磁盘上
diff --git a/docs/astro/src/content/docs/zh-cn/graphics/terrain.mdx b/docs/astro/src/content/docs/zh-cn/graphics/terrain.mdx
new file mode 100644
index 000000000..2c3dfee95
--- /dev/null
+++ b/docs/astro/src/content/docs/zh-cn/graphics/terrain.mdx
@@ -0,0 +1,51 @@
+---
+title: 地形
+description: 一个 Terrain 组件,用高度图或噪声生成地面,按高度和坡度上色,并分块绘制、随距离降低细节。
+---
+
+地面是大多数 3D 场景里画得最大的东西,也是网格最不擅长的东西:相机近处三角形太多,而真正需要的地方又太少。`Terrain` 组件从一张高度网格生成它,并切成块,每块按多个细节层级构建,所以脚下的山丘画得很细,而地平线上的同一座山丘只有几百个三角形。
+
+## 组件
+
+给某个实体加一个 `Terrain` 组件。地形以该实体为中心;它的子实体就是这些块,在场景运行时(以及编辑器的场景视图里)生成,字段一变就重建。没有任何东西被烘焙,除了组件本身也没有任何东西被保存。
+
+| 字段 | 作用 |
+|---|---|
+| `heightmap` | 一张图:红色通道是高度。如果绿色通道不全是灰,它被当作 16 位高度的低字节,所以导出到每通道 8 位 PNG 里的 16 位高度图也能保留精度。为空则用噪声生成地面。 |
+| `sizeX`、`sizeZ`、`height` | 地形的世界尺寸,以及最高处地面的世界高度。 |
+| `chunks` | 每边的块数。每块单独剔除和绘制,块越多剔除越好、绘制调用越多。 |
+| `chunkCells` | 一块在最细层级时每边的格数。 |
+| `lodLevels`、`detail` | 每块有几个层级(每级比前一级粗一半),以及细层级能延伸多远的倍率。 |
+| `seed`、`frequency`、`octaves`、`persistence`、`ridged`、`resolution` | 噪声地面:换一个种子就是另一片地面;`ridged` 从起伏的丘陵到尖锐的山脊。 |
+| `splatmap` | 一张图,四个通道是四个图层的权重。为空则按高度和坡度上色。 |
+| `rockSlope`、`dirtHeight`、`snowHeight` | 地面要多陡才变成岩石,以及草地转为泥土、雪开始出现的高度。 |
+| `layerColor0`–`3` | 草、泥土、雪、岩石:没有材质时地面绘制用的颜色。 |
+| `material` | 用 **Terrain** 着色器的材质(见下)。为空则直接把图层颜色画在地面上。 |
+
+## 图层与 Terrain 材质
+
+四个图层是草、泥土、雪和岩石。每个顶点会得到它在每个图层上的权重,来自 splatmap 或来自那里有多高多陡,**Terrain** 着色器(`builtin:terrain`)把它们画出来:`u_layer0`–`3` 是纹理,`u_tint0`–`3` 是它们的颜色,`u_tile0`–`3` 是一次重复覆盖多少世界单位。纹理按*世界位置*平铺,所以图层从一块到下一块不会断开,岩石从三个方向投影,所以悬崖不会被拉成一团。`u_sharpness` 让接缝更硬,`u_macroVariation` 在草地上叠一层缓慢的变化,让草地不是同一块图案的反复。
+
+## 细节层级如何工作
+
+每块是每边 `chunkCells` 格的网格,再按一半、四分之一……一直到两格各构建一次。引擎自己的[细节层级](/docs/zh-cn/performance/level-of-detail/)按这块在屏幕上有多大来选择。两个层级不同的邻居在共用的边上顶点数不同,会留下裂缝;所以每块都有一圈**裙边**,从边缘垂下的一堵墙,使一块可以单独构建,换层级时也不必重建任何其他块。每个层级的高度和法线都读自同一个场,所以一块在变粗时光照保持不变,只有轮廓变化。
+
+## 从代码里用
+
+可以问地面某处有多高,用来把东西放上去:
+
+```ts
+import { TerrainsRes } from 'esengine';
+
+const terrains = app.getResource(TerrainsRes);
+const y = terrains.heightAt(x, z); // 世界高度,没有地形的地方为 null
+const n = terrains.normalAt(x, z); // 那里的单位法线,或 null
+```
+
+## 限制
+
+- **没有碰撞。** 地面只是被绘制,不被模拟:要把东西立在上面用 `heightAt`,物理刚体会穿过它,除非项目自己加碰撞体。
+- **高度只是一个场。** Splat 权重是逐顶点的,精度就是最细层级的网格精度。
+- **没有洞、洞穴或悬挑。** 高度场在每个位置只有一个高度。洞穴和桥是和它放在一起的网格。
+- **`heightAt` 不考虑旋转。** 地形的位置和均匀缩放会被考虑,绕 y 的旋转不会。
+- **块每帧构建几个**,所以大地形会在一小会儿内出现,而不是卡住某一帧。
diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.json
index c0fa93f4a..40a8c2b3e 100644
--- a/docs/astro/src/data/apiStability.generated.json
+++ b/docs/astro/src/data/apiStability.generated.json
@@ -1,12 +1,12 @@
{
"note": "Generated by tools/api-stability.mjs from sdk/etc/*.api.md — do not edit.",
"counts": {
- "public": 122,
- "beta": 164,
- "experimental": 2298,
+ "public": 115,
+ "beta": 171,
+ "experimental": 2334,
"deprecated": 3
},
- "total": 2584,
+ "total": 2620,
"subsystems": [
{
"id": "mobile-controls",
@@ -369,6 +369,18 @@
"MeshRenderers"
]
},
+ {
+ "id": "terrain-foliage",
+ "title": "Terrain & foliage",
+ "titleZh": "地形与植被",
+ "tier": "experimental",
+ "why": "the ground and the plants on it draw and are checked in the editor on both backends, but nothing collides with the ground yet and the authoring panels have not been read for a shape",
+ "whyZh": "地面和上面的植物在编辑器里两个后端都能画出来并有检查,但还没有东西和地面碰撞,创作面板也还没有被拿来定下这套接口的形状",
+ "entry": [
+ "Terrain",
+ "Foliage"
+ ]
+ },
{
"id": "decal",
"title": "Decals",
@@ -1718,42 +1730,6 @@
"minigame"
]
},
- {
- "name": "blendWeather",
- "kind": "function",
- "deprecated": false,
- "entries": [
- "index",
- "index.node",
- "index.native",
- "wechat",
- "minigame"
- ]
- },
- {
- "name": "currentTimeOfDay",
- "kind": "function",
- "deprecated": false,
- "entries": [
- "index",
- "index.node",
- "index.native",
- "wechat",
- "minigame"
- ]
- },
- {
- "name": "currentWeather",
- "kind": "function",
- "deprecated": false,
- "entries": [
- "index",
- "index.node",
- "index.native",
- "wechat",
- "minigame"
- ]
- },
{
"name": "defineComponent",
"kind": "function",
@@ -1861,54 +1837,6 @@
"wechat",
"minigame"
]
- },
- {
- "name": "registerWeatherPreset",
- "kind": "function",
- "deprecated": false,
- "entries": [
- "index",
- "index.node",
- "index.native",
- "wechat",
- "minigame"
- ]
- },
- {
- "name": "timeOfDayAt",
- "kind": "function",
- "deprecated": false,
- "entries": [
- "index",
- "index.node",
- "index.native",
- "wechat",
- "minigame"
- ]
- },
- {
- "name": "weatherPresetId",
- "kind": "function",
- "deprecated": false,
- "entries": [
- "index",
- "index.node",
- "index.native",
- "wechat",
- "minigame"
- ]
- },
- {
- "name": "weatherPresetNames",
- "kind": "function",
- "deprecated": false,
- "entries": [
- "index",
- "index.node",
- "index.native",
- "wechat",
- "minigame"
- ]
}
],
"beta": [
@@ -3430,6 +3358,18 @@
"minigame"
]
},
+ {
+ "name": "blendWeather",
+ "kind": "function",
+ "deprecated": false,
+ "entries": [
+ "index",
+ "index.node",
+ "index.native",
+ "wechat",
+ "minigame"
+ ]
+ },
{
"name": "cameraCommitChanged",
"kind": "function",
@@ -3550,6 +3490,30 @@
"minigame"
]
},
+ {
+ "name": "currentTimeOfDay",
+ "kind": "function",
+ "deprecated": false,
+ "entries": [
+ "index",
+ "index.node",
+ "index.native",
+ "wechat",
+ "minigame"
+ ]
+ },
+ {
+ "name": "currentWeather",
+ "kind": "function",
+ "deprecated": false,
+ "entries": [
+ "index",
+ "index.node",
+ "index.native",
+ "wechat",
+ "minigame"
+ ]
+ },
{
"name": "disconnect",
"kind": "function",
@@ -3694,6 +3658,18 @@
"minigame"
]
},
+ {
+ "name": "registerWeatherPreset",
+ "kind": "function",
+ "deprecated": false,
+ "entries": [
+ "index",
+ "index.node",
+ "index.native",
+ "wechat",
+ "minigame"
+ ]
+ },
{
"name": "removeNode",
"kind": "function",
@@ -3802,6 +3778,18 @@
"minigame"
]
},
+ {
+ "name": "timeOfDayAt",
+ "kind": "function",
+ "deprecated": false,
+ "entries": [
+ "index",
+ "index.node",
+ "index.native",
+ "wechat",
+ "minigame"
+ ]
+ },
{
"name": "transitionTo",
"kind": "function",
@@ -3837,6 +3825,30 @@
"wechat",
"minigame"
]
+ },
+ {
+ "name": "weatherPresetId",
+ "kind": "function",
+ "deprecated": false,
+ "entries": [
+ "index",
+ "index.node",
+ "index.native",
+ "wechat",
+ "minigame"
+ ]
+ },
+ {
+ "name": "weatherPresetNames",
+ "kind": "function",
+ "deprecated": false,
+ "entries": [
+ "index",
+ "index.node",
+ "index.native",
+ "wechat",
+ "minigame"
+ ]
}
]
}
diff --git a/docs/astro/src/data/componentDocs.ts b/docs/astro/src/data/componentDocs.ts
index 344624437..9ca9a1766 100644
--- a/docs/astro/src/data/componentDocs.ts
+++ b/docs/astro/src/data/componentDocs.ts
@@ -87,6 +87,8 @@ export const COMPONENT_DOCS: Record<string, ComponentDoc> = {
SpriteMask: { category: 'graphics', summary: "Turns this entity's Sprite into a stencil that cuts the sprites drawn after it — a window, or a hole.", doc: 'graphics/sprites', anchor: 'sprite-masks', anchorZh: '精灵遮罩' },
SortingGroup: { category: 'graphics', summary: 'Makes an entity and its whole subtree sort as one unit — the group states the layer and order, members state their place inside it.', doc: 'graphics/sprites', anchor: 'sorting-groups', anchorZh: '排序组' },
StaticBatch: { category: 'graphics', summary: 'Marks a mesh that will not move, so the meshes sharing its material are merged into one draw while the game runs; it also records what became of this one.', doc: 'performance/static-batching', anchor: 'what-happens', anchorZh: '会发生什么' },
+ Terrain: { category: 'graphics', summary: 'Ground made from a heightmap or noise, painted by height and slope, and drawn in chunks that coarsen with distance.', doc: 'graphics/terrain', anchor: 'the-component', anchorZh: '组件' },
+ Foliage: { category: 'graphics', summary: 'Scatters grass or a mesh across an area and over a terrain, drawn a cell at a time, swaying in the wind and thinning out with distance.', doc: 'graphics/foliage', anchor: 'the-component', anchorZh: '组件' },
LODGroup: { category: 'graphics', summary: 'Cheaper stand-in meshes for a MeshRenderer, chosen by how much of the screen the object covers.', doc: 'performance/level-of-detail', anchor: 'the-lodgroup-component', anchorZh: 'lodgroup-组件' },
ReflectionProbe: { category: 'graphics', summary: 'A box inside which reflections come from a bake rather than from the sky — the specular half of what a light probe volume answers.', doc: 'graphics/lighting', anchor: 'baked-light', anchorZh: '烘焙光照' },
PlanarReflection: { category: 'graphics', summary: 'Captures a mirrored view for flat lit surfaces, with layer filtering, capture quality and update controls.', doc: 'graphics/lighting' },
diff --git a/docs/astro/src/data/components.generated.json b/docs/astro/src/data/components.generated.json
index 10d7a0204..babd426ed 100644
--- a/docs/astro/src/data/components.generated.json
+++ b/docs/astro/src/data/components.generated.json
@@ -1606,6 +1606,172 @@
"tabIndex"
]
},
+ {
+ "name": "Foliage",
+ "source": "ts",
+ "fields": [
+ {
+ "key": "mesh",
+ "type": "Asset<mesh>",
+ "default": "none",
+ "doc": "The plant to scatter. Empty grows grass."
+ },
+ {
+ "key": "material",
+ "type": "Asset<material>",
+ "default": "none",
+ "doc": "A material on the Foliage shader, which makes the wind. Empty draws the plants still, in their own colours."
+ },
+ {
+ "key": "sizeX",
+ "type": "number",
+ "default": "400",
+ "doc": "World size along x, centred on this entity.",
+ "range": "≥ 1"
+ },
+ {
+ "key": "sizeZ",
+ "type": "number",
+ "default": "400",
+ "doc": "World size along z, centred on this entity.",
+ "range": "≥ 1"
+ },
+ {
+ "key": "cellSize",
+ "type": "number",
+ "default": "40",
+ "doc": "Side of the cells the area is cut into. Each is one mesh, culled whole.",
+ "range": "≥ 4"
+ },
+ {
+ "key": "count",
+ "type": "number",
+ "default": "500",
+ "doc": "Plants per cell.",
+ "range": "≥ 0, step 1"
+ },
+ {
+ "key": "seed",
+ "type": "number",
+ "default": "1",
+ "doc": "Another seed grows the same plants in other places.",
+ "range": "step 1"
+ },
+ {
+ "key": "minScale",
+ "type": "number",
+ "default": "0.8",
+ "range": "≥ 0.01"
+ },
+ {
+ "key": "maxScale",
+ "type": "number",
+ "default": "1.25",
+ "range": "≥ 0.01"
+ },
+ {
+ "key": "minUp",
+ "type": "number",
+ "default": "0.7",
+ "doc": "The least a place may face up and still grow something. Lower lets plants onto slopes.",
+ "range": "0–1, step 0.01"
+ },
+ {
+ "key": "heightMin",
+ "type": "number",
+ "default": "-100000",
+ "doc": "The lowest world height plants grow at."
+ },
+ {
+ "key": "heightMax",
+ "type": "number",
+ "default": "100000",
+ "doc": "The highest world height plants grow at."
+ },
+ {
+ "key": "bladeHeight",
+ "type": "number",
+ "default": "14",
+ "doc": "Height of a blade at scale 1.",
+ "range": "≥ 0.1"
+ },
+ {
+ "key": "bladeWidth",
+ "type": "number",
+ "default": "1.6",
+ "doc": "Width of a blade at its base, at scale 1.",
+ "range": "≥ 0.01"
+ },
+ {
+ "key": "lodDistance",
+ "type": "number",
+ "default": "140",
+ "doc": "Past this a cell is drawn as its far version: fewer, broader blades, or a tree as crossed cards.",
+ "range": "≥ 1"
+ },
+ {
+ "key": "drawDistance",
+ "type": "number",
+ "default": "420",
+ "doc": "Past this a cell is not drawn.",
+ "range": "≥ 1"
+ },
+ {
+ "key": "cardU0",
+ "type": "number",
+ "default": "0",
+ "doc": "The part of the plant's texture a far tree shows (left, bottom, right, top)."
+ },
+ {
+ "key": "cardV0",
+ "type": "number",
+ "default": "0"
+ },
+ {
+ "key": "cardU1",
+ "type": "number",
+ "default": "1"
+ },
+ {
+ "key": "cardV1",
+ "type": "number",
+ "default": "1"
+ },
+ {
+ "key": "cardTent",
+ "type": "enum",
+ "default": "Rectangle",
+ "doc": "The outline of the cards a far tree is drawn as.",
+ "values": [
+ "Rectangle",
+ "Tent (conifer)"
+ ]
+ }
+ ],
+ "animatable": [
+ "mesh",
+ "material",
+ "sizeX",
+ "sizeZ",
+ "cellSize",
+ "count",
+ "seed",
+ "minScale",
+ "maxScale",
+ "minUp",
+ "heightMin",
+ "heightMax",
+ "bladeHeight",
+ "bladeWidth",
+ "lodDistance",
+ "drawDistance",
+ "cardU0",
+ "cardV0",
+ "cardU1",
+ "cardV1",
+ "cardTent"
+ ]
+ },
{
"name": "FollowTarget",
"source": "ts",
@@ -4872,6 +5038,199 @@
"twistMaxAngle"
]
},
+ {
+ "name": "Terrain",
+ "source": "ts",
+ "fields": [
+ {
+ "key": "heightmap",
+ "type": "Asset<texture>",
+ "default": "none",
+ "doc": "A heightmap image: red is the height. Empty makes the ground from noise."
+ },
+ {
+ "key": "splatmap",
+ "type": "Asset<texture>",
+ "default": "none",
+ "doc": "An image whose red, green, blue and alpha are the weights of grass, dirt, snow and rock."
+ },
+ {
+ "key": "material",
+ "type": "Asset<material>",
+ "default": "none",
+ "doc": "A material on the Terrain shader. Empty draws the layer colours onto the ground."
+ },
+ {
+ "key": "sizeX",
+ "type": "number",
+ "default": "1000",
+ "doc": "World size along x.",
+ "range": "≥ 1"
+ },
+ {
+ "key": "sizeZ",
+ "type": "number",
+ "default": "1000",
+ "doc": "World size along z.",
+ "range": "≥ 1"
+ },
+ {
+ "key": "height",
+ "type": "number",
+ "default": "150",
+ "doc": "World height of the highest ground.",
+ "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",
+ "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"
+ },
+ {
+ "key": "lodLevels",
+ "type": "number",
+ "default": "4",
+ "doc": "Levels of detail per chunk, each half as fine as the one before.",
+ "range": "1–4, step 1"
+ },
+ {
+ "key": "detail",
+ "type": "number",
+ "default": "1",
+ "doc": "Above 1 the finer levels are kept out to a greater distance.",
+ "range": "0.1–8, step 0.1"
+ },
+ {
+ "key": "seed",
+ "type": "number",
+ "default": "1",
+ "doc": "Another seed is another ground.",
+ "range": "step 1"
+ },
+ {
+ "key": "frequency",
+ "type": "number",
+ "default": "3",
+ "doc": "How many hills across the terrain.",
+ "range": "0.1–32, step 0.1"
+ },
+ {
+ "key": "octaves",
+ "type": "number",
+ "default": "5",
+ "doc": "Layers of detail in the noise.",
+ "range": "1–8, step 1"
+ },
+ {
+ "key": "persistence",
+ "type": "number",
+ "default": "0.5",
+ "doc": "How much of its height each finer layer keeps. Lower is smoother.",
+ "range": "0–1, step 0.01"
+ },
+ {
+ "key": "ridged",
+ "type": "number",
+ "default": "0.35",
+ "doc": "0 is rolling hills; 1 is sharp ridges.",
+ "range": "0–1, step 0.01"
+ },
+ {
+ "key": "resolution",
+ "type": "number",
+ "default": "257",
+ "doc": "Samples along each side of the noise ground.",
+ "range": "17–2049, step 1"
+ },
+ {
+ "key": "rockSlope",
+ "type": "number",
+ "default": "0.35",
+ "doc": "How steep ground must be to turn to rock. 0 is flat, 1 is sheer.",
+ "range": "0–1, step 0.01"
+ },
+ {
+ "key": "dirtHeight",
+ "type": "number",
+ "default": "0.62",
+ "doc": "The height, as a share of the terrain, where grass gives way to dirt.",
+ "range": "0–1, step 0.01"
+ },
+ {
+ "key": "snowHeight",
+ "type": "number",
+ "default": "0.88",
+ "doc": "The height, as a share of the terrain, where snow begins.",
+ "range": "0–1, step 0.01"
+ },
+ {
+ "key": "layerColor0",
+ "type": "Color",
+ "default": "#477533"
+ },
+ {
+ "key": "layerColor1",
+ "type": "Color",
+ "default": "#735c3d"
+ },
+ {
+ "key": "layerColor2",
+ "type": "Color",
+ "default": "#edf2fa"
+ },
+ {
+ "key": "layerColor3",
+ "type": "Color",
+ "default": "#66615c"
+ }
+ ],
+ "animatable": [
+ "heightmap",
+ "splatmap",
+ "material",
+ "sizeX",
+ "sizeZ",
+ "height",
+ "chunks",
+ "chunkCells",
+ "lodLevels",
+ "detail",
+ "seed",
+ "frequency",
+ "octaves",
+ "persistence",
+ "ridged",
+ "resolution",
+ "rockSlope",
+ "dirtHeight",
+ "snowHeight",
+ "layerColor0.r",
+ "layerColor0.g",
+ "layerColor0.b",
+ "layerColor0.a",
+ "layerColor1.r",
+ "layerColor1.g",
+ "layerColor1.b",
+ "layerColor1.a",
+ "layerColor2.r",
+ "layerColor2.g",
+ "layerColor2.b",
+ "layerColor2.a",
+ "layerColor3.r",
+ "layerColor3.g",
+ "layerColor3.b",
+ "layerColor3.a"
+ ]
+ },
{
"name": "Text",
"source": "ts",
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 8acd15ac2..169d452ba 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: 122 public · 152 beta · 1670 experimental · 3 deprecated
+Symbols: 115 public · 159 beta · 1706 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -1640,6 +1640,15 @@ op: CompareOp
value: string | number | boolean | undefined
```
+## BladeParams — interface @experimental
+```
+height: number
+paint: { base: [number, number, number]; tip: [number, number, number]; } | null | undefined
+segments: number
+thin: number
+width: number
+```
+
## BlendCurve — type @experimental
```
(typeof BlendCurve)[keyof typeof BlendCurve]
@@ -2171,6 +2180,14 @@ rgb: Float32Array<ArrayBufferLike>
width: number
```
+## CardRect — interface @experimental
+```
+u0: number
+u1: number
+v0: number
+v1: number
+```
+
## Catalog — class @experimental
```
addressOf: (path: string) => string | null
@@ -4023,6 +4040,59 @@ isFocused: boolean
tabIndex: number
```
+## Foliage — const @experimental
+```
+ComponentDef<FoliageData>
+```
+
+## FoliageData — interface @experimental
+```
+bladeHeight: number
+bladeWidth: number
+cardTent: number
+cardU0: number
+cardU1: number
+cardV0: number
+cardV1: number
+cellSize: number
+count: number
+drawDistance: number
+heightMax: number
+heightMin: number
+lodDistance: number
+material: number
+maxScale: number
+mesh: number
+minScale: number
+minUp: number
+seed: number
+sizeX: number
+sizeZ: number
+```
+
+## FoliageField — class @experimental
+```
+@internal built_: Map<number, BuiltFoliage>
+cellCount: number
+pending: number
+static new (): FoliageField
+static prototype: FoliageField
+```
+
+## FoliagePlugin — class @experimental
+```
+build: (app: App) => void
+cleanup: (app?: App) => void
+name: string
+static new (): FoliagePlugin
+static prototype: FoliagePlugin
+```
+
+## FoliageRes — const @experimental
+```
+ResourceDef<FoliageField>
+```
+
## FollowTarget — const @experimental
```
ComponentDef<FollowTargetData>
@@ -4377,6 +4447,11 @@ static new (opts: GridLayoutOptions): GridLayoutProvider
static prototype: GridLayoutProvider
```
+## Ground — type @experimental
+```
+(x: number, z: number) => { y: number; up: number } | null
+```
+
## HdrFormat — interface @experimental
```
effective: string
@@ -4392,6 +4467,13 @@ plugins: Plugin[] | undefined
sideModules: SideModuleHost | undefined
```
+## Heightfield — interface @experimental
+```
+data: Float32Array<ArrayBufferLike>
+height: number
+width: number
+```
+
## HingeJoint2D — const @experimental
```
ComponentDef<HingeJoint2DData>
@@ -6230,6 +6312,17 @@ updated: boolean | undefined
width: number | undefined
```
+## Plant — interface @experimental
+```
+phase: number
+scale: number
+shade: number
+x: number
+y: number
+yaw: number
+z: number
+```
+
## PlatformAdapter — interface @experimental
```
bindInputEvents: (callbacks: InputEventCallbacks, target?: unknown) => void
@@ -6826,6 +6919,16 @@ fingerprint: string
pending: PendingSystemEntry[]
```
+## ProceduralParams — interface @experimental
+```
+frequency: number
+octaves: number
+persistence: number
+resolution: number
+ridged: number
+seed: number
+```
+
## ProcessedEntity — interface @experimental
```
children: number[]
@@ -7667,6 +7770,21 @@ setJSON: <T>(key: string, value: T) => void
(typeof ScaleMode)[keyof typeof ScaleMode]
```
+## ScatterParams — interface @experimental
+```
+cellKey: number
+centerX: number
+centerZ: number
+count: number
+heightMax: number
+heightMin: number
+maxScale: number
+minScale: number
+minUp: number
+seed: number
+size: number
+```
+
## SceneAmbientLight — interface @experimental
```
drawEnvironment: boolean
@@ -9276,6 +9394,81 @@ setPaused: (paused: boolean) => void
suspendAudio: () => void
```
+## Terrain — const @experimental
+```
+ComponentDef<TerrainData>
+```
+
+## TerrainData — interface @experimental
+```
+chunkCells: number
+chunks: number
+detail: number
+dirtHeight: number
+frequency: number
+height: number
+heightmap: number
+layerColor0: Color
+layerColor1: Color
+layerColor2: Color
+layerColor3: Color
+lodLevels: number
+material: number
+octaves: number
+persistence: number
+resolution: number
+ridged: number
+rockSlope: number
+seed: number
+sizeX: number
+sizeZ: number
+snowHeight: number
+splatmap: number
+```
+
+## TerrainPaint — type @experimental
+```
+(
+ u: number, v: number, height01: number, slope: number,
+) => [number, number, number, number]
+```
+
+## TerrainPlugin — class @experimental
+```
+build: (app: App) => void
+cleanup: (app?: App) => void
+name: string
+static new (): TerrainPlugin
+static prototype: TerrainPlugin
+```
+
+## TerrainShape — interface @experimental
+```
+chunkCells: number
+chunks: number
+height: number
+sizeX: number
+sizeZ: number
+```
+
+## Terrains — class @experimental
+```
+@internal app_: App | null
+@internal built_: Map<number, Built>
+@internal revision_: number
+heightAt: (x: number, z: number) => number | null
+loading: boolean
+normalAt: (x: number, z: number) => [number, number, number] | null
+pending: number
+static new (): Terrains
+static prototype: Terrains
+```
+
+## TerrainsRes — const @experimental
+```
+ResourceDef<Terrains>
+```
+
## Text — const @public
```
ComponentDef<TextData>
@@ -11606,7 +11799,7 @@ MotionDriver<AnimatorBlend2DMotion>
(blend: AnimatorBlend2DMotion, x: number, y: number, out: { weight: number; }[]): void
```
-## blendWeather — function @public
+## blendWeather — function @beta
```
(from: number, to: number, progress: number): WeatherState
```
@@ -11616,11 +11809,31 @@ MotionDriver<AnimatorBlend2DMotion>
(overrides: readonly PrefabOverride[]): Map<PrefabEntityId, PrefabOverride[]>
```
+## buildBillboardMesh — function @experimental
+```
+(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
```
+## buildGrassMesh — function @experimental
+```
+(plants: readonly Plant[], blade: BladeParams): MeshData
+```
+
+## buildInstancedMesh — function @experimental
+```
+(source: MeshData, plants: readonly Plant[], paint?: BladeParams["paint"]): MeshData
+```
+
## buildText — function @experimental
```
(init?: TextInit): TextData
@@ -11731,11 +11944,21 @@ 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
@@ -12061,12 +12284,12 @@ Plugin
(module: ESEngineModule, options?: CreateWebAppOptions): App
```
-## currentTimeOfDay — function @public
+## currentTimeOfDay — function @beta
```
(): TimeOfDayState | null
```
-## currentWeather — function @public
+## currentWeather — function @beta
```
(): WeatherState | null
```
@@ -12516,6 +12739,11 @@ FocusPlugin
(config: AssetGroupsConfig | null | undefined, folder: string): AssetGroupMode
```
+## foliagePlugin — const @experimental
+```
+Plugin
+```
+
## formatActionArg — function @experimental
```
(params: Readonly<Record<string, AiParamValue>> | undefined, defs: readonly AiParamDef[], separator?: string): string | undefined
@@ -12756,6 +12984,11 @@ FocusPlugin
() => Plugin[]
```
+## heightfieldFromPixels — function @experimental
+```
+(width: number, height: number, pixels: ArrayLike<number>): Heightfield
+```
+
## imageBitmapOptions — function @experimental
```
(flip: boolean): ImageBitmapOptions
@@ -13056,6 +13289,11 @@ LifecyclePlugin
LocalizationPlugin
```
+## lodCount — function @experimental
+```
+(shape: TerrainShape, wanted?: number): number
+```
+
## log — const @experimental
```
Logger
@@ -13221,6 +13459,11 @@ MeshRendererPlugin
(config: Pick<PackagedGameConfig, "physicsEnabled" | "physicsConfig" | "audioConfig" | "uiTheme" | "uiThemeColors" | "achievements" | "steamAppId" | "screenFit" | "aot" | "debugChannel">): { physicsEnabled?: boolean; physicsConfig?: Physics2DPluginConfig; audioConfig?: AudioProjectConfig; uiTheme?: "light"; uiThemeOverrides?: ThemeOverrides; achievements?: string[]; steamAppId?: number; screenFit?: PackagedGameConfig["screenFit"]; aot?: PackagedGameConfig["aot"]; debugChannel?: DebugChannelConfig; }
```
+## paintWeights — function @experimental
+```
+(h: number, ny: number, t: Pick<TerrainData, "rockSlope" | "dirtHeight" | "snowHeight">): [number, number, number, number]
+```
+
## panoramaDirection — function @experimental
```
(u: number, v: number): [number, number, number]
@@ -13511,6 +13754,11 @@ PrefabsPlugin
(register: () => Promise<void>): Promise<ProbedRegistrations>
```
+## proceduralHeightfield — function @experimental
+```
+(p: ProceduralParams): Heightfield
+```
+
## projectSideModuleIds — function @experimental
```
(): string[]
@@ -13641,6 +13889,11 @@ PrefabsPlugin
(id: string, fn: DrawCallback, scene?: string): void
```
+## registerEffect — function @experimental
+```
+(def: EffectDef): void
+```
+
## registerPackagedSideModules — function @experimental
```
(config: Pick<PackagedGameConfig, "sideModules">): void
@@ -13666,7 +13919,7 @@ PrefabsPlugin
(name: string, spec: AiValueSpec<AiContext>): void
```
-## registerWeatherPreset — function @public
+## registerWeatherPreset — function @beta
```
(name: string, preset: WeatherPreset): number
```
@@ -13821,6 +14074,11 @@ PrefabsPlugin
(base: "dark" | "light", overrides?: ThemeOverrides): ThemeTokens
```
+## rng — function @experimental
+```
+(seed: number): () => number
+```
+
## rotateVec3ByQuat — function @experimental
```
(rot: Quat, v: Vec3): Vec3
@@ -13841,6 +14099,11 @@ PrefabsPlugin
SafeAreaPlugin
```
+## sampleHeight — function @experimental
+```
+(field: Heightfield, u: number, v: number): number
+```
+
## sampleKeyframes — function @experimental
```
(keys: readonly Keyframe[], at: number): number
@@ -13866,6 +14129,11 @@ SafeAreaPlugin
{ readonly clamp: (x: number, min: number, max: number) => number; readonly clamp01: (x: number) => number; readonly lerp: (a: number, b: number, t: number) => number; readonly inverseLerp: (a: number, b: number, value: number) => number; readonly remap: (value: number, inMin: number, inMax: number, outMin: number, outMax: number) => number; readonly deg2rad: (deg: number) => number; readonly rad2deg: (rad: number) => number; readonly approximately: (a: number, b: number, epsilon?: number) => boolean; readonly smoothstep: (edge0: number, edge1: number, x: number) => number; readonly mod: (x: number, n: number) => number; readonly sign: (x: number) => number; }
```
+## scatterCell — function @experimental
+```
+(p: ScatterParams, ground: Ground): Plant[]
+```
+
## sceneAmbientLights — function @experimental
```
(entities: readonly EnvironmentLightEntity[], exists: (ref: string) => boolean): SceneAmbientLight[]
@@ -14321,6 +14589,16 @@ StatsPlugin
(ctx?: CensusContext): Census
```
+## terrainNormal — function @experimental
+```
+(field: Heightfield, u: number, v: number, sizeX: number, sizeZ: number, heightScale: number): [number, number, number]
+```
+
+## terrainPlugin — const @experimental
+```
+Plugin
+```
+
## textInputPlugin — const @experimental
```
TextInputPlugin
@@ -14356,7 +14634,7 @@ TextPlugin
(): ThemeType
```
-## timeOfDayAt — function @public
+## timeOfDayAt — function @beta
```
(hour: number, latitude?: number, declination?: number, north?: number): TimeOfDayState
```
@@ -14581,12 +14859,12 @@ VideoPlugin
(category: string, message: string, data?: unknown): void
```
-## weatherPresetId — function @public
+## weatherPresetId — function @beta
```
(name: string): number | undefined
```
-## weatherPresetNames — function @public
+## weatherPresetNames — function @beta
```
(): string[]
```
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index db40e4c8b..97806178e 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: 122 public · 157 beta · 1689 experimental · 3 deprecated
+Symbols: 115 public · 164 beta · 1725 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -1640,6 +1640,15 @@ op: CompareOp
value: string | number | boolean | undefined
```
+## BladeParams — interface @experimental
+```
+height: number
+paint: { base: [number, number, number]; tip: [number, number, number]; } | null | undefined
+segments: number
+thin: number
+width: number
+```
+
## BlendCurve — type @experimental
```
(typeof BlendCurve)[keyof typeof BlendCurve]
@@ -2171,6 +2180,14 @@ rgb: Float32Array<ArrayBufferLike>
width: number
```
+## CardRect — interface @experimental
+```
+u0: number
+u1: number
+v0: number
+v1: number
+```
+
## Catalog — class @experimental
```
addressOf: (path: string) => string | null
@@ -4031,6 +4048,59 @@ isFocused: boolean
tabIndex: number
```
+## Foliage — const @experimental
+```
+ComponentDef<FoliageData>
+```
+
+## FoliageData — interface @experimental
+```
+bladeHeight: number
+bladeWidth: number
+cardTent: number
+cardU0: number
+cardU1: number
+cardV0: number
+cardV1: number
+cellSize: number
+count: number
+drawDistance: number
+heightMax: number
+heightMin: number
+lodDistance: number
+material: number
+maxScale: number
+mesh: number
+minScale: number
+minUp: number
+seed: number
+sizeX: number
+sizeZ: number
+```
+
+## FoliageField — class @experimental
+```
+@internal built_: Map<number, BuiltFoliage>
+cellCount: number
+pending: number
+static new (): FoliageField
+static prototype: FoliageField
+```
+
+## FoliagePlugin — class @experimental
+```
+build: (app: App) => void
+cleanup: (app?: App) => void
+name: string
+static new (): FoliagePlugin
+static prototype: FoliagePlugin
+```
+
+## FoliageRes — const @experimental
+```
+ResourceDef<FoliageField>
+```
+
## FollowTarget — const @experimental
```
ComponentDef<FollowTargetData>
@@ -4385,6 +4455,11 @@ static new (opts: GridLayoutOptions): GridLayoutProvider
static prototype: GridLayoutProvider
```
+## Ground — type @experimental
+```
+(x: number, z: number) => { y: number; up: number } | null
+```
+
## HdrFormat — interface @experimental
```
effective: string
@@ -4400,6 +4475,13 @@ plugins: Plugin[] | undefined
sideModules: SideModuleHost | undefined
```
+## Heightfield — interface @experimental
+```
+data: Float32Array<ArrayBufferLike>
+height: number
+width: number
+```
+
## HingeJoint2D — const @experimental
```
ComponentDef<HingeJoint2DData>
@@ -6433,6 +6515,17 @@ updated: boolean | undefined
width: number | undefined
```
+## Plant — interface @experimental
+```
+phase: number
+scale: number
+shade: number
+x: number
+y: number
+yaw: number
+z: number
+```
+
## PlatformAdapter — interface @experimental
```
bindInputEvents: (callbacks: InputEventCallbacks, target?: unknown) => void
@@ -7029,6 +7122,16 @@ fingerprint: string
pending: PendingSystemEntry[]
```
+## ProceduralParams — interface @experimental
+```
+frequency: number
+octaves: number
+persistence: number
+resolution: number
+ridged: number
+seed: number
+```
+
## ProcessedEntity — interface @experimental
```
children: number[]
@@ -7880,6 +7983,21 @@ setJSON: <T>(key: string, value: T) => void
(typeof ScaleMode)[keyof typeof ScaleMode]
```
+## ScatterParams — interface @experimental
+```
+cellKey: number
+centerX: number
+centerZ: number
+count: number
+heightMax: number
+heightMin: number
+maxScale: number
+minScale: number
+minUp: number
+seed: number
+size: number
+```
+
## SceneAmbientLight — interface @experimental
```
drawEnvironment: boolean
@@ -9489,6 +9607,81 @@ setPaused: (paused: boolean) => void
suspendAudio: () => void
```
+## Terrain — const @experimental
+```
+ComponentDef<TerrainData>
+```
+
+## TerrainData — interface @experimental
+```
+chunkCells: number
+chunks: number
+detail: number
+dirtHeight: number
+frequency: number
+height: number
+heightmap: number
+layerColor0: Color
+layerColor1: Color
+layerColor2: Color
+layerColor3: Color
+lodLevels: number
+material: number
+octaves: number
+persistence: number
+resolution: number
+ridged: number
+rockSlope: number
+seed: number
+sizeX: number
+sizeZ: number
+snowHeight: number
+splatmap: number
+```
+
+## TerrainPaint — type @experimental
+```
+(
+ u: number, v: number, height01: number, slope: number,
+) => [number, number, number, number]
+```
+
+## TerrainPlugin — class @experimental
+```
+build: (app: App) => void
+cleanup: (app?: App) => void
+name: string
+static new (): TerrainPlugin
+static prototype: TerrainPlugin
+```
+
+## TerrainShape — interface @experimental
+```
+chunkCells: number
+chunks: number
+height: number
+sizeX: number
+sizeZ: number
+```
+
+## Terrains — class @experimental
+```
+@internal app_: App | null
+@internal built_: Map<number, Built>
+@internal revision_: number
+heightAt: (x: number, z: number) => number | null
+loading: boolean
+normalAt: (x: number, z: number) => [number, number, number] | null
+pending: number
+static new (): Terrains
+static prototype: Terrains
+```
+
+## TerrainsRes — const @experimental
+```
+ResourceDef<Terrains>
+```
+
## Text — const @public
```
ComponentDef<TextData>
@@ -11834,7 +12027,7 @@ MotionDriver<AnimatorBlend2DMotion>
(blend: AnimatorBlend2DMotion, x: number, y: number, out: { weight: number; }[]): void
```
-## blendWeather — function @public
+## blendWeather — function @beta
```
(from: number, to: number, progress: number): WeatherState
```
@@ -11844,11 +12037,31 @@ MotionDriver<AnimatorBlend2DMotion>
(overrides: readonly PrefabOverride[]): Map<PrefabEntityId, PrefabOverride[]>
```
+## buildBillboardMesh — function @experimental
+```
+(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
```
+## buildGrassMesh — function @experimental
+```
+(plants: readonly Plant[], blade: BladeParams): MeshData
+```
+
+## buildInstancedMesh — function @experimental
+```
+(source: MeshData, plants: readonly Plant[], paint?: BladeParams["paint"]): MeshData
+```
+
## buildText — function @experimental
```
(init?: TextInit): TextData
@@ -11959,11 +12172,21 @@ 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
@@ -12314,12 +12537,12 @@ Plugin
(module: ESEngineModule, options?: CreateWebAppOptions): App
```
-## currentTimeOfDay — function @public
+## currentTimeOfDay — function @beta
```
(): TimeOfDayState | null
```
-## currentWeather — function @public
+## currentWeather — function @beta
```
(): WeatherState | null
```
@@ -12769,6 +12992,11 @@ FocusPlugin
(config: AssetGroupsConfig | null | undefined, folder: string): AssetGroupMode
```
+## foliagePlugin — const @experimental
+```
+Plugin
+```
+
## formatActionArg — function @experimental
```
(params: Readonly<Record<string, AiParamValue>> | undefined, defs: readonly AiParamDef[], separator?: string): string | undefined
@@ -13009,6 +13237,11 @@ FocusPlugin
() => Plugin[]
```
+## heightfieldFromPixels — function @experimental
+```
+(width: number, height: number, pixels: ArrayLike<number>): Heightfield
+```
+
## imageBitmapOptions — function @experimental
```
(flip: boolean): ImageBitmapOptions
@@ -13319,6 +13552,11 @@ LifecyclePlugin
LocalizationPlugin
```
+## lodCount — function @experimental
+```
+(shape: TerrainShape, wanted?: number): number
+```
+
## log — const @experimental
```
Logger
@@ -13484,6 +13722,11 @@ MeshRendererPlugin
(config: Pick<PackagedGameConfig, "physicsEnabled" | "physicsConfig" | "audioConfig" | "uiTheme" | "uiThemeColors" | "achievements" | "steamAppId" | "screenFit" | "aot" | "debugChannel">): { physicsEnabled?: boolean; physicsConfig?: Physics2DPluginConfig; audioConfig?: AudioProjectConfig; uiTheme?: "light"; uiThemeOverrides?: ThemeOverrides; achievements?: string[]; steamAppId?: number; screenFit?: PackagedGameConfig["screenFit"]; aot?: PackagedGameConfig["aot"]; debugChannel?: DebugChannelConfig; }
```
+## paintWeights — function @experimental
+```
+(h: number, ny: number, t: Pick<TerrainData, "rockSlope" | "dirtHeight" | "snowHeight">): [number, number, number, number]
+```
+
## panoramaDirection — function @experimental
```
(u: number, v: number): [number, number, number]
@@ -13774,6 +14017,11 @@ PrefabsPlugin
(register: () => Promise<void>): Promise<ProbedRegistrations>
```
+## proceduralHeightfield — function @experimental
+```
+(p: ProceduralParams): Heightfield
+```
+
## projectSideModuleIds — function @experimental
```
(): string[]
@@ -13904,6 +14152,11 @@ PrefabsPlugin
(id: string, fn: DrawCallback, scene?: string): void
```
+## registerEffect — function @experimental
+```
+(def: EffectDef): void
+```
+
## registerPackagedSideModules — function @experimental
```
(config: Pick<PackagedGameConfig, "sideModules">): void
@@ -13929,7 +14182,7 @@ PrefabsPlugin
(name: string, spec: AiValueSpec<AiContext>): void
```
-## registerWeatherPreset — function @public
+## registerWeatherPreset — function @beta
```
(name: string, preset: WeatherPreset): number
```
@@ -14084,6 +14337,11 @@ PrefabsPlugin
(base: "dark" | "light", overrides?: ThemeOverrides): ThemeTokens
```
+## rng — function @experimental
+```
+(seed: number): () => number
+```
+
## rotateVec3ByQuat — function @experimental
```
(rot: Quat, v: Vec3): Vec3
@@ -14104,6 +14362,11 @@ PrefabsPlugin
SafeAreaPlugin
```
+## sampleHeight — function @experimental
+```
+(field: Heightfield, u: number, v: number): number
+```
+
## sampleKeyframes — function @experimental
```
(keys: readonly Keyframe[], at: number): number
@@ -14129,6 +14392,11 @@ SafeAreaPlugin
{ readonly clamp: (x: number, min: number, max: number) => number; readonly clamp01: (x: number) => number; readonly lerp: (a: number, b: number, t: number) => number; readonly inverseLerp: (a: number, b: number, value: number) => number; readonly remap: (value: number, inMin: number, inMax: number, outMin: number, outMax: number) => number; readonly deg2rad: (deg: number) => number; readonly rad2deg: (rad: number) => number; readonly approximately: (a: number, b: number, epsilon?: number) => boolean; readonly smoothstep: (edge0: number, edge1: number, x: number) => number; readonly mod: (x: number, n: number) => number; readonly sign: (x: number) => number; }
```
+## scatterCell — function @experimental
+```
+(p: ScatterParams, ground: Ground): Plant[]
+```
+
## sceneAmbientLights — function @experimental
```
(entities: readonly EnvironmentLightEntity[], exists: (ref: string) => boolean): SceneAmbientLight[]
@@ -14584,6 +14852,16 @@ StatsPlugin
(ctx?: CensusContext): Census
```
+## terrainNormal — function @experimental
+```
+(field: Heightfield, u: number, v: number, sizeX: number, sizeZ: number, heightScale: number): [number, number, number]
+```
+
+## terrainPlugin — const @experimental
+```
+Plugin
+```
+
## textInputPlugin — const @experimental
```
TextInputPlugin
@@ -14619,7 +14897,7 @@ TextPlugin
(): ThemeType
```
-## timeOfDayAt — function @public
+## timeOfDayAt — function @beta
```
(hour: number, latitude?: number, declination?: number, north?: number): TimeOfDayState
```
@@ -14844,12 +15122,12 @@ VideoPlugin
(category: string, message: string, data?: unknown): void
```
-## weatherPresetId — function @public
+## weatherPresetId — function @beta
```
(name: string): number | undefined
```
-## weatherPresetNames — function @public
+## weatherPresetNames — function @beta
```
(): string[]
```
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index bd9ff82ca..0b7d9a5c8 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: 122 public · 154 beta · 1669 experimental · 3 deprecated
+Symbols: 115 public · 161 beta · 1705 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -1635,6 +1635,15 @@ op: CompareOp
value: string | number | boolean | undefined
```
+## BladeParams — interface @experimental
+```
+height: number
+paint: { base: [number, number, number]; tip: [number, number, number]; } | null | undefined
+segments: number
+thin: number
+width: number
+```
+
## BlendCurve — type @experimental
```
(typeof BlendCurve)[keyof typeof BlendCurve]
@@ -2166,6 +2175,14 @@ rgb: Float32Array<ArrayBufferLike>
width: number
```
+## CardRect — interface @experimental
+```
+u0: number
+u1: number
+v0: number
+v1: number
+```
+
## Catalog — class @experimental
```
addressOf: (path: string) => string | null
@@ -4018,6 +4035,59 @@ isFocused: boolean
tabIndex: number
```
+## Foliage — const @experimental
+```
+ComponentDef<FoliageData>
+```
+
+## FoliageData — interface @experimental
+```
+bladeHeight: number
+bladeWidth: number
+cardTent: number
+cardU0: number
+cardU1: number
+cardV0: number
+cardV1: number
+cellSize: number
+count: number
+drawDistance: number
+heightMax: number
+heightMin: number
+lodDistance: number
+material: number
+maxScale: number
+mesh: number
+minScale: number
+minUp: number
+seed: number
+sizeX: number
+sizeZ: number
+```
+
+## FoliageField — class @experimental
+```
+@internal built_: Map<number, BuiltFoliage>
+cellCount: number
+pending: number
+static new (): FoliageField
+static prototype: FoliageField
+```
+
+## FoliagePlugin — class @experimental
+```
+build: (app: App) => void
+cleanup: (app?: App) => void
+name: string
+static new (): FoliagePlugin
+static prototype: FoliagePlugin
+```
+
+## FoliageRes — const @experimental
+```
+ResourceDef<FoliageField>
+```
+
## FollowTarget — const @experimental
```
ComponentDef<FollowTargetData>
@@ -4372,6 +4442,11 @@ static new (opts: GridLayoutOptions): GridLayoutProvider
static prototype: GridLayoutProvider
```
+## Ground — type @experimental
+```
+(x: number, z: number) => { y: number; up: number } | null
+```
+
## HdrFormat — interface @experimental
```
effective: string
@@ -4387,6 +4462,13 @@ plugins: Plugin[] | undefined
sideModules: SideModuleHost | undefined
```
+## Heightfield — interface @experimental
+```
+data: Float32Array<ArrayBufferLike>
+height: number
+width: number
+```
+
## HingeJoint2D — const @experimental
```
ComponentDef<HingeJoint2DData>
@@ -6225,6 +6307,17 @@ updated: boolean | undefined
width: number | undefined
```
+## Plant — interface @experimental
+```
+phase: number
+scale: number
+shade: number
+x: number
+y: number
+yaw: number
+z: number
+```
+
## PlatformAdapter — interface @experimental
```
bindInputEvents: (callbacks: InputEventCallbacks, target?: unknown) => void
@@ -6821,6 +6914,16 @@ fingerprint: string
pending: PendingSystemEntry[]
```
+## ProceduralParams — interface @experimental
+```
+frequency: number
+octaves: number
+persistence: number
+resolution: number
+ridged: number
+seed: number
+```
+
## ProcessedEntity — interface @experimental
```
children: number[]
@@ -7662,6 +7765,21 @@ setJSON: <T>(key: string, value: T) => void
(typeof ScaleMode)[keyof typeof ScaleMode]
```
+## ScatterParams — interface @experimental
+```
+cellKey: number
+centerX: number
+centerZ: number
+count: number
+heightMax: number
+heightMin: number
+maxScale: number
+minScale: number
+minUp: number
+seed: number
+size: number
+```
+
## SceneAmbientLight — interface @experimental
```
drawEnvironment: boolean
@@ -9271,6 +9389,81 @@ setPaused: (paused: boolean) => void
suspendAudio: () => void
```
+## Terrain — const @experimental
+```
+ComponentDef<TerrainData>
+```
+
+## TerrainData — interface @experimental
+```
+chunkCells: number
+chunks: number
+detail: number
+dirtHeight: number
+frequency: number
+height: number
+heightmap: number
+layerColor0: Color
+layerColor1: Color
+layerColor2: Color
+layerColor3: Color
+lodLevels: number
+material: number
+octaves: number
+persistence: number
+resolution: number
+ridged: number
+rockSlope: number
+seed: number
+sizeX: number
+sizeZ: number
+snowHeight: number
+splatmap: number
+```
+
+## TerrainPaint — type @experimental
+```
+(
+ u: number, v: number, height01: number, slope: number,
+) => [number, number, number, number]
+```
+
+## TerrainPlugin — class @experimental
+```
+build: (app: App) => void
+cleanup: (app?: App) => void
+name: string
+static new (): TerrainPlugin
+static prototype: TerrainPlugin
+```
+
+## TerrainShape — interface @experimental
+```
+chunkCells: number
+chunks: number
+height: number
+sizeX: number
+sizeZ: number
+```
+
+## Terrains — class @experimental
+```
+@internal app_: App | null
+@internal built_: Map<number, Built>
+@internal revision_: number
+heightAt: (x: number, z: number) => number | null
+loading: boolean
+normalAt: (x: number, z: number) => [number, number, number] | null
+pending: number
+static new (): Terrains
+static prototype: Terrains
+```
+
+## TerrainsRes — const @experimental
+```
+ResourceDef<Terrains>
+```
+
## Text — const @public
```
ComponentDef<TextData>
@@ -11601,7 +11794,7 @@ MotionDriver<AnimatorBlend2DMotion>
(blend: AnimatorBlend2DMotion, x: number, y: number, out: { weight: number; }[]): void
```
-## blendWeather — function @public
+## blendWeather — function @beta
```
(from: number, to: number, progress: number): WeatherState
```
@@ -11611,11 +11804,31 @@ MotionDriver<AnimatorBlend2DMotion>
(overrides: readonly PrefabOverride[]): Map<PrefabEntityId, PrefabOverride[]>
```
+## buildBillboardMesh — function @experimental
+```
+(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
```
+## buildGrassMesh — function @experimental
+```
+(plants: readonly Plant[], blade: BladeParams): MeshData
+```
+
+## buildInstancedMesh — function @experimental
+```
+(source: MeshData, plants: readonly Plant[], paint?: BladeParams["paint"]): MeshData
+```
+
## buildText — function @experimental
```
(init?: TextInit): TextData
@@ -11726,11 +11939,21 @@ 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
@@ -12056,12 +12279,12 @@ Plugin
(module: ESEngineModule, options?: CreateWebAppOptions): App
```
-## currentTimeOfDay — function @public
+## currentTimeOfDay — function @beta
```
(): TimeOfDayState | null
```
-## currentWeather — function @public
+## currentWeather — function @beta
```
(): WeatherState | null
```
@@ -12511,6 +12734,11 @@ FocusPlugin
(config: AssetGroupsConfig | null | undefined, folder: string): AssetGroupMode
```
+## foliagePlugin — const @experimental
+```
+Plugin
+```
+
## formatActionArg — function @experimental
```
(params: Readonly<Record<string, AiParamValue>> | undefined, defs: readonly AiParamDef[], separator?: string): string | undefined
@@ -12751,6 +12979,11 @@ FocusPlugin
() => Plugin[]
```
+## heightfieldFromPixels — function @experimental
+```
+(width: number, height: number, pixels: ArrayLike<number>): Heightfield
+```
+
## imageBitmapOptions — function @experimental
```
(flip: boolean): ImageBitmapOptions
@@ -13056,6 +13289,11 @@ LifecyclePlugin
LocalizationPlugin
```
+## lodCount — function @experimental
+```
+(shape: TerrainShape, wanted?: number): number
+```
+
## log — const @experimental
```
Logger
@@ -13226,6 +13464,11 @@ NodePlatformAdapter
(config: Pick<PackagedGameConfig, "physicsEnabled" | "physicsConfig" | "audioConfig" | "uiTheme" | "uiThemeColors" | "achievements" | "steamAppId" | "screenFit" | "aot" | "debugChannel">): { physicsEnabled?: boolean; physicsConfig?: Physics2DPluginConfig; audioConfig?: AudioProjectConfig; uiTheme?: "light"; uiThemeOverrides?: ThemeOverrides; achievements?: string[]; steamAppId?: number; screenFit?: PackagedGameConfig["screenFit"]; aot?: PackagedGameConfig["aot"]; debugChannel?: DebugChannelConfig; }
```
+## paintWeights — function @experimental
+```
+(h: number, ny: number, t: Pick<TerrainData, "rockSlope" | "dirtHeight" | "snowHeight">): [number, number, number, number]
+```
+
## panoramaDirection — function @experimental
```
(u: number, v: number): [number, number, number]
@@ -13516,6 +13759,11 @@ PrefabsPlugin
(register: () => Promise<void>): Promise<ProbedRegistrations>
```
+## proceduralHeightfield — function @experimental
+```
+(p: ProceduralParams): Heightfield
+```
+
## projectSideModuleIds — function @experimental
```
(): string[]
@@ -13646,6 +13894,11 @@ PrefabsPlugin
(id: string, fn: DrawCallback, scene?: string): void
```
+## registerEffect — function @experimental
+```
+(def: EffectDef): void
+```
+
## registerPackagedSideModules — function @experimental
```
(config: Pick<PackagedGameConfig, "sideModules">): void
@@ -13671,7 +13924,7 @@ PrefabsPlugin
(name: string, spec: AiValueSpec<AiContext>): void
```
-## registerWeatherPreset — function @public
+## registerWeatherPreset — function @beta
```
(name: string, preset: WeatherPreset): number
```
@@ -13826,6 +14079,11 @@ PrefabsPlugin
(base: "dark" | "light", overrides?: ThemeOverrides): ThemeTokens
```
+## rng — function @experimental
+```
+(seed: number): () => number
+```
+
## rotateVec3ByQuat — function @experimental
```
(rot: Quat, v: Vec3): Vec3
@@ -13846,6 +14104,11 @@ PrefabsPlugin
SafeAreaPlugin
```
+## sampleHeight — function @experimental
+```
+(field: Heightfield, u: number, v: number): number
+```
+
## sampleKeyframes — function @experimental
```
(keys: readonly Keyframe[], at: number): number
@@ -13871,6 +14134,11 @@ SafeAreaPlugin
{ readonly clamp: (x: number, min: number, max: number) => number; readonly clamp01: (x: number) => number; readonly lerp: (a: number, b: number, t: number) => number; readonly inverseLerp: (a: number, b: number, value: number) => number; readonly remap: (value: number, inMin: number, inMax: number, outMin: number, outMax: number) => number; readonly deg2rad: (deg: number) => number; readonly rad2deg: (rad: number) => number; readonly approximately: (a: number, b: number, epsilon?: number) => boolean; readonly smoothstep: (edge0: number, edge1: number, x: number) => number; readonly mod: (x: number, n: number) => number; readonly sign: (x: number) => number; }
```
+## scatterCell — function @experimental
+```
+(p: ScatterParams, ground: Ground): Plant[]
+```
+
## sceneAmbientLights — function @experimental
```
(entities: readonly EnvironmentLightEntity[], exists: (ref: string) => boolean): SceneAmbientLight[]
@@ -14326,6 +14594,16 @@ StatsPlugin
(ctx?: CensusContext): Census
```
+## terrainNormal — function @experimental
+```
+(field: Heightfield, u: number, v: number, sizeX: number, sizeZ: number, heightScale: number): [number, number, number]
+```
+
+## terrainPlugin — const @experimental
+```
+Plugin
+```
+
## textInputPlugin — const @experimental
```
TextInputPlugin
@@ -14361,7 +14639,7 @@ TextPlugin
(): ThemeType
```
-## timeOfDayAt — function @public
+## timeOfDayAt — function @beta
```
(hour: number, latitude?: number, declination?: number, north?: number): TimeOfDayState
```
@@ -14586,12 +14864,12 @@ VideoPlugin
(category: string, message: string, data?: unknown): void
```
-## weatherPresetId — function @public
+## weatherPresetId — function @beta
```
(name: string): number | undefined
```
-## weatherPresetNames — function @public
+## weatherPresetNames — function @beta
```
(): string[]
```
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 87ff733d8..25f33a6cc 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: 122 public · 152 beta · 1691 experimental · 3 deprecated
+Symbols: 115 public · 159 beta · 1727 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -1635,6 +1635,15 @@ op: CompareOp
value: string | number | boolean | undefined
```
+## BladeParams — interface @experimental
+```
+height: number
+paint: { base: [number, number, number]; tip: [number, number, number]; } | null | undefined
+segments: number
+thin: number
+width: number
+```
+
## BlendCurve — type @experimental
```
(typeof BlendCurve)[keyof typeof BlendCurve]
@@ -2166,6 +2175,14 @@ rgb: Float32Array<ArrayBufferLike>
width: number
```
+## CardRect — interface @experimental
+```
+u0: number
+u1: number
+v0: number
+v1: number
+```
+
## Catalog — class @experimental
```
addressOf: (path: string) => string | null
@@ -4018,6 +4035,59 @@ isFocused: boolean
tabIndex: number
```
+## Foliage — const @experimental
+```
+ComponentDef<FoliageData>
+```
+
+## FoliageData — interface @experimental
+```
+bladeHeight: number
+bladeWidth: number
+cardTent: number
+cardU0: number
+cardU1: number
+cardV0: number
+cardV1: number
+cellSize: number
+count: number
+drawDistance: number
+heightMax: number
+heightMin: number
+lodDistance: number
+material: number
+maxScale: number
+mesh: number
+minScale: number
+minUp: number
+seed: number
+sizeX: number
+sizeZ: number
+```
+
+## FoliageField — class @experimental
+```
+@internal built_: Map<number, BuiltFoliage>
+cellCount: number
+pending: number
+static new (): FoliageField
+static prototype: FoliageField
+```
+
+## FoliagePlugin — class @experimental
+```
+build: (app: App) => void
+cleanup: (app?: App) => void
+name: string
+static new (): FoliagePlugin
+static prototype: FoliagePlugin
+```
+
+## FoliageRes — const @experimental
+```
+ResourceDef<FoliageField>
+```
+
## FollowTarget — const @experimental
```
ComponentDef<FollowTargetData>
@@ -4372,6 +4442,11 @@ static new (opts: GridLayoutOptions): GridLayoutProvider
static prototype: GridLayoutProvider
```
+## Ground — type @experimental
+```
+(x: number, z: number) => { y: number; up: number } | null
+```
+
## HdrFormat — interface @experimental
```
effective: string
@@ -4387,6 +4462,13 @@ plugins: Plugin[] | undefined
sideModules: SideModuleHost | undefined
```
+## Heightfield — interface @experimental
+```
+data: Float32Array<ArrayBufferLike>
+height: number
+width: number
+```
+
## HingeJoint2D — const @experimental
```
ComponentDef<HingeJoint2DData>
@@ -6518,6 +6600,17 @@ updated: boolean | undefined
width: number | undefined
```
+## Plant — interface @experimental
+```
+phase: number
+scale: number
+shade: number
+x: number
+y: number
+yaw: number
+z: number
+```
+
## PlatformAdapter — interface @experimental
```
bindInputEvents: (callbacks: InputEventCallbacks, target?: unknown) => void
@@ -7114,6 +7207,16 @@ fingerprint: string
pending: PendingSystemEntry[]
```
+## ProceduralParams — interface @experimental
+```
+frequency: number
+octaves: number
+persistence: number
+resolution: number
+ridged: number
+seed: number
+```
+
## ProcessedEntity — interface @experimental
```
children: number[]
@@ -7955,6 +8058,21 @@ setJSON: <T>(key: string, value: T) => void
(typeof ScaleMode)[keyof typeof ScaleMode]
```
+## ScatterParams — interface @experimental
+```
+cellKey: number
+centerX: number
+centerZ: number
+count: number
+heightMax: number
+heightMin: number
+maxScale: number
+minScale: number
+minUp: number
+seed: number
+size: number
+```
+
## SceneAmbientLight — interface @experimental
```
drawEnvironment: boolean
@@ -9564,6 +9682,81 @@ setPaused: (paused: boolean) => void
suspendAudio: () => void
```
+## Terrain — const @experimental
+```
+ComponentDef<TerrainData>
+```
+
+## TerrainData — interface @experimental
+```
+chunkCells: number
+chunks: number
+detail: number
+dirtHeight: number
+frequency: number
+height: number
+heightmap: number
+layerColor0: Color
+layerColor1: Color
+layerColor2: Color
+layerColor3: Color
+lodLevels: number
+material: number
+octaves: number
+persistence: number
+resolution: number
+ridged: number
+rockSlope: number
+seed: number
+sizeX: number
+sizeZ: number
+snowHeight: number
+splatmap: number
+```
+
+## TerrainPaint — type @experimental
+```
+(
+ u: number, v: number, height01: number, slope: number,
+) => [number, number, number, number]
+```
+
+## TerrainPlugin — class @experimental
+```
+build: (app: App) => void
+cleanup: (app?: App) => void
+name: string
+static new (): TerrainPlugin
+static prototype: TerrainPlugin
+```
+
+## TerrainShape — interface @experimental
+```
+chunkCells: number
+chunks: number
+height: number
+sizeX: number
+sizeZ: number
+```
+
+## Terrains — class @experimental
+```
+@internal app_: App | null
+@internal built_: Map<number, Built>
+@internal revision_: number
+heightAt: (x: number, z: number) => number | null
+loading: boolean
+normalAt: (x: number, z: number) => [number, number, number] | null
+pending: number
+static new (): Terrains
+static prototype: Terrains
+```
+
+## TerrainsRes — const @experimental
+```
+ResourceDef<Terrains>
+```
+
## Text — const @public
```
ComponentDef<TextData>
@@ -11900,7 +12093,7 @@ MotionDriver<AnimatorBlend2DMotion>
(blend: AnimatorBlend2DMotion, x: number, y: number, out: { weight: number; }[]): void
```
-## blendWeather — function @public
+## blendWeather — function @beta
```
(from: number, to: number, progress: number): WeatherState
```
@@ -11910,11 +12103,31 @@ MotionDriver<AnimatorBlend2DMotion>
(overrides: readonly PrefabOverride[]): Map<PrefabEntityId, PrefabOverride[]>
```
+## buildBillboardMesh — function @experimental
+```
+(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
```
+## buildGrassMesh — function @experimental
+```
+(plants: readonly Plant[], blade: BladeParams): MeshData
+```
+
+## buildInstancedMesh — function @experimental
+```
+(source: MeshData, plants: readonly Plant[], paint?: BladeParams["paint"]): MeshData
+```
+
## buildText — function @experimental
```
(init?: TextInit): TextData
@@ -12025,11 +12238,21 @@ 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
@@ -12360,12 +12583,12 @@ Plugin
(module: ESEngineModule, options?: CreateWebAppOptions): App
```
-## currentTimeOfDay — function @public
+## currentTimeOfDay — function @beta
```
(): TimeOfDayState | null
```
-## currentWeather — function @public
+## currentWeather — function @beta
```
(): WeatherState | null
```
@@ -12815,6 +13038,11 @@ FocusPlugin
(config: AssetGroupsConfig | null | undefined, folder: string): AssetGroupMode
```
+## foliagePlugin — const @experimental
+```
+Plugin
+```
+
## formatActionArg — function @experimental
```
(params: Readonly<Record<string, AiParamValue>> | undefined, defs: readonly AiParamDef[], separator?: string): string | undefined
@@ -13055,6 +13283,11 @@ FocusPlugin
() => Plugin[]
```
+## heightfieldFromPixels — function @experimental
+```
+(width: number, height: number, pixels: ArrayLike<number>): Heightfield
+```
+
## imageBitmapOptions — function @experimental
```
(flip: boolean): ImageBitmapOptions
@@ -13365,6 +13598,11 @@ LifecyclePlugin
LocalizationPlugin
```
+## lodCount — function @experimental
+```
+(shape: TerrainShape, wanted?: number): number
+```
+
## log — const @experimental
```
Logger
@@ -13530,6 +13768,11 @@ MeshRendererPlugin
(config: Pick<PackagedGameConfig, "physicsEnabled" | "physicsConfig" | "audioConfig" | "uiTheme" | "uiThemeColors" | "achievements" | "steamAppId" | "screenFit" | "aot" | "debugChannel">): { physicsEnabled?: boolean; physicsConfig?: Physics2DPluginConfig; audioConfig?: AudioProjectConfig; uiTheme?: "light"; uiThemeOverrides?: ThemeOverrides; achievements?: string[]; steamAppId?: number; screenFit?: PackagedGameConfig["screenFit"]; aot?: PackagedGameConfig["aot"]; debugChannel?: DebugChannelConfig; }
```
+## paintWeights — function @experimental
+```
+(h: number, ny: number, t: Pick<TerrainData, "rockSlope" | "dirtHeight" | "snowHeight">): [number, number, number, number]
+```
+
## panoramaDirection — function @experimental
```
(u: number, v: number): [number, number, number]
@@ -13820,6 +14063,11 @@ PrefabsPlugin
(register: () => Promise<void>): Promise<ProbedRegistrations>
```
+## proceduralHeightfield — function @experimental
+```
+(p: ProceduralParams): Heightfield
+```
+
## projectSideModuleIds — function @experimental
```
(): string[]
@@ -13950,6 +14198,11 @@ PrefabsPlugin
(id: string, fn: DrawCallback, scene?: string): void
```
+## registerEffect — function @experimental
+```
+(def: EffectDef): void
+```
+
## registerPackagedSideModules — function @experimental
```
(config: Pick<PackagedGameConfig, "sideModules">): void
@@ -13975,7 +14228,7 @@ PrefabsPlugin
(name: string, spec: AiValueSpec<AiContext>): void
```
-## registerWeatherPreset — function @public
+## registerWeatherPreset — function @beta
```
(name: string, preset: WeatherPreset): number
```
@@ -14130,6 +14383,11 @@ PrefabsPlugin
(base: "dark" | "light", overrides?: ThemeOverrides): ThemeTokens
```
+## rng — function @experimental
+```
+(seed: number): () => number
+```
+
## rotateVec3ByQuat — function @experimental
```
(rot: Quat, v: Vec3): Vec3
@@ -14150,6 +14408,11 @@ PrefabsPlugin
SafeAreaPlugin
```
+## sampleHeight — function @experimental
+```
+(field: Heightfield, u: number, v: number): number
+```
+
## sampleKeyframes — function @experimental
```
(keys: readonly Keyframe[], at: number): number
@@ -14175,6 +14438,11 @@ SafeAreaPlugin
{ readonly clamp: (x: number, min: number, max: number) => number; readonly clamp01: (x: number) => number; readonly lerp: (a: number, b: number, t: number) => number; readonly inverseLerp: (a: number, b: number, value: number) => number; readonly remap: (value: number, inMin: number, inMax: number, outMin: number, outMax: number) => number; readonly deg2rad: (deg: number) => number; readonly rad2deg: (rad: number) => number; readonly approximately: (a: number, b: number, epsilon?: number) => boolean; readonly smoothstep: (edge0: number, edge1: number, x: number) => number; readonly mod: (x: number, n: number) => number; readonly sign: (x: number) => number; }
```
+## scatterCell — function @experimental
+```
+(p: ScatterParams, ground: Ground): Plant[]
+```
+
## sceneAmbientLights — function @experimental
```
(entities: readonly EnvironmentLightEntity[], exists: (ref: string) => boolean): SceneAmbientLight[]
@@ -14630,6 +14898,16 @@ StatsPlugin
(ctx?: CensusContext): Census
```
+## terrainNormal — function @experimental
+```
+(field: Heightfield, u: number, v: number, sizeX: number, sizeZ: number, heightScale: number): [number, number, number]
+```
+
+## terrainPlugin — const @experimental
+```
+Plugin
+```
+
## textInputPlugin — const @experimental
```
TextInputPlugin
@@ -14665,7 +14943,7 @@ TextPlugin
(): ThemeType
```
-## timeOfDayAt — function @public
+## timeOfDayAt — function @beta
```
(hour: number, latitude?: number, declination?: number, north?: number): TimeOfDayState
```
@@ -14890,12 +15168,12 @@ VideoPlugin
(category: string, message: string, data?: unknown): void
```
-## weatherPresetId — function @public
+## weatherPresetId — function @beta
```
(name: string): number | undefined
```
-## weatherPresetNames — function @public
+## weatherPresetNames — function @beta
```
(): string[]
```
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 500e000ee..6d8feb08e 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: 122 public · 152 beta · 1682 experimental · 3 deprecated
+Symbols: 115 public · 159 beta · 1718 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -1635,6 +1635,15 @@ op: CompareOp
value: string | number | boolean | undefined
```
+## BladeParams — interface @experimental
+```
+height: number
+paint: { base: [number, number, number]; tip: [number, number, number]; } | null | undefined
+segments: number
+thin: number
+width: number
+```
+
## BlendCurve — type @experimental
```
(typeof BlendCurve)[keyof typeof BlendCurve]
@@ -2166,6 +2175,14 @@ rgb: Float32Array<ArrayBufferLike>
width: number
```
+## CardRect — interface @experimental
+```
+u0: number
+u1: number
+v0: number
+v1: number
+```
+
## Catalog — class @experimental
```
addressOf: (path: string) => string | null
@@ -4018,6 +4035,59 @@ isFocused: boolean
tabIndex: number
```
+## Foliage — const @experimental
+```
+ComponentDef<FoliageData>
+```
+
+## FoliageData — interface @experimental
+```
+bladeHeight: number
+bladeWidth: number
+cardTent: number
+cardU0: number
+cardU1: number
+cardV0: number
+cardV1: number
+cellSize: number
+count: number
+drawDistance: number
+heightMax: number
+heightMin: number
+lodDistance: number
+material: number
+maxScale: number
+mesh: number
+minScale: number
+minUp: number
+seed: number
+sizeX: number
+sizeZ: number
+```
+
+## FoliageField — class @experimental
+```
+@internal built_: Map<number, BuiltFoliage>
+cellCount: number
+pending: number
+static new (): FoliageField
+static prototype: FoliageField
+```
+
+## FoliagePlugin — class @experimental
+```
+build: (app: App) => void
+cleanup: (app?: App) => void
+name: string
+static new (): FoliagePlugin
+static prototype: FoliagePlugin
+```
+
+## FoliageRes — const @experimental
+```
+ResourceDef<FoliageField>
+```
+
## FollowTarget — const @experimental
```
ComponentDef<FollowTargetData>
@@ -4372,6 +4442,11 @@ static new (opts: GridLayoutOptions): GridLayoutProvider
static prototype: GridLayoutProvider
```
+## Ground — type @experimental
+```
+(x: number, z: number) => { y: number; up: number } | null
+```
+
## HdrFormat — interface @experimental
```
effective: string
@@ -4387,6 +4462,13 @@ plugins: Plugin[] | undefined
sideModules: SideModuleHost | undefined
```
+## Heightfield — interface @experimental
+```
+data: Float32Array<ArrayBufferLike>
+height: number
+width: number
+```
+
## HingeJoint2D — const @experimental
```
ComponentDef<HingeJoint2DData>
@@ -6232,6 +6314,17 @@ updated: boolean | undefined
width: number | undefined
```
+## Plant — interface @experimental
+```
+phase: number
+scale: number
+shade: number
+x: number
+y: number
+yaw: number
+z: number
+```
+
## PlatformAdapter — interface @experimental
```
bindInputEvents: (callbacks: InputEventCallbacks, target?: unknown) => void
@@ -6828,6 +6921,16 @@ fingerprint: string
pending: PendingSystemEntry[]
```
+## ProceduralParams — interface @experimental
+```
+frequency: number
+octaves: number
+persistence: number
+resolution: number
+ridged: number
+seed: number
+```
+
## ProcessedEntity — interface @experimental
```
children: number[]
@@ -7669,6 +7772,21 @@ setJSON: <T>(key: string, value: T) => void
(typeof ScaleMode)[keyof typeof ScaleMode]
```
+## ScatterParams — interface @experimental
+```
+cellKey: number
+centerX: number
+centerZ: number
+count: number
+heightMax: number
+heightMin: number
+maxScale: number
+minScale: number
+minUp: number
+seed: number
+size: number
+```
+
## SceneAmbientLight — interface @experimental
```
drawEnvironment: boolean
@@ -9278,6 +9396,81 @@ setPaused: (paused: boolean) => void
suspendAudio: () => void
```
+## Terrain — const @experimental
+```
+ComponentDef<TerrainData>
+```
+
+## TerrainData — interface @experimental
+```
+chunkCells: number
+chunks: number
+detail: number
+dirtHeight: number
+frequency: number
+height: number
+heightmap: number
+layerColor0: Color
+layerColor1: Color
+layerColor2: Color
+layerColor3: Color
+lodLevels: number
+material: number
+octaves: number
+persistence: number
+resolution: number
+ridged: number
+rockSlope: number
+seed: number
+sizeX: number
+sizeZ: number
+snowHeight: number
+splatmap: number
+```
+
+## TerrainPaint — type @experimental
+```
+(
+ u: number, v: number, height01: number, slope: number,
+) => [number, number, number, number]
+```
+
+## TerrainPlugin — class @experimental
+```
+build: (app: App) => void
+cleanup: (app?: App) => void
+name: string
+static new (): TerrainPlugin
+static prototype: TerrainPlugin
+```
+
+## TerrainShape — interface @experimental
+```
+chunkCells: number
+chunks: number
+height: number
+sizeX: number
+sizeZ: number
+```
+
+## Terrains — class @experimental
+```
+@internal app_: App | null
+@internal built_: Map<number, Built>
+@internal revision_: number
+heightAt: (x: number, z: number) => number | null
+loading: boolean
+normalAt: (x: number, z: number) => [number, number, number] | null
+pending: number
+static new (): Terrains
+static prototype: Terrains
+```
+
+## TerrainsRes — const @experimental
+```
+ResourceDef<Terrains>
+```
+
## Text — const @public
```
ComponentDef<TextData>
@@ -11632,7 +11825,7 @@ MotionDriver<AnimatorBlend2DMotion>
(blend: AnimatorBlend2DMotion, x: number, y: number, out: { weight: number; }[]): void
```
-## blendWeather — function @public
+## blendWeather — function @beta
```
(from: number, to: number, progress: number): WeatherState
```
@@ -11642,11 +11835,31 @@ MotionDriver<AnimatorBlend2DMotion>
(overrides: readonly PrefabOverride[]): Map<PrefabEntityId, PrefabOverride[]>
```
+## buildBillboardMesh — function @experimental
+```
+(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
```
+## buildGrassMesh — function @experimental
+```
+(plants: readonly Plant[], blade: BladeParams): MeshData
+```
+
+## buildInstancedMesh — function @experimental
+```
+(source: MeshData, plants: readonly Plant[], paint?: BladeParams["paint"]): MeshData
+```
+
## buildText — function @experimental
```
(init?: TextInit): TextData
@@ -11757,11 +11970,21 @@ 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
@@ -12087,12 +12310,12 @@ Plugin
(module: ESEngineModule, options?: CreateWebAppOptions): App
```
-## currentTimeOfDay — function @public
+## currentTimeOfDay — function @beta
```
(): TimeOfDayState | null
```
-## currentWeather — function @public
+## currentWeather — function @beta
```
(): WeatherState | null
```
@@ -12542,6 +12765,11 @@ FocusPlugin
(config: AssetGroupsConfig | null | undefined, folder: string): AssetGroupMode
```
+## foliagePlugin — const @experimental
+```
+Plugin
+```
+
## formatActionArg — function @experimental
```
(params: Readonly<Record<string, AiParamValue>> | undefined, defs: readonly AiParamDef[], separator?: string): string | undefined
@@ -12782,6 +13010,11 @@ FocusPlugin
() => Plugin[]
```
+## heightfieldFromPixels — function @experimental
+```
+(width: number, height: number, pixels: ArrayLike<number>): Heightfield
+```
+
## imageBitmapOptions — function @experimental
```
(flip: boolean): ImageBitmapOptions
@@ -13092,6 +13325,11 @@ LifecyclePlugin
LocalizationPlugin
```
+## lodCount — function @experimental
+```
+(shape: TerrainShape, wanted?: number): number
+```
+
## log — const @experimental
```
Logger
@@ -13257,6 +13495,11 @@ MeshRendererPlugin
(config: Pick<PackagedGameConfig, "physicsEnabled" | "physicsConfig" | "audioConfig" | "uiTheme" | "uiThemeColors" | "achievements" | "steamAppId" | "screenFit" | "aot" | "debugChannel">): { physicsEnabled?: boolean; physicsConfig?: Physics2DPluginConfig; audioConfig?: AudioProjectConfig; uiTheme?: "light"; uiThemeOverrides?: ThemeOverrides; achievements?: string[]; steamAppId?: number; screenFit?: PackagedGameConfig["screenFit"]; aot?: PackagedGameConfig["aot"]; debugChannel?: DebugChannelConfig; }
```
+## paintWeights — function @experimental
+```
+(h: number, ny: number, t: Pick<TerrainData, "rockSlope" | "dirtHeight" | "snowHeight">): [number, number, number, number]
+```
+
## panoramaDirection — function @experimental
```
(u: number, v: number): [number, number, number]
@@ -13547,6 +13790,11 @@ PrefabsPlugin
(register: () => Promise<void>): Promise<ProbedRegistrations>
```
+## proceduralHeightfield — function @experimental
+```
+(p: ProceduralParams): Heightfield
+```
+
## projectSideModuleIds — function @experimental
```
(): string[]
@@ -13677,6 +13925,11 @@ PrefabsPlugin
(id: string, fn: DrawCallback, scene?: string): void
```
+## registerEffect — function @experimental
+```
+(def: EffectDef): void
+```
+
## registerPackagedSideModules — function @experimental
```
(config: Pick<PackagedGameConfig, "sideModules">): void
@@ -13702,7 +13955,7 @@ PrefabsPlugin
(name: string, spec: AiValueSpec<AiContext>): void
```
-## registerWeatherPreset — function @public
+## registerWeatherPreset — function @beta
```
(name: string, preset: WeatherPreset): number
```
@@ -13857,6 +14110,11 @@ PrefabsPlugin
(base: "dark" | "light", overrides?: ThemeOverrides): ThemeTokens
```
+## rng — function @experimental
+```
+(seed: number): () => number
+```
+
## rotateVec3ByQuat — function @experimental
```
(rot: Quat, v: Vec3): Vec3
@@ -13877,6 +14135,11 @@ PrefabsPlugin
SafeAreaPlugin
```
+## sampleHeight — function @experimental
+```
+(field: Heightfield, u: number, v: number): number
+```
+
## sampleKeyframes — function @experimental
```
(keys: readonly Keyframe[], at: number): number
@@ -13902,6 +14165,11 @@ SafeAreaPlugin
{ readonly clamp: (x: number, min: number, max: number) => number; readonly clamp01: (x: number) => number; readonly lerp: (a: number, b: number, t: number) => number; readonly inverseLerp: (a: number, b: number, value: number) => number; readonly remap: (value: number, inMin: number, inMax: number, outMin: number, outMax: number) => number; readonly deg2rad: (deg: number) => number; readonly rad2deg: (rad: number) => number; readonly approximately: (a: number, b: number, epsilon?: number) => boolean; readonly smoothstep: (edge0: number, edge1: number, x: number) => number; readonly mod: (x: number, n: number) => number; readonly sign: (x: number) => number; }
```
+## scatterCell — function @experimental
+```
+(p: ScatterParams, ground: Ground): Plant[]
+```
+
## sceneAmbientLights — function @experimental
```
(entities: readonly EnvironmentLightEntity[], exists: (ref: string) => boolean): SceneAmbientLight[]
@@ -14357,6 +14625,16 @@ StatsPlugin
(ctx?: CensusContext): Census
```
+## terrainNormal — function @experimental
+```
+(field: Heightfield, u: number, v: number, sizeX: number, sizeZ: number, heightScale: number): [number, number, number]
+```
+
+## terrainPlugin — const @experimental
+```
+Plugin
+```
+
## textInputPlugin — const @experimental
```
TextInputPlugin
@@ -14392,7 +14670,7 @@ TextPlugin
(): ThemeType
```
-## timeOfDayAt — function @public
+## timeOfDayAt — function @beta
```
(hour: number, latitude?: number, declination?: number, north?: number): TimeOfDayState
```
@@ -14617,12 +14895,12 @@ VideoPlugin
(category: string, message: string, data?: unknown): void
```
-## weatherPresetId — function @public
+## weatherPresetId — function @beta
```
(name: string): number | undefined
```
-## weatherPresetNames — function @public
+## weatherPresetNames — function @beta
```
(): string[]
```
diff --git a/sdk/src/app/pluginSets.ts b/sdk/src/app/pluginSets.ts
index a77ef8668..5e0ebffe2 100644
--- a/sdk/src/app/pluginSets.ts
+++ b/sdk/src/app/pluginSets.ts
@@ -28,6 +28,8 @@ import { particlePlugin } from '../particle';
import { trailPlugin } from '../trail';
import { meshRendererPlugin } from '../render/meshRenderer';
import { staticBatchPlugin } from '../render/staticBatchPlugin';
+import { terrainPlugin } from '../terrain/terrainPlugin';
+import { foliagePlugin } from '../foliage/foliagePlugin';
import { postProcessPlugin } from '../postprocess';
import { timelinePlugin } from '../timeline';
import { timerPlugin } from '../ecs/timer';
@@ -57,7 +59,7 @@ export const simulationBasePlugins = (): Plugin[] => [
/** What exists to be seen. Every entry drives the engine through `engineApi`. */
export const presentationBasePlugins = (): Plugin[] => [
- animationPlugin, videoPlugin, particlePlugin, trailPlugin, meshRendererPlugin, staticBatchPlugin,
+ animationPlugin, videoPlugin, particlePlugin, trailPlugin, meshRendererPlugin, staticBatchPlugin, terrainPlugin, foliagePlugin,
postProcessPlugin, timelinePlugin,
];
@@ -68,7 +70,7 @@ export const presentationBasePlugins = (): Plugin[] => [
*/
export const PLUGIN_BUILD_ORDER: readonly string[] = [
'Diagnostics', 'timer', 'velocity', 'lifecycle', 'animation', 'audio', 'video',
- 'particle', 'trail', 'meshRenderer', 'staticBatch', 'tilemap', 'postProcess', 'timeline',
+ 'particle', 'trail', 'meshRenderer', 'staticBatch', 'terrain', 'foliage', 'tilemap', 'postProcess', 'timeline',
'gameplay',
'perception', 'fsm', 'bt', 'scriptGraph', 'nav', 'eventBinding', 'replication',
'services',
@@ -94,7 +96,7 @@ export function inBuildOrder(plugins: readonly Plugin[]): Plugin[] {
export const webBasePlugins = (): Plugin[] => [
diagnosticsPlugin,
timerPlugin, velocityPlugin, lifecyclePlugin, animationPlugin, audioPlugin, videoPlugin,
- particlePlugin, trailPlugin, meshRendererPlugin, staticBatchPlugin, postProcessPlugin, timelinePlugin,
+ particlePlugin, trailPlugin, meshRendererPlugin, staticBatchPlugin, terrainPlugin, foliagePlugin, postProcessPlugin, timelinePlugin,
eventBindingPlugin,
servicesPlugin,
];
diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.ts
index 2f2da6039..40c5592f7 100644
--- a/sdk/src/core-content.ts
+++ b/sdk/src/core-content.ts
@@ -779,6 +779,23 @@ export {
StaticBatch, StaticBatching, StaticBatchingRes, StaticBatchPlugin, staticBatchPlugin,
StaticBatchState, type StaticBatchData, type StaticBatchSummary,
} from './render/staticBatchPlugin';
+export {
+ Terrain, Terrains, TerrainsRes, TerrainPlugin, terrainPlugin, paintWeights, type TerrainData,
+} from './terrain/terrainPlugin';
+export {
+ Foliage, FoliageField, FoliageRes, FoliagePlugin, foliagePlugin, type FoliageData,
+} from './foliage/foliagePlugin';
+export {
+ scatterCell, buildGrassMesh, buildInstancedMesh, buildBillboardMesh, rng,
+ type Plant, type Ground, type ScatterParams, type BladeParams, type CardRect,
+} from './foliage/builder';
+export {
+ heightfieldFromPixels, proceduralHeightfield, sampleHeight, terrainNormal,
+ type Heightfield, type ProceduralParams,
+} from './terrain/heightfield';
+export {
+ buildChunkMesh, cellsAtLod, chunkCenter, lodCount, type TerrainShape, type TerrainPaint,
+} from './terrain/mesh';
export {
mergeMeshes, planStaticBatches, STATIC_BATCH_DEFAULTS,
type StaticBatchGroup, type StaticBatchLimits, type StaticBatchRefusal, type StaticBatchReport,
diff --git a/sdk/src/core-render.ts b/sdk/src/core-render.ts
index 54105419e..ca62fafcc 100644
--- a/sdk/src/core-render.ts
+++ b/sdk/src/core-render.ts
@@ -172,6 +172,7 @@ export {
type EffectDef,
type ComputeEffectSource,
type EffectUniformDef,
+ registerEffect,
getEffectDef,
getEffectTypes,
getAllEffectDefs,
diff --git a/sdk/src/foliage/builder.ts b/sdk/src/foliage/builder.ts
new file mode 100644
index 000000000..7e77a74cf
--- /dev/null
+++ b/sdk/src/foliage/builder.ts
@@ -0,0 +1,278 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file builder.ts
+ * @brief Where plants stand, and the geometry of a patch of them.
+ *
+ * @details A field of grass is tens of thousands of blades and a forest is thousands of trees, which no engine draws one entity at a time. The
+ * ground is cut into cells and every cell is ONE mesh with all its plants in it, so a field is a few hundred draws that
+ * culling can drop whole. Each cell is built at the detail its distance deserves — fewer, broader blades; a tree
+ * reduced to two crossed cards — and the engine's own level-of-detail picks among them.
+ *
+ * What the wind needs is painted into the vertices, because a plant is not a thing the vertex stage can see once it is
+ * merged: the colour's red is how far up the plant the vertex is (the tip moves and the root does not), green is a
+ * phase of the plant's own so a meadow does not sway as one, and blue is how much light reaches it (the base of a
+ * clump is darker). The Foliage material reads them; a mesh drawn without it shows them as colour, so a field with
+ * no material is painted in its own colours instead.
+ */
+import { MeshChannel, MeshChannelType, packChannels, type MeshData } from '../asset/meshFormat';
+
+/** One plant, in the space of the cell that holds it. */
+export interface Plant {
+ x: number;
+ y: number;
+ z: number;
+ /** Turn about the vertical, radians. */
+ yaw: number;
+ scale: number;
+ /** 0 to 1: its own phase in the wind, and how dark its roots are. */
+ phase: number;
+ shade: number;
+}
+
+/** What a place is, as the ground answers: how high it is and how much it faces up. */
+export type Ground = (x: number, z: number) => { y: number; up: number } | null;
+
+export interface ScatterParams {
+ /** The cell: its centre and its side, in the space the ground answers in. */
+ centerX: number;
+ centerZ: number;
+ size: number;
+ count: number;
+ seed: number;
+ /** An integer naming the cell, so two cells never roll the same dice. */
+ cellKey: number;
+ minScale: number;
+ maxScale: number;
+ /** The least a place may face up (the normal's y) and still grow something. */
+ minUp: number;
+ heightMin: number;
+ heightMax: number;
+}
+
+/** A deterministic 32-bit generator: the same seed grows the same field on every host. */
+export function rng(seed: number): () => number {
+ let a = seed | 0;
+ return () => {
+ a = (a + 0x6d2b79f5) | 0;
+ let t = Math.imul(a ^ (a >>> 15), 1 | a);
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
+ };
+}
+
+/**
+ * The plants of one cell: `count` tries at random places, each kept only where the ground is gentle enough and in the height band.
+ * Positions come back relative to the cell's centre, with the ground's height already in them.
+ */
+export function scatterCell(p: ScatterParams, ground: Ground): Plant[] {
+ const random = rng(Math.imul(p.seed | 0, 73856093) ^ Math.imul(p.cellKey | 0, 19349663) ^ 0x9e3779b9);
+ const out: Plant[] = [];
+ for (let i = 0; i < p.count; i++) {
+ const x = p.centerX + (random() - 0.5) * p.size;
+ const z = p.centerZ + (random() - 0.5) * p.size;
+ const yaw = random() * Math.PI * 2;
+ const scale = p.minScale + (p.maxScale - p.minScale) * random();
+ const phase = random();
+ const shade = 0.7 + 0.3 * random();
+ const g = ground(x, z);
+ if (!g || g.up < p.minUp || g.y < p.heightMin || g.y > p.heightMax) continue;
+ out.push({ x: x - p.centerX, y: g.y, z: z - p.centerZ, yaw, scale, phase, shade });
+ }
+ return out;
+}
+
+/** The vertices a patch is made of, before they are packed. */
+interface Builder {
+ pos: number[];
+ uv: number[];
+ color: number[];
+ nrm: number[];
+ idx: number[];
+}
+
+const newBuilder = (): Builder => ({ pos: [], uv: [], color: [], nrm: [], idx: [] });
+
+function vertex(b: Builder, x: number, y: number, z: number, u: number, v: number,
+ r: number, g: number, bl: number, nx: number, ny: number, nz: number): number {
+ b.pos.push(x, y, z);
+ b.uv.push(u, v);
+ b.color.push(r, g, bl, 1);
+ b.nrm.push(nx, ny, nz);
+ return b.pos.length / 3 - 1;
+}
+
+function pack(b: Builder): MeshData {
+ 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 vertexCount = b.pos.length / 3;
+ const vertices = new Uint8Array(Math.max(1, vertexCount) * vertexStride);
+ const view = new DataView(vertices.buffer);
+ const posAt = channels[0]!.offset, uvAt = channels[1]!.offset, colorAt = channels[2]!.offset, normalAt = channels[3]!.offset;
+ const min: [number, number, number] = [Infinity, Infinity, Infinity];
+ const max: [number, number, number] = [-Infinity, -Infinity, -Infinity];
+ for (let i = 0; i < vertexCount; i++) {
+ const at = i * vertexStride;
+ for (let k = 0; k < 3; k++) {
+ const value = b.pos[i * 3 + k]!;
+ view.setFloat32(at + posAt + k * 4, value, true);
+ view.setFloat32(at + normalAt + k * 4, b.nrm[i * 3 + k]!, true);
+ if (value < min[k]!) min[k] = value;
+ if (value > max[k]!) max[k] = value;
+ }
+ view.setFloat32(at + uvAt, b.uv[i * 2]!, true);
+ view.setFloat32(at + uvAt + 4, b.uv[i * 2 + 1]!, true);
+ for (let k = 0; k < 4; k++) view.setUint8(at + colorAt + k, Math.round(Math.min(Math.max(b.color[i * 4 + k]!, 0), 1) * 255));
+ }
+ if (vertexCount === 0) { min.fill(0); max.fill(0); }
+ return { channels, vertexStride, vertexCount, vertices, indices: new Uint32Array(b.idx), aabbMin: min, aabbMax: max };
+}
+
+/** How blades are drawn. */
+export interface BladeParams {
+ height: number;
+ width: number;
+ /** Segments up a blade; the more, the smoother its bend. */
+ segments: number;
+ /** Every n-th plant only, drawn broader to make up for the ones left out. */
+ thin: number;
+ /** Paint a colour the plain material shows, instead of the wind's weights. */
+ paint?: { base: [number, number, number]; tip: [number, number, number] } | null;
+}
+
+/**
+ * A patch of grass: a tapered, slightly bent blade for each plant, facing where its yaw says. The normal leans toward the ground's up
+ * so a meadow is lit as one surface and not as ten thousand knives.
+ */
+export function buildGrassMesh(plants: readonly Plant[], blade: BladeParams): MeshData {
+ const b = newBuilder();
+ const segments = Math.max(1, Math.floor(blade.segments));
+ const thin = Math.max(1, Math.floor(blade.thin));
+ const widen = Math.sqrt(thin);
+ for (let i = 0; i < plants.length; i += thin) {
+ const p = plants[i]!;
+ const h = blade.height * p.scale * (widen > 1 ? 1.1 : 1);
+ const w = blade.width * p.scale * widen * 0.5;
+ const cos = Math.cos(p.yaw), sin = Math.sin(p.yaw);
+ // The blade's width runs along (cos, 0, -sin) and it faces (sin, 0, cos).
+ const fx = sin, fz = cos;
+ const base = b.pos.length / 3;
+ const ring: number[] = [];
+ for (let s = 0; s <= segments; s++) {
+ const t = s / segments;
+ const half = s === segments ? 0 : w * (1 - t * 0.85);
+ const lean = t * t * h * 0.12;
+ const y = p.y + t * h;
+ const cx = p.x + fx * lean, cz = p.z + fz * lean;
+ const color = blade.paint ? paintColor(blade.paint, t, p.shade) : [t, p.phase, p.shade * (0.55 + 0.45 * t)] as const;
+ const ny = 0.65;
+ const nx = fx * 0.75, nz = fz * 0.75;
+ const left = vertex(b, cx - cos * half, y, cz + sin * half, 0, t, color[0], color[1], color[2], nx, ny, nz);
+ if (s === segments) { ring.push(left, left); continue; }
+ const right = vertex(b, cx + cos * half, y, cz - sin * half, 1, t, color[0], color[1], color[2], nx, ny, nz);
+ ring.push(left, right);
+ }
+ void base;
+ for (let s = 0; s < segments; s++) {
+ const l0 = ring[s * 2]!, r0 = ring[s * 2 + 1]!, l1 = ring[s * 2 + 2]!, r1 = ring[s * 2 + 3]!;
+ b.idx.push(l0, r0, l1);
+ if (r1 !== l1) b.idx.push(r0, r1, l1);
+ }
+ }
+ return pack(b);
+}
+
+function paintColor(paint: NonNullable<BladeParams['paint']>, t: number, shade: number): [number, number, number] {
+ const light = shade * (0.55 + 0.45 * t);
+ return [
+ (paint.base[0] + (paint.tip[0] - paint.base[0]) * t) * light,
+ (paint.base[1] + (paint.tip[1] - paint.base[1]) * t) * light,
+ (paint.base[2] + (paint.tip[2] - paint.base[2]) * t) * light,
+ ];
+}
+
+/** Reads a channel of a source mesh as floats. */
+function reader(mesh: MeshData, semantic: number, components: number): ((v: number, out: number[]) => boolean) {
+ const channel = mesh.channels.find((c) => c.semantic === semantic);
+ if (!channel || channel.type !== MeshChannelType.Float32 || channel.components < components) return () => false;
+ const view = new DataView(mesh.vertices.buffer, mesh.vertices.byteOffset, mesh.vertices.byteLength);
+ return (v, out) => {
+ for (let k = 0; k < components; k++) out[k] = view.getFloat32(v * mesh.vertexStride + channel.offset + k * 4, true);
+ return true;
+ };
+}
+
+/**
+ * Copies of a mesh, one per plant, as one mesh: placed, turned about the vertical and scaled, with the wind's weights painted by how
+ * high each vertex stands on its own copy (a tree's trunk hardly moves, its crown does).
+ */
+export function buildInstancedMesh(source: MeshData, plants: readonly Plant[], paint?: BladeParams['paint']): MeshData {
+ const b = newBuilder();
+ const readPosition = reader(source, MeshChannel.Position, 3);
+ const readNormal = reader(source, MeshChannel.Normal, 3);
+ const readUv = reader(source, MeshChannel.TexCoord0, 2);
+ const minY = source.aabbMin[1], span = Math.max(1e-6, source.aabbMax[1] - source.aabbMin[1]);
+ const p3 = [0, 0, 0], n3 = [0, 1, 0], uv2 = [0, 0];
+ for (const plant of plants) {
+ const base = b.pos.length / 3;
+ const cos = Math.cos(plant.yaw), sin = Math.sin(plant.yaw);
+ for (let v = 0; v < source.vertexCount; v++) {
+ readPosition(v, p3);
+ if (!readNormal(v, n3)) { n3[0] = 0; n3[1] = 1; n3[2] = 0; }
+ if (!readUv(v, uv2)) { uv2[0] = 0; uv2[1] = 0; }
+ const t = Math.min(Math.max((p3[1]! - minY) / span, 0), 1);
+ const x = p3[0]! * plant.scale, y = p3[1]! * plant.scale, z = p3[2]! * plant.scale;
+ const color = paint ? paintColor(paint, t, plant.shade) : [t, plant.phase, plant.shade * (0.6 + 0.4 * t)] as const;
+ vertex(b, plant.x + x * cos + z * sin, plant.y + y, plant.z - x * sin + z * cos, uv2[0]!, uv2[1]!,
+ color[0], color[1], color[2], n3[0]! * cos + n3[2]! * sin, n3[1]!, -n3[0]! * sin + n3[2]! * cos);
+ }
+ for (const i of source.indices) b.idx.push(base + i);
+ }
+ return pack(b);
+}
+
+/** The rectangle of the plant's texture a card shows, in uv. */
+export interface CardRect {
+ u0: number;
+ v0: number;
+ u1: number;
+ v1: number;
+}
+
+/**
+ * The far version of a plant: two cards crossed at right angles, as wide and as tall as the plant is, each showing the rectangle of the
+ * plant's texture that is its picture. Cheap enough that a forest on the horizon is a few triangles a tree, and seen from any side.
+ */
+export function buildBillboardMesh(
+ plants: readonly Plant[], width: number, height: number, rect: CardRect, paint?: BladeParams['paint'], triangle = false,
+): MeshData {
+ const b = newBuilder();
+ for (const plant of plants) {
+ const w = width * plant.scale * 0.5, h = height * plant.scale;
+ for (const turn of [0, Math.PI / 2]) {
+ const a = plant.yaw + turn;
+ const cos = Math.cos(a), sin = Math.sin(a);
+ const lower = paint ? paintColor(paint, 0, plant.shade) : [0, plant.phase, plant.shade * 0.6] as const;
+ const upper = paint ? paintColor(paint, 1, plant.shade) : [1, plant.phase, plant.shade] as const;
+ if (triangle) {
+ // A tent: wide at a tenth of the height, where a conifer's needles begin, and a point at the top.
+ const foot = h * 0.1, vMid = rect.v0 + (rect.v1 - rect.v0) * 0.1, uMid = (rect.u0 + rect.u1) / 2;
+ const t0 = vertex(b, plant.x - cos * w, plant.y + foot, plant.z + sin * w, rect.u0, vMid, lower[0], lower[1], lower[2], 0, 1, 0);
+ const t1 = vertex(b, plant.x + cos * w, plant.y + foot, plant.z - sin * w, rect.u1, vMid, lower[0], lower[1], lower[2], 0, 1, 0);
+ const t2 = vertex(b, plant.x, plant.y + h, plant.z, uMid, rect.v1, upper[0], upper[1], upper[2], 0, 1, 0);
+ b.idx.push(t0, t1, t2);
+ continue;
+ }
+ const v0 = vertex(b, plant.x - cos * w, plant.y, plant.z + sin * w, rect.u0, rect.v0, lower[0], lower[1], lower[2], 0, 1, 0);
+ const v1 = vertex(b, plant.x + cos * w, plant.y, plant.z - sin * w, rect.u1, rect.v0, lower[0], lower[1], lower[2], 0, 1, 0);
+ const v2 = vertex(b, plant.x + cos * w, plant.y + h, plant.z - sin * w, rect.u1, rect.v1, upper[0], upper[1], upper[2], 0, 1, 0);
+ const v3 = vertex(b, plant.x - cos * w, plant.y + h, plant.z + sin * w, rect.u0, rect.v1, upper[0], upper[1], upper[2], 0, 1, 0);
+ b.idx.push(v0, v1, v2, v0, v2, v3);
+ }
+ }
+ return pack(b);
+}
diff --git a/sdk/src/foliage/foliagePlugin.ts b/sdk/src/foliage/foliagePlugin.ts
new file mode 100644
index 000000000..37fc90cc4
--- /dev/null
+++ b/sdk/src/foliage/foliagePlugin.ts
@@ -0,0 +1,306 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file foliagePlugin.ts
+ * @brief Grass and trees across an area, drawn a cell at a time and swaying in the wind.
+ *
+ * @details The `Foliage` component says what grows where; this grows it. The entity stays as authored and the cells are its children,
+ * made when the scene runs (and in the editor's scene view) and made again when a field changes, so nothing is baked.
+ * Each cell is a MeshRenderer with a LODGroup (see builder.ts for what each level is), so culling and the choice of level are
+ * the engine's. If there is a Terrain, plants stand on it, avoid what is too steep and wait for it to be built.
+ */
+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,
+} from '../ecs/component';
+import { Assets } from '../asset/AssetPlugin';
+import type { MeshData } from '../asset/meshFormat';
+import { log } from '../util/logger';
+import type { Entity } from '../types';
+import { TerrainsRes } from '../terrain/terrainPlugin';
+import {
+ buildBillboardMesh, buildGrassMesh, buildInstancedMesh, scatterCell,
+ type Ground, type Plant,
+} from './builder';
+
+/** The fields of the `Foliage` component. @experimental */
+export interface FoliageData {
+ /** The plant to scatter. Empty grows grass, blades made here. */
+ mesh: number;
+ /** A material on the Foliage shader, which makes the wind. Empty draws the plants in their own colours, still. */
+ material: number;
+ /** The area, centred on the entity, and the side of the cells it is cut into. */
+ sizeX: number;
+ sizeZ: number;
+ cellSize: number;
+ /** Plants per cell. */
+ count: number;
+ seed: number;
+ minScale: number;
+ maxScale: number;
+ /** The least a place may face up (0 to 1) and still grow something: lower lets plants onto slopes. */
+ minUp: number;
+ /** The band of heights, in world units, plants grow in. */
+ heightMin: number;
+ heightMax: number;
+ /** Grass: how tall and how wide a blade is, at scale 1. */
+ bladeHeight: number;
+ bladeWidth: number;
+ /** Distance past which a cell is drawn as its far version, and past which it is not drawn. */
+ lodDistance: number;
+ drawDistance: number;
+ /** A tree's far version is two crossed cards showing this rectangle of its texture, as uv: left, bottom, right, top. */
+ cardU0: number;
+ cardV0: number;
+ cardU1: number;
+ cardV1: number;
+ /** 1 draws a far tree's cards as tents (a conifer's outline) rather than rectangles. */
+ cardTent: number;
+}
+
+/**
+ * Plants across an area. Presence is the opt-in; its children are the cells that draw them.
+ *
+ * @experimental
+ */
+export const Foliage: ComponentDef<FoliageData> = defineComponent<FoliageData>('Foliage', {
+ mesh: 0, material: 0,
+ sizeX: 400, sizeZ: 400, cellSize: 40, count: 500, seed: 1,
+ minScale: 0.8, maxScale: 1.25, minUp: 0.7, heightMin: -100000, heightMax: 100000,
+ bladeHeight: 14, bladeWidth: 1.6, lodDistance: 140, drawDistance: 420,
+ cardU0: 0, cardV0: 0, cardU1: 1, cardV1: 1, cardTent: 0,
+}, {
+ assetFields: [{ field: 'mesh', type: 'mesh' }, { field: 'material', type: 'material' }],
+ fields: {
+ mesh: { tooltip: 'The plant to scatter. Empty grows grass.', category: 'Plant' },
+ material: { tooltip: 'A material on the Foliage shader, which makes the wind. Empty draws the plants still, in their own colours.', category: 'Plant' },
+ sizeX: { min: 1, category: 'Area', tooltip: 'World size along x, centred on this entity.' },
+ sizeZ: { min: 1, category: 'Area', tooltip: 'World size along z, centred on this entity.' },
+ cellSize: { min: 4, category: 'Area', tooltip: 'Side of the cells the area is cut into. Each is one mesh, culled whole.' },
+ count: { min: 0, step: 1, category: 'Area', tooltip: 'Plants per cell.' },
+ seed: { step: 1, category: 'Area', tooltip: 'Another seed grows the same plants in other places.' },
+ minScale: { min: 0.01, category: 'Plant' },
+ maxScale: { min: 0.01, category: 'Plant' },
+ minUp: { min: 0, max: 1, step: 0.01, category: 'Placement', tooltip: 'The least a place may face up and still grow something. Lower lets plants onto slopes.' },
+ heightMin: { category: 'Placement', tooltip: 'The lowest world height plants grow at.' },
+ heightMax: { category: 'Placement', tooltip: 'The highest world height plants grow at.' },
+ bladeHeight: { min: 0.1, category: 'Grass', tooltip: 'Height of a blade at scale 1.' },
+ bladeWidth: { min: 0.01, category: 'Grass', tooltip: 'Width of a blade at its base, at scale 1.' },
+ lodDistance: { min: 1, category: 'Distance', tooltip: 'Past this a cell is drawn as its far version: fewer, broader blades, or a tree as crossed cards.' },
+ drawDistance: { min: 1, category: 'Distance', tooltip: 'Past this a cell is not drawn.' },
+ cardU0: { label: 'Card left', category: 'Far version', tooltip: 'The part of the plant\'s texture a far tree shows (left, bottom, right, top).' },
+ cardV0: { label: 'Card bottom', category: 'Far version' },
+ cardU1: { label: 'Card right', category: 'Far version' },
+ cardV1: { label: 'Card top', category: 'Far version' },
+ cardTent: { label: 'Card shape', category: 'Far version', enum: [{ label: 'Rectangle', value: 0 }, { label: 'Tent (conifer)', value: 1 }], tooltip: 'The outline of the cards a far tree is drawn as.' },
+ },
+});
+
+interface BuiltFoliage {
+ signature: string;
+ data: FoliageData;
+ cells: Entity[];
+ handles: number[];
+ queue: [number, number][];
+ source: MeshData | null;
+ loading: boolean;
+ epoch: number;
+ /** What the terrain was when this was grown. */
+ terrainRevision: number;
+}
+
+const CELLS_PER_FRAME = 3;
+
+/** Run-time facts about the foliage the plugin has grown. */
+export class FoliageField {
+ /** @internal */ readonly built_ = new Map<Entity, BuiltFoliage>();
+
+ /** How many cells across every field are still waiting to be built. */
+ get pending(): number {
+ let n = 0;
+ for (const b of this.built_.values()) n += b.queue.length + (b.loading ? 1 : 0);
+ return n;
+ }
+
+ /** How many plants stand in the cells built so far, across every field. */
+ get cellCount(): number {
+ let n = 0;
+ for (const b of this.built_.values()) n += b.cells.length;
+ return n;
+ }
+}
+
+/** The resource the plugin installs. @experimental */
+export const FoliageRes = defineResource<FoliageField>(new FoliageField(), 'Foliage');
+
+export class FoliagePlugin implements Plugin {
+ name = 'foliage';
+
+ build(app: App): void {
+ const field = new FoliageField();
+ app.insertResource(FoliageRes, field);
+
+ app.addSystemToSchedule(Schedule.Update, defineSystem([], () => {
+ if (!app.hasResource(Assets)) return;
+ const terrains = app.hasResource(TerrainsRes) ? app.getResource(TerrainsRes) : null;
+ this.sweep(app, field);
+ // What stands on the ground waits for it: a plant placed before its terrain is read would stand on nothing.
+ if (terrains?.loading) return;
+ const revision = terrains?.revision_ ?? 0;
+ for (const entity of app.world.getEntitiesWithComponents([Foliage, Transform])) {
+ const data = app.world.get(entity, Foliage) as FoliageData;
+ const signature = JSON.stringify(data);
+ let built = field.built_.get(entity);
+ if (!built || built.signature !== signature || built.terrainRevision !== revision) {
+ if (built) this.destroy(app, built);
+ built = {
+ signature, data: { ...data }, cells: [], handles: [], queue: [], source: null, loading: true,
+ epoch: (built?.epoch ?? 0) + 1, terrainRevision: revision,
+ };
+ field.built_.set(entity, built);
+ void this.start(app, entity, built);
+ continue;
+ }
+ if (built.loading) continue;
+ for (let i = 0; i < CELLS_PER_FRAME && built.queue.length > 0; i++) {
+ const [cx, cz] = built.queue.shift()!;
+ this.buildCell(app, entity, built, cx, cz);
+ }
+ }
+ }, { name: 'FoliageSystem' }));
+ }
+
+ cleanup(app?: App): void {
+ if (!app?.hasResource(FoliageRes)) return;
+ const field = app.getResource(FoliageRes);
+ for (const built of field.built_.values()) this.destroy(app, built);
+ field.built_.clear();
+ }
+
+ /** Reads the plant's geometry, if it has one, then queues the cells. */
+ private async start(app: App, entity: Entity, built: BuiltFoliage): Promise<void> {
+ const epoch = built.epoch;
+ const data = built.data;
+ try {
+ if (data.mesh) {
+ const source = await app.getResource(Assets).readMeshData(data.mesh);
+ if (built.epoch !== epoch) return;
+ built.source = source;
+ if (!source) log.warn('foliage', `the geometry of mesh ${data.mesh} cannot be read, so its plants are grass instead`);
+ }
+ if (!app.world.valid(entity)) return;
+ const cells = this.cellsAcross(data);
+ for (let cz = 0; cz < cells.z; cz++) for (let cx = 0; cx < cells.x; cx++) built.queue.push([cx, cz]);
+ } catch (e) {
+ log.error('foliage', 'growing the foliage failed', e);
+ } finally {
+ if (built.epoch === epoch) built.loading = false;
+ }
+ }
+
+ private cellsAcross(data: FoliageData): { x: number; z: number } {
+ const side = Math.max(1, data.cellSize);
+ return { x: Math.min(200, Math.max(1, Math.ceil(data.sizeX / side))), z: Math.min(200, Math.max(1, Math.ceil(data.sizeZ / side))) };
+ }
+
+ private buildCell(app: App, parent: Entity, built: BuiltFoliage, cx: number, cz: number): void {
+ const world = app.world;
+ if (!world.valid(parent)) return;
+ const data = built.data;
+ const assets = app.getResource(Assets);
+ const terrains = app.hasResource(TerrainsRes) ? app.getResource(TerrainsRes) : null;
+ const t = world.tryGet(parent, Transform) as TransformData | null;
+ if (!t) return;
+ const side = Math.max(1, data.cellSize);
+ const cells = this.cellsAcross(data);
+ // The cell's centre in the entity's own space, then in the world's (the ground is answered in the world's).
+ const localX = -data.sizeX / 2 + (cx + 0.5) * (data.sizeX / cells.x);
+ const localZ = -data.sizeZ / 2 + (cz + 0.5) * (data.sizeZ / cells.z);
+ const sx = t.worldScale.x || 1, sz = t.worldScale.z || 1;
+ const worldX = t.worldPosition.x + localX * sx, worldZ = t.worldPosition.z + localZ * sz;
+ const hasTerrain = !!terrains && terrains.built_.size > 0;
+ const ground: Ground = (x, z) => {
+ // With a terrain, a plant stands where there is ground and nowhere else; with none, the area is flat at the entity's height.
+ if (!hasTerrain) return { y: t.worldPosition.y, up: 1 };
+ const y = terrains!.heightAt(x, z);
+ if (y === null) return null;
+ const n = terrains!.normalAt(x, z);
+ return { y, up: n ? n[1] : 1 };
+ };
+ const plants: Plant[] = scatterCell({
+ centerX: worldX, centerZ: worldZ, size: Math.min(side, data.sizeX / cells.x), count: Math.floor(data.count), seed: data.seed,
+ cellKey: cz * 1000 + cx, minScale: data.minScale, maxScale: data.maxScale, minUp: data.minUp,
+ heightMin: data.heightMin, heightMax: data.heightMax,
+ }, ground);
+ if (plants.length === 0) return;
+ // The cell stands at its centre, on the entity's own base height; the plants carry the ground's height relative to that.
+ for (const p of plants) p.y -= t.worldPosition.y;
+
+ const paint = data.material ? null : { base: [0.14, 0.3, 0.08] as [number, number, number], tip: [0.55, 0.72, 0.25] as [number, number, number] };
+ const source = built.source;
+ const meshes: MeshData[] = [];
+ if (source) {
+ meshes.push(buildInstancedMesh(source, plants, paint));
+ const width = Math.max(source.aabbMax[0] - source.aabbMin[0], source.aabbMax[2] - source.aabbMin[2]);
+ meshes.push(buildBillboardMesh(plants, width, source.aabbMax[1] - source.aabbMin[1],
+ { u0: data.cardU0, v0: data.cardV0, u1: data.cardU1, v1: data.cardV1 }, paint, data.cardTent === 1));
+ } else {
+ const blade = { height: data.bladeHeight, width: data.bladeWidth, paint };
+ meshes.push(buildGrassMesh(plants, { ...blade, segments: 3, thin: 1 }));
+ meshes.push(buildGrassMesh(plants, { ...blade, segments: 1, thin: 3 }));
+ }
+ const handles: number[] = [];
+ for (const mesh of meshes) {
+ const handle = assets.createMesh(mesh);
+ if (handle === 0) {
+ log.warn('foliage', `the engine refused the geometry of cell ${cx},${cz}`);
+ for (const h of handles) assets.releaseBuiltMesh(h);
+ return;
+ }
+ handles.push(handle);
+ }
+ built.handles.push(...handles);
+
+ const cell = world.spawn(`FoliageCell ${cx},${cz}`);
+ world.insert(cell, Transform, { position: { x: localX, y: 0, z: localZ } });
+ world.insert(cell, MeshRenderer, {
+ mesh: handles[0]!, material: data.material, lit: true, opaque: true, cullBackfaces: false,
+ color: { r: 1, g: 1, b: 1, a: 1 },
+ } as Partial<MeshRendererData>);
+ const lodDef = getComponent('LODGroup');
+ if (lodDef) {
+ // The engine measures a cell by how much of the screen its bounding sphere covers: radius over distance, for a 60 degree view.
+ const radius = Math.hypot(side, side) * 0.5;
+ const sizeAt = (distance: number): number => radius / (Math.max(1, distance) * 0.577);
+ world.insert(cell, lodDef, {
+ lod1: handles[1] ?? 0, lod2: 0, lod3: 0,
+ lod1Size: sizeAt(data.lodDistance), lod2Size: 0, lod3Size: 0, cullSize: sizeAt(data.drawDistance), hysteresis: 0.1, enabled: true,
+ });
+ }
+ world.setParent(cell, parent);
+ built.cells.push(cell);
+ }
+
+ private destroy(app: App, built: BuiltFoliage): void {
+ built.epoch++;
+ built.queue.length = 0;
+ const assets = app.hasResource(Assets) ? app.getResource(Assets) : null;
+ for (const cell of built.cells) if (app.world.valid(cell)) app.world.despawn(cell);
+ for (const handle of built.handles) assets?.releaseBuiltMesh(handle);
+ built.cells.length = 0;
+ built.handles.length = 0;
+ }
+
+ private sweep(app: App, field: FoliageField): void {
+ for (const [entity, built] of field.built_) {
+ if (app.world.valid(entity) && app.world.has(entity, Foliage)) continue;
+ this.destroy(app, built);
+ field.built_.delete(entity);
+ }
+ }
+}
+
+export const foliagePlugin: Plugin = new FoliagePlugin();
diff --git a/sdk/src/render/builtinShaders.ts b/sdk/src/render/builtinShaders.ts
index 85673e9df..87e000b3b 100644
--- a/sdk/src/render/builtinShaders.ts
+++ b/sdk/src/render/builtinShaders.ts
@@ -1026,6 +1026,345 @@ fn waveSlope(p : vec2f, time : f32, dist : f32) -> Waves {
#pragma end
`;
+// Ground painted by four layers. The Terrain component writes how much of each layer a point of ground has into the vertex colour
+// (red, green, blue, alpha: grass, dirt, snow, rock), and this shader draws them: each layer is a texture tiled by world position so
+// it runs unbroken from one chunk to the next, and the rock is projected from three sides so a cliff is not a smear.
+const TERRAIN = `#pragma shader "Terrain"
+#pragma version 300 es
+#pragma domain Lit
+#pragma param u_layer0 texture default(white)
+#pragma param u_layer1 texture default(white)
+#pragma param u_layer2 texture default(white)
+#pragma param u_layer3 texture default(white)
+// Each layer's colour, which multiplies its texture, and how many world units one repeat of it covers.
+#pragma param u_tint0 color default(0.28,0.46,0.2,1)
+#pragma param u_tint1 color default(0.45,0.36,0.24,1)
+#pragma param u_tint2 color default(0.93,0.95,0.98,1)
+#pragma param u_tint3 color default(0.4,0.38,0.36,1)
+#pragma param u_tile0 float default(24) range(1,800) ui(slider)
+#pragma param u_tile1 float default(24) range(1,800) ui(slider)
+#pragma param u_tile2 float default(24) range(1,800) ui(slider)
+#pragma param u_tile3 float default(40) range(1,800) ui(slider)
+// How much a layer with more weight takes over from the others at the seam: 1 is a plain blend, higher a harder edge.
+#pragma param u_sharpness float default(1.6) range(1,8) ui(slider)
+// The wide, slow variation laid over the first layer so a big meadow does not read as one repeated tile.
+#pragma param u_macroVariation float default(0.35) range(0,1) ui(slider)
+#pragma param u_roughness float default(0.92) range(0,1) ui(slider)
+
+#pragma fragment
+precision highp float;
+
+in vec4 v_color;
+in vec2 v_texCoord;
+in highp vec2 v_worldPos;
+#ifdef MESH_NORMALS
+in highp vec3 v_worldNormal;
+in highp vec3 v_worldXYZ;
+#endif
+
+#ifdef ES_GBUFFER
+layout(location = 0) out vec4 fragColor;
+layout(location = 1) out vec4 fragSurface;
+
+vec2 packNormal(vec3 n) {
+ n /= (abs(n.x) + abs(n.y) + abs(n.z));
+ vec2 sgn = vec2(n.x >= 0.0 ? 1.0 : -1.0, n.y >= 0.0 ? 1.0 : -1.0);
+ vec2 e = n.z >= 0.0 ? n.xy : (1.0 - abs(n.yx)) * sgn;
+ return e * 0.5 + 0.5;
+}
+#else
+out vec4 fragColor;
+#endif
+
+void main() {
+#ifdef MESH_NORMALS
+ highp vec3 P = v_worldXYZ;
+ highp vec3 N = normalize(v_worldNormal);
+#else
+ 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));
+ 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));
+ w /= max(dot(w, vec4(1.0)), 1e-4);
+
+ vec3 c0 = texture(u_layer0, P.xz / u_tile0).rgb * u_tint0.rgb;
+ c0 *= mix(1.0, texture(u_layer0, P.xz / (u_tile0 * 7.3)).r * 1.8, u_macroVariation);
+ vec3 c1 = texture(u_layer1, P.xz / u_tile1).rgb * u_tint1.rgb;
+ vec3 c2 = texture(u_layer2, P.xz / u_tile2).rgb * u_tint2.rgb;
+ // Rock is seen from three sides, in proportion to how the ground faces them, so a sheer face is not stretched.
+ vec3 axis = pow(abs(N), vec3(4.0));
+ axis /= dot(axis, vec3(1.0));
+ vec3 c3 = (texture(u_layer3, P.zy / u_tile3).rgb * axis.x
+ + texture(u_layer3, P.xz / u_tile3).rgb * axis.y
+ + texture(u_layer3, P.xy / u_tile3).rgb * axis.z) * u_tint3.rgb;
+ vec3 albedo = c0 * w.x + c1 * w.y + c2 * w.z + c3 * w.w;
+
+ SurfaceExt ext = surfaceExtNone(N);
+ vec3 viewDir = viewDirection(P);
+ vec3 lit = applyLightingSurface(albedo, N, P, viewDir, 0.0, u_roughness, 0.5, 1.0, ext);
+ fragColor = vec4(lit, 1.0);
+#ifdef ES_GBUFFER
+ fragSurface = vec4(packNormal(N), u_roughness, 0.75);
+#endif
+}
+#pragma end
+
+#pragma fragment wgsl
+#ifdef ES_GBUFFER
+struct FragOut {
+ @location(0) color : vec4f,
+ @location(1) surface : vec4f,
+};
+
+fn packNormal(n : vec3f) -> vec2f {
+ let a = n / (abs(n.x) + abs(n.y) + abs(n.z));
+ let sgn = vec2f(select(-1.0, 1.0, a.x >= 0.0), select(-1.0, 1.0, a.y >= 0.0));
+ var e = a.xy;
+ if (a.z < 0.0) { e = (vec2f(1.0) - abs(a.yx)) * sgn; }
+ return e * 0.5 + 0.5;
+}
+
+@fragment fn fs_main(v : VSOut) -> FragOut {
+#else
+@fragment fn fs_main(v : VSOut) -> @location(0) vec4f {
+#endif
+ g_probeSlot = v.v_probeSlot;
+#ifdef MESH_LIGHTMAP
+ g_lightmap = v.v_lightmap;
+#endif
+#ifdef MESH_NORMALS
+ let P = v.v_worldXYZ;
+ let 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);
+#endif
+ // Every sample is taken here, in uniform control flow, where a derivative is allowed.
+ let layer0 = textureSample(u_layer0, u_layer0_s, P.xz / mc.u_tile0).rgb;
+ let macro0 = textureSample(u_layer0, u_layer0_s, P.xz / (mc.u_tile0 * 7.3)).r;
+ let layer1 = textureSample(u_layer1, u_layer1_s, P.xz / mc.u_tile1).rgb;
+ let layer2 = textureSample(u_layer2, u_layer2_s, P.xz / mc.u_tile2).rgb;
+ let rockX = textureSample(u_layer3, u_layer3_s, P.zy / mc.u_tile3).rgb;
+ let rockY = textureSample(u_layer3, u_layer3_s, P.xz / mc.u_tile3).rgb;
+ let rockZ = textureSample(u_layer3, u_layer3_s, P.xy / mc.u_tile3).rgb;
+
+ var w = max(v.v_color, 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);
+
+ let c0 = layer0 * mc.u_tint0.rgb * mix(1.0, macro0 * 1.8, mc.u_macroVariation);
+ let c1 = layer1 * mc.u_tint1.rgb;
+ let c2 = layer2 * mc.u_tint2.rgb;
+ var axis = pow(abs(N), vec3f(4.0));
+ axis = axis / dot(axis, vec3f(1.0));
+ let c3 = (rockX * axis.x + rockY * axis.y + rockZ * axis.z) * mc.u_tint3.rgb;
+ let albedo = c0 * w.x + c1 * w.y + c2 * w.z + c3 * w.w;
+
+ let ext = surfaceExtNone(N);
+ let viewDir = viewDirection(P);
+ let lit = applyLightingSurface(albedo, N, P, viewDir, 0.0, mc.u_roughness, 0.5, 1.0, ext);
+#ifdef ES_GBUFFER
+ var frag : FragOut;
+ frag.color = vec4f(lit, 1.0);
+ frag.surface = vec4f(packNormal(N), mc.u_roughness, 0.75);
+ return frag;
+#else
+ return vec4f(lit, 1.0);
+#endif
+}
+#pragma end
+`;
+
+// Plants that sway: the vertex hook bends by the weights the Foliage component paints in the vertex colour (red the height up the plant,
+// green its own phase, blue how much light reaches it), with a travelling gust and a flutter. Two-sided and translucent.
+const FOLIAGE = `#pragma shader "Foliage"
+#pragma version 300 es
+#pragma domain Lit
+#pragma param u_baseColor color default(0.14,0.30,0.08,1)
+#pragma param u_tipColor color default(0.55,0.72,0.25,1)
+// A texture over the plant (leaves, bark), and whether it is used at all: grass is drawn from the two colours and wants none.
+#pragma param u_albedo texture default(white)
+#pragma param u_useTexture float default(0) range(0,1) ui(slider)
+#pragma param u_alphaCutoff float default(0.5) range(0,1) ui(slider)
+#pragma coverage u_alphaCutoff
+#pragma param u_roughness float default(0.8) range(0,1) ui(slider)
+// Light that comes through a leaf from behind, and how thick the leaf is.
+#pragma param u_translucency float default(0.5) range(0,1) ui(slider)
+#pragma param u_thickness float default(0.3) range(0,1) ui(slider)
+// The wind: how hard it blows, how fast it moves, where it comes from (degrees), how long a gust is (the lower, the longer), and how much flutter rides on it.
+#pragma param u_windStrength float default(2) range(0,20) ui(slider)
+#pragma param u_windSpeed float default(1.2) range(0,6) ui(slider)
+#pragma param u_windDirection float default(40) range(0,360) ui(slider)
+#pragma param u_gustScale float default(0.02) range(0.001,0.5) ui(slider)
+#pragma param u_flutter float default(0.4) range(0,4) ui(slider)
+#pragma vertexbounds 30
+#pragma vertexoffset
+void esMaterialVertex(inout vec3 local, inout vec3 localNormal, in vec2 uv) {
+ float weight = es_vertexColor.r;
+ float phase = es_vertexColor.g * 6.2831853;
+ vec3 anchor = (esInstanceModel() * vec4(local, 1.0)).xyz;
+ float angle = radians(u_windDirection);
+ vec2 dir = vec2(sin(angle), cos(angle));
+ float t = u_time.x * u_windSpeed;
+ float gust = sin(dot(anchor.xz, dir) * u_gustScale - t * 1.3) * 0.5 + 0.5;
+ float flutter = sin(t * 3.1 + phase + anchor.x * 0.7) * u_flutter;
+ float sway = (gust + 0.25 * sin(t + phase)) * u_windStrength + flutter * weight;
+ float bend = weight * weight * sway;
+ local.xz += dir * bend;
+ // The length is kept: what the sideways bend takes from the height it gives back by lowering the tip.
+ local.y -= abs(bend) * 0.35 * weight;
+}
+#pragma end
+
+#pragma vertexoffset wgsl
+fn esMaterialVertex(local : ptr<function, vec3f>, localNormal : ptr<function, vec3f>, uv : vec2f) {
+ let weight = es_vertexColor.r;
+ let phase = es_vertexColor.g * 6.2831853;
+ let anchor = (esInstanceModel() * vec4f(*local, 1.0)).xyz;
+ let angle = radians(mc.u_windDirection);
+ let dir = vec2f(sin(angle), cos(angle));
+ let t = tc.u_time.x * mc.u_windSpeed;
+ let gust = sin(dot(anchor.xz, dir) * mc.u_gustScale - t * 1.3) * 0.5 + 0.5;
+ let flutter = sin(t * 3.1 + phase + anchor.x * 0.7) * mc.u_flutter;
+ let sway = (gust + 0.25 * sin(t + phase)) * mc.u_windStrength + flutter * weight;
+ let bend = weight * weight * sway;
+ (*local).x = (*local).x + dir.x * bend;
+ (*local).z = (*local).z + dir.y * bend;
+ (*local).y = (*local).y - abs(bend) * 0.35 * weight;
+}
+#pragma end
+
+#pragma fragment
+precision highp float;
+
+in vec4 v_color;
+in vec2 v_texCoord;
+in highp vec2 v_worldPos;
+#ifdef MESH_NORMALS
+in highp vec3 v_worldNormal;
+in highp vec3 v_worldXYZ;
+#endif
+
+#ifdef ES_GBUFFER
+layout(location = 0) out vec4 fragColor;
+layout(location = 1) out vec4 fragSurface;
+
+vec2 packNormal(vec3 n) {
+ n /= (abs(n.x) + abs(n.y) + abs(n.z));
+ vec2 sgn = vec2(n.x >= 0.0 ? 1.0 : -1.0, n.y >= 0.0 ? 1.0 : -1.0);
+ vec2 e = n.z >= 0.0 ? n.xy : (1.0 - abs(n.yx)) * sgn;
+ return e * 0.5 + 0.5;
+}
+#else
+out vec4 fragColor;
+#endif
+
+void main() {
+#ifdef MESH_NORMALS
+ highp vec3 P = v_worldXYZ;
+ highp vec3 N = normalize(v_worldNormal);
+ if (!gl_FrontFacing) N = -N;
+#else
+ highp vec3 P = vec3(v_worldPos, 0.0);
+ highp vec3 N = vec3(0.0, 0.0, 1.0);
+#endif
+ float height = clamp(v_color.r, 0.0, 1.0);
+ float light = v_color.b;
+ vec4 tex = texture(u_albedo, v_texCoord);
+ vec3 albedo = mix(u_baseColor.rgb, u_tipColor.rgb, height);
+ float alpha = 1.0;
+ if (u_useTexture > 0.5) {
+ albedo *= tex.rgb;
+ alpha = tex.a;
+ alpha = (alpha - u_alphaCutoff) / max(fwidth(alpha), 1e-4) + 0.5;
+ if (alpha <= 0.0) discard;
+ alpha = min(alpha, 1.0);
+ }
+ albedo *= light;
+ SurfaceExt ext = surfaceExtNone(N);
+ if (u_translucency > 0.0) {
+ ext.scatter = vec4(albedo * 1.3, u_translucency * 0.5);
+ ext.trans = vec4(u_translucency, u_thickness, 0.0, 0.0);
+ }
+ vec3 viewDir = viewDirection(P);
+ vec3 lit = applyLightingSurface(albedo, N, P, viewDir, 0.0, u_roughness, 0.5, 1.0, ext);
+ fragColor = vec4(lit, alpha);
+#ifdef ES_GBUFFER
+ fragSurface = vec4(packNormal(N), u_roughness, 0.75);
+#endif
+}
+#pragma end
+
+#pragma fragment wgsl
+#ifdef ES_GBUFFER
+struct FragOut {
+ @location(0) color : vec4f,
+ @location(1) surface : vec4f,
+};
+
+fn packNormal(n : vec3f) -> vec2f {
+ let a = n / (abs(n.x) + abs(n.y) + abs(n.z));
+ let sgn = vec2f(select(-1.0, 1.0, a.x >= 0.0), select(-1.0, 1.0, a.y >= 0.0));
+ var e = a.xy;
+ if (a.z < 0.0) { e = (vec2f(1.0) - abs(a.yx)) * sgn; }
+ return e * 0.5 + 0.5;
+}
+
+@fragment fn fs_main(v : VSOut, @builtin(front_facing) front : bool) -> FragOut {
+#else
+@fragment fn fs_main(v : VSOut, @builtin(front_facing) front : bool) -> @location(0) vec4f {
+#endif
+ // Taken before any branch: a derivative needs every fragment of its quad.
+ let duvx = dpdx(v.v_texCoord);
+ let duvy = dpdy(v.v_texCoord);
+ g_probeSlot = v.v_probeSlot;
+#ifdef MESH_LIGHTMAP
+ g_lightmap = v.v_lightmap;
+#endif
+ let tex = textureSampleGrad(u_albedo, u_albedo_s, v.v_texCoord, duvx, duvy);
+ let edge = max(fwidth(tex.a), 1e-4);
+#ifdef MESH_NORMALS
+ let P = v.v_worldXYZ;
+ var N = normalize(v.v_worldNormal);
+ if (!front) { N = -N; }
+#else
+ let P = vec3f(v.v_worldPos.x, 0.0, v.v_worldPos.y);
+ let N = vec3f(0.0, 0.0, 1.0);
+#endif
+ let height = clamp(v.v_color.r, 0.0, 1.0);
+ let light = v.v_color.b;
+ var albedo = mix(mc.u_baseColor.rgb, mc.u_tipColor.rgb, vec3f(height));
+ var alpha = 1.0;
+ if (mc.u_useTexture > 0.5) {
+ albedo = albedo * tex.rgb;
+ alpha = (tex.a - mc.u_alphaCutoff) / edge + 0.5;
+ if (alpha <= 0.0) { discard; }
+ alpha = min(alpha, 1.0);
+ }
+ albedo = albedo * light;
+ var ext = surfaceExtNone(N);
+ if (mc.u_translucency > 0.0) {
+ ext.scatter = vec4f(albedo * 1.3, mc.u_translucency * 0.5);
+ ext.trans = vec4f(mc.u_translucency, mc.u_thickness, 0.0, 0.0);
+ }
+ let viewDir = viewDirection(P);
+ let lit = applyLightingSurface(albedo, N, P, viewDir, 0.0, mc.u_roughness, 0.5, 1.0, ext);
+#ifdef ES_GBUFFER
+ var frag : FragOut;
+ frag.color = vec4f(lit, alpha);
+ frag.surface = vec4f(packNormal(N), mc.u_roughness, 0.75);
+ return frag;
+#else
+ return vec4f(lit, alpha);
+#endif
+}
+#pragma end
+`;
+
export const BUILTIN_SHADER_TEMPLATES: readonly BuiltinShaderTemplate[] = [
template('sprite-unlit', 'Unlit', 'Texture × vertex color × tint, no lighting.', SPRITE_UNLIT),
template('sprite-lit', 'Lit', 'Lit by the scene\'s 2D lights; optional normal map.', SPRITE_LIT),
@@ -1043,6 +1382,10 @@ export const BUILTIN_SHADER_TEMPLATES: readonly BuiltinShaderTemplate[] = [
MODEL),
template('water', 'Water',
'Waves, refraction, reflection, depth absorption and foam for a horizontal body of water.', WATER),
+ template('terrain', 'Terrain',
+ 'Four texture layers (grass, dirt, snow, rock) weighted by the Terrain component, tiled by world position.', TERRAIN),
+ template('foliage', 'Foliage',
+ 'Plants that sway in the wind: a vertex bend by painted weights, two-sided and translucent, with an optional cutout texture.', FOLIAGE),
];
export function builtinShaderTemplate(id: string): BuiltinShaderTemplate | undefined {
diff --git a/sdk/src/terrain/heightfield.ts b/sdk/src/terrain/heightfield.ts
new file mode 100644
index 000000000..0aa8972be
--- /dev/null
+++ b/sdk/src/terrain/heightfield.ts
@@ -0,0 +1,116 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file heightfield.ts
+ * @brief The ground as numbers: a grid of heights, read by a heightmap image or made by noise.
+ *
+ * @details Heights are stored as 0..1 and scaled by the terrain's own height, so the same field
+ * serves a terrain of any size and a rescale never touches the data. Everything here is
+ * pure and has no engine in it, which is what lets the mesh builder and the tests stand on it.
+ */
+
+/** A rectangular grid of heights, 0 to 1, row-major with z as the row. */
+export interface Heightfield {
+ readonly width: number;
+ readonly height: number;
+ readonly data: Float32Array;
+}
+
+/**
+ * A heightfield from an RGBA image: the red channel is the height. 8 bits is 256 steps, which on a tall terrain
+ * reads as terraces, so a green channel that is not all zero is taken as the low byte of a 16-bit height
+ * (red is the high one), the way an exported 16-bit map is usually packed into an 8-bit-per-channel PNG.
+ */
+export function heightfieldFromPixels(width: number, height: number, pixels: ArrayLike<number>): Heightfield {
+ const data = new Float32Array(width * height);
+ let wide = false;
+ for (let i = 0; i < width * height; i++) {
+ if (pixels[i * 4 + 1]! !== 0 && pixels[i * 4 + 1]! !== pixels[i * 4]!) { wide = true; break; }
+ }
+ for (let i = 0; i < width * height; i++) {
+ const hi = pixels[i * 4]!;
+ data[i] = wide ? (hi * 256 + pixels[i * 4 + 1]!) / 65535 : hi / 255;
+ }
+ return { width, height, data };
+}
+
+/** 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;
+}
+
+function valueNoise(x: number, y: number, seed: 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 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);
+ return (a + (b - a) * sx) + ((c + (d - c) * sx) - (a + (b - a) * sx)) * sy;
+}
+
+/** What {@link proceduralHeightfield} is made from. */
+export interface ProceduralParams {
+ /** Samples along each side. */
+ resolution: number;
+ seed: number;
+ /** How many times the biggest hill repeats across the terrain. */
+ frequency: number;
+ octaves: number;
+ /** What each octave keeps of the height of the one before it: lower is smoother. */
+ persistence: number;
+ /** 0 is rolling hills; 1 is sharp ridges, the way eroded mountains look. */
+ ridged: number;
+}
+
+/** Fractal noise as a heightfield, scaled to span 0 to 1 so the terrain's height is its true range. */
+export function proceduralHeightfield(p: ProceduralParams): Heightfield {
+ const n = Math.max(2, Math.floor(p.resolution));
+ const data = new Float32Array(n * n);
+ let min = Infinity, max = -Infinity;
+ for (let j = 0; j < n; j++) {
+ for (let i = 0; i < n; i++) {
+ let amplitude = 1, frequency = p.frequency, sum = 0, norm = 0;
+ for (let o = 0; o < Math.max(1, Math.min(8, Math.floor(p.octaves))); o++) {
+ let v = valueNoise(i / (n - 1) * frequency, j / (n - 1) * frequency, p.seed + o * 101);
+ v = v * (1 - p.ridged) + (1 - Math.abs(v * 2 - 1)) * p.ridged;
+ sum += v * amplitude;
+ norm += amplitude;
+ amplitude *= p.persistence;
+ frequency *= 2;
+ }
+ const v = sum / norm;
+ data[j * n + i] = v;
+ if (v < min) min = v;
+ if (v > max) max = v;
+ }
+ }
+ const span = max - min || 1;
+ for (let i = 0; i < data.length; i++) data[i] = (data[i]! - min) / span;
+ return { width: n, height: n, data };
+}
+
+/** The height at (u, v), each 0 to 1 across the field, bilinear between the four samples it falls among. */
+export function sampleHeight(field: Heightfield, u: number, v: number): number {
+ const x = Math.min(Math.max(u, 0), 1) * (field.width - 1);
+ const y = Math.min(Math.max(v, 0), 1) * (field.height - 1);
+ const x0 = Math.min(Math.floor(x), field.width - 2), y0 = Math.min(Math.floor(y), field.height - 2);
+ const fx = x - x0, fy = y - y0;
+ const at = (i: number, j: number): number => field.data[j * field.width + i]!;
+ const top = at(x0, y0) + (at(x0 + 1, y0) - at(x0, y0)) * fx;
+ const bottom = at(x0, y0 + 1) + (at(x0 + 1, y0 + 1) - at(x0, y0 + 1)) * fx;
+ return top + (bottom - top) * fy;
+}
+
+/** The unit normal of the ground at (u, v), from the heights a texel either side of it, in world units. */
+export function terrainNormal(
+ field: Heightfield, u: number, v: number, sizeX: number, sizeZ: number, heightScale: number,
+): [number, number, number] {
+ const du = 1 / (field.width - 1), dv = 1 / (field.height - 1);
+ const dx = (sampleHeight(field, u + du, v) - sampleHeight(field, u - du, v)) * heightScale / (2 * du * sizeX);
+ const dz = (sampleHeight(field, u, v + dv) - sampleHeight(field, u, v - dv)) * heightScale / (2 * dv * sizeZ);
+ const len = Math.hypot(dx, 1, dz);
+ return [-dx / len, 1 / len, -dz / len];
+}
diff --git a/sdk/src/terrain/mesh.ts b/sdk/src/terrain/mesh.ts
new file mode 100644
index 000000000..61d35b57d
--- /dev/null
+++ b/sdk/src/terrain/mesh.ts
@@ -0,0 +1,151 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file mesh.ts
+ * @brief One square of the ground, as geometry, at as many levels of detail as it is wanted at.
+ *
+ * @details The terrain is cut into chunks and each chunk is built several times over, a grid a half
+ * as fine at every level. The engine's own level-of-detail picks among them by how large
+ * the chunk is on screen, so a hill in the distance costs a few hundred triangles and one
+ * underfoot a couple of thousand.
+ *
+ * Two neighbours at different levels have different numbers of vertices along the edge they
+ * share, so their surfaces part there — a crack the sky shows through. The cure is a skirt:
+ * a wall let down from each edge of the chunk, deep enough to hide the gap. It is cheap, it
+ * needs no knowledge of the neighbour (a chunk is built alone, and may change level without
+ * rebuilding anyone else), and it costs a ring of triangles that is never seen from above.
+ *
+ * Heights and normals are read from the one field at every level, so a chunk keeps its
+ * lighting as it coarsens; only its silhouette changes.
+ */
+import { MeshChannel, MeshChannelType, packChannels, type MeshData } from '../asset/meshFormat';
+import { sampleHeight, terrainNormal, type Heightfield } from './heightfield';
+
+/** The size and cut of a terrain. */
+export interface TerrainShape {
+ /** World extent along x and z. The terrain is centred on its entity. */
+ sizeX: number;
+ sizeZ: number;
+ /** World height of a field value of 1. */
+ height: number;
+ /** Chunks along each side. */
+ chunks: number;
+ /** Cells along a chunk's side at the finest level (a power of two reads best). */
+ chunkCells: number;
+}
+
+/** What a vertex is painted: the weights of four layers, or the colour of a terrain that has no material. */
+export type TerrainPaint = (
+ u: number, v: number, height01: number, slope: number,
+) => [number, number, number, number];
+
+/** How many cells a chunk has a side at `lod`: half as many at each, never fewer than two. */
+export function cellsAtLod(shape: TerrainShape, lod: number): number {
+ return Math.max(2, shape.chunkCells >> lod);
+}
+
+/** How many levels of detail a chunk is worth having, from the finest down to one that is still two cells across. */
+export function lodCount(shape: TerrainShape, wanted = 4): number {
+ let levels = 1;
+ while (levels < wanted && cellsAtLod(shape, levels) < cellsAtLod(shape, levels - 1)) levels++;
+ return levels;
+}
+
+/** The centre of chunk (cx, cz) in the terrain's own space, which is centred on its origin. */
+export function chunkCenter(shape: TerrainShape, cx: number, cz: number): [number, number] {
+ const w = shape.sizeX / shape.chunks, d = shape.sizeZ / shape.chunks;
+ return [-shape.sizeX / 2 + (cx + 0.5) * w, -shape.sizeZ / 2 + (cz + 0.5) * d];
+}
+
+/**
+ * Chunk (cx, cz) at level `lod`. Positions are relative to {@link chunkCenter}, so the entity that draws it is
+ * placed there and the mesh itself stays small and centred (which is what culling and sorting measure).
+ */
+export function buildChunkMesh(
+ field: Heightfield, shape: TerrainShape, cx: number, cz: number, lod: number, paint: TerrainPaint,
+): MeshData {
+ const cells = cellsAtLod(shape, lod);
+ const w = shape.sizeX / shape.chunks, d = shape.sizeZ / shape.chunks;
+ const stepX = w / cells, stepZ = d / cells;
+ const skirt = Math.max(stepX, stepZ) * 1.5 + shape.height * 0.02;
+ const row = cells + 1;
+
+ const positions: number[] = [];
+ const uvs: number[] = [];
+ const normals: number[] = [];
+ const colors: number[] = [];
+ const indices: number[] = [];
+
+ const addVertex = (i: number, j: number, drop: number): number => {
+ // The vertex's place in the whole terrain, 0 to 1.
+ const u = (cx * cells + i) / (shape.chunks * cells);
+ const v = (cz * cells + j) / (shape.chunks * cells);
+ const h = sampleHeight(field, u, v);
+ const n = terrainNormal(field, u, v, shape.sizeX, shape.sizeZ, shape.height);
+ positions.push(-w / 2 + i * stepX, h * shape.height - drop, -d / 2 + j * stepZ);
+ uvs.push(u, v);
+ normals.push(n[0], n[1], n[2]);
+ const c = paint(u, v, h, n[1]);
+ colors.push(c[0], c[1], c[2], c[3]);
+ return positions.length / 3 - 1;
+ };
+
+ for (let j = 0; j <= cells; j++) for (let i = 0; i <= cells; i++) addVertex(i, j, 0);
+ const at = (i: number, j: number): number => j * row + i;
+ for (let j = 0; j < cells; j++) {
+ for (let i = 0; i < cells; i++) {
+ // Up is the way the face looks: a, then the next row, then the next column, runs counter-clockwise from above.
+ indices.push(at(i, j), at(i, j + 1), at(i + 1, j));
+ indices.push(at(i + 1, j), at(i, j + 1), at(i + 1, j + 1));
+ }
+ }
+
+ // The skirt: a second row of vertices under each edge one, wound to face outward.
+ const wall = (edge: number[], flip: boolean): void => {
+ const below = edge.map((v) => {
+ const i = v % row, j = Math.floor(v / row);
+ return addVertex(i, j, skirt);
+ });
+ for (let k = 0; k < edge.length - 1; k++) {
+ const a = edge[k]!, b = edge[k + 1]!, c = below[k]!, e = below[k + 1]!;
+ if (flip) { indices.push(a, c, b); indices.push(b, c, e); }
+ else { indices.push(a, b, c); indices.push(b, e, c); }
+ }
+ };
+ const north: number[] = [], south: number[] = [], west: number[] = [], east: number[] = [];
+ for (let i = 0; i <= cells; i++) { north.push(at(i, 0)); south.push(at(i, cells)); }
+ for (let j = 0; j <= cells; j++) { west.push(at(0, j)); east.push(at(cells, j)); }
+ wall(north, false);
+ wall(south, true);
+ wall(west, true);
+ wall(east, false);
+
+ 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 vertexCount = positions.length / 3;
+ const vertices = new Uint8Array(vertexCount * vertexStride);
+ const view = new DataView(vertices.buffer);
+ const posAt = channels[0]!.offset, uvAt = channels[1]!.offset, colorAt = channels[2]!.offset, normalAt = channels[3]!.offset;
+ const min: [number, number, number] = [Infinity, Infinity, Infinity];
+ const max: [number, number, number] = [-Infinity, -Infinity, -Infinity];
+ for (let i = 0; i < vertexCount; i++) {
+ const base = i * vertexStride;
+ for (let k = 0; k < 3; k++) {
+ const value = positions[i * 3 + k]!;
+ view.setFloat32(base + posAt + k * 4, value, true);
+ view.setFloat32(base + normalAt + k * 4, normals[i * 3 + k]!, true);
+ if (value < min[k]!) min[k] = value;
+ if (value > max[k]!) max[k] = value;
+ }
+ view.setFloat32(base + uvAt, uvs[i * 2]!, true);
+ view.setFloat32(base + uvAt + 4, uvs[i * 2 + 1]!, true);
+ for (let k = 0; k < 4; k++) {
+ view.setUint8(base + colorAt + k, Math.round(Math.min(Math.max(colors[i * 4 + k]!, 0), 1) * 255));
+ }
+ }
+ return { channels, vertexStride, vertexCount, vertices, indices: new Uint32Array(indices), aabbMin: min, aabbMax: max };
+}
diff --git a/sdk/src/terrain/terrainPlugin.ts b/sdk/src/terrain/terrainPlugin.ts
new file mode 100644
index 000000000..ee7816c38
--- /dev/null
+++ b/sdk/src/terrain/terrainPlugin.ts
@@ -0,0 +1,388 @@
+// SPDX-License-Identifier: Apache-2.0
+// 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.
+ *
+ * @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.
+ */
+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,
+} from '../ecs/component';
+import { Assets } from '../asset/AssetPlugin';
+import { platformLoadImagePixels } from '../platform/base';
+import { decodeImagePixels } from '../asset/imageDecode';
+import { log } from '../util/logger';
+import type { Color, Entity } from '../types';
+import {
+ heightfieldFromPixels, proceduralHeightfield, sampleHeight, terrainNormal, type Heightfield,
+} from './heightfield';
+import { buildChunkMesh, chunkCenter, lodCount, type TerrainPaint, type TerrainShape } from './mesh';
+
+/** The fields of the `Terrain` component. @experimental */
+export interface TerrainData {
+ /** 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. */
+ material: number;
+ /** World size along x and z; the terrain is centred on its entity. */
+ 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. */
+ detail: number;
+ /** Noise ground: the seed, how many hills across, how many octaves, how rough, how ridged, and how many samples. */
+ seed: number;
+ frequency: number;
+ octaves: number;
+ persistence: number;
+ ridged: number;
+ resolution: 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;
+ dirtHeight: number;
+ snowHeight: number;
+ /** The four layers: grass, dirt, snow, rock. With no material these are the colours the ground is drawn in; a material has its own layers and tints. */
+ layerColor0: Color;
+ layerColor1: Color;
+ layerColor2: Color;
+ layerColor3: Color;
+}
+
+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.
+ *
+ * @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,
+ seed: 1, frequency: 3, octaves: 5, persistence: 0.5, ridged: 0.35, resolution: 257,
+ 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' },
+ 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.' },
+ 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.' },
+ 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.' },
+ 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.' },
+ 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.' },
+ layerColor0: { label: 'Grass', category: 'Layers' },
+ layerColor1: { label: 'Dirt', category: 'Layers' },
+ layerColor2: { label: 'Snow', category: 'Layers' },
+ layerColor3: { label: 'Rock', category: 'Layers' },
+ },
+});
+
+const 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);
+};
+
+/** The weights of grass, dirt, snow and rock at a point of ground, by how high 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);
+ const dirt = smooth(t.dirtHeight - 0.15, t.dirtHeight + 0.15, h) * (1 - snow) * (1 - rock);
+ const grass = (1 - rock) * (1 - snow) * (1 - dirt);
+ const sum = grass + dirt + snow + rock || 1;
+ return [grass / sum, dirt / sum, snow / sum, rock / sum];
+}
+
+/** 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;
+ materialHandle: number;
+ /** Bumped on every rebuild so an answer that arrives for an older one is thrown away. */
+ epoch: number;
+ loading: boolean;
+}
+
+/** Chunks built per frame: enough that a terrain appears quickly, few enough that no frame is a stall. */
+const CHUNKS_PER_FRAME = 4;
+
+/** 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.
+ */
+ 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;
+ 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;
+ }
+ return null;
+ }
+
+ /** Where the ground faces at (x, z) (a unit normal), or null where no terrain is. */
+ normalAt(x: number, z: number): [number, 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;
+ 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);
+ }
+ return null;
+ }
+
+ /** @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. */
+ 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. */
+ get pending(): number {
+ let n = 0;
+ for (const b of this.built_.values()) n += b.queue.length + (b.loading ? 1 : 0);
+ return n;
+ }
+}
+
+/** The resource the plugin installs. @experimental */
+export const TerrainsRes = defineResource<Terrains>(new Terrains(), 'Terrains');
+
+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))),
+ };
+}
+
+export class TerrainPlugin implements Plugin {
+ name = 'terrain';
+
+ build(app: App): void {
+ const terrains = new Terrains();
+ terrains.app_ = app;
+ app.insertResource(TerrainsRes, terrains);
+
+ app.addSystemToSchedule(Schedule.Update, defineSystem([], () => {
+ if (!app.hasResource(Assets)) return;
+ this.sweep(app, terrains);
+ for (const entity of app.world.getEntitiesWithComponents([Terrain, Transform])) {
+ const data = app.world.get(entity, Terrain) as TerrainData;
+ const signature = signatureOf(data);
+ let built = terrains.built_.get(entity);
+ if (!built || built.signature !== signature) {
+ if (built) this.destroy(app, built);
+ built = {
+ signature, field: null, data: { ...data }, handles: [], chunks: [], queue: [], splat: null,
+ materialHandle: data.material, epoch: (built?.epoch ?? 0) + 1, loading: true,
+ };
+ terrains.built_.set(entity, built);
+ void this.load(app, entity, built);
+ continue;
+ }
+ if (built.loading) continue;
+ for (let i = 0; i < CHUNKS_PER_FRAME && built.queue.length > 0; i++) {
+ const [cx, cz] = built.queue.shift()!;
+ this.buildChunk(app, entity, built, cx, cz);
+ }
+ }
+ }, { name: 'TerrainSystem' }));
+ }
+
+ cleanup(app?: App): void {
+ if (!app?.hasResource(TerrainsRes)) return;
+ const terrains = app.getResource(TerrainsRes);
+ for (const built of terrains.built_.values()) this.destroy(app, built);
+ terrains.built_.clear();
+ }
+
+ /** Reads the images the terrain names (or makes the noise), then queues its chunks. */
+ 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.
+ if (typeof createImageBitmap === 'function' && typeof Blob !== 'undefined') {
+ return await decodeImagePixels(new Blob([await assets.fetchBinary(path)]));
+ }
+ 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;
+ built.field = 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,
+ });
+ 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]);
+ } catch (e) {
+ log.error('terrain', 'building the terrain failed', e);
+ } finally {
+ if (built.epoch === epoch) built.loading = false;
+ }
+ }
+
+ private paintFor(built: Built): TerrainPaint {
+ const data = built.data;
+ const colors = [data.layerColor0, data.layerColor1, data.layerColor2, data.layerColor3];
+ const splat = built.splat;
+ 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];
+ }
+ // 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,
+ ];
+ };
+ }
+
+ 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);
+ return;
+ }
+ handles.push(handle);
+ }
+ 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,
+ });
+ }
+ world.setParent(chunk, parent);
+ built.chunks.push(chunk);
+ }
+
+ private destroy(app: App, built: Built): void {
+ built.epoch++;
+ built.queue.length = 0;
+ 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;
+ }
+
+ /** Releases the chunks 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;
+ this.destroy(app, built);
+ terrains.built_.delete(entity);
+ terrains.revision_++;
+ }
+ }
+}
+
+export const terrainPlugin: Plugin = new TerrainPlugin();
diff --git a/sdk/tests/foliage-builder.test.ts b/sdk/tests/foliage-builder.test.ts
new file mode 100644
index 000000000..375d534ba
--- /dev/null
+++ b/sdk/tests/foliage-builder.test.ts
@@ -0,0 +1,135 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { describe, it, expect } from 'vitest';
+import { MeshChannel } from '../src/asset/meshFormat';
+import { buildBillboardMesh, buildGrassMesh, buildInstancedMesh, rng, scatterCell, type Ground, type Plant } from '../src/foliage/builder';
+
+const flat: Ground = () => ({ y: 2, up: 1 });
+const params = {
+ centerX: 100, centerZ: -40, size: 20, count: 50, seed: 3, cellKey: 7,
+ minScale: 0.8, maxScale: 1.2, minUp: 0.7, heightMin: -1e5, heightMax: 1e5,
+};
+
+function colorOf(mesh: ReturnType<typeof buildGrassMesh>, v: number): number[] {
+ const c = mesh.channels.find((x) => x.semantic === MeshChannel.Color)!;
+ return [...mesh.vertices.slice(v * mesh.vertexStride + c.offset, v * mesh.vertexStride + c.offset + 4)];
+}
+function positionOf(mesh: ReturnType<typeof buildGrassMesh>, v: number): number[] {
+ const c = mesh.channels.find((x) => x.semantic === MeshChannel.Position)!;
+ const view = new DataView(mesh.vertices.buffer);
+ const at = v * mesh.vertexStride + c.offset;
+ return [view.getFloat32(at, true), view.getFloat32(at + 4, true), view.getFloat32(at + 8, true)];
+}
+
+describe('scattering', () => {
+ it('is the same on every run and different for another seed or cell', () => {
+ const a = scatterCell(params, flat), b = scatterCell(params, flat);
+ expect(a).toEqual(b);
+ expect(scatterCell({ ...params, seed: 4 }, flat)).not.toEqual(a);
+ expect(scatterCell({ ...params, cellKey: 8 }, flat)).not.toEqual(a);
+ const r = rng(5);
+ expect(r()).not.toBe(r());
+ });
+
+ it('keeps every plant inside its cell, relative to its centre, at the ground\'s height', () => {
+ for (const p of scatterCell(params, flat)) {
+ expect(Math.abs(p.x)).toBeLessThanOrEqual(10);
+ expect(Math.abs(p.z)).toBeLessThanOrEqual(10);
+ expect(p.y).toBe(2);
+ expect(p.scale).toBeGreaterThanOrEqual(0.8);
+ expect(p.scale).toBeLessThanOrEqual(1.2);
+ }
+ });
+
+ it('leaves out steep ground, ground outside the height band and places with no ground', () => {
+ expect(scatterCell(params, () => ({ y: 0, up: 0.3 }))).toHaveLength(0);
+ expect(scatterCell({ ...params, heightMax: 1 }, flat)).toHaveLength(0);
+ expect(scatterCell(params, () => null)).toHaveLength(0);
+ const half = scatterCell(params, (x) => (x > 100 ? { y: 0, up: 1 } : null));
+ expect(half.length).toBeGreaterThan(0);
+ expect(half.length).toBeLessThan(50);
+ });
+});
+
+describe('grass', () => {
+ const plants: Plant[] = [
+ { x: 0, y: 0, z: 0, yaw: 0, scale: 1, phase: 0.5, shade: 1 },
+ { x: 5, y: 0, z: 5, yaw: 1, scale: 1, phase: 0.25, shade: 0.8 },
+ { x: -5, y: 0, z: 5, yaw: 2, scale: 1, phase: 0.75, shade: 0.9 },
+ ];
+
+ it('has 2s+1 vertices and 2s-1 triangles a blade', () => {
+ const mesh = buildGrassMesh(plants, { height: 10, width: 2, segments: 3, thin: 1 });
+ expect(mesh.vertexCount).toBe(3 * 7);
+ expect(mesh.indices.length / 3).toBe(3 * 5);
+ });
+
+ it('draws every n-th blade, broader, so the far version costs a share of the near one', () => {
+ const near = buildGrassMesh(plants, { height: 10, width: 2, segments: 3, thin: 1 });
+ const far = buildGrassMesh(plants, { height: 10, width: 2, segments: 1, thin: 3 });
+ expect(far.indices.length).toBeLessThan(near.indices.length / 4);
+ const wide = (m: typeof near): number => positionOf(m, 1)[0]! - positionOf(m, 0)[0]!;
+ expect(Math.abs(wide(far))).toBeGreaterThan(Math.abs(wide(near)));
+ });
+
+ it('paints the wind\'s weights: red from the root up, green the plant\'s phase', () => {
+ const mesh = buildGrassMesh(plants, { height: 10, width: 2, segments: 3, thin: 1 });
+ const root = colorOf(mesh, 0), tip = colorOf(mesh, 6);
+ expect(root[0]).toBe(0);
+ expect(tip[0]).toBe(255);
+ expect(root[1]).toBe(Math.round(0.5 * 255));
+ expect(root[2]!).toBeLessThan(tip[2]!);
+ expect(positionOf(mesh, 6)[1]).toBeCloseTo(10, 4);
+ });
+
+ it('paints a colour instead when it has no material to read the weights', () => {
+ const mesh = buildGrassMesh(plants, { height: 10, width: 2, segments: 3, thin: 1, paint: { base: [0, 0.2, 0], tip: [0.5, 1, 0] } });
+ const tip = colorOf(mesh, 6);
+ expect(tip[1]).toBeGreaterThan(tip[2]!);
+ });
+});
+
+describe('instanced meshes and billboards', () => {
+ const quad = buildGrassMesh([{ x: 0, y: 0, z: 0, yaw: 0, scale: 1, phase: 0, shade: 1 }], { height: 10, width: 2, segments: 1, thin: 1 });
+
+ it('copies a mesh once a plant, placed and scaled, with its weights painted by height on its own copy', () => {
+ const plants: Plant[] = [
+ { x: 10, y: 1, z: 0, yaw: 0, scale: 2, phase: 0.3, shade: 1 },
+ { x: -10, y: 0, z: 0, yaw: Math.PI / 2, scale: 1, phase: 0.6, shade: 1 },
+ ];
+ const mesh = buildInstancedMesh(quad, plants);
+ expect(mesh.vertexCount).toBe(quad.vertexCount * 2);
+ expect(mesh.indices.length).toBe(quad.indices.length * 2);
+ // The tip of the first copy is twice as tall, a metre up, ten along.
+ const tip = positionOf(mesh, 2);
+ expect(tip[1]).toBeCloseTo(1 + 20, 3);
+ expect(colorOf(mesh, 0)[0]).toBe(0);
+ expect(colorOf(mesh, 2)[0]).toBe(255);
+ });
+
+ it('makes two crossed cards a plant showing the rectangle it is given', () => {
+ const mesh = buildBillboardMesh([{ x: 0, y: 0, z: 0, yaw: 0, scale: 1, phase: 0, shade: 1 }], 4, 8, { u0: 0.25, v0: 0, u1: 0.75, v1: 0.5 });
+ expect(mesh.vertexCount).toBe(8);
+ expect(mesh.indices.length / 3).toBe(4);
+ expect(mesh.aabbMax[1]).toBeCloseTo(8, 4);
+ const uv = mesh.channels.find((c) => c.semantic === MeshChannel.TexCoord0)!;
+ const view = new DataView(mesh.vertices.buffer);
+ expect(view.getFloat32(uv.offset, true)).toBeCloseTo(0.25, 5);
+ expect(view.getFloat32(2 * mesh.vertexStride + uv.offset + 4, true)).toBeCloseTo(0.5, 5);
+ });
+
+ it('draws a tent, one triangle a card, when asked', () => {
+ const plant: Plant = { x: 0, y: 0, z: 0, yaw: 0, scale: 1, phase: 0, shade: 1 };
+ const tent = buildBillboardMesh([plant], 4, 8, { u0: 0, v0: 0, u1: 1, v1: 1 }, null, true);
+ expect(tent.vertexCount).toBe(6);
+ expect(tent.indices.length / 3).toBe(2);
+ expect(tent.aabbMax[1]).toBeCloseTo(8, 4);
+ expect(tent.aabbMin[1]).toBeCloseTo(0.8, 4);
+ });
+
+ it('is an empty mesh, not a crash, for a cell with no plants', () => {
+ const mesh = buildGrassMesh([], { height: 10, width: 2, segments: 3, thin: 1 });
+ expect(mesh.vertexCount).toBe(0);
+ expect(mesh.indices.length).toBe(0);
+ });
+});
diff --git a/sdk/tests/shader-twins.test.ts b/sdk/tests/shader-twins.test.ts
index 40075f5c0..d296a2b01 100644
--- a/sdk/tests/shader-twins.test.ts
+++ b/sdk/tests/shader-twins.test.ts
@@ -28,7 +28,7 @@ function sectionsBalance(source: string): boolean {
let open = 0;
for (const line of source.split('\n')) {
const t = line.trim();
- if (/^#pragma (vertex|fragment|properties|variant)\b/.test(t)) {
+ if (/^#pragma (vertex|vertexoffset|fragment|properties|variant)\b/.test(t)) {
if (open !== 0) return false;
open = 1;
} else if (t === '#pragma end') {
diff --git a/sdk/tests/terrain-mesh.test.ts b/sdk/tests/terrain-mesh.test.ts
new file mode 100644
index 000000000..90b4980a5
--- /dev/null
+++ b/sdk/tests/terrain-mesh.test.ts
@@ -0,0 +1,134 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { describe, it, expect } from 'vitest';
+import { MeshChannel } from '../src/asset/meshFormat';
+import { heightfieldFromPixels, proceduralHeightfield, sampleHeight, terrainNormal } from '../src/terrain/heightfield';
+import { buildChunkMesh, cellsAtLod, chunkCenter, lodCount, type TerrainShape } from '../src/terrain/mesh';
+
+const SHAPE: TerrainShape = { sizeX: 800, sizeZ: 400, height: 100, chunks: 4, chunkCells: 16 };
+const paint = (): [number, number, number, number] => [1, 0, 0, 1];
+
+function positionsOf(mesh: ReturnType<typeof buildChunkMesh>): number[][] {
+ const pos = mesh.channels.find((c) => c.semantic === MeshChannel.Position)!;
+ const view = new DataView(mesh.vertices.buffer);
+ const out: number[][] = [];
+ for (let i = 0; i < mesh.vertexCount; i++) {
+ const at = i * mesh.vertexStride + pos.offset;
+ out.push([view.getFloat32(at, true), view.getFloat32(at + 4, true), view.getFloat32(at + 8, true)]);
+ }
+ return out;
+}
+
+describe('heightfield', () => {
+ it('reads a red channel as the height, and a green one as the low byte of a 16-bit height', () => {
+ const flat = heightfieldFromPixels(2, 2, [0, 0, 0, 255, 255, 255, 255, 255, 128, 0, 0, 255, 0, 0, 0, 255]);
+ expect(flat.data[0]).toBe(0);
+ expect(flat.data[1]).toBe(1);
+ expect(flat.data[2]).toBeCloseTo(128 / 255, 5);
+ const wide = heightfieldFromPixels(2, 1, [1, 0, 0, 255, 1, 7, 0, 255]);
+ expect(wide.data[1]!).toBeGreaterThan(wide.data[0]!);
+ expect(wide.data[1]).toBeCloseTo(263 / 65535, 6);
+ });
+
+ it('makes the same ground from the same seed, different ground from another, spanning 0 to 1', () => {
+ const params = { resolution: 33, seed: 7, frequency: 3, octaves: 4, persistence: 0.5, ridged: 0 };
+ const a = proceduralHeightfield(params), b = proceduralHeightfield(params), c = proceduralHeightfield({ ...params, seed: 8 });
+ expect([...a.data]).toEqual([...b.data]);
+ expect([...a.data]).not.toEqual([...c.data]);
+ expect(Math.min(...a.data)).toBeCloseTo(0, 6);
+ expect(Math.max(...a.data)).toBeCloseTo(1, 6);
+ });
+
+ it('is bilinear between samples and clamps outside the field', () => {
+ const f = heightfieldFromPixels(2, 2, [0, 0, 0, 255, 255, 0, 0, 255, 0, 0, 0, 255, 255, 0, 0, 255]);
+ expect(sampleHeight(f, 0.5, 0.5)).toBeCloseTo(0.5, 5);
+ expect(sampleHeight(f, -3, 0)).toBe(0);
+ expect(sampleHeight(f, 4, 0)).toBe(1);
+ });
+
+ it('has an upward normal on level ground and one that leans away from a rise', () => {
+ const level = heightfieldFromPixels(4, 4, new Array(64).fill(0));
+ const n0 = terrainNormal(level, 0.5, 0.5, 100, 100, 50);
+ expect(n0[0]).toBeCloseTo(0, 6);
+ expect(n0[1]).toBeCloseTo(1, 6);
+ // Heights climb with x: the ground faces back toward -x and up.
+ const ramp = heightfieldFromPixels(4, 4, new Array(16).fill(0).flatMap((_, i) => [(i % 4) * 85, 0, 0, 255]));
+ const n = terrainNormal(ramp, 0.5, 0.5, 100, 100, 50);
+ expect(n[0]).toBeLessThan(-0.1);
+ expect(n[1]).toBeGreaterThan(0);
+ expect(Math.hypot(...n)).toBeCloseTo(1, 5);
+ });
+});
+
+describe('terrain chunk mesh', () => {
+ const field = proceduralHeightfield({ resolution: 65, seed: 3, frequency: 4, octaves: 4, persistence: 0.5, ridged: 0.3 });
+
+ it('halves its grid at each level and keeps at least two cells', () => {
+ expect([0, 1, 2, 3].map((l) => cellsAtLod(SHAPE, l))).toEqual([16, 8, 4, 2]);
+ expect(lodCount(SHAPE, 4)).toBe(4);
+ expect(lodCount({ ...SHAPE, chunkCells: 2 }, 4)).toBe(1);
+ });
+
+ it('has a surface of cells x cells x 2 triangles and a skirt of 8 x cells more', () => {
+ for (const lod of [0, 1, 2, 3]) {
+ const cells = cellsAtLod(SHAPE, lod);
+ const mesh = buildChunkMesh(field, SHAPE, 1, 2, lod, paint);
+ expect(mesh.indices.length / 3).toBe(cells * cells * 2 + cells * 8);
+ expect(mesh.vertexCount).toBe((cells + 1) ** 2 + 4 * (cells + 1));
+ for (const i of mesh.indices) expect(i).toBeLessThan(mesh.vertexCount);
+ }
+ });
+
+ it('is centred on its own origin and spans one chunk', () => {
+ const mesh = buildChunkMesh(field, SHAPE, 0, 0, 0, paint);
+ expect(mesh.aabbMin[0]).toBeCloseTo(-100, 4);
+ expect(mesh.aabbMax[0]).toBeCloseTo(100, 4);
+ expect(mesh.aabbMin[2]).toBeCloseTo(-50, 4);
+ expect(mesh.aabbMax[2]).toBeCloseTo(50, 4);
+ expect(chunkCenter(SHAPE, 0, 0)).toEqual([-300, -150]);
+ expect(chunkCenter(SHAPE, 3, 3)).toEqual([300, 150]);
+ });
+
+ it('faces its surface triangles up', () => {
+ const mesh = buildChunkMesh(field, SHAPE, 2, 1, 0, paint);
+ const p = positionsOf(mesh);
+ const cells = cellsAtLod(SHAPE, 0);
+ let up = 0;
+ for (let t = 0; t < cells * cells * 2; t++) {
+ const [a, b, c] = [mesh.indices[t * 3]!, mesh.indices[t * 3 + 1]!, mesh.indices[t * 3 + 2]!];
+ const u = [p[b]![0]! - p[a]![0]!, p[b]![1]! - p[a]![1]!, p[b]![2]! - p[a]![2]!];
+ const v = [p[c]![0]! - p[a]![0]!, p[c]![1]! - p[a]![1]!, p[c]![2]! - p[a]![2]!];
+ if (u[2]! * v[0]! - u[0]! * v[2]! < 0) up++;
+ }
+ expect(up).toBe(0);
+ });
+
+ it('lets a skirt down below every edge so a coarser neighbour cannot show a crack', () => {
+ const mesh = buildChunkMesh(field, SHAPE, 1, 1, 1, paint);
+ const p = positionsOf(mesh);
+ const cells = cellsAtLod(SHAPE, 1);
+ const surface = (cells + 1) ** 2;
+ for (let k = 0; k < 4 * (cells + 1); k++) {
+ const drop = p[surface + k]!;
+ const edge = p.slice(0, surface).find((q) => q[0] === drop[0] && q[2] === drop[2]);
+ expect(edge).toBeDefined();
+ expect(edge![1]! - drop[1]!).toBeGreaterThan(0);
+ }
+ });
+
+ it('agrees with its neighbour on the height of the corners they share, at every level', () => {
+ for (const lod of [0, 1, 2, 3]) {
+ const left = positionsOf(buildChunkMesh(field, SHAPE, 1, 1, lod, paint));
+ const right = positionsOf(buildChunkMesh(field, SHAPE, 2, 1, lod, paint));
+ const cells = cellsAtLod(SHAPE, lod);
+ const row = cells + 1;
+ for (let j = 0; j <= cells; j++) expect(left[j * row + cells]![1]).toBeCloseTo(right[j * row]![1]!, 4);
+ }
+ });
+
+ it('carries the paint in the vertex colour', () => {
+ const mesh = buildChunkMesh(field, SHAPE, 0, 0, 3, () => [0, 0.5, 1, 1]);
+ const color = mesh.channels.find((c) => c.semantic === MeshChannel.Color)!;
+ expect([...mesh.vertices.slice(color.offset, color.offset + 4)]).toEqual([0, 128, 255, 255]);
+ });
+});
diff --git a/src/esengine/aot/EngineDigest.generated.h b/src/esengine/aot/EngineDigest.generated.h
index e5a2b9840..d650d0992 100644
--- a/src/esengine/aot/EngineDigest.generated.h
+++ b/src/esengine/aot/EngineDigest.generated.h
@@ -6,7 +6,7 @@
/* One per address width, because the width is IN the digest: a host that
took the other one would refuse every module built for it. */
-#define ES_ENGINE_ABI_DIGEST_32 0x79c6158c29eb57abULL
-#define ES_ENGINE_ABI_DIGEST_64 0x5b7515b290a65867ULL
+#define ES_ENGINE_ABI_DIGEST_32 0x2442b4c2fa79d124ULL
+#define ES_ENGINE_ABI_DIGEST_64 0x83e8a5bdeea599a8ULL
#define ES_ENGINE_ABI_DIGEST \
(sizeof(es_addr_t) == 8 ? ES_ENGINE_ABI_DIGEST_64 : ES_ENGINE_ABI_DIGEST_32)
diff --git a/src/esengine/data/shaders/mesh.esshader b/src/esengine/data/shaders/mesh.esshader
index 7aa97013f..ac54f04ab 100644
--- a/src/esengine/data/shaders/mesh.esshader
+++ b/src/esengine/data/shaders/mesh.esshader
@@ -150,6 +150,8 @@ out highp vec4 v_velPrev;
// caster has to bend where the lit surface does, or its shadow stands still. The assembler puts the
// material's hook where the marker is; without ES_MATERIAL_VERTEX none of it exists.
#ifdef ES_MATERIAL_VERTEX
+// The vertex's own colour, for a hook that bends by a weight painted in it (see ShaderParser's canonical stage).
+highp vec4 es_vertexColor;
@@ES_VERTEX_HOOK@@
#endif
@@ -174,6 +176,7 @@ void main() {
#endif
applyMorph(local, localNormal);
#ifdef ES_MATERIAL_VERTEX
+ es_vertexColor = a_color;
esMaterialVertex(local, localNormal, a_texCoord);
#endif
#ifdef SKINNED
@@ -394,6 +397,7 @@ struct VSOut {
};
#ifdef ES_MATERIAL_VERTEX
+var<private> es_vertexColor : vec4f;
@@ES_VERTEX_HOOK@@
#endif
@@ -431,6 +435,7 @@ fn esPrevBone(joint : u32) -> mat4x4f {
}
}
#ifdef ES_MATERIAL_VERTEX
+ es_vertexColor = v.a_color;
esMaterialVertex(&local, &localNormal, v.a_texCoord);
#endif
#ifdef SKINNED
diff --git a/src/esengine/renderer/frame/RenderFrame.cpp b/src/esengine/renderer/frame/RenderFrame.cpp
index cddd838c7..65b17eb7c 100644
--- a/src/esengine/renderer/frame/RenderFrame.cpp
+++ b/src/esengine/renderer/frame/RenderFrame.cpp
@@ -2382,7 +2382,6 @@ void RenderFrame::collectMotion(ecs::Registry& registry) {
if (plugin->drawsMotion()) plugin->collect(collectCtx);
}
velocity_list_.finalize(velocity_pool_);
- velocity_pool_.upload();
#else
(void)registry;
#endif
@@ -2421,7 +2420,6 @@ void RenderFrame::collectCover(ecs::Registry& registry) {
if (plugin->castsShadows()) plugin->collect(collectCtx);
}
cover_list_.finalize(cover_pool_);
- cover_pool_.upload();
#else
(void)registry;
#endif
@@ -2430,6 +2428,8 @@ void RenderFrame::collectCover(ecs::Registry& registry) {
void RenderFrame::executeCoverPass() {
if (cover_list_.commandCount() == 0) return;
ES_PROFILE_SCOPE("render.cover");
+ // Here, in the pass, and not while collecting: an upload during collect opens a pass that swallows the host draws that follow it.
+ cover_pool_.upload();
if (cover_frame_ubo_ == BufferHandle::Invalid) {
cover_frame_ubo_ = device_.createBuffer({GfxBufferUsage::Uniform, RenderContext::frameConstantsSize(), /*dynamic=*/true},
GfxContent::transient(), nullptr);
@@ -2449,6 +2449,7 @@ void RenderFrame::executeCoverPass() {
void RenderFrame::executeMotionPass() {
if (velocity_list_.commandCount() == 0) return;
ES_PROFILE_SCOPE("render.motion");
+ velocity_pool_.upload();
// Through the camera the scene was drawn with, jitter included: a surface's depth here has to be the
// scene's, since that is what the reader compares it with.
context_.updateCameraConstants(view_projection_, velocity_jitter_);
diff --git a/src/esengine/renderer/rhi/ShaderEmbeds.generated.hpp b/src/esengine/renderer/rhi/ShaderEmbeds.generated.hpp
index 1e78b6ac5..fbad7880e 100644
--- a/src/esengine/renderer/rhi/ShaderEmbeds.generated.hpp
+++ b/src/esengine/renderer/rhi/ShaderEmbeds.generated.hpp
@@ -625,6 +625,8 @@ out highp vec4 v_velPrev;
#ifdef ES_MATERIAL_VERTEX
+
+highp vec4 es_vertexColor;
@@ES_VERTEX_HOOK@@
#endif
@@ -649,6 +651,7 @@ void main() {
#endif
applyMorph(local, localNormal);
#ifdef ES_MATERIAL_VERTEX
+ es_vertexColor = a_color;
esMaterialVertex(local, localNormal, a_texCoord);
#endif
#ifdef SKINNED
@@ -869,6 +872,7 @@ struct VSOut {
};
#ifdef ES_MATERIAL_VERTEX
+var<private> es_vertexColor : vec4f;
@@ES_VERTEX_HOOK@@
#endif
@@ -906,6 +910,7 @@ fn esPrevBone(joint : u32) -> mat4x4f {
}
}
#ifdef ES_MATERIAL_VERTEX
+ es_vertexColor = v.a_color;
esMaterialVertex(&local, &localNormal, v.a_texCoord);
#endif
#ifdef SKINNED
diff --git a/src/esengine/resource/ShaderParser.cpp b/src/esengine/resource/ShaderParser.cpp
index ae2e9c24b..6920b3940 100644
--- a/src/esengine/resource/ShaderParser.cpp
+++ b/src/esengine/resource/ShaderParser.cpp
@@ -370,10 +370,12 @@ std::string canonicalVertexStageWGSL(bool lit, const std::string& hook = {}) {
src +=
" return out;\n"
"}\n";
+ // The vertex's own colour is the one per-vertex channel a hook has besides its position, normal and uv: wind sways a plant by
+ // a weight painted in it. A hook reads `es_vertexColor`; one that does not is not changed.
fillHook(src, "@@WGSL_HOOK@@", hook.empty() ? std::string() :
- "#ifdef MESH\n" + hook + "\n#endif\n");
+ "#ifdef MESH\nvar<private> es_vertexColor : vec4f;\n" + hook + "\n#endif\n");
fillHook(src, "@@WGSL_CALL@@", hook.empty() ? std::string() :
- " esMaterialVertex(&local, &localNormal, v.a_texCoord);\n");
+ " es_vertexColor = v.a_color;\n esMaterialVertex(&local, &localNormal, v.a_texCoord);\n");
return src;
}
@@ -576,9 +578,9 @@ std::string canonicalVertexStage(bool lit, const std::string& hook = {}) {
}
src += "}\n";
fillHook(src, "@@GLSL_HOOK@@", hook.empty() ? std::string() :
- "#ifdef MESH\n" + hook + "\n#endif\n");
+ "#ifdef MESH\nhighp vec4 es_vertexColor;\n" + hook + "\n#endif\n");
fillHook(src, "@@GLSL_CALL@@", hook.empty() ? std::string() :
- " esMaterialVertex(local, localNormal, a_texCoord);\n");
+ " es_vertexColor = a_color;\n esMaterialVertex(local, localNormal, a_texCoord);\n");
return src;
}
diff --git a/tests/aot/generated/move_system_decl.c b/tests/aot/generated/move_system_decl.c
index 51de4c640..905090f2d 100644
--- a/tests/aot/generated/move_system_decl.c
+++ b/tests/aot/generated/move_system_decl.c
@@ -10,7 +10,7 @@
answer, it is a read of a different field. The address width belongs
to the MACHINE, so it mixes in here rather than in the compiler and a
32-bit artifact cannot load into a 64-bit host. */
-#define ES_ABI_ENGINE_DIGEST 0x5b7515b290a65867ULL
+#define ES_ABI_ENGINE_DIGEST 0x83e8a5bdeea599a8ULL
ES_EXPORT const uint64_t es_abi_hash =
ES_ABI_ENGINE_DIGEST ^ (0x9e3779b97f4a7c15ULL * (uint64_t)sizeof(es_addr_t));
diff --git a/tests/aot/generated/move_system_hash.h b/tests/aot/generated/move_system_hash.h
index e50a725de..782506327 100644
--- a/tests/aot/generated/move_system_hash.h
+++ b/tests/aot/generated/move_system_hash.h
@@ -1,6 +1,6 @@
/* GENERATED by @estella/compiler — do not edit. */
/* The contract half of the handshake. The width half is the harness. */
-#define ES_EXPECTED_CONTRACT_HASH 0x5b7515b290a65867ULL
+#define ES_EXPECTED_CONTRACT_HASH 0x83e8a5bdeea599a8ULL
/* And which BUILD the artifact beside this one is, which the sidecar
written with it has to carry too. */
#define ES_EXPECTED_MODULE_CONTRACT 0x10bf77bb714ea1e3ULL
diff --git a/tools/apiSubsystems.mjs b/tools/apiSubsystems.mjs
index 96c7d6bdb..9caafe6a7 100644
--- a/tools/apiSubsystems.mjs
+++ b/tools/apiSubsystems.mjs
@@ -315,6 +315,16 @@ export const SUBSYSTEMS = [
whyZh: '导入链路已经端到端认证,但游戏用来驱动模型的运行时面(几何体、逐子网格材质、关节实体)还没有被拿来定级',
entry: ['MeshRenderer', 'MeshRendererAPI', 'MeshRenderers'],
},
+ {
+ id: 'terrain-foliage',
+ title: 'Terrain & foliage',
+ titleZh: '地形与植被',
+ source: ['terrain', 'foliage'],
+ tier: 'experimental',
+ why: 'the ground and the plants on it draw and are checked in the editor on both backends, but nothing collides with the ground yet and the authoring panels have not been read for a shape',
+ whyZh: '地面和上面的植物在编辑器里两个后端都能画出来并有检查,但还没有东西和地面碰撞,创作面板也还没有被拿来定下这套接口的形状',
+ entry: ['Terrain', 'Foliage'],
+ },
{
id: 'decal',
title: 'Decals',
diff --git a/tools/check-corpus-authoring.mjs b/tools/check-corpus-authoring.mjs
index 88e113044..d9888c01d 100644
--- a/tools/check-corpus-authoring.mjs
+++ b/tools/check-corpus-authoring.mjs
@@ -92,6 +92,9 @@ const NOT_INSTANCE_FORMATS = {
'.hdr': 'an environment map',
'.fnt': 'a bitmap font\'s metrics; the page beside it is a texture and what USES it is authored elsewhere',
'.gltf': 'an imported model',
+ '.glb': 'an imported model, binary',
+ '.txt': 'prose or a licence beside the project, not the project',
+ '.py': 'tooling beside the project, not the project',
'.bin': 'model or compressed-asset payload',
'.atlas': 'a Spine atlas, written by Spine',
'.skel': 'a Spine skeleton, written by Spine',
@@ -124,6 +127,8 @@ const DISPOSITION = {
// — owed: a creator-facing component nothing in the shipped corpus authors.
// Each reason names where the coverage belongs. —
+ Foliage: ['owed', 'no corpus scene has foliage yet: the cells are built by the plugin while the game runs, which a golden project has no frame to certify — the foliage-look editor check and tests/foliage-builder.test.ts hold it'],
+ Terrain: ['owed', 'no corpus scene has a terrain yet: the ground is built by the plugin while the game runs, which a golden project has no frame to certify — the terrain-look editor check and tests/terrain-mesh.test.ts hold it'],
StaticBatch: ['owed', 'no corpus scene marks a mesh yet: a marked mesh is merged while the game runs, which a golden project has no frame to certify — the static-batch-on / static-batch-off render scenes, tests/static-batch.test.ts and the static-batch editor check hold it'],
};
diff --git a/tools/check-gizmo-coverage.mjs b/tools/check-gizmo-coverage.mjs
index 8c0cd5269..cb6dc82c2 100644
--- a/tools/check-gizmo-coverage.mjs
+++ b/tools/check-gizmo-coverage.mjs
@@ -106,6 +106,20 @@ const DISPOSITION = {
// The component's own drawing is the picture; an outline round it would trace
// what is already on screen.
+ 'Terrain.sizeX': ['renders', 'the ground drawn at it is the outline'],
+ 'Terrain.sizeZ': ['renders', 'the ground drawn at it is the outline'],
+ 'Terrain.height': ['renders', 'the ground drawn at it is the outline'],
+ 'Terrain.dirtHeight': ['not-world', 'a share of the height of the terrain, 0 to 1'],
+ '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'],
+ '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'],
+ 'Foliage.heightMin': ['no-place', 'a band of world heights plants grow in, not a region round the entity'],
+ 'Foliage.heightMax': ['no-place', 'a band of world heights plants grow in, not a region round the entity'],
+ 'Foliage.lodDistance': ['no-place', 'a distance from the camera past which the far version is drawn'],
+ 'Foliage.drawDistance': ['no-place', 'a distance from the camera past which nothing is drawn'],
'Sprite.size': ['renders', 'the sprite drawn at it is the outline'],
'Sprite.tileSize': ['renders', 'the repeat of a drawn sprite'],
'ShapeRenderer.size': ['renders', 'the shape drawn at it is the outline'],
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index 1e204a988..3c15bc4f2 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -2509,6 +2509,14 @@ export const NOTED = {
{"note":"A Water material: waves that travel, the scene seen through it bent and tinted by how deep the water is, reflections, and foam at the shore and on the crests."},
"chore(editor-checks): a water-look check":
{"internal":"the editor check for the Water material entry above"},
+ "feat(render): Terrain and Foliage components with heightmaps, painted layers, wind and level of detail":
+ {"note":"A Terrain component makes ground from a heightmap or noise, paints it with grass, dirt, snow and rock layers and draws it in chunks that coarsen with distance; a Foliage component scatters grass or a mesh over it, swaying in the wind and thinning out with distance."},
+ "chore(editor-checks): terrain and foliage checks, and the inspector's buttons on the shared components":
+ {"internal":"the editor checks for the Terrain and Foliage entry above, and the effect stack and weather panels moved onto the shared Button and IconButton"},
+ "feat(examples): add the Wilds example, a lake under mountains with terrain, water, foliage and cloud shadows":
+ {"note":"Wilds is a new 3D example: a lake under mountains at dusk, made from a generated heightmap with the Terrain, Water and Foliage features and the sky's cloud shadows."},
+ "chore(tools): the gates run in parallel with --jobs, and the reds a full run gathered are cleared":
+ {"internal":"tooling for the static gates, and fixes to checks that had drifted from the code they guard"},
"fix(render): a wire narrower than a pixel is no longer painted over by the sky in dashes":
{"note":"A wire or railing thinner than a pixel stays one line against the sky instead of breaking into dashes."},
"fix(render): contact shadows no longer speckle a surface the sun does not reach, and a temporal pass placed before a noisy effect is flagged":