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.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(terrain): bodies collide with the ground drawn near the eye, built in tiles round what moves, and queries answer from the same triangles
yhh81190722990f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3e13bfbfc..70928adf2 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -23,6 +23,7 @@ published separately; it ships inside the editor.- **Terrain without cracks, and without end.** The ground is now a CDLOD quadtree round the eye: every node is the same small patch drawn as instances of one mesh, its heights and normals read on the GPU from pages of a height atlas, and its vertices slide onto the coarser grid toward the end of their level's range, so levels meet without cracks or skirts and nothing pops as the camera moves. `Terrain.extent` Infinite makes ground that goes on for ever from seeded noise read anywhere (worn by the noise's own erosion), drawn out to `drawDistance`; `cellSize` is the finest cell near the eye. Pages are made a few a frame, coarse and near first, and shown as progress.- **Terrain from a generator the game names, versioned.** Infinite ground is now made by a terrain provider: a function of the world position that samples whole regions (heights, and paint if it has its own), the same on every machine, and that may answer later from a worker or a server. `Terrain.provider`, `world` and `generatorVersion` name it; `registerTerrainProvider` adds a game's own, and the engine's noise is `estella:noise` version 1. A terrain whose provider is missing, whose version its provider no longer has, or whose heightmap cannot be read fails with a reason in `Terrains.status` and answers nothing, instead of growing noise in its place.+- **Terrain collision, the same ground that is drawn.** 3D bodies and characters now collide with a `Terrain`: it is built in tiles round everything that moves on it (`collision`, `collisionDistance`, `collisionLayer`, `friction`), the tile under a body at once, and kept through a rebuild until the new ground replaces it. What is collided with, what `Terrains.heightAt` and `normalAt` answer and the finest level drawn near the eye are now one set of triangles, so a ray, a query and the picture agree wherever the camera is; `Terrains.collisionReadyAt` says when the ground under a point is ready. Any system that makes static geometry while the game runs can hand it to the 3D world through the new `CollisionGeometry` resource.- **A vertex hook can hand the fragment a colour.** What a material's vertex hook leaves in `es_vertexColor` is now the colour its fragment receives (times the instance's tint), on both backends.- **Bakes run over frames, with progress.** Work that used to hold a frame until it was done (a terrain worn by rain, a water zone baked, terrain chunks built, plants grown) is now spread over frames within a budget, and listed with its progress in the new `Bakes` resource (`bakesOf(app).active`). The editor's status bar shows it as a bar, for the edit world and for the game running in Play, and a game can show it on a loading screen. Plants wait for the ground and the water they stand on instead of being grown twice.- **Eroded and warped terrain.** `Terrain.erosion` wears the ground with rain (a heightmap's as well as the noise's): gullies down the slopes, sharper ridges, silt in the valleys, and dirt painted where the water ran; the same seed wears the same ground. `Terrain.warp` bends the noise by noise of its own for winding valleys and bent ridges. `erodeHeightfield` and `erosionJob` do the same for a tool.diff --git a/docs/WORLD_GENERATION_PLAN.md b/docs/WORLD_GENERATION_PLAN.mdindex 4b4e6b9b3..4573cfce5 100644--- a/docs/WORLD_GENERATION_PLAN.md+++ b/docs/WORLD_GENERATION_PLAN.md@@ -20,14 +20,14 @@- 需要:程序化区块数据入口,接收 `generateChunk(seed, algoVersion, cx, cz)` 或同职责的 provider;输入含星球/区块身份、生成器版本、世界坐标原点、采样间距、高度与群落权重;渲染、碰撞、放置、服务端共用同一数据。不替换已保存星球的旧算法。- 失败处理:高度数据缺失或加载失败时,持久星球报告失败并保持旧数据或等待,不得悄悄回退为噪声。-- 当前状态:地形已改为“数据源”(`TerrainSource`)驱动:`FieldSource`(区域高度场)、`NoiseSource`(世界坐标、按种子、无限)。尚缺:外部 provider 接口、生成器版本、区块身份、区域噪声仍按局部 0..1 归一化、缺图时仍回退噪声。+- 当前状态:已完成(e4937e148)。`TerrainProvider`(`sdk/src/terrain/provider.ts`)按区域采样(世界、种子、版本、世界坐标起点、间距、样本数),可异步;`registerTerrainProvider` 注册游戏自己的生成器,引擎噪声为 `estella:noise` 版本 1;`Terrain.provider/world/generatorVersion`;未注册、版本不存在、高度图读不到 → `Terrains.status` 为 failed 并给出原因,不回退噪声。测试 `sdk/tests/terrain-provider.test.ts`。仍欠:区域(Area)噪声仍按局部归一化,不用于连续世界;地形实体移动后 provider 原点不更新。- 验收:同版本/种子/坐标在客户端与服务端结果相同;不同加载顺序一致;共享边高度与法线一致;缺失数据不改变旧星球。### T-02 碰撞、贴地查询与可视表面一致- 需要:地形碰撞(先桥接静态 `MeshCollider3D`,再评估专用高度场碰撞);碰撞精度有自己稳定的规则,不随摄像机 LOD 变化;高度/法线查询、射线、碰撞与三角面在约定精度内吻合。- 已知差异:`sampleHeight` 双线性插值,渲染为两片三角形(3×3 合成例中对角线中点 0.5 对 1.0)。新 CDLOD 渲染按页样本插值并在细节级之间形变,同样需要与查询统一定义。-- 当前状态:未开始。+- 当前状态:已完成第一步。统一定义见 `sdk/src/terrain/surface.ts`:`cellSize` 格点、节点高度取数据源、每格沿 (1,0)–(0,1) 对角线切分,与最细一级渲染补丁同一三角面(差异仅 GPU 16 位高度编码);`heightAt`/`normalAt`(三角面法线)读它;碰撞按 32 格分块,在每个运动刚体与角色周围 `collisionDistance` 内构建,经通用的 `CollisionGeometry` 资源(`sdk/src/runtime/collisionGeometry.ts`)交给 3D 物理,每块一个静态网格刚体;重建期间旧块保留到新块覆盖;`Terrains.collisionReadyAt` 供游戏等待。测试 `sdk/tests/terrain-surface.test.ts`(含真实 Jolt:射线跨块缝与 `heightAt` 吻合到 1e-3、落球静止在地面上)。仍欠:专用高度场形状(Jolt HeightFieldShape,省内存)评估;远处没有运动物体的位置无碰撞(远程射线需走 `heightAt`);分块驻留尚未归 T-03 的统一预算。- 验收:机器人离地高度稳定;建筑四角支撑不悬空;LOD 切换、跨块、重载不掉落;掉落物、障碍、设备有真实碰撞。### T-03 程序化区块的驻留与统一预算diff --git a/docs/astro/src/content/docs/graphics/terrain.mdx b/docs/astro/src/content/docs/graphics/terrain.mdxindex 5faff4bf9..270af1379 100644--- a/docs/astro/src/content/docs/graphics/terrain.mdx+++ b/docs/astro/src/content/docs/graphics/terrain.mdx@@ -28,6 +28,7 @@ The ground is one of two kinds, chosen by `extent`:| `cellSize` | The finest cell of the ground's mesh, in world units: what the ground is drawn at near the eye. Further off the cells double, level by level. || `detail` | A multiplier on how far the finest cells reach before the ground coarsens. Above 1 is finer at a distance and costs more triangles. || `drawDistance` | Infinite only. How far from the eye the ground is drawn. |+| `collision`, `collisionDistance` | Whether 3D bodies and characters collide with the ground, and how far round each one that moves the ground is built for it. `collisionLayer` and `friction` (advanced) are the ground's layer and grip. || `provider`, `world`, `generatorVersion` | Infinite only. The generator the ground is made by (`estella:noise`, the engine's noise, or one the game registers), the world it belongs to as the game names it, and the generator version that world was made with. || `seed`, `frequency`, `octaves`, `persistence`, `ridged` | The noise: another seed is another ground; `frequency` is how many hills across; `ridged` goes from rolling hills to sharp ridges. || `resolution` | Area only. Samples along each side of an area's noise ground. |@@ -122,7 +123,10 @@ const y = terrains.heightAt(x, z); // world height, or null where there isconst n = terrains.normalAt(x, z); // the unit normal there, or null```-These read the same source the pages are made from (the area's field, or the provider), so they agree with what is drawn, and they+These read the surface: the lattice of `cellSize` cells, each node as high as the source says there, each cell cut in two along the+diagonal from its (1, 0) corner to its (0, 1) corner. That is exactly the finest level the ground is drawn at near the eye and what+bodies collide with, so a query, a ray and the drawn triangles agree (to the GPU's 16-bit height encoding, a few millimetres for a+few hundred units of height), and the answer does not change with the camera. `normalAt` is the normal of the triangle there. Theyanswer for any point whether or not its page has been made. Until an area's images are read and its erosion is done, `heightAt`returns null and `terrains.loading` is true. A provider that answers later leaves a point null until the samples round it come in.@@ -130,6 +134,19 @@ returns null and `terrains.loading` is true. A provider that answers later leavecannot be read, whose provider is not registered, or whose version its provider no longer has fails: it draws nothing and answersnull, rather than growing noise where the game expected its own ground.+### Collision++With `collision` on, the ground is built for the 3D physics world in tiles of 32 cells within `collisionDistance` of every 3D body+that moves and every character: the tile under one at once, the rest a few a frame, nearest first, and let go once nothing is near.+Each tile is a static mesh body owned by the terrain entity, so a ray or a contact that hits the ground reports the terrain. While a+terrain is rebuilt its old tiles stay until the new ones replace them, so nothing standing on it falls.+`terrains.collisionReadyAt(x, z)` says whether the ground under a point is built, for a game to wait on before it drops something+there (a provider that answers later builds a tile once its samples are in). Far from anything that moves there is nothing to hit:+ask `heightAt` there instead.++The tiles go through the `CollisionGeometry` resource (`esengine`), which any system that makes static geometry as the game runs can+use; the 3D physics world keeps one static body for each piece in it.+### Providers and versionsGround without end is made by a provider: one function of the world position, the same on every machine. It is asked for a region@@ -160,8 +177,8 @@ with `heightAt` answers a point at once; without it a point is answered from sma## 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.+- **Collision is the finest level.** Far off the ground is drawn coarser than it collides, which is unseen from where anything collides+ with it; only what moves gets ground to hit, within `collisionDistance`.- **Paint is as fine as the pages.** Layer weights are sampled with the heights, two to a cell, so a splatmap finer than that near theeye is averaged, and far off it is coarser still.- **No holes, caves or overhangs.** A heightfield has one height at each place. Caves and bridges are meshes placed with it.diff --git a/docs/astro/src/content/docs/zh-cn/graphics/terrain.mdx b/docs/astro/src/content/docs/zh-cn/graphics/terrain.mdxindex 73f3a9e4b..b0b566532 100644--- a/docs/astro/src/content/docs/zh-cn/graphics/terrain.mdx+++ b/docs/astro/src/content/docs/zh-cn/graphics/terrain.mdx@@ -22,6 +22,7 @@ description: 一个 Terrain 组件,用高度图或噪声生成地面,可以是| `cellSize` | 地面网格最细的格子,以世界单位计:视点近处地面按它绘制。再远一些,格子逐级加倍。 || `detail` | 最细格子在地面变粗之前能延伸多远的倍率。大于 1 时远处更细,三角形也更多。 || `drawDistance` | 仅无限地面。地面从视点向外绘制多远。 |+| `collision`、`collisionDistance` | 3D 刚体和角色是否与地面碰撞,以及在每个运动物体周围多远的范围内为碰撞构建地面。`collisionLayer` 和 `friction`(高级)是地面的碰撞层和摩擦。 || `provider`、`world`、`generatorVersion` | 仅无限。生成地面的生成器(`estella:noise` 为引擎自带噪声,或游戏注册的生成器)、游戏给这个世界起的名字,以及这个世界生成时用的生成器版本。 || `seed`、`frequency`、`octaves`、`persistence`、`ridged` | 噪声:换一个种子就是另一片地面;`frequency` 是横跨有几座山丘;`ridged` 从起伏的丘陵到尖锐的山脊。 || `resolution` | 仅区域。区域噪声地面每边的采样数。 |@@ -91,10 +92,16 @@ const y = terrains.heightAt(x, z); // 世界高度,没有地形的地方const n = terrains.normalAt(x, z); // 那里的单位法线,或 null```-它们读的是生成页所用的同一个来源(区域的场,或生成器),所以和画出来的一致,而且任何一点都能回答,不管那里的页做没做好。区域的图读完、侵蚀做完之前,`heightAt` 返回 null,`terrains.loading` 为 true。稍后才应答的生成器,在某点周围的样本到达之前,该点返回 null。+它们读的是地表:`cellSize` 的格点网,每个节点取数据源在那里的高度,每格沿 (1, 0) 角到 (0, 1) 角的对角线切成两片三角形。这正是视点近处最细一级画出来的三角面,也是物体碰撞的三角面,所以查询、射线和画出的三角面一致(差别只在 GPU 的 16 位高度编码,几百单位高的地形是几毫米),而且答案不随摄像机变化。`normalAt` 是那里三角面的法线。任何一点都能回答,不管那里的页做没做好。区域的图读完、侵蚀做完之前,`heightAt` 返回 null,`terrains.loading` 为 true。稍后才应答的生成器,在某点周围的样本到达之前,该点返回 null。`terrains.status(entity)` 说明地形所处的状态:`loading`、`ready`,或带 `reason` 的 `failed`。高度图读不到、生成器没注册、或生成器已没有所要的版本时,地形失败:什么都不画,查询返回 null,而不是在游戏期待自己地面的地方长出噪声。+### 碰撞++打开 `collision` 后,地面以 32 格为一块,在每个运动的 3D 刚体和每个角色周围 `collisionDistance` 内为 3D 物理世界构建:它脚下那块立刻构建,其余每帧几块、由近及远,没有东西靠近后释放。每块是属于地形实体的静态网格刚体,所以射线或接触打到地面时报告的是地形实体。地形重建期间旧块保留到新块替换它们,站在上面的东西不会掉下去。`terrains.collisionReadyAt(x, z)` 说明某点下的地面是否已构建好,游戏可以等它再往那里放东西(稍后才应答的生成器在样本到达后才构建那块)。离任何运动物体都远的地方没有可碰的东西,那里请用 `heightAt`。++这些块经由 `CollisionGeometry` 资源(`esengine`)交出,任何在游戏运行中生成静态几何的系统都可以用它;3D 物理世界为其中每一片保留一个静态刚体。+### 生成器与版本无限地面由生成器生成:一个关于世界位置的函数,在每台机器上都一样。它被要求采样一个区域(世界、种子和版本、以世界单位计的起点、间距和每边样本数),返回那里的高度;如果它自己给地面上色,还返回每个样本四个图层权重。每个区域都是同一个函数在不同点上的读数,所以相邻页共享边上的样本,粗页和细页在样本重合处一致,页生成的先后不改变任何东西。位置是世界的,不是地形的:同一个世界上分开摆放的两个地形是同一片地面。@@ -119,7 +126,7 @@ registerTerrainProvider(planet);## 限制-- **没有碰撞。** 地面只是被绘制,不被模拟:要把东西立在上面用 `heightAt`,物理刚体会穿过它,除非项目自己加碰撞体。+- **碰撞按最细一级。** 远处的地面画得比碰撞粗,但碰撞发生的地方看不出来;只有运动的物体在 `collisionDistance` 内才有可碰的地面。- **上色精度就是页的精度。** 图层权重和高度一起采样,每格两个,所以近处比这更细的 splatmap 会被平均,远处更粗。- **没有洞、洞穴或悬挑。** 高度场在每个位置只有一个高度。洞穴和桥是和它放在一起的网格。- **只有位置。** 地形跟随实体的位置;它的旋转和缩放不被考虑,`heightAt` 不考虑,抬起地面的着色器也不考虑。让实体保持不旋转、不缩放,用 `sizeX`、`sizeZ` 和 `height` 设定地面大小。diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex 06dfeca39..c6e2fb9c0 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -1,7 +1,7 @@# API surface — esengine/index<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 159 beta · 1782 experimental · 3 deprecated+Symbols: 115 public · 159 beta · 1786 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -2492,6 +2492,24 @@ normalX: numbernormalY: number```+## CollisionGeometry — class @experimental+```+delete: (key: string) => void+deleteAll: (prefix: string) => void+entries: () => IterableIterator<[string, CollisionPiece]>+get: (key: string) => CollisionPiece | undefined+revision: number+set: (key: string, piece: CollisionPiece) => void+size: number+static new (): CollisionGeometry+static prototype: CollisionGeometry+```++## CollisionGeometryRes — const @experimental+```+ResourceDef<CollisionGeometry>+```+## CollisionHitEvent — interface @experimental```approachSpeed: number@@ -2503,6 +2521,17 @@ pointX: numberpointY: number```+## CollisionPiece — interface @experimental+```+friction: number+indices: Uint32Array<ArrayBufferLike>+layer: number+origin: readonly [number, number, number]+owner: number+positions: Float32Array<ArrayBufferLike>+restitution: number+```+## Color — interface @public```a: number@@ -9700,12 +9729,16 @@ ComponentDef<TerrainData>## TerrainData — interface @experimental```cellSize: number+collision: boolean+collisionDistance: number+collisionLayer: numberdetail: numberdirtHeight: numberdrawDistance: numbererosion: numberextent: numberfrequency: number+friction: numbergeneratorVersion: numberheight: numberheightmap: number@@ -9808,6 +9841,7 @@ static prototype: TerrainUnavailable@internal app_: App | null@internal built_: Map<number, Built>@internal revision_: number+collisionReadyAt: (x: number, z: number) => booleanheightAt: (x: number, z: number) => number | nullloading: booleannormalAt: (x: number, z: number) => [number, number, number] | null@@ -12551,6 +12585,11 @@ MotionDriver<AnimatorBlend2DMotion>(shape: Collider3DShape, segments?: number): Vec3[][]```+## collisionGeometryOf — function @experimental+```+(app: App): CollisionGeometry+```+## color — const @experimental```(r?: number, g?: number, b?: number, a?: number) => Colordiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex ae0a4bc49..f27292627 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.native<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 164 beta · 1801 experimental · 3 deprecated+Symbols: 115 public · 164 beta · 1805 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -2492,6 +2492,24 @@ normalX: numbernormalY: number```+## CollisionGeometry — class @experimental+```+delete: (key: string) => void+deleteAll: (prefix: string) => void+entries: () => IterableIterator<[string, CollisionPiece]>+get: (key: string) => CollisionPiece | undefined+revision: number+set: (key: string, piece: CollisionPiece) => void+size: number+static new (): CollisionGeometry+static prototype: CollisionGeometry+```++## CollisionGeometryRes — const @experimental+```+ResourceDef<CollisionGeometry>+```+## CollisionHitEvent — interface @experimental```approachSpeed: number@@ -2503,6 +2521,17 @@ pointX: numberpointY: number```+## CollisionPiece — interface @experimental+```+friction: number+indices: Uint32Array<ArrayBufferLike>+layer: number+origin: readonly [number, number, number]+owner: number+positions: Float32Array<ArrayBufferLike>+restitution: number+```+## Color — interface @public```a: number@@ -9913,12 +9942,16 @@ ComponentDef<TerrainData>## TerrainData — interface @experimental```cellSize: number+collision: boolean+collisionDistance: number+collisionLayer: numberdetail: numberdirtHeight: numberdrawDistance: numbererosion: numberextent: numberfrequency: number+friction: numbergeneratorVersion: numberheight: numberheightmap: number@@ -10021,6 +10054,7 @@ static prototype: TerrainUnavailable@internal app_: App | null@internal built_: Map<number, Built>@internal revision_: number+collisionReadyAt: (x: number, z: number) => booleanheightAt: (x: number, z: number) => number | nullloading: booleannormalAt: (x: number, z: number) => [number, number, number] | null@@ -12779,6 +12813,11 @@ MotionDriver<AnimatorBlend2DMotion>(shape: Collider3DShape, segments?: number): Vec3[][]```+## collisionGeometryOf — function @experimental+```+(app: App): CollisionGeometry+```+## color — const @experimental```(r?: number, g?: number, b?: number, a?: number) => Colordiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex 4291374f6..e23f8c324 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.node<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 161 beta · 1781 experimental · 3 deprecated+Symbols: 115 public · 161 beta · 1785 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -2487,6 +2487,24 @@ normalX: numbernormalY: number```+## CollisionGeometry — class @experimental+```+delete: (key: string) => void+deleteAll: (prefix: string) => void+entries: () => IterableIterator<[string, CollisionPiece]>+get: (key: string) => CollisionPiece | undefined+revision: number+set: (key: string, piece: CollisionPiece) => void+size: number+static new (): CollisionGeometry+static prototype: CollisionGeometry+```++## CollisionGeometryRes — const @experimental+```+ResourceDef<CollisionGeometry>+```+## CollisionHitEvent — interface @experimental```approachSpeed: number@@ -2498,6 +2516,17 @@ pointX: numberpointY: number```+## CollisionPiece — interface @experimental+```+friction: number+indices: Uint32Array<ArrayBufferLike>+layer: number+origin: readonly [number, number, number]+owner: number+positions: Float32Array<ArrayBufferLike>+restitution: number+```+## Color — interface @public```a: number@@ -9695,12 +9724,16 @@ ComponentDef<TerrainData>## TerrainData — interface @experimental```cellSize: number+collision: boolean+collisionDistance: number+collisionLayer: numberdetail: numberdirtHeight: numberdrawDistance: numbererosion: numberextent: numberfrequency: number+friction: numbergeneratorVersion: numberheight: numberheightmap: number@@ -9803,6 +9836,7 @@ static prototype: TerrainUnavailable@internal app_: App | null@internal built_: Map<number, Built>@internal revision_: number+collisionReadyAt: (x: number, z: number) => booleanheightAt: (x: number, z: number) => number | nullloading: booleannormalAt: (x: number, z: number) => [number, number, number] | null@@ -12546,6 +12580,11 @@ MotionDriver<AnimatorBlend2DMotion>(shape: Collider3DShape, segments?: number): Vec3[][]```+## collisionGeometryOf — function @experimental+```+(app: App): CollisionGeometry+```+## color — const @experimental```(r?: number, g?: number, b?: number, a?: number) => Colordiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex b64b13ea9..2834dfd18 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -1,7 +1,7 @@# API surface — esengine/minigame<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 159 beta · 1803 experimental · 3 deprecated+Symbols: 115 public · 159 beta · 1807 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -2487,6 +2487,24 @@ normalX: numbernormalY: number```+## CollisionGeometry — class @experimental+```+delete: (key: string) => void+deleteAll: (prefix: string) => void+entries: () => IterableIterator<[string, CollisionPiece]>+get: (key: string) => CollisionPiece | undefined+revision: number+set: (key: string, piece: CollisionPiece) => void+size: number+static new (): CollisionGeometry+static prototype: CollisionGeometry+```++## CollisionGeometryRes — const @experimental+```+ResourceDef<CollisionGeometry>+```+## CollisionHitEvent — interface @experimental```approachSpeed: number@@ -2498,6 +2516,17 @@ pointX: numberpointY: number```+## CollisionPiece — interface @experimental+```+friction: number+indices: Uint32Array<ArrayBufferLike>+layer: number+origin: readonly [number, number, number]+owner: number+positions: Float32Array<ArrayBufferLike>+restitution: number+```+## Color — interface @public```a: number@@ -9988,12 +10017,16 @@ ComponentDef<TerrainData>## TerrainData — interface @experimental```cellSize: number+collision: boolean+collisionDistance: number+collisionLayer: numberdetail: numberdirtHeight: numberdrawDistance: numbererosion: numberextent: numberfrequency: number+friction: numbergeneratorVersion: numberheight: numberheightmap: number@@ -10096,6 +10129,7 @@ static prototype: TerrainUnavailable@internal app_: App | null@internal built_: Map<number, Built>@internal revision_: number+collisionReadyAt: (x: number, z: number) => booleanheightAt: (x: number, z: number) => number | nullloading: booleannormalAt: (x: number, z: number) => [number, number, number] | null@@ -12845,6 +12879,11 @@ MotionDriver<AnimatorBlend2DMotion>(shape: Collider3DShape, segments?: number): Vec3[][]```+## collisionGeometryOf — function @experimental+```+(app: App): CollisionGeometry+```+## color — const @experimental```(r?: number, g?: number, b?: number, a?: number) => Colordiff --git a/sdk/etc/physics3d.api.md b/sdk/etc/physics3d.api.mdindex c3eaff903..17a999593 100644--- a/sdk/etc/physics3d.api.md+++ b/sdk/etc/physics3d.api.md@@ -290,6 +290,7 @@ config: Physics3DConfig | nullinitPromise: Promise<unknown> | nulljoints: Joint3DMapmodule: Physics3DWasmModule | null+pieces: PieceMap```## Physics3DWasmModule — interface @experimental@@ -530,6 +531,6 @@ twistMinAngle: number## stepPhysics3D — function @experimental```-(app: App, module: Physics3DWasmModule, bodies: BodyMap, config: Physics3DConfig, characters?: BodyMap, events?: Physics3DEventsData, joints?: Joint3DMap): void+(app: App, module: Physics3DWasmModule, bodies: BodyMap, config: Physics3DConfig, characters?: BodyMap, events?: Physics3DEventsData, joints?: Joint3DMap, pieces?: PieceMap, geometry?: CollisionGeometry | null): void```diff --git a/sdk/etc/terrain.api.md b/sdk/etc/terrain.api.mdindex 40f7ee653..b9ed151c3 100644--- a/sdk/etc/terrain.api.md+++ b/sdk/etc/terrain.api.md@@ -165,12 +165,16 @@ ComponentDef<TerrainData>## TerrainData — interface @experimental```cellSize: number+collision: boolean+collisionDistance: number+collisionLayer: numberdetail: numberdirtHeight: numberdrawDistance: numbererosion: numberextent: numberfrequency: number+friction: numbergeneratorVersion: numberheight: numberheightmap: number@@ -273,6 +277,7 @@ static prototype: TerrainUnavailable@internal app_: App | null@internal built_: Map<number, Built>@internal revision_: number+collisionReadyAt: (x: number, z: number) => booleanheightAt: (x: number, z: number) => number | nullloading: booleannormalAt: (x: number, z: number) => [number, number, number] | nulldiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 006c18707..4562b8483 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -1,7 +1,7 @@# API surface — esengine/wechat<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 159 beta · 1794 experimental · 3 deprecated+Symbols: 115 public · 159 beta · 1798 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -2487,6 +2487,24 @@ normalX: numbernormalY: number```+## CollisionGeometry — class @experimental+```+delete: (key: string) => void+deleteAll: (prefix: string) => void+entries: () => IterableIterator<[string, CollisionPiece]>+get: (key: string) => CollisionPiece | undefined+revision: number+set: (key: string, piece: CollisionPiece) => void+size: number+static new (): CollisionGeometry+static prototype: CollisionGeometry+```++## CollisionGeometryRes — const @experimental+```+ResourceDef<CollisionGeometry>+```+## CollisionHitEvent — interface @experimental```approachSpeed: number@@ -2498,6 +2516,17 @@ pointX: numberpointY: number```+## CollisionPiece — interface @experimental+```+friction: number+indices: Uint32Array<ArrayBufferLike>+layer: number+origin: readonly [number, number, number]+owner: number+positions: Float32Array<ArrayBufferLike>+restitution: number+```+## Color — interface @public```a: number@@ -9702,12 +9731,16 @@ ComponentDef<TerrainData>## TerrainData — interface @experimental```cellSize: number+collision: boolean+collisionDistance: number+collisionLayer: numberdetail: numberdirtHeight: numberdrawDistance: numbererosion: numberextent: numberfrequency: number+friction: numbergeneratorVersion: numberheight: numberheightmap: number@@ -9810,6 +9843,7 @@ static prototype: TerrainUnavailable@internal app_: App | null@internal built_: Map<number, Built>@internal revision_: number+collisionReadyAt: (x: number, z: number) => booleanheightAt: (x: number, z: number) => number | nullloading: booleannormalAt: (x: number, z: number) => [number, number, number] | null@@ -12577,6 +12611,11 @@ MotionDriver<AnimatorBlend2DMotion>(shape: Collider3DShape, segments?: number): Vec3[][]```+## collisionGeometryOf — function @experimental+```+(app: App): CollisionGeometry+```+## color — const @experimental```(r?: number, g?: number, b?: number, a?: number) => Colordiff --git a/sdk/src/core-content.ts b/sdk/src/core-content.tsindex eac6c5c9d..464982390 100644--- a/sdk/src/core-content.ts+++ b/sdk/src/core-content.ts@@ -801,6 +801,7 @@ export {} from './foliage/foliagePlugin';// Splines and water are optional modules too (`esengine/spline`, `esengine/water`).export { Bakes, BakesRes, bakesOf, finish, type WorkJob, type BakeProgress } from './runtime/bakes';+export { CollisionGeometry, CollisionGeometryRes, collisionGeometryOf, type CollisionPiece } from './runtime/collisionGeometry';export { Spline, SplinePlugin, splinePlugin, type SplineData } from './spline/splinePlugin';export { SplineCurve, type SplinePoint, type SplineNearest } from './spline/curve';export {diff --git a/sdk/src/physics3d/Physics3DPlugin.ts b/sdk/src/physics3d/Physics3DPlugin.tsindex bf2393fc9..0ca54f882 100644--- a/sdk/src/physics3d/Physics3DPlugin.ts+++ b/sdk/src/physics3d/Physics3DPlugin.ts@@ -13,9 +13,10 @@ import {type Physics3DWasmModule, type Physics3DEventsData,} from './Physics3DModule';import {- stepPhysics3D, DEFAULT_PHYSICS3D_CONFIG, type Physics3DConfig,+ stepPhysics3D, DEFAULT_PHYSICS3D_CONFIG, type Physics3DConfig, type PieceMap,} from './Physics3DSystem';import { Physics3DQueries } from './Physics3DQueries';+import { CollisionGeometryRes } from '../runtime/collisionGeometry';import { setupPhysics3DDebugDraw } from './Physics3DDebugDraw';import type { Joint3DMap } from './Physics3DJoints';@@ -32,13 +33,15 @@ export interface Physics3DRuntime {characters: Map<Entity, number>;/** Entity -> the joint it declared, with the bodies it was built between. */joints: Joint3DMap;+ /** Key -> the body built for that piece of the app's collision geometry. */+ pieces: PieceMap;/** The world's configuration (gravity, the scale of a world unit), for what applies forces to it. Null until the plugin is built. */config: Physics3DConfig | null;}export const Physics3DRuntime = defineResource<Physics3DRuntime>({ module: null, initPromise: null, bodies: new Map(), characters: new Map(),- joints: new Map(), config: null },+ joints: new Map(), pieces: new Map(), config: null },'Physics3DRuntime',);@@ -59,7 +62,7 @@ export class Physics3DPlugin implements Plugin {build(app: App): void {const runtime: Physics3DRuntime = {module: null, initPromise: null, bodies: new Map(), characters: new Map(),- joints: new Map(), config: this.config_,+ joints: new Map(), pieces: new Map(), config: this.config_,};const events: Physics3DEventsData = {contactEnters: [], contactExits: [], sensorEnters: [], sensorExits: [],@@ -84,7 +87,8 @@ export class Physics3DPlugin implements Plugin {module, this.config_.pixelsPerUnit, runtime.characters));app.addSystemToSchedule(Schedule.FixedUpdate, defineSystem([], () => {stepPhysics3D(app, module, runtime.bodies, this.config_,- runtime.characters, events, runtime.joints);+ runtime.characters, events, runtime.joints, runtime.pieces,+ app.hasResource(CollisionGeometryRes) ? app.getResource(CollisionGeometryRes) : null);}));// Installed with the world, drawn only once a game turns the resource// on — a scene that never asks for it pays a resource and nothing else.diff --git a/sdk/src/physics3d/Physics3DSystem.ts b/sdk/src/physics3d/Physics3DSystem.tsindex fd9a56693..44e209688 100644--- a/sdk/src/physics3d/Physics3DSystem.ts+++ b/sdk/src/physics3d/Physics3DSystem.ts@@ -29,6 +29,7 @@ import { syncJoints3D, type Joint3DMap } from './Physics3DJoints';import type { Entity } from '../types';import type { Physics3DWasmModule, Physics3DEventsData } from './Physics3DModule';import { PHYSICS3D_TRANSFORM_STRIDE, drainPhysics3DEvents } from './Physics3DModule';+import type { CollisionGeometry, CollisionPiece } from '../runtime/collisionGeometry';/** Body kinds, in the order the module reads them. */const MOTION = { Static: 0, Kinematic: 1, Dynamic: 2 } as const;@@ -55,6 +56,9 @@ export const DEFAULT_PHYSICS3D_CONFIG: Physics3DConfig = {/** Which body an entity owns, so a removed component takes its body with it. */type BodyMap = Map<Entity, number>;+/** The body each piece of collision geometry was built as, by its key, and the piece it was built from. */+export type PieceMap = Map<string, { piece: CollisionPiece; id: number }>;+/** Ground states, as CharacterVirtual reports them. */const ON_GROUND = 0;@@ -226,7 +230,16 @@ function addMeshBody(module: Physics3DWasmModule, entity: Entity,ppu: number, layer: number): number {const geometry = getMeshCollision(collider.mesh);if (!geometry) return 0;- const { positions, indices } = geometry;+ return addTriangles(module, entity, geometry.positions, geometry.indices, px, py, pz, r, ppu, layer,+ collider.friction, collider.restitution);+}++/** Triangles in world units, scaled into metres on the module's heap, as one static body at (px, py, pz) in metres. */+function addTriangles(module: Physics3DWasmModule, entity: Entity,+ positions: Float32Array, indices: Uint32Array,+ px: number, py: number, pz: number,+ r: { x: number; y: number; z: number; w: number },+ ppu: number, layer: number, friction: number, restitution: number): number {const vertexPtr = module._malloc(positions.length * 4);const indexPtr = module._malloc(indices.length * 4);try {@@ -235,14 +248,37 @@ function addMeshBody(module: Physics3DWasmModule, entity: Entity,module.HEAPU32.set(indices, indexPtr >> 2);return module._physics3d_addMeshBody(entity as number, vertexPtr, positions.length / 3, indexPtr, indices.length,- px, py, pz, r.x, r.y, r.z, r.w, layer,- collider.friction, collider.restitution);+ px, py, pz, r.x, r.y, r.z, r.w, layer, friction, restitution);} finally {module._free(vertexPtr);module._free(indexPtr);}}+/** Follows the app's collision geometry: a static mesh body a piece, built again when its piece is replaced, removed with it. */+function syncPieces(module: Physics3DWasmModule, geometry: CollisionGeometry | null, pieces: PieceMap, ppu: number): void {+ if (!geometry && pieces.size === 0) return;+ const live = new Set<string>();+ if (geometry) {+ for (const [key, piece] of geometry.entries()) {+ live.add(key);+ const had = pieces.get(key);+ if (had?.piece === piece) continue;+ if (had) module._physics3d_removeBody(had.id);+ const [ox, oy, oz] = piece.origin;+ const id = addTriangles(module, piece.owner, piece.positions, piece.indices,+ ox / ppu, oy / ppu, oz / ppu, { x: 0, y: 0, z: 0, w: 1 }, ppu, piece.layer, piece.friction, piece.restitution);+ if (id !== 0) pieces.set(key, { piece, id });+ else pieces.delete(key);+ }+ }+ for (const [key, had] of pieces) {+ if (live.has(key)) continue;+ module._physics3d_removeBody(had.id);+ pieces.delete(key);+ }+}+/*** Hand a mesh's vertices over as a convex hull.*@@ -276,7 +312,9 @@ export function stepPhysics3D(app: App, module: Physics3DWasmModule,bodies: BodyMap, config: Physics3DConfig,characters: BodyMap = new Map(),events?: Physics3DEventsData,- joints: Joint3DMap = new Map()): void {+ joints: Joint3DMap = new Map(),+ pieces: PieceMap = new Map(),+ geometry: CollisionGeometry | null = null): void {const ppu = config.pixelsPerUnit;// Both directions read a parent's COMPOSED transform — the pose a body is// created at, and the local pose its answer is turned back into — so the@@ -307,6 +345,8 @@ export function stepPhysics3D(app: App, module: Physics3DWasmModule,bodies.delete(entity);}+ syncPieces(module, geometry, pieces, ppu);+// Characters have just written local poses of their own, and a body may be// parented to one.app.world.ensureTransformsComposed();diff --git a/sdk/src/runtime/collisionGeometry.ts b/sdk/src/runtime/collisionGeometry.tsnew file mode 100644index 000000000..a723a8938--- /dev/null+++ b/sdk/src/runtime/collisionGeometry.ts@@ -0,0 +1,71 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file collisionGeometry.ts+ * @brief Static triangles made while the game runs, for the physics world to collide with: tiles of terrain, and the like.+ *+ * @details A system that makes ground or walls as it goes (the terrain round what moves on it) puts its triangles here under keys of+ * its own; the 3D physics world, when there is one, keeps one static body a piece and follows the pieces as they are set,+ * replaced and deleted. Neither side knows the other: a server without physics still makes the pieces, and physics needs no+ * terrain module. A piece is replaced whole, by setting a new object under its key.+ */+import type { App } from '../app/app';+import { defineResource } from '../ecs/resource';+import type { Entity } from '../types';++/** One piece of static geometry, in world units. */+export interface CollisionPiece {+ /** The entity the piece belongs to: what a contact or a ray that hits it reports. */+ owner: Entity;+ /** Where the piece's positions are measured from, in the world. */+ origin: readonly [number, number, number];+ /** `vertexCount * 3` floats, relative to `origin`. */+ positions: Float32Array;+ /** Three a triangle, counter-clockwise seen from the side that faces out. */+ indices: Uint32Array;+ friction: number;+ restitution: number;+ /** The collision layer (0 to 15). */+ layer: number;+}++/** The pieces now, by key. */+export class CollisionGeometry {+ private readonly pieces_ = new Map<string, CollisionPiece>();+ /** Bumped on every change, so a reader can skip a frame where nothing changed. */+ revision = 0;++ set(key: string, piece: CollisionPiece): void {+ this.pieces_.set(key, piece);+ this.revision++;+ }++ delete(key: string): void {+ if (this.pieces_.delete(key)) this.revision++;+ }++ get(key: string): CollisionPiece | undefined {+ return this.pieces_.get(key);+ }++ /** Deletes every piece whose key starts with `prefix`. */+ deleteAll(prefix: string): void {+ for (const key of [...this.pieces_.keys()]) if (key.startsWith(prefix)) this.delete(key);+ }++ entries(): IterableIterator<[string, CollisionPiece]> {+ return this.pieces_.entries();+ }++ get size(): number {+ return this.pieces_.size;+ }+}++export const CollisionGeometryRes = defineResource<CollisionGeometry>(new CollisionGeometry(), 'CollisionGeometry');++/** The app's collision geometry, installed on first use. */+export function collisionGeometryOf(app: App): CollisionGeometry {+ if (!app.hasResource(CollisionGeometryRes)) app.insertResource(CollisionGeometryRes, new CollisionGeometry());+ return app.getResource(CollisionGeometryRes);+}diff --git a/sdk/src/terrain/surface.ts b/sdk/src/terrain/surface.tsnew file mode 100644index 000000000..6967ba819--- /dev/null+++ b/sdk/src/terrain/surface.ts@@ -0,0 +1,92 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file surface.ts+ * @brief The ground as one set of triangles: what is drawn near the eye, what is collided with and what a query answers.+ *+ * @details The ground is the lattice of `cellSize` cells in the terrain's space (a node at every multiple of the cell), each node as+ * high as the source says there (an area's nodes past its edge take the edge's height), and each cell cut in two along the+ * diagonal from its (1, 0) corner to its (0, 1) corner. That is the finest level the quadtree draws (a patch's vertices fall+ * on the lattice and are cut the same way), the triangles collision is built from, and what `heightAt` and `normalAt` read, so+ * all three agree to the GPU's 16-bit height encoding. Coarser levels farther from the eye are drawn coarser; nothing collides+ * with them. The rule does not change with the camera, the order tiles are made in, or a reload.+ */+import type { TerrainSource } from './source';++/** Cells along a collision tile's side. */+export const TILE_CELLS = 32;++/** A tile's triangles: positions relative to its corner (x0, 0, z0) in the terrain's space, wound counter-clockwise from above. */+export interface SurfaceTile { x0: number; z0: number; positions: Float32Array; indices: Uint32Array }++export class TerrainSurface {+ constructor(readonly source: TerrainSource, readonly cell: number) {}++ /** The height of lattice node (i, k), or null where the source has not answered. Off an area it is its nearest edge's, as the pages have it. */+ node(i: number, k: number): number | null {+ let x = i * this.cell, z = k * this.cell;+ const b = this.source.bounds;+ if (b) {+ x = Math.min(Math.max(x, b[0]), b[2]);+ z = Math.min(Math.max(z, b[1]), b[3]);+ }+ return this.source.height(x, z);+ }++ /** Whether (x, z) is on the ground: inside an area, anywhere for ground without end. */+ covers(x: number, z: number): boolean {+ const b = this.source.bounds;+ return !b || (x >= b[0] && x <= b[2] && z >= b[1] && z <= b[3]);+ }++ /** The height at (x, z) on its cell's triangle, or null off the ground or where a corner is not known yet. */+ height(x: number, z: number): number | null {+ const c = this.corners(x, z);+ if (!c) return null;+ const [a, b, cc, d, fx, fz] = c;+ return fx + fz <= 1 ? a + (b - a) * fx + (cc - a) * fz : d + (cc - d) * (1 - fx) + (b - d) * (1 - fz);+ }++ /** The normal of the triangle under (x, z), or null where its height is not known. */+ normal(x: number, z: number): [number, number, number] | null {+ const c = this.corners(x, z);+ if (!c) return null;+ const [a, b, cc, d, fx, fz] = c;+ const sx = (fx + fz <= 1 ? b - a : d - cc) / this.cell, sz = (fx + fz <= 1 ? cc - a : d - b) / this.cell;+ const len = Math.hypot(sx, 1, sz);+ return [-sx / len, 1 / len, -sz / len];+ }++ /** Tile (tx, tz)'s triangles, or null while a node of it is not known yet. */+ tile(tx: number, tz: number): SurfaceTile | null {+ const n = TILE_CELLS, side = n + 1;+ const positions = new Float32Array(side * side * 3);+ for (let k = 0; k <= n; k++) for (let i = 0; i <= n; i++) {+ const h = this.node(tx * n + i, tz * n + k);+ if (h === null) return null;+ const at = (k * side + i) * 3;+ positions[at] = i * this.cell;+ positions[at + 1] = h;+ positions[at + 2] = k * this.cell;+ }+ const indices = new Uint32Array(n * n * 6);+ let at = 0;+ for (let k = 0; k < n; k++) for (let i = 0; i < n; i++) {+ const a = k * side + i, b = a + 1, c = a + side, d = c + 1;+ // The patch's cut and winding (patch.ts): a, the next row, the next column; then the other half.+ indices.set([a, c, b, b, c, d], at);+ at += 6;+ }+ return { x0: tx * n * this.cell, z0: tz * n * this.cell, positions, indices };+ }++ /** The four corners of the cell under (x, z) and where in it the point is, or null. */+ private corners(x: number, z: number): [number, number, number, number, number, number] | null {+ if (!this.covers(x, z)) return null;+ const u = x / this.cell, v = z / this.cell;+ const i = Math.floor(u), k = Math.floor(v);+ const a = this.node(i, k), b = this.node(i + 1, k), c = this.node(i, k + 1), d = this.node(i + 1, k + 1);+ if (a === null || b === null || c === null || d === null) return null;+ return [a, b, c, d, u - i, v - k];+ }+}diff --git a/sdk/src/terrain/terrainPlugin.ts b/sdk/src/terrain/terrainPlugin.tsindex 7a875f22d..b49ec3b86 100644--- a/sdk/src/terrain/terrainPlugin.ts+++ b/sdk/src/terrain/terrainPlugin.ts@@ -10,6 +10,10 @@* lifts from the node's page and slides onto the coarser grid toward the end of their level's range, so neighbouring levels* meet without a crack. The nodes are ordinary MeshRenderers of one mesh and one material, which the renderer draws as instanced* runs; pages are made a few a frame, coarse first, and a node whose page is not ready is drawn by an ancestor's.+ *+ * What is collided with and what `heightAt` answers is the surface (surface.ts): the finest level's triangles, the same+ * wherever the eye is. Collision is built in tiles round what moves on the ground (a moving 3D body, a character) and handed+ * to the physics world as collision geometry.*/import type { App, Plugin } from '../app/app';import { defineSystem, Schedule } from '../ecs/system';@@ -38,6 +42,9 @@ import { levelRange, nodeKey, parentOf, selectNodes, type QuadtreeParams, type Timport { makePage, PageTable, PAGE_SIDE, PAGE_TEXELS, PATCH_CELLS, type PageImage } from './pages';import { noiseProvider, ProviderSource, terrainProvider, TerrainUnavailable } from './provider';import { buildPatchMesh } from './patch';+import { TerrainSurface, TILE_CELLS } from './surface';+import { collisionGeometryOf } from '../runtime/collisionGeometry';+import { CharacterController3D, RigidBody3D, type RigidBody3DData } from '../physics3d/Physics3DComponents';/** The engine's own provider of ground without end: seeded noise of the world's position. */export const NOISE_PROVIDER = 'estella:noise';@@ -73,6 +80,11 @@ export interface TerrainData {detail: number;/** How far ground without end is drawn. */drawDistance: number;+ /** Whether bodies collide with the ground; how far round each thing that moves on it the ground is built for collision; its layer and friction. */+ collision: boolean;+ collisionDistance: number;+ collisionLayer: number;+ friction: number;/** Noise ground: the seed, how many hills across, how many octaves, how rough, how ridged, and (an area's) how many samples. */seed: number;frequency: number;@@ -105,6 +117,7 @@ const rgb = (r: number, g: number, b: number): Color => ({ r, g, b, a: 1 });export const Terrain: ComponentDef<TerrainData> = defineComponent<TerrainData>('Terrain', {extent: TerrainExtent.Area, provider: NOISE_PROVIDER, world: '', generatorVersion: 1, heightmap: 0, splatmap: 0, material: 0,sizeX: 1000, sizeZ: 1000, height: 150, cellSize: 2, detail: 1, drawDistance: 4000,+ collision: true, collisionDistance: 64, collisionLayer: 0, friction: 0.6,seed: 1, frequency: 3, octaves: 5, persistence: 0.5, ridged: 0.35, resolution: 257, warp: 0, erosion: 0,rockSlope: 0.35, dirtHeight: 0.62, snowHeight: 0.88,layerColor0: rgb(0.28, 0.46, 0.2), layerColor1: rgb(0.45, 0.36, 0.24), layerColor2: rgb(0.93, 0.95, 0.98), layerColor3: rgb(0.4, 0.38, 0.36),@@ -124,6 +137,10 @@ export const Terrain: ComponentDef<TerrainData> = defineComponent<TerrainData>('cellSize: { min: 0.01, category: 'Detail', tooltip: 'The finest cell of the ground\'s mesh, in world units: what it is drawn at near the eye. Further off the cells double, level by level.' },detail: { min: 0.25, max: 8, step: 0.05, category: 'Detail', tooltip: 'Above 1 the finest cells reach further out before the ground coarsens.' },drawDistance: { min: 1, category: 'Detail', tooltip: 'How far ground without end is drawn.', shownWhen: { field: 'extent', values: [TerrainExtent.Infinite] } },+ collision: { category: 'Collision', tooltip: 'Whether 3D bodies and characters collide with the ground: the finest level\'s triangles, wherever the camera is.' },+ collisionDistance: { min: 1, category: 'Collision', tooltip: 'How far round each moving body and character the ground is built for collision, in world units.' },+ collisionLayer: { min: 0, max: 15, step: 1, category: 'Collision', advanced: true, tooltip: 'The collision layer the ground is in (0 to 15).' },+ friction: { min: 0, category: 'Collision', advanced: true, tooltip: 'How much the ground holds what slides on it.' },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 (or across sizeX, for ground without end).' },octaves: { min: 1, max: 8, step: 1, category: 'Noise', tooltip: 'Layers of detail in the noise.' },@@ -159,6 +176,11 @@ export function paintWeights(h: number, ny: number, t: Pick<TerrainData, 'rockSl/** The side of the atlases the pages are kept in, in texels: 900 pages of 67 by 67. */const ATLAS_SIZE = 2048;+/** Collision tiles built a frame beyond the ones under something that moves, which are built at once. */+const TILE_BUDGET = 4;++const tileKey = (entity: Entity, tx: number, tz: number): string => `terrain:${entity}:${tx}:${tz}`;+/** How long a frame may spend making pages, in milliseconds; at least one is made a frame while any is wanted. */const PAGE_BUDGET_MS = 5;@@ -167,6 +189,13 @@ interface Built {signature: string;data: TerrainData;source: TerrainSource | null;+ /** The triangles of the finest level, which queries and collision read. */+ surface: TerrainSurface | null;+ /** The collision tiles built from this source, by key, and the settings they were built with. */+ tiles: Set<string>;+ /** Tiles of the ground this one replaced, kept until its own are built over them or nothing is near them. */+ stale: Set<string>;+ tileSettings: string;/** Bumped on every rebuild so an answer that arrives for an older one is thrown away. */epoch: number;loading: boolean;@@ -205,10 +234,10 @@ export class Terrains {const world = this.app_?.world;if (!world) return null;for (const [entity, built] of this.built_) {- if (!built.source || !world.valid(entity)) continue;+ if (!built.surface || !world.valid(entity)) continue;const t = world.tryGet(entity, Transform) as TransformData | null;if (!t) continue;- const h = built.source.height(x - t.worldPosition.x, z - t.worldPosition.z);+ const h = built.surface.height(x - t.worldPosition.x, z - t.worldPosition.z);if (h !== null) return t.worldPosition.y + h;}return null;@@ -219,17 +248,33 @@ export class Terrains {const world = this.app_?.world;if (!world) return null;for (const [entity, built] of this.built_) {- const source = built.source;- if (!source || !world.valid(entity)) continue;+ const surface = built.surface;+ if (!surface || !world.valid(entity)) continue;const t = world.tryGet(entity, Transform) as TransformData | null;if (!t) continue;- const lx = x - t.worldPosition.x, lz = z - t.worldPosition.z;- const n = source.normal(lx, lz);+ const n = surface.normal(x - t.worldPosition.x, z - t.worldPosition.z);if (n) return n;}return null;}+ /** Whether the ground under (x, z) is built for collision: what a game waits on before it drops something there. */+ collisionReadyAt(x: number, z: number): boolean {+ const world = this.app_?.world;+ if (!world) return false;+ for (const [entity, built] of this.built_) {+ const surface = built.surface;+ if (!surface || !world.valid(entity)) continue;+ const t = world.tryGet(entity, Transform) as TransformData | null;+ if (!t) continue;+ const lx = x - t.worldPosition.x, lz = z - t.worldPosition.z;+ if (!surface.covers(lx, lz)) continue;+ const span = TILE_CELLS * surface.cell;+ return built.tiles.has(tileKey(entity, Math.floor(lx / span), Math.floor(lz / span)));+ }+ return false;+ }+/** Where a terrain's ground stands. A failed one draws and answers nothing, and says why. */status(entity: Entity): TerrainStatus | null {const built = this.built_.get(entity);@@ -258,9 +303,10 @@ export class Terrains {/** The resource the plugin installs. @experimental */export const TerrainsRes = defineResource<Terrains>(new Terrains(), 'Terrains');-/** What, changed, rebuilds the ground: everything but the colours and the detail, which are written each frame. */+/** What, changed, rebuilds the ground: everything but the colours, the detail and the collision, which are read each frame. */function signatureOf(data: TerrainData): string {- const { layerColor0: _a, layerColor1: _b, layerColor2: _c, layerColor3: _d, detail: _e, drawDistance: _f, ...shape } = data;+ const { layerColor0: _a, layerColor1: _b, layerColor2: _c, layerColor3: _d, detail: _e, drawDistance: _f,+ collision: _g, collisionDistance: _h, collisionLayer: _i, friction: _j, ...shape } = data;return JSON.stringify(shape);}@@ -284,9 +330,11 @@ export class TerrainPlugin implements Plugin {const signature = signatureOf(data);let built = terrains.built_.get(entity);if (!built || built.signature !== signature) {+ // The old ground's collision tiles stay until the new ground's replace them, so nothing on it falls while it rebuilds.+ const kept = built?.tiles ?? new Set<string>();if (built) this.destroy(app, built);built = {- signature, data: { ...data }, source: null, epoch: (built?.epoch ?? 0) + 1, loading: true, cancel: null,+ signature, data: { ...data }, source: null, surface: null, tiles: new Set(), stale: kept, tileSettings: '', epoch: (built?.epoch ?? 0) + 1, loading: true, cancel: null,table: new PageTable(ATLAS_SIZE), heights: 0, paint: 0, mesh: 0, instance: 0,nodes: new Map(), spare: [], wanted: new Map(), asked: new Set(), pending: false, failure: null,};@@ -295,7 +343,10 @@ export class TerrainPlugin implements Plugin {continue;}built.data = { ...data };- if (built.loading || !built.source || !rendering) continue;+ if (built.failure) this.dropCollision(app, entity, built);+ if (built.loading || !built.source) continue;+ this.collide(app, entity, built);+ if (!rendering) continue;if (!built.instance) {if (!built.pending) void this.prepare(app, built);continue;@@ -308,7 +359,10 @@ export class TerrainPlugin implements Plugin {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);+ for (const [entity, built] of terrains.built_) {+ this.dropCollision(app, entity, built);+ this.destroy(app, built);+ }terrains.built_.clear();if (this.stock_) Material.release(this.stock_);this.stock_ = 0;@@ -324,7 +378,7 @@ export class TerrainPlugin implements Plugin {const provider = data.provider === NOISE_PROVIDER ? noiseProvider(() => data) : terrainProvider(data.provider);if (!provider) throw new TerrainUnavailable(`no terrain provider ${data.provider} is registered`);built.source = new ProviderSource(provider, data.world, data.seed, data.generatorVersion, t.worldPosition.x, t.worldPosition.z,- Math.max(data.cellSize, 1e-3) / 2, (h, ny) => paintWeights(h / Math.max(provider.range(data.seed, data.generatorVersion)[1], 1e-6), ny, data));+ Math.max(data.cellSize, 1e-3), (h, ny) => paintWeights(h / Math.max(provider.range(data.seed, data.generatorVersion)[1], 1e-6), ny, data));} else {// A heightmap named and not read is a failure: a world built on that ground must not quietly get other ground.const height = await this.pixelsOf(app, data.heightmap);@@ -351,6 +405,7 @@ export class TerrainPlugin implements Plugin {}built.source = new FieldSource(field, data, splat, flow);}+ built.surface = new TerrainSurface(built.source, Math.max(data.cellSize, 1e-3));app.getResource(TerrainsRes).revision_++;} catch (e) {if (built.epoch === epoch) built.failure = e instanceof Error ? e.message : String(e);@@ -428,6 +483,83 @@ export class TerrainPlugin implements Plugin {}}+ /**+ * Builds the collision tiles within `collisionDistance` of every moving 3D body and character, the ones under them at once and+ * the rest a few a frame, nearest first; lets go of tiles nothing has come within a tile of that distance.+ */+ private collide(app: App, entity: Entity, built: Built): void {+ const d = built.data, surface = built.surface;+ if (!d.collision || !surface) { this.dropCollision(app, entity, built); return; }+ const geometry = collisionGeometryOf(app);+ // Where things are now, not where they were when transforms were last composed: O(1) when nothing moved.+ app.world.ensureTransformsComposed();+ const t = app.world.get(entity, Transform) as TransformData;+ const at = t.worldPosition;+ // A tile is placed where the terrain was when it was built: moving the terrain, or another layer or friction, builds them again.+ const settings = `${d.collisionLayer}:${d.friction}:${at.x}:${at.y}:${at.z}`;+ if (settings !== built.tileSettings) {+ for (const k of built.tiles) built.stale.add(k);+ built.tiles.clear();+ built.tileSettings = settings;+ }+ const span = TILE_CELLS * surface.cell, reach = Math.max(d.collisionDistance, 0), keep = reach + span;+ const bounds = surface.source.bounds;+ const near = new Map<string, { tx: number; tz: number; dist: number }>();+ const visit = (x: number, z: number): void => {+ const lx = x - at.x, lz = z - at.z;+ for (let tz = Math.floor((lz - keep) / span); tz <= Math.floor((lz + keep) / span); tz++) {+ for (let tx = Math.floor((lx - keep) / span); tx <= Math.floor((lx + keep) / span); tx++) {+ const x0 = tx * span, z0 = tz * span;+ if (bounds && (x0 >= bounds[2] || z0 >= bounds[3] || x0 + span <= bounds[0] || z0 + span <= bounds[1])) continue;+ const dist = Math.hypot(Math.max(x0 - lx, 0, lx - x0 - span), Math.max(z0 - lz, 0, lz - z0 - span));+ if (dist > keep) continue;+ const key = tileKey(entity, tx, tz);+ const had = near.get(key);+ if (!had || dist < had.dist) near.set(key, { tx, tz, dist });+ }+ }+ };+ for (const e of app.world.getEntitiesWithComponents([RigidBody3D, Transform])) {+ const body = app.world.get(e, RigidBody3D) as RigidBody3DData;+ if (!body.enabled || body.bodyType === 0) continue;+ const p = (app.world.get(e, Transform) as TransformData).worldPosition;+ visit(p.x, p.z);+ }+ for (const e of app.world.getEntitiesWithComponents([CharacterController3D, Transform])) {+ const p = (app.world.get(e, Transform) as TransformData).worldPosition;+ visit(p.x, p.z);+ }++ const missing = [...near].filter(([key, n]) => n.dist <= reach && !built.tiles.has(key)).sort((a, b) => a[1].dist - b[1].dist);+ let budget = TILE_BUDGET;+ for (const [key, n] of missing) {+ if (n.dist > 0 && budget <= 0) break;+ const tile = surface.tile(n.tx, n.tz);+ // A provider that answers later has been asked for the samples; the tile is built once they are in.+ if (!tile) continue;+ if (n.dist > 0) budget--;+ geometry.set(key, {+ owner: entity, origin: [at.x + tile.x0, at.y, at.z + tile.z0], positions: tile.positions, indices: tile.indices,+ friction: d.friction, restitution: 0, layer: d.collisionLayer,+ });+ built.tiles.add(key);+ built.stale.delete(key);+ }+ for (const key of built.tiles) if (!near.has(key)) { geometry.delete(key); built.tiles.delete(key); }+ for (const key of built.stale) if (!near.has(key)) { geometry.delete(key); built.stale.delete(key); }+ }++ /** Takes a terrain's collision tiles out of the world, its own and those of the ground it replaced. */+ private dropCollision(app: App, entity: Entity, built: Built): void {+ if (built.tiles.size === 0 && built.stale.size === 0) return;+ const geometry = collisionGeometryOf(app);+ for (const key of built.tiles) geometry.delete(key);+ for (const key of built.stale) geometry.delete(key);+ built.tiles.clear();+ built.stale.clear();+ built.tileSettings = '';+ }+/** Where the eye is, in the terrain's space: the active camera, or the editor's own eye while it looks at the scene in 3D. */private eye(app: App, t: TransformData): [number, number, number] | null {if (app.hasResource(EditorView)) {@@ -616,6 +748,7 @@ export class TerrainPlugin implements Plugin {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.dropCollision(app, entity, built);this.destroy(app, built);terrains.built_.delete(entity);terrains.revision_++;diff --git a/sdk/tests/terrain-provider.test.ts b/sdk/tests/terrain-provider.test.tsindex 1b861d75b..07eb263eb 100644--- a/sdk/tests/terrain-provider.test.ts+++ b/sdk/tests/terrain-provider.test.ts@@ -113,7 +113,8 @@ describe('a Terrain with no renderer (a server)', () => {await settle(app);const terrains = app.getResource(TerrainsRes);expect(terrains.status(e)).toEqual({ state: 'ready' });- expect(terrains.heightAt(321, -654)).toBeCloseTo(ground(noiseProvider(() => params)).height(321, -654)!, 6);+ // On a lattice node the surface is the provider's sample itself.+ expect(terrains.heightAt(322, -654)).toBeCloseTo(ground(noiseProvider(() => params)).height(322, -654)!, 6);});it('fails, and answers nothing, when its provider is not registered or its version is gone', async () => {diff --git a/sdk/tests/terrain-surface.test.ts b/sdk/tests/terrain-surface.test.tsnew file mode 100644index 000000000..95da6b113--- /dev/null+++ b/sdk/tests/terrain-surface.test.ts@@ -0,0 +1,224 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file The ground is one set of triangles: what is drawn near the eye, what bodies collide with and what heightAt answers.+ */+import { afterEach, beforeAll, describe, expect, it } from 'vitest';+import { App } from '../src/app/app';+import { AppContext, setDefaultContext } from '../src/ecs/context';+import { setEditorMode, setPlayMode } from '../src/ecs/env';+import { Transform } from '../src/ecs/component';+import type { TransformData } from '../src/ecs/component.generated';+import { createMockModule } from './mocks/wasm';+import { Terrain, TerrainExtent, TerrainPlugin, TerrainsRes } from '../src/terrain/terrainPlugin';+import { TerrainSurface, TILE_CELLS } from '../src/terrain/surface';+import { NoiseSource, type NoiseParams } from '../src/terrain/source';+import { makePage, PAGE_SIDE, PAGE_TEXELS, PATCH_CELLS, type PageImage } from '../src/terrain/pages';+import { buildPatchMesh } from '../src/terrain/patch';+import { CollisionGeometryRes, type CollisionPiece } from '../src/runtime/collisionGeometry';+import { RigidBody3D, SphereCollider3D } from '../src/physics3d/Physics3DComponents';+import { Physics3D, Physics3DPlugin, Physics3DRuntime } from '../src/physics3d/Physics3DPlugin';+import type { Physics3DWasmModule } from '../src/physics3d/Physics3DModule';+import type { ESEngineModule } from '../src/wasm';+import type { Entity } from '../src/types';+import { HAS_WASM, hasSideModule, loadSideModule, loadWasmModule } from './helpers/loadWasm';++const params: NoiseParams = { seed: 3, frequency: 4, octaves: 5, persistence: 0.5, ridged: 0.3, warp: 0.2, erosion: 1, sizeX: 400, height: 40,+ rockSlope: 0.35, dirtHeight: 0.62, snowHeight: 0.88 };+const terrainOf = (over: Record<string, unknown> = {}) => ({ ...Terrain._default, extent: TerrainExtent.Infinite, cellSize: 2, ...params, ...over });++/** The height at (x, z) on a piece's triangles, found the way a ray straight down would. */+function onPiece(piece: CollisionPiece, x: number, z: number): number | null {+ const p = piece.positions, ix = piece.indices;+ const lx = x - piece.origin[0], lz = z - piece.origin[2];+ for (let t = 0; t < ix.length; t += 3) {+ const [a, b, c] = [ix[t]!, ix[t + 1]!, ix[t + 2]!].map((v) => [p[v * 3]!, p[v * 3 + 1]!, p[v * 3 + 2]!]) as [number[], number[], number[]];+ const d = (b[2]! - c[2]!) * (a[0]! - c[0]!) + (c[0]! - b[0]!) * (a[2]! - c[2]!);+ const wa = ((b[2]! - c[2]!) * (lx - c[0]!) + (c[0]! - b[0]!) * (lz - c[2]!)) / d;+ const wb = ((c[2]! - a[2]!) * (lx - c[0]!) + (a[0]! - c[0]!) * (lz - c[2]!)) / d;+ const wc = 1 - wa - wb;+ if (wa >= -1e-9 && wb >= -1e-9 && wc >= -1e-9) return piece.origin[1] + wa * a[1]! + wb * b[1]! + wc * c[1]!;+ }+ return null;+}++describe('the surface', () => {+ const surface = new TerrainSurface(new NoiseSource(params), 2);++ it('is the source at every lattice node, and flat across each triangle', () => {+ const source = new NoiseSource(params);+ for (const [i, k] of [[0, 0], [17, -9], [-300, 41]] as const) expect(surface.height(i * 2, k * 2)).toBeCloseTo(source.height(i * 2, k * 2), 9);+ // Halfway along the cut from (1, 0) to (0, 1) is the mean of those two corners, not of all four.+ const b = surface.node(4, 3)!, c = surface.node(3, 4)!;+ expect(surface.height(7, 7)).toBeCloseTo((b + c) / 2, 9);+ });++ it('is cut the way the drawn patch is, and its nodes are the drawn finest page\'s vertices', () => {+ const tile = surface.tile(0, 0)!;+ expect(Array.from(tile.indices)).toEqual(Array.from(buildPatchMesh(TILE_CELLS).indices));+ expect(TILE_CELLS).toBe(PATCH_CELLS);+ // A level-0 node is a patch of `cellSize` cells; its vertices read every second sample of its page.+ const page = makePage(new NoiseSource(params), 0, 0, PATCH_CELLS * 2) as PageImage;+ const span = params.height;+ for (const [i, k] of [[0, 0], [5, 9], [32, 32]] as const) {+ const at = ((1 + 2 * k) * PAGE_SIDE + 1 + 2 * i) * 4;+ const drawn = (page.heights[at]! * 256 + page.heights[at + 1]!) / 65535 * span;+ expect(Math.abs(drawn - surface.node(i, k)!)).toBeLessThanOrEqual(span / 65535);+ }+ expect(PAGE_TEXELS).toBe(PATCH_CELLS * 2);+ });++ it('faces the way its triangle does', () => {+ const n = surface.normal(7.2, 6.1)!;+ const h = (x: number, z: number) => surface.height(x, z)!;+ const e = 0.01;+ const sx = (h(7.2 + e, 6.1) - h(7.2 - e, 6.1)) / (2 * e), sz = (h(7.2, 6.1 + e) - h(7.2, 6.1 - e)) / (2 * e);+ const len = Math.hypot(sx, 1, sz);+ expect(n[0]).toBeCloseTo(-sx / len, 6);+ expect(n[1]).toBeCloseTo(1 / len, 6);+ expect(n[2]).toBeCloseTo(-sz / len, 6);+ });+});++describe('collision tiles', () => {+ const boot = (): App => {+ setDefaultContext(new AppContext());+ setEditorMode(false);+ setPlayMode(false);+ const app = App.new();+ const module = createMockModule();+ app.connectCpp(module.getRegistry(), module);+ app.addPlugin(new TerrainPlugin());+ return app;+ };+ // The mock engine composes no transforms: an entity without a parent is given its world pose as well.+ const placed = (x: number, y: number, z: number) => ({ position: { x, y, z }, worldPosition: { x, y, z } });+ const tick = async (app: App, n = 1) => { for (let i = 0; i < n; i++) { app.tick(1 / 60); await new Promise((r) => setTimeout(r, 0)); } };+ const spawn = (app: App, over: Record<string, unknown> = {}, at = { x: 0, y: 0, z: 0 }): Entity => {+ const e = app.world.spawn();+ app.world.insert(e, Transform, placed(at.x, at.y, at.z));+ app.world.insert(e, Terrain, terrainOf(over));+ return e;+ };+ const mover = (app: App, x: number, z: number): Entity => {+ const e = app.world.spawn();+ app.world.insert(e, Transform, placed(x, 50, z));+ app.world.insert(e, RigidBody3D, { bodyType: 2 });+ return e;+ };+ const pieces = (app: App) => [...app.getResource(CollisionGeometryRes).entries()];++ it('are built round what moves, agree with heightAt everywhere on them, and go when it does', async () => {+ const app = boot();+ const terrain = spawn(app, {}, { x: 10, y: -5, z: 3 });+ await tick(app);+ expect(pieces(app)).toHaveLength(0);+ const body = mover(app, 100, -40);+ await tick(app, 10);+ const terrains = app.getResource(TerrainsRes);+ expect(terrains.collisionReadyAt(100, -40)).toBe(true);+ const built = pieces(app);+ expect(built.length).toBeGreaterThan(1);+ for (const [, piece] of built) {+ expect(piece.owner).toBe(terrain);+ for (let s = 0; s < 20; s++) {+ const x = piece.origin[0] + ((s * 37) % 64) + 0.31, z = piece.origin[2] + ((s * 53) % 64) + 0.77;+ expect(onPiece(piece, x, z)!).toBeCloseTo(terrains.heightAt(x, z)!, 4);+ }+ }+ app.world.insert(body, Transform, placed(5000, 50, -40));+ await tick(app, 10);+ expect(terrains.collisionReadyAt(100, -40)).toBe(false);+ app.world.despawn(body);+ await tick(app);+ expect(pieces(app)).toHaveLength(0);+ });++ it('keep the old ground under what stands on it until the new ground is built, and go with the terrain', async () => {+ const app = boot();+ const terrain = spawn(app);+ mover(app, 0, 0);+ await tick(app, 10);+ const before = new Map(pieces(app));+ app.world.insert(terrain, Terrain, terrainOf({ seed: 99 }));+ app.tick(1 / 60);+ // Never a frame with nothing under the body.+ expect(app.getResource(TerrainsRes).collisionReadyAt(0, 0) || pieces(app).length >= before.size).toBe(true);+ await tick(app, 10);+ const after = new Map(pieces(app));+ expect([...after.keys()].sort()).toEqual([...before.keys()].sort());+ for (const [key, piece] of after) expect(piece).not.toBe(before.get(key));+ app.world.insert(terrain, Terrain, terrainOf({ seed: 99, collision: false }));+ await tick(app);+ expect(pieces(app)).toHaveLength(0);+ app.world.insert(terrain, Terrain, terrainOf({ seed: 99 }));+ await tick(app, 10);+ expect(pieces(app).length).toBeGreaterThan(0);+ app.world.despawn(terrain);+ await tick(app);+ expect(pieces(app)).toHaveLength(0);+ });++ it('cover an area only where it is, including its last partial tile', async () => {+ const app = boot();+ spawn(app, { extent: TerrainExtent.Area, sizeX: 100, sizeZ: 100, resolution: 65 });+ mover(app, 49, 49);+ await tick(app, 20);+ const terrains = app.getResource(TerrainsRes);+ expect(terrains.collisionReadyAt(49.5, 49.5)).toBe(true);+ expect(terrains.heightAt(51, 0)).toBeNull();+ for (const [, piece] of pieces(app)) expect(piece.origin[0]).toBeLessThan(50);+ });+});++let engine: ESEngineModule;+const apps: App[] = [];+afterEach(() => { for (const app of apps.splice(0)) app.quit(); });++describe.skipIf(!HAS_WASM || !hasSideModule('physics3d'))('the ground in the 3D world (Jolt)', () => {+ beforeAll(async () => { engine = await loadWasmModule(); });++ const world = async () => {+ engine.setActiveContext(null);+ const app = App.new(); apps.push(app);+ app.connectCpp(new engine.Registry(), engine, { ownedRegistry: true });+ const module = await loadSideModule<Physics3DWasmModule>('physics3d');+ app.addPlugin(new Physics3DPlugin('', { pixelsPerUnit: 1 }, async () => module));+ await app.getResource(Physics3DRuntime).initPromise;+ app.addPlugin(new TerrainPlugin());+ const terrain = app.world.spawn();+ app.world.insert(terrain, Transform, { position: { x: 0, y: 0, z: 0 } });+ app.world.insert(terrain, Terrain, terrainOf());+ return { app, terrain };+ };++ it('a ray down meets the ground heightAt answers, across tile seams', async () => {+ const { app, terrain } = await world();+ const e = app.world.spawn();+ app.world.insert(e, Transform, { position: { x: 64, y: 80, z: 64 } });+ app.world.insert(e, RigidBody3D, { bodyType: 1 });+ await app.stepFrames(6, 1 / 60);+ const physics = app.getResource(Physics3D)!, terrains = app.getResource(TerrainsRes);+ for (const [x, z] of [[64, 64], [63.99, 64.01], [70.3, 41.7], [100.5, 90.25], [128, 127.5]] as const) {+ const hit = physics.raycast({ x, y: 200, z }, { x: 0, y: -400, z: 0 });+ expect(hit?.entity).toBe(terrain);+ expect(hit!.y).toBeCloseTo(terrains.heightAt(x, z)!, 3);+ }+ });++ it('a ball dropped on it comes to rest on it, not through it', async () => {+ const { app } = await world();+ const terrains = app.getResource(TerrainsRes);+ await app.stepFrames(1, 1 / 60);+ const ball = app.world.spawn();+ const ground = terrains.heightAt(20, 20)!;+ app.world.insert(ball, Transform, { position: { x: 20, y: ground + 3, z: 20 } });+ app.world.insert(ball, RigidBody3D, { bodyType: 2, linearDamping: 2, angularDamping: 2 });+ app.world.insert(ball, SphereCollider3D, { radius: 0.5 });+ await app.stepFrames(180, 1 / 60);+ const p = (app.world.get(ball, Transform) as TransformData).worldPosition;+ const under = terrains.heightAt(p.x, p.z)!;+ expect(p.y).toBeGreaterThan(under + 0.3);+ expect(p.y).toBeLessThan(under + 1.2);+ });+});diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex e19244756..bb322baa8 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -2764,4 +2764,6 @@ export const NOTED = {{"internal":"A planning document; nothing a creator can use yet."},"feat(terrain): ground without end comes from a versioned provider the game names, and a terrain that cannot get its ground fails":{"note":"Terrain from a generator the game names, versioned."},+ "feat(terrain): bodies collide with the ground drawn near the eye, built in tiles round what moves, and queries answer from the same triangles":+ {"note":"Terrain collision, the same ground that is drawn."},};