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(foliage): a plant can have a third mesh, and the trees of Terrain & Water do

yhh87d27e82c000
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 43437fb8d..372737b40 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,6 +16,7 @@ published separately; it ships inside the editor.
### Added
+- **A third mesh for a plant.** A part of a world's plants can name `lod2Mesh` and its kind `lod2Distance`: past that distance the third mesh stands in for the cheaper one, until the kind stops being drawn as itself. The Terrain & Water example's trees have one (a tenth of the triangles, made by `tools/plant-lod2.mjs`) from 80 m, which takes 9 to 15 ms off a frame on an RTX 3060 where trees stand between 60 and 170 m. `tools/terrain-water-cost.mjs` measures what each part of that example costs a frame headless, and `docs/TERRAIN_WATER_GPU_COST.md` has the numbers.
- **A generated world on worker threads.** A planet provider can give the engine its generator as `workerSource` (the text of a self-contained module), and the world's placements and the planet's pages (heights, normals, and the paint by the biomes) are then worked out by a pool of workers (`runtime/jobs.ts`), byte for byte what the main thread works out, while the main thread only puts each answer in the world as it arrives. Laying out a planet's world no longer costs the frame: 2 to 8 frames a second while it was laid out became 60.
- **A flat world's generation on worker threads too.** Laying out a `WorldGen` over a `Terrain` (a field or noise ground, with its baked water) is worked out by the same pool of workers, from the ground and the water handed over as data, byte for byte what the main thread works out. Stopping the terrain-water example no longer leaves the editor at 2 frames a second: it is back at 60.
- **A planet's sea and sky.** `Planet.sea` draws a translucent, lit sphere at `seaLevel` in which the ground that dips below it stands, and `skyAtmosphere` takes the planet's radius and centre (`u_planetRadius`, `u_planetX/Y/Z`, as `heightFog` does) to work the sky out in the frame of the ground the camera stands on, so the horizon, the sun and the haze follow it round.
diff --git a/docs/TERRAIN_WATER_GPU_COST.md b/docs/TERRAIN_WATER_GPU_COST.md
index 0639c769a..505df9284 100644
--- a/docs/TERRAIN_WATER_GPU_COST.md
+++ b/docs/TERRAIN_WATER_GPU_COST.md
@@ -61,3 +61,38 @@
- WebGPU 没量;一块显卡,一个分辨率。
- 在“湖与河口”机位拿掉水体,页面崩溃(`Target crashed`),重试同样崩;默认机位的同一变体第一次跑也崩过一次,重跑正常。没有查原因。
- `tools/terrain-water-cost.mjs` 把导出目录里的场景与配置改写后在退出时还原;原始数据在 `output/perf/`(被忽略,不入库)。
+
+## 植物(2026-10-25 第二轮)
+
+按层与按部件拿掉植物,默认机位:
+
+| 变体 | 每帧 ms | 三角形 |
+|---|---|---|
+| 原样 | 43.1 | 1.89 M |
+| 去掉 `groves` 层(树) | 28.9 | 0.45 M |
+| 去掉 `cover`、`drifts`、`reeds`、`banks`、`stones`、`sea`、`shoals` 任一层 | 都在噪声内(±3) | |
+| 植物不投影 | 不变,阴影绘制 432 → 2 | |
+| 树只画远景卡片 | 28.2 | 0.49 M |
+| 树 95 米外就换成卡片(原 380 米) | 32.2 | 0.59 M |
+| 树的 lod1 提前到四分之一的距离 | 44.4(不变) | 1.89 M |
+
+- **植物的成本几乎全在树**:一个层(`groves`)占 14 到 18 ms,其余七个层加起来在噪声里。花海机位里树占 45 ms 以上。
+- **植物投影本身不花钱**。阴影的 12 到 38 ms 是接收端:每个像素的着色都在采样级联。
+- **树在 60 到 170 米之间最贵**:art 给的 lod1 只有 lod0 的一半三角形(一棵橡树约 2 万,每块叶片卡片是独立的小四边形),从 60 米起就是约 1 万三角形盖几百个像素,而卡片要到 380 米才接手;层又只在 170 米内长出树本身。把 lod1 提前没有用(上表最后一行),缺的是 lod1 和卡片之间的一级。
+- 管线的 `meshSimplify` 带 `LockBorder`,叶片卡片合不拢(橡树叶片部件锁边后一个三角形也减不掉);不锁边、带 `Sparse` 才能降到十分之一。
+
+**做了什么:**每个部件可以有第三个网格 `lod2Mesh`,种类有 `lod2Distance`,到了这个距离换用它。树各有一份(约原来的十分之一:橡树两个部件 1588 与 2182 个三角形),`examples/terrain-water/tools/plant-lod2.mjs` 生成,换用距离 80 米(`lod` 为 60 米)。不动引擎:两组实例各画自己的距离段(`MeshInstances` 的 `minDistance` / `drawDistance`),所以两段交界处,中心距离在交界上下一个树冠半径之内的树两个网格都画。
+
+同一次运行里 A/B(有第三个网格 vs `trees-no-lod2`,每个机位各量两次取平均):
+
+| 机位 | 之前 ms | 之后 ms | 差 | 三角形 |
+|---|---|---|---|---|
+| 默认 | 43.4 | 34.8 | −8.6 | 1.89 → 0.88 M |
+| 花海 | 102.7 | 87.9 | −14.8 | 2.81 → 2.20 M |
+| 湖边 | 84.9 | 70.8 | −14.1 | 2.49 → 1.86 M |
+| 湖与河口 | 75.3 | 66.6 | −8.7 | 2.57 → 1.74 M |
+| 沿河 | 54.1 | 54.4 | +0.4 | 0.94 → 0.95 M |
+
+(这一轮机器比第一轮热,绝对值偏高;只看同一轮里的差。)四个机位的截图对比看不出差别,远处山脊上的松树从网格换成了卡片的位置略有不同。
+
+**还剩的:**花海里只把树换成卡片,帧就从 88 降到 40 ms,所以近处(60 米内)的树仍是最大的一块。把 lod1 提前到 40 米、lod2 提前到 80 米,花海再省约 8 到 13 ms,但近处树冠明显变疏;这是画面取舍,没有改。
diff --git a/examples/terrain-water/assets/plants/models/tree-beech-dense/lod2/tree-beech-dense_0_0.esmesh b/examples/terrain-water/assets/plants/models/tree-beech-dense/lod2/tree-beech-dense_0_0.esmesh
new file mode 100644
index 000000000..e5b45b3f6
Binary files /dev/null and b/examples/terrain-water/assets/plants/models/tree-beech-dense/lod2/tree-beech-dense_0_0.esmesh differ
diff --git a/examples/terrain-water/assets/plants/models/tree-beech-dense/lod2/tree-beech-dense_0_0.esmesh.meta b/examples/terrain-water/assets/plants/models/tree-beech-dense/lod2/tree-beech-dense_0_0.esmesh.meta
new file mode 100644
index 000000000..f7d66cf93
--- /dev/null
+++ b/examples/terrain-water/assets/plants/models/tree-beech-dense/lod2/tree-beech-dense_0_0.esmesh.meta
@@ -0,0 +1,6 @@
+{
+ "uuid": "f334fc05-006e-49a8-9529-6b2a42c9169d",
+ "version": "2.0",
+ "type": "mesh",
+ "importer": {}
+}
diff --git a/examples/terrain-water/assets/plants/models/tree-beech-dense/lod2/tree-beech-dense_0_1.esmesh b/examples/terrain-water/assets/plants/models/tree-beech-dense/lod2/tree-beech-dense_0_1.esmesh
new file mode 100644
index 000000000..0906e88ee
Binary files /dev/null and b/examples/terrain-water/assets/plants/models/tree-beech-dense/lod2/tree-beech-dense_0_1.esmesh differ
diff --git a/examples/terrain-water/assets/plants/models/tree-beech-dense/lod2/tree-beech-dense_0_1.esmesh.meta b/examples/terrain-water/assets/plants/models/tree-beech-dense/lod2/tree-beech-dense_0_1.esmesh.meta
new file mode 100644
index 000000000..adbca62c1
--- /dev/null
+++ b/examples/terrain-water/assets/plants/models/tree-beech-dense/lod2/tree-beech-dense_0_1.esmesh.meta
@@ -0,0 +1,6 @@
+{
+ "uuid": "13db9e38-1d7e-43c7-b96a-145cccc7e616",
+ "version": "2.0",
+ "type": "mesh",
+ "importer": {}
+}
diff --git a/examples/terrain-water/assets/plants/models/tree-birch/lod2/tree-birch_0_0.esmesh b/examples/terrain-water/assets/plants/models/tree-birch/lod2/tree-birch_0_0.esmesh
new file mode 100644
index 000000000..6cd15000c
Binary files /dev/null and b/examples/terrain-water/assets/plants/models/tree-birch/lod2/tree-birch_0_0.esmesh differ
diff --git a/examples/terrain-water/assets/plants/models/tree-birch/lod2/tree-birch_0_0.esmesh.meta b/examples/terrain-water/assets/plants/models/tree-birch/lod2/tree-birch_0_0.esmesh.meta
new file mode 100644
index 000000000..7711fdd48
--- /dev/null
+++ b/examples/terrain-water/assets/plants/models/tree-birch/lod2/tree-birch_0_0.esmesh.meta
@@ -0,0 +1,6 @@
+{
+ "uuid": "f587cbd6-5b96-43f4-b657-f937dc3fc0c2",
+ "version": "2.0",
+ "type": "mesh",
+ "importer": {}
+}
diff --git a/examples/terrain-water/assets/plants/models/tree-birch/lod2/tree-birch_0_1.esmesh b/examples/terrain-water/assets/plants/models/tree-birch/lod2/tree-birch_0_1.esmesh
new file mode 100644
index 000000000..3e0652848
Binary files /dev/null and b/examples/terrain-water/assets/plants/models/tree-birch/lod2/tree-birch_0_1.esmesh differ
diff --git a/examples/terrain-water/assets/plants/models/tree-birch/lod2/tree-birch_0_1.esmesh.meta b/examples/terrain-water/assets/plants/models/tree-birch/lod2/tree-birch_0_1.esmesh.meta
new file mode 100644
index 000000000..7cecbb2cc
--- /dev/null
+++ b/examples/terrain-water/assets/plants/models/tree-birch/lod2/tree-birch_0_1.esmesh.meta
@@ -0,0 +1,6 @@
+{
+ "uuid": "5784c42d-90e9-4946-bbbb-1d19659066d3",
+ "version": "2.0",
+ "type": "mesh",
+ "importer": {}
+}
diff --git a/examples/terrain-water/assets/plants/models/tree-oak-dense/lod2/tree-oak-dense_0_0.esmesh b/examples/terrain-water/assets/plants/models/tree-oak-dense/lod2/tree-oak-dense_0_0.esmesh
new file mode 100644
index 000000000..0c4fb411e
Binary files /dev/null and b/examples/terrain-water/assets/plants/models/tree-oak-dense/lod2/tree-oak-dense_0_0.esmesh differ
diff --git a/examples/terrain-water/assets/plants/models/tree-oak-dense/lod2/tree-oak-dense_0_0.esmesh.meta b/examples/terrain-water/assets/plants/models/tree-oak-dense/lod2/tree-oak-dense_0_0.esmesh.meta
new file mode 100644
index 000000000..e6b0e1b05
--- /dev/null
+++ b/examples/terrain-water/assets/plants/models/tree-oak-dense/lod2/tree-oak-dense_0_0.esmesh.meta
@@ -0,0 +1,6 @@
+{
+ "uuid": "ab6003fa-fba5-462c-bbe3-7f62099748b5",
+ "version": "2.0",
+ "type": "mesh",
+ "importer": {}
+}
diff --git a/examples/terrain-water/assets/plants/models/tree-oak-dense/lod2/tree-oak-dense_0_1.esmesh b/examples/terrain-water/assets/plants/models/tree-oak-dense/lod2/tree-oak-dense_0_1.esmesh
new file mode 100644
index 000000000..e1ba91118
Binary files /dev/null and b/examples/terrain-water/assets/plants/models/tree-oak-dense/lod2/tree-oak-dense_0_1.esmesh differ
diff --git a/examples/terrain-water/assets/plants/models/tree-oak-dense/lod2/tree-oak-dense_0_1.esmesh.meta b/examples/terrain-water/assets/plants/models/tree-oak-dense/lod2/tree-oak-dense_0_1.esmesh.meta
new file mode 100644
index 000000000..bfead26f3
--- /dev/null
+++ b/examples/terrain-water/assets/plants/models/tree-oak-dense/lod2/tree-oak-dense_0_1.esmesh.meta
@@ -0,0 +1,6 @@
+{
+ "uuid": "b31a84a9-daee-4ae7-957d-b6b5657e9a24",
+ "version": "2.0",
+ "type": "mesh",
+ "importer": {}
+}
diff --git a/examples/terrain-water/assets/plants/models/tree-pine-lakeside/lod2/tree-pine-lakeside_0_0.esmesh b/examples/terrain-water/assets/plants/models/tree-pine-lakeside/lod2/tree-pine-lakeside_0_0.esmesh
new file mode 100644
index 000000000..636104f43
Binary files /dev/null and b/examples/terrain-water/assets/plants/models/tree-pine-lakeside/lod2/tree-pine-lakeside_0_0.esmesh differ
diff --git a/examples/terrain-water/assets/plants/models/tree-pine-lakeside/lod2/tree-pine-lakeside_0_0.esmesh.meta b/examples/terrain-water/assets/plants/models/tree-pine-lakeside/lod2/tree-pine-lakeside_0_0.esmesh.meta
new file mode 100644
index 000000000..62762b6f0
--- /dev/null
+++ b/examples/terrain-water/assets/plants/models/tree-pine-lakeside/lod2/tree-pine-lakeside_0_0.esmesh.meta
@@ -0,0 +1,6 @@
+{
+ "uuid": "2205d229-befd-4826-9bb2-e2303fbf5b67",
+ "version": "2.0",
+ "type": "mesh",
+ "importer": {}
+}
diff --git a/examples/terrain-water/assets/plants/models/tree-pine-lakeside/lod2/tree-pine-lakeside_0_1.esmesh b/examples/terrain-water/assets/plants/models/tree-pine-lakeside/lod2/tree-pine-lakeside_0_1.esmesh
new file mode 100644
index 000000000..7bb2cb3e6
Binary files /dev/null and b/examples/terrain-water/assets/plants/models/tree-pine-lakeside/lod2/tree-pine-lakeside_0_1.esmesh differ
diff --git a/examples/terrain-water/assets/plants/models/tree-pine-lakeside/lod2/tree-pine-lakeside_0_1.esmesh.meta b/examples/terrain-water/assets/plants/models/tree-pine-lakeside/lod2/tree-pine-lakeside_0_1.esmesh.meta
new file mode 100644
index 000000000..edc348d0c
--- /dev/null
+++ b/examples/terrain-water/assets/plants/models/tree-pine-lakeside/lod2/tree-pine-lakeside_0_1.esmesh.meta
@@ -0,0 +1,6 @@
+{
+ "uuid": "1fafb7aa-6f15-4033-97d5-2e69081d419e",
+ "version": "2.0",
+ "type": "mesh",
+ "importer": {}
+}
diff --git a/examples/terrain-water/assets/plants/models/tree-pine-ridge/lod2/tree-pine-ridge_0_0.esmesh b/examples/terrain-water/assets/plants/models/tree-pine-ridge/lod2/tree-pine-ridge_0_0.esmesh
new file mode 100644
index 000000000..efe480c9c
Binary files /dev/null and b/examples/terrain-water/assets/plants/models/tree-pine-ridge/lod2/tree-pine-ridge_0_0.esmesh differ
diff --git a/examples/terrain-water/assets/plants/models/tree-pine-ridge/lod2/tree-pine-ridge_0_0.esmesh.meta b/examples/terrain-water/assets/plants/models/tree-pine-ridge/lod2/tree-pine-ridge_0_0.esmesh.meta
new file mode 100644
index 000000000..9df2771d5
--- /dev/null
+++ b/examples/terrain-water/assets/plants/models/tree-pine-ridge/lod2/tree-pine-ridge_0_0.esmesh.meta
@@ -0,0 +1,6 @@
+{
+ "uuid": "f4dfcda6-c9df-4e94-aa8b-65810e485394",
+ "version": "2.0",
+ "type": "mesh",
+ "importer": {}
+}
diff --git a/examples/terrain-water/assets/plants/models/tree-pine-ridge/lod2/tree-pine-ridge_0_1.esmesh b/examples/terrain-water/assets/plants/models/tree-pine-ridge/lod2/tree-pine-ridge_0_1.esmesh
new file mode 100644
index 000000000..2104ad592
Binary files /dev/null and b/examples/terrain-water/assets/plants/models/tree-pine-ridge/lod2/tree-pine-ridge_0_1.esmesh differ
diff --git a/examples/terrain-water/assets/plants/models/tree-pine-ridge/lod2/tree-pine-ridge_0_1.esmesh.meta b/examples/terrain-water/assets/plants/models/tree-pine-ridge/lod2/tree-pine-ridge_0_1.esmesh.meta
new file mode 100644
index 000000000..870a9850a
--- /dev/null
+++ b/examples/terrain-water/assets/plants/models/tree-pine-ridge/lod2/tree-pine-ridge_0_1.esmesh.meta
@@ -0,0 +1,6 @@
+{
+ "uuid": "d2b78e81-1dfb-4e97-bde6-2a8c969971b7",
+ "version": "2.0",
+ "type": "mesh",
+ "importer": {}
+}
diff --git a/examples/terrain-water/assets/plants/models/tree-willow/lod2/tree-willow_0_0.esmesh b/examples/terrain-water/assets/plants/models/tree-willow/lod2/tree-willow_0_0.esmesh
new file mode 100644
index 000000000..3d6b3274c
Binary files /dev/null and b/examples/terrain-water/assets/plants/models/tree-willow/lod2/tree-willow_0_0.esmesh differ
diff --git a/examples/terrain-water/assets/plants/models/tree-willow/lod2/tree-willow_0_0.esmesh.meta b/examples/terrain-water/assets/plants/models/tree-willow/lod2/tree-willow_0_0.esmesh.meta
new file mode 100644
index 000000000..654bb6879
--- /dev/null
+++ b/examples/terrain-water/assets/plants/models/tree-willow/lod2/tree-willow_0_0.esmesh.meta
@@ -0,0 +1,6 @@
+{
+ "uuid": "5c3581f0-3ea9-46e0-be23-9ee017f269df",
+ "version": "2.0",
+ "type": "mesh",
+ "importer": {}
+}
diff --git a/examples/terrain-water/assets/plants/models/tree-willow/lod2/tree-willow_0_1.esmesh b/examples/terrain-water/assets/plants/models/tree-willow/lod2/tree-willow_0_1.esmesh
new file mode 100644
index 000000000..16537d57a
Binary files /dev/null and b/examples/terrain-water/assets/plants/models/tree-willow/lod2/tree-willow_0_1.esmesh differ
diff --git a/examples/terrain-water/assets/plants/models/tree-willow/lod2/tree-willow_0_1.esmesh.meta b/examples/terrain-water/assets/plants/models/tree-willow/lod2/tree-willow_0_1.esmesh.meta
new file mode 100644
index 000000000..28825a2bc
--- /dev/null
+++ b/examples/terrain-water/assets/plants/models/tree-willow/lod2/tree-willow_0_1.esmesh.meta
@@ -0,0 +1,6 @@
+{
+ "uuid": "6ca4d37e-7a96-4284-bb88-02507435a579",
+ "version": "2.0",
+ "type": "mesh",
+ "importer": {}
+}
diff --git a/examples/terrain-water/assets/worlds/plants.esworld b/examples/terrain-water/assets/worlds/plants.esworld
index a8b4410f2..225f4d3d4 100644
--- a/examples/terrain-water/assets/worlds/plants.esworld
+++ b/examples/terrain-water/assets/worlds/plants.esworld
@@ -31,6 +31,7 @@
{
"mesh": "assets/plants/models/tree-oak-dense/tree-oak-dense_0_0.esmesh",
"lod1Mesh": "assets/plants/models/tree-oak-dense/lod1/tree-oak-dense_0_0.esmesh",
+ "lod2Mesh": "assets/plants/models/tree-oak-dense/lod2/tree-oak-dense_0_0.esmesh",
"material": "assets/plants/models/tree-oak-dense/tree-oak-dense_m0.esmaterial",
"texture": "assets/plants/textures/06df0060cfc9.png",
"tint": [
@@ -44,6 +45,7 @@
{
"mesh": "assets/plants/models/tree-oak-dense/tree-oak-dense_0_1.esmesh",
"lod1Mesh": "assets/plants/models/tree-oak-dense/lod1/tree-oak-dense_0_1.esmesh",
+ "lod2Mesh": "assets/plants/models/tree-oak-dense/lod2/tree-oak-dense_0_1.esmesh",
"material": "assets/plants/models/tree-oak-dense/tree-oak-dense_m1.esmaterial",
"texture": "assets/plants/textures/938bddcdab05.png",
"tint": [
@@ -56,6 +58,7 @@
}
],
"lodDistance": 6000,
+ "lod2Distance": 8000,
"drawDistance": 38000,
"far": [
{
@@ -99,6 +102,7 @@
{
"mesh": "assets/plants/models/tree-beech-dense/tree-beech-dense_0_0.esmesh",
"lod1Mesh": "assets/plants/models/tree-beech-dense/lod1/tree-beech-dense_0_0.esmesh",
+ "lod2Mesh": "assets/plants/models/tree-beech-dense/lod2/tree-beech-dense_0_0.esmesh",
"material": "assets/plants/models/tree-beech-dense/tree-beech-dense_m0.esmaterial",
"texture": "assets/plants/textures/06df0060cfc9.png",
"tint": [
@@ -112,6 +116,7 @@
{
"mesh": "assets/plants/models/tree-beech-dense/tree-beech-dense_0_1.esmesh",
"lod1Mesh": "assets/plants/models/tree-beech-dense/lod1/tree-beech-dense_0_1.esmesh",
+ "lod2Mesh": "assets/plants/models/tree-beech-dense/lod2/tree-beech-dense_0_1.esmesh",
"material": "assets/plants/models/tree-beech-dense/tree-beech-dense_m1.esmaterial",
"texture": "assets/plants/textures/938bddcdab05.png",
"tint": [
@@ -124,6 +129,7 @@
}
],
"lodDistance": 6000,
+ "lod2Distance": 8000,
"drawDistance": 38000,
"far": [
{
@@ -167,6 +173,7 @@
{
"mesh": "assets/plants/models/tree-birch/tree-birch_0_0.esmesh",
"lod1Mesh": "assets/plants/models/tree-birch/lod1/tree-birch_0_0.esmesh",
+ "lod2Mesh": "assets/plants/models/tree-birch/lod2/tree-birch_0_0.esmesh",
"material": "assets/plants/models/tree-birch/tree-birch_m0.esmaterial",
"texture": "assets/plants/textures/6ac5a795fda4.png",
"tint": [
@@ -180,6 +187,7 @@
{
"mesh": "assets/plants/models/tree-birch/tree-birch_0_1.esmesh",
"lod1Mesh": "assets/plants/models/tree-birch/lod1/tree-birch_0_1.esmesh",
+ "lod2Mesh": "assets/plants/models/tree-birch/lod2/tree-birch_0_1.esmesh",
"material": "assets/plants/models/tree-birch/tree-birch_m1.esmaterial",
"texture": "assets/plants/textures/938bddcdab05.png",
"tint": [
@@ -192,6 +200,7 @@
}
],
"lodDistance": 6000,
+ "lod2Distance": 8000,
"drawDistance": 38000,
"far": [
{
@@ -235,6 +244,7 @@
{
"mesh": "assets/plants/models/tree-willow/tree-willow_0_0.esmesh",
"lod1Mesh": "assets/plants/models/tree-willow/lod1/tree-willow_0_0.esmesh",
+ "lod2Mesh": "assets/plants/models/tree-willow/lod2/tree-willow_0_0.esmesh",
"material": "assets/plants/models/tree-willow/tree-willow_m0.esmaterial",
"texture": "assets/plants/textures/06df0060cfc9.png",
"tint": [
@@ -248,6 +258,7 @@
{
"mesh": "assets/plants/models/tree-willow/tree-willow_0_1.esmesh",
"lod1Mesh": "assets/plants/models/tree-willow/lod1/tree-willow_0_1.esmesh",
+ "lod2Mesh": "assets/plants/models/tree-willow/lod2/tree-willow_0_1.esmesh",
"material": "assets/plants/models/tree-willow/tree-willow_m1.esmaterial",
"texture": "assets/plants/textures/938bddcdab05.png",
"tint": [
@@ -260,6 +271,7 @@
}
],
"lodDistance": 6000,
+ "lod2Distance": 8000,
"drawDistance": 38000,
"far": [
{
@@ -303,6 +315,7 @@
{
"mesh": "assets/plants/models/tree-pine-ridge/tree-pine-ridge_0_0.esmesh",
"lod1Mesh": "assets/plants/models/tree-pine-ridge/lod1/tree-pine-ridge_0_0.esmesh",
+ "lod2Mesh": "assets/plants/models/tree-pine-ridge/lod2/tree-pine-ridge_0_0.esmesh",
"material": "assets/plants/models/tree-pine-ridge/tree-pine-ridge_m0.esmaterial",
"texture": "assets/plants/textures/06df0060cfc9.png",
"tint": [
@@ -316,6 +329,7 @@
{
"mesh": "assets/plants/models/tree-pine-ridge/tree-pine-ridge_0_1.esmesh",
"lod1Mesh": "assets/plants/models/tree-pine-ridge/lod1/tree-pine-ridge_0_1.esmesh",
+ "lod2Mesh": "assets/plants/models/tree-pine-ridge/lod2/tree-pine-ridge_0_1.esmesh",
"material": "assets/plants/models/tree-pine-ridge/tree-pine-ridge_m1.esmaterial",
"texture": "assets/plants/textures/d06a9a16a81d.png",
"tint": [
@@ -328,6 +342,7 @@
}
],
"lodDistance": 6000,
+ "lod2Distance": 8000,
"drawDistance": 38000,
"far": [
{
@@ -371,6 +386,7 @@
{
"mesh": "assets/plants/models/tree-pine-lakeside/tree-pine-lakeside_0_0.esmesh",
"lod1Mesh": "assets/plants/models/tree-pine-lakeside/lod1/tree-pine-lakeside_0_0.esmesh",
+ "lod2Mesh": "assets/plants/models/tree-pine-lakeside/lod2/tree-pine-lakeside_0_0.esmesh",
"material": "assets/plants/models/tree-pine-lakeside/tree-pine-lakeside_m0.esmaterial",
"texture": "assets/plants/textures/06df0060cfc9.png",
"tint": [
@@ -384,6 +400,7 @@
{
"mesh": "assets/plants/models/tree-pine-lakeside/tree-pine-lakeside_0_1.esmesh",
"lod1Mesh": "assets/plants/models/tree-pine-lakeside/lod1/tree-pine-lakeside_0_1.esmesh",
+ "lod2Mesh": "assets/plants/models/tree-pine-lakeside/lod2/tree-pine-lakeside_0_1.esmesh",
"material": "assets/plants/models/tree-pine-lakeside/tree-pine-lakeside_m1.esmaterial",
"texture": "assets/plants/textures/d06a9a16a81d.png",
"tint": [
@@ -396,6 +413,7 @@
}
],
"lodDistance": 6000,
+ "lod2Distance": 8000,
"drawDistance": 38000,
"far": [
{
diff --git a/examples/terrain-water/tools/plant-lod2.mjs b/examples/terrain-water/tools/plant-lod2.mjs
new file mode 100644
index 000000000..1cc854431
--- /dev/null
+++ b/examples/terrain-water/tools/plant-lod2.mjs
@@ -0,0 +1,82 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file plant-lod2.mjs — the third mesh of the trees: a tenth of the first, for the stretch between the art's cheaper mesh and the far cards.
+ *
+ * The art ships a mesh and a cheaper one at about half its triangles, then crossed cards. Between 60 m and where the cards take over a tree is the
+ * cheaper mesh, ten thousand triangles that cover a few hundred pixels: the GPU spends its time on triangles smaller than a pixel. A leaf crown is
+ * many separate cards, which the pipeline's border-locked collapse (meshSimplify.ts) cannot merge, so this collapses with the borders free and
+ * keeps the normal and the UV as attributes, from the full mesh, never from a cheaper one.
+ *
+ * node examples/terrain-water/tools/plant-lod2.mjs [--ratio 0.1] [--error 0.1]
+ */
+import { readFileSync, writeFileSync, mkdirSync, existsSync } from 'node:fs';
+import { createRequire } from 'node:module';
+import { randomUUID } from 'node:crypto';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..', '..');
+const PROJECT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+const { MeshoptSimplifier } = createRequire(path.join(ROOT, 'pipeline/package.json'))('meshoptimizer');
+const { decodeMesh, encodeMesh, MeshChannel, MeshChannelType } = await import(`file:///${path.join(ROOT, 'sdk/dist/index.js').replace(/\\/g, '/')}`);
+
+const argv = process.argv.slice(2);
+const flag = (n, d) => { const i = argv.indexOf(`--${n}`); return i >= 0 ? Number(argv[i + 1]) : d; };
+const RATIO = flag('ratio', 0.1);
+const ERROR = flag('error', 0.1);
+
+/** The prefabs that get a third mesh: the trees. The crowns past the cheaper mesh are what a wood costs. */
+export const LOD2_PREFABS = ['tree-oak-dense', 'tree-beech-dense', 'tree-birch', 'tree-willow', 'tree-pine-ridge', 'tree-pine-lakeside'];
+
+/** The meshes a prefab's renderers name, in order. */
+const meshesOf = (file) => JSON.parse(readFileSync(file, 'utf8')).entities
+ .flatMap((e) => e.components.filter((c) => c.type === 'MeshRenderer').map((c) => c.data.mesh));
+
+const NORMAL_WEIGHT = 0.5, UV_WEIGHT = 1;
+
+function collapse(data) {
+ const channel = (semantic, components) => data.channels.find((c) => c.semantic === semantic && c.components >= components && c.type === MeshChannelType.Float32);
+ const position = channel(MeshChannel.Position, 3), normal = channel(MeshChannel.Normal, 3), uv = channel(MeshChannel.TexCoord0, 2);
+ const view = new DataView(data.vertices.buffer, data.vertices.byteOffset, data.vertices.byteLength);
+ const positions = new Float32Array(data.vertexCount * 3);
+ const stride = (normal ? 3 : 0) + (uv ? 2 : 0);
+ const attributes = new Float32Array(data.vertexCount * stride);
+ for (let v = 0; v < data.vertexCount; v++) {
+ const at = v * data.vertexStride;
+ for (let k = 0; k < 3; k++) positions[v * 3 + k] = view.getFloat32(at + position.offset + k * 4, true);
+ let a = v * stride;
+ if (normal) for (let k = 0; k < 3; k++) attributes[a++] = view.getFloat32(at + normal.offset + k * 4, true);
+ if (uv) for (let k = 0; k < 2; k++) attributes[a++] = view.getFloat32(at + uv.offset + k * 4, true);
+ }
+ const weights = [...(normal ? [NORMAL_WEIGHT, NORMAL_WEIGHT, NORMAL_WEIGHT] : []), ...(uv ? [UV_WEIGHT, UV_WEIGHT] : [])];
+ const triangles = data.indices.length / 3;
+ const target = Math.max(1, Math.floor(triangles * RATIO)) * 3;
+ const [kept] = MeshoptSimplifier.simplifyWithAttributes(data.indices, positions, 3, attributes, stride, weights, null, target, ERROR, ['Sparse']);
+ const remap = new Int32Array(data.vertexCount).fill(-1);
+ let used = 0;
+ for (const i of kept) if (remap[i] < 0) remap[i] = used++;
+ const vertices = new Uint8Array(used * data.vertexStride);
+ for (let v = 0; v < data.vertexCount; v++) if (remap[v] >= 0) vertices.set(data.vertices.subarray(v * data.vertexStride, (v + 1) * data.vertexStride), remap[v] * data.vertexStride);
+ const indices = new Uint32Array(kept.length);
+ for (let i = 0; i < kept.length; i++) indices[i] = remap[kept[i]];
+ return { ...data, vertexCount: used, vertices, indices };
+}
+
+await MeshoptSimplifier.ready;
+for (const prefab of LOD2_PREFABS) {
+ const base = `assets/plants/models/${prefab}`;
+ const prefabFile = path.join(PROJECT, base, `${prefab}.esprefab`);
+ if (!existsSync(prefabFile)) { console.log(`${prefab}: no prefab`); continue; }
+ for (const mesh of meshesOf(prefabFile)) {
+ const data = decodeMesh(new Uint8Array(readFileSync(path.join(PROJECT, mesh))));
+ const made = collapse(data);
+ const out = path.join(PROJECT, base, 'lod2', path.basename(mesh));
+ mkdirSync(path.dirname(out), { recursive: true });
+ writeFileSync(out, encodeMesh(made));
+ // The export finds a mesh by its meta, which the rules name by path.
+ if (!existsSync(`${out}.meta`)) writeFileSync(`${out}.meta`, `${JSON.stringify({ uuid: randomUUID(), version: '2.0', type: 'mesh', importer: {} }, null, 2)}
+`);
+ console.log(`${path.basename(mesh).padEnd(34)} ${String(data.indices.length / 3).padStart(6)} -> ${String(made.indices.length / 3).padStart(5)} triangles`);
+ }
+}
diff --git a/examples/terrain-water/tools/plants.mjs b/examples/terrain-water/tools/plants.mjs
index d88085295..cd6b2d60d 100644
--- a/examples/terrain-water/tools/plants.mjs
+++ b/examples/terrain-water/tools/plants.mjs
@@ -31,8 +31,8 @@ function partsOf(project, file) {
const SOFT_CARDS = 0.85;
const SOFT_GROUND = 0.6;
-const asPart = (d, lod1Mesh = '') => ({
- mesh: d.mesh, lod1Mesh, material: d.material ?? '', texture: d.texture ?? '',
+const asPart = (d, lod1Mesh = '', lod2Mesh = '') => ({
+ mesh: d.mesh, lod1Mesh, ...(lod2Mesh ? { lod2Mesh } : {}), material: d.material ?? '', texture: d.texture ?? '',
tint: [d.color?.r ?? 1, d.color?.g ?? 1, d.color?.b ?? 1, d.color?.a ?? 1], opaque: d.opaque !== false,
});
@@ -55,12 +55,12 @@ const TINTS = {
/** The kinds of plant: the prefab each is made of, how far it is drawn (metres: the cheaper mesh from `lod`, nothing past `draw`, the far version out to `far`). */
const KINDS = {
- oak: { prefab: 'tree-oak-dense', lod: 60, draw: 380, far: 2000, tints: TINTS.oak },
- beech: { prefab: 'tree-beech-dense', lod: 60, draw: 380, far: 2000, tints: TINTS.beech },
- birch: { prefab: 'tree-birch', lod: 60, draw: 380, far: 2000, tints: TINTS.birch },
- willow: { prefab: 'tree-willow', lod: 60, draw: 380, far: 2000, tints: TINTS.willow },
- 'pine-ridge': { prefab: 'tree-pine-ridge', lod: 60, draw: 380, far: 2000, tints: TINTS.conifer },
- 'pine-lakeside': { prefab: 'tree-pine-lakeside', lod: 60, draw: 380, far: 2000, tints: TINTS.conifer },
+ oak: { prefab: 'tree-oak-dense', lod: 60, lod2: 80, draw: 380, far: 2000, tints: TINTS.oak },
+ beech: { prefab: 'tree-beech-dense', lod: 60, lod2: 80, draw: 380, far: 2000, tints: TINTS.beech },
+ birch: { prefab: 'tree-birch', lod: 60, lod2: 80, draw: 380, far: 2000, tints: TINTS.birch },
+ willow: { prefab: 'tree-willow', lod: 60, lod2: 80, draw: 380, far: 2000, tints: TINTS.willow },
+ 'pine-ridge': { prefab: 'tree-pine-ridge', lod: 60, lod2: 80, draw: 380, far: 2000, tints: TINTS.conifer },
+ 'pine-lakeside': { prefab: 'tree-pine-lakeside', lod: 60, lod2: 80, draw: 380, far: 2000, tints: TINTS.conifer },
hazel: { prefab: 'shrub-hazel', lod: 40, draw: 120, tints: TINTS.shrub },
coppice: { prefab: 'shrub-woodland-coppice', lod: 40, draw: 120, tints: TINTS.shrub },
lowleaf: { prefab: 'woodland-lowleaf', lod: 30, draw: 100, tints: TINTS.fern },
@@ -102,13 +102,16 @@ function plants(project) {
const parts = partsOf(project, `${base}/${k.prefab}.esprefab`), near = partsOf(project, `${base}/lod1/${k.prefab}.esprefab`);
const cards = partsOf(project, `${base}/far/${k.prefab}.esprefab`);
const cheaper = near.length === parts.length;
+ // A third mesh, where plant-lod2.mjs made one beside the others for every part (the trees).
+ const third = k.lod2 ? parts.map((d) => `${base}/lod2/${path.basename(d.mesh)}`) : [];
+ const thirdMade = third.length > 0 && third.every((m) => existsSync(path.join(project, m)));
const cover = COVER[name];
// Ground cover: the cheaper mesh stands for it far off, thinned; trees: the art's cards.
// The art's cards where it made them; ground cover with none (a flower) stands in as its own cheaper mesh, thinned.
const far = cards.length ? cards.map((d) => ({ ...asPart(d), soft: cover ? SOFT_GROUND : SOFT_CARDS })) : cover ? (cheaper ? near : parts).map((d) => asPart(d)) : [];
out[name] = {
- parts: parts.map((d, j) => asPart(d, cheaper ? near[j].mesh : '')),
- lodDistance: cheaper ? k.lod * M : 0, drawDistance: k.draw * M,
+ parts: parts.map((d, j) => asPart(d, cheaper ? near[j].mesh : '', cheaper && thirdMade ? third[j] : '')),
+ lodDistance: cheaper ? k.lod * M : 0, ...(cheaper && thirdMade ? { lod2Distance: k.lod2 * M } : {}), drawDistance: k.draw * M,
far, farDistance: far.length ? (cover?.far ?? k.far ?? 0) * M : 0,
...(cover ? { farKeep: cover.keep } : {}),
...(k.tints ? { tints: k.tints, tintScale: 1300 } : {}),
diff --git a/sdk/etc/foliage.api.md b/sdk/etc/foliage.api.md
index 196acd533..188577e1f 100644
--- a/sdk/etc/foliage.api.md
+++ b/sdk/etc/foliage.api.md
@@ -130,6 +130,7 @@ drawDistance: number
far: PlacedPart[]
farDistance: number
farKeep: number | undefined
+lod2Distance: number | undefined
lodDistance: number
parts: PlacedPart[]
```
@@ -138,6 +139,7 @@ parts: PlacedPart[]
```
castShadows: boolean | undefined
lod1Mesh: string
+lod2Mesh: string | undefined
material: string
mesh: string
opaque: boolean
@@ -184,6 +186,7 @@ drawDistance: number
far: PlacedPart[]
farDistance: number
farKeep: number | undefined
+lod2Distance: number | undefined
lodDistance: number
parts: PlacedPart[]
sink: number | undefined
diff --git a/sdk/src/foliage/placedFoliage.ts b/sdk/src/foliage/placedFoliage.ts
index 04a54aed4..31c162aa3 100644
--- a/sdk/src/foliage/placedFoliage.ts
+++ b/sdk/src/foliage/placedFoliage.ts
@@ -53,6 +53,7 @@ export const PlacedFoliage: ComponentDef<PlacedFoliageData> = defineComponent<Pl
for (const p of kind.parts ?? []) {
if (p.mesh) refs.push({ type: 'mesh', path: p.mesh });
if (p.lod1Mesh) refs.push({ type: 'mesh', path: p.lod1Mesh });
+ if (p.lod2Mesh) refs.push({ type: 'mesh', path: p.lod2Mesh });
if (p.material) refs.push({ type: 'material', path: p.material });
if (p.texture) refs.push({ type: 'texture', path: p.texture });
}
diff --git a/sdk/src/foliage/plantGrowth.ts b/sdk/src/foliage/plantGrowth.ts
index d8a494ddf..ab56fb7fb 100644
--- a/sdk/src/foliage/plantGrowth.ts
+++ b/sdk/src/foliage/plantGrowth.ts
@@ -30,7 +30,7 @@ import { buildPlacements, PLACEMENT_FLOATS, softenNormals, thinPlants, type Plan
import type { PlacedKind, PlacedPart } from './plantKind';
/** A part with what it needs in hand: the handles of its meshes (shared by every cell) and of its material and texture. */
-export interface ReadyPart { part: PlacedPart; mesh: number; lod1: number; material: number; texture: number }
+export interface ReadyPart { part: PlacedPart; mesh: number; lod1: number; lod2?: number; material: number; texture: number }
/** Every kind's parts in hand, and the parts that stand for each far off; `owned` are the meshes made here, which `releaseKinds` gives back. */
export interface ReadyKinds { kinds: ReadyPart[][]; far: ReadyPart[][]; owned: number[] }
@@ -59,8 +59,10 @@ export async function prepareKinds(assets: AssetsApi, kinds: readonly PlacedKind
if (mesh === 0) { log.warn('foliage', `the geometry of ${part.mesh} cannot be read, so its plants are left out`); return null; }
let lod1 = 0;
if (withLod && part.lod1Mesh) { try { lod1 = await handleOf(part.lod1Mesh, part.soft ?? 0); } catch { lod1 = 0; } }
+ let lod2 = 0;
+ if (withLod && part.lod2Mesh) { try { lod2 = await handleOf(part.lod2Mesh, part.soft ?? 0); } catch { lod2 = 0; } }
return {
- part, mesh, lod1,
+ part, mesh, lod1, ...(lod2 ? { lod2 } : {}),
material: part.material ? (await assets.loadMaterial(part.material)).handle : 0,
texture: part.texture ? (await assets.loadTexture(part.texture)).handle : 0,
};
@@ -99,7 +101,7 @@ export class PlantGrowth {
* Makes one entity under `parent` that draws `part`'s mesh at every place in `plants`, relative to `parent`. `from` and `to` are the distances
* from the eye between which a plant is drawn (0 for no limit); `lod` is the distance past which the part's cheaper mesh stands in, and `shadow` the one past which it casts no shadow. All of them are scaled by the quality level's `detailScale`.
*/
- private place(app: App, parent: Entity, name: string, part: ReadyPart, plants: readonly Plant[], lod: number, from: number, to: number, shadow = 0, far = false): void {
+ private place(app: App, parent: Entity, name: string, part: ReadyPart, plants: readonly Plant[], lod: number, from: number, to: number, shadow = 0, far = false, mesh = part.mesh, lod1 = part.lod1): void {
const world = app.world;
// The quality level's share of the kind's distances: a weaker device changes to the cheaper mesh sooner and draws less far.
const quality = app.hasResource(Quality) ? app.getResource(Quality) : null;
@@ -111,12 +113,12 @@ export class PlantGrowth {
world.insert(e, RuntimeOnly);
world.insert(e, Transform, {});
world.insert(e, MeshRenderer, {
- mesh: part.mesh, material: part.material, texture: part.texture, lit: true, opaque: part.part.opaque !== false, cullBackfaces: false,
+ mesh, material: part.material, texture: part.texture, lit: true, opaque: part.part.opaque !== false, cullBackfaces: false,
castShadows: part.part.castShadows !== false,
color: { r: part.part.tint[0], g: part.part.tint[1], b: part.part.tint[2], a: part.part.tint[3] },
} as Partial<MeshRendererData>);
const placements = getComponent('MeshInstances');
- if (placements) world.insert(e, placements, { lod1Mesh: part.lod1, lodDistance: part.lod1 ? lod : 0, minDistance: from, drawDistance: to, shadowDistance: shadow });
+ if (placements) world.insert(e, placements, { lod1Mesh: lod1, lodDistance: lod1 ? lod : 0, minDistance: from, drawDistance: to, shadowDistance: shadow });
world.setParent(e, parent);
const api = engineApi(app);
const set = api?.meshInstances_set;
@@ -145,7 +147,11 @@ export class PlantGrowth {
this.queue.push({ cell, run: () => {
if (!world.valid(entity)) return;
try {
- this.place(app, entity, `${kindIndex}:${j}`, r, plants, kind.lodDistance, 0, kind.drawDistance, kind.lodDistance > 0 ? kind.lodDistance * 2 : 0);
+ const shadow = kind.lodDistance > 0 ? kind.lodDistance * 2 : 0;
+ // A third mesh takes over where the kind's `lod2Distance` is: two sets, each drawn between its own distances.
+ const third = r.lod2 && (kind.lod2Distance ?? 0) > 0 ? kind.lod2Distance! : 0;
+ this.place(app, entity, `${kindIndex}:${j}`, r, plants, kind.lodDistance, 0, third || kind.drawDistance, shadow);
+ if (third) this.place(app, entity, `${kindIndex}:${j}:lod2`, r, plants, 0, third, kind.drawDistance, shadow, false, r.lod2, 0);
} catch (error) {
log.error('foliage', 'growing a piece of a cell of plants failed', error);
}
diff --git a/sdk/src/foliage/plantKind.ts b/sdk/src/foliage/plantKind.ts
index 9dd8a685b..45bb4666f 100644
--- a/sdk/src/foliage/plantKind.ts
+++ b/sdk/src/foliage/plantKind.ts
@@ -12,6 +12,8 @@ export interface PlacedPart {
mesh: string;
/** A cheaper mesh with the same parts, drawn past the kind's `lodDistance`; empty draws the mesh to the end. */
lod1Mesh: string;
+ /** A cheaper still, drawn from the kind's `lod2Distance`; empty or absent keeps the cheaper mesh to the end of the kind's reach. */
+ lod2Mesh?: string;
material: string;
texture: string;
tint: [number, number, number, number];
@@ -31,6 +33,11 @@ export interface PlacedKind {
parts: PlacedPart[];
/** Past this the cheaper mesh stands in. */
lodDistance: number;
+ /**
+ * Past this the parts' `lod2Mesh` stands in for the cheaper mesh (default 0: none). The cheaper mesh of a tree is half the triangles of the first, still
+ * thousands, and from far enough they cover a few pixels each, which is dear for what they show; the third is a tenth.
+ */
+ lod2Distance?: number;
/** Past this the kind is not drawn as itself. */
drawDistance: number;
/**
diff --git a/sdk/src/worldgen/plants.ts b/sdk/src/worldgen/plants.ts
index 737da1a56..50a84ae6a 100644
--- a/sdk/src/worldgen/plants.ts
+++ b/sdk/src/worldgen/plants.ts
@@ -34,7 +34,7 @@ export function expandPlants(plants: Readonly<Record<string, PlantKind>>): Plant
const first = kinds.length;
for (const t of tints) {
const tint = (part: PlacedKind['parts'][number]): PlacedKind['parts'][number] => ({ ...part, tint: [part.tint[0] * t[0], part.tint[1] * t[1], part.tint[2] * t[2], part.tint[3]] });
- kinds.push({ parts: p.parts.map(tint), lodDistance: p.lodDistance, drawDistance: p.drawDistance, far: p.far.map(tint), farDistance: p.farDistance, ...(p.farKeep === undefined ? {} : { farKeep: p.farKeep }) });
+ kinds.push({ parts: p.parts.map(tint), lodDistance: p.lodDistance, ...(p.lod2Distance === undefined ? {} : { lod2Distance: p.lod2Distance }), drawDistance: p.drawDistance, far: p.far.map(tint), farDistance: p.farDistance, ...(p.farKeep === undefined ? {} : { farKeep: p.farKeep }) });
}
slots.set(name, { first, count: tints.length, scale: p.tintScale ?? 1300, seed: hashString(name), sink: p.sink ?? 0, unit: p.unit ?? 1 });
reach = Math.max(reach, p.drawDistance, p.far.length > 0 ? p.farDistance : 0);
diff --git a/sdk/src/worldgen/rulesAsset.ts b/sdk/src/worldgen/rulesAsset.ts
index 5ca5cd307..c91970287 100644
--- a/sdk/src/worldgen/rulesAsset.ts
+++ b/sdk/src/worldgen/rulesAsset.ts
@@ -63,7 +63,8 @@ function part(v: unknown, where: string): PlantKind['parts'][number] {
const tint = p.tint ?? [1, 1, 1, 1];
if (!Array.isArray(tint) || tint.length !== 4) fail(`${where}.tint`, 'four numbers, red, green, blue and alpha');
return {
- mesh: str(p.mesh, `${where}.mesh`), lod1Mesh: typeof p.lod1Mesh === 'string' ? p.lod1Mesh : '', material: typeof p.material === 'string' ? p.material : '',
+ mesh: str(p.mesh, `${where}.mesh`), lod1Mesh: typeof p.lod1Mesh === 'string' ? p.lod1Mesh : '',
+ ...(typeof p.lod2Mesh === 'string' && p.lod2Mesh !== '' ? { lod2Mesh: p.lod2Mesh } : {}), material: typeof p.material === 'string' ? p.material : '',
texture: typeof p.texture === 'string' ? p.texture : '', tint: (tint as unknown[]).map((c, i) => num(c, `${where}.tint[${i}]`)) as [number, number, number, number],
opaque: p.opaque !== false,
...(p.soft === undefined ? {} : { soft: Math.min(Math.max(num(p.soft, `${where}.soft`), 0), 1) }),
@@ -86,7 +87,9 @@ function plant(v: unknown, where: string): PlantKind {
}
return {
parts: (o.parts as unknown[]).map((p, i) => part(p, `${where}.parts[${i}]`)),
- lodDistance: num(o.lodDistance ?? 0, `${where}.lodDistance`, 0), drawDistance: num(o.drawDistance, `${where}.drawDistance`, 0),
+ lodDistance: num(o.lodDistance ?? 0, `${where}.lodDistance`, 0),
+ ...(o.lod2Distance === undefined ? {} : { lod2Distance: num(o.lod2Distance, `${where}.lod2Distance`, 0) }),
+ drawDistance: num(o.drawDistance, `${where}.drawDistance`, 0),
far, farDistance: far.length > 0 ? num(o.farDistance, `${where}.farDistance`, 0) : 0,
...(o.farKeep === undefined ? {} : { farKeep: num(o.farKeep, `${where}.farKeep`, 1e-3) }),
...(tints ? { tints, tintScale: num(o.tintScale ?? 1300, `${where}.tintScale`, 1e-6) } : {}),
diff --git a/sdk/tests/worldgen-plants.test.ts b/sdk/tests/worldgen-plants.test.ts
index 7ed77df3f..b75cd8a49 100644
--- a/sdk/tests/worldgen-plants.test.ts
+++ b/sdk/tests/worldgen-plants.test.ts
@@ -9,7 +9,7 @@ import type { PlantKind } from '../src/foliage/plantKind';
const part = (mesh: string, tint: [number, number, number, number] = [1, 1, 1, 1]) => ({ mesh, lod1Mesh: '', material: '', texture: '', tint, opaque: true });
const plants: Record<string, PlantKind> = {
- oak: { parts: [part('trunk', [0.5, 0.5, 0.5, 1]), part('crown')], lodDistance: 6000, drawDistance: 16000, far: [part('cards')], farDistance: 200000,
+ oak: { parts: [part('trunk', [0.5, 0.5, 0.5, 1]), part('crown')], lodDistance: 6000, lod2Distance: 9000, drawDistance: 16000, far: [part('cards')], farDistance: 200000,
tints: [[0.9, 1, 0.9], [1, 1, 1], [1.1, 1, 0.8]], tintScale: 1000, sink: 8, unit: 100, farKeep: 0.5 },
stone: { parts: [part('rock')], lodDistance: 0, drawDistance: 30000, far: [], farDistance: 0 },
};
@@ -27,6 +27,11 @@ describe('expanding plants into kinds', () => {
expect(set.kinds[3]!.far).toHaveLength(0);
});
+ it('carries the distance of the third mesh into every colouring, and none where the plant has none', () => {
+ expect(set.kinds.slice(0, 3).map((k) => k.lod2Distance)).toEqual([9000, 9000, 9000]);
+ expect(set.kinds[3]!.lod2Distance).toBeUndefined();
+ });
+
it('gives a place one colouring, the same each time, and a plant without any its one kind', () => {
const seen = new Set<number>();
for (let i = 0; i < 400; i++) {
diff --git a/sdk/tests/worldgen-rules-asset.test.ts b/sdk/tests/worldgen-rules-asset.test.ts
index 08da71221..179ebb464 100644
--- a/sdk/tests/worldgen-rules-asset.test.ts
+++ b/sdk/tests/worldgen-rules-asset.test.ts
@@ -43,8 +43,8 @@ describe('plants in a world rules file', () => {
const withPlants = () => {
const r = JSON.parse(JSON.stringify(good));
r.plants = {
- oak: { parts: [{ mesh: 'assets/oak_trunk.esmesh', material: 'assets/bark.esmaterial' }, { mesh: 'assets/oak_crown.esmesh', lod1Mesh: 'assets/oak_crown1.esmesh', opaque: true }],
- lodDistance: 6000, drawDistance: 16000, far: [{ mesh: 'assets/oak_cards.esmesh', soft: 0.85, castShadows: false }], farDistance: 200000, farKeep: 0.25, tints: [[0.9, 1, 0.9], [1, 1, 1]], sink: 8 },
+ oak: { parts: [{ mesh: 'assets/oak_trunk.esmesh', material: 'assets/bark.esmaterial' }, { mesh: 'assets/oak_crown.esmesh', lod1Mesh: 'assets/oak_crown1.esmesh', lod2Mesh: 'assets/oak_crown2.esmesh', opaque: true }],
+ lodDistance: 6000, lod2Distance: 8000, drawDistance: 16000, far: [{ mesh: 'assets/oak_cards.esmesh', soft: 0.85, castShadows: false }], farDistance: 200000, farKeep: 0.25, tints: [[0.9, 1, 0.9], [1, 1, 1]], sink: 8 },
};
r.recipes[0].anchor = { id: 'oak', plant: 'oak', footprint: 8 };
delete r.recipes[0].anchor.mesh;
@@ -58,6 +58,9 @@ describe('plants in a world rules file', () => {
const oak = rules.plants!.oak!;
expect(oak.parts).toHaveLength(2);
expect(oak.parts[1]!.lod1Mesh).toBe('assets/oak_crown1.esmesh');
+ expect(oak.parts[1]!.lod2Mesh).toBe('assets/oak_crown2.esmesh');
+ expect(oak.parts[0]!.lod2Mesh).toBeUndefined();
+ expect(oak.lod2Distance).toBe(8000);
expect(oak.far[0]!.mesh).toBe('assets/oak_cards.esmesh');
expect(oak.far[0]!.soft).toBe(0.85);
expect(oak.far[0]!.castShadows).toBe(false);
diff --git a/tools/terrain-water-cost.mjs b/tools/terrain-water-cost.mjs
index 7aa55016e..dab9090eb 100644
--- a/tools/terrain-water-cost.mjs
+++ b/tools/terrain-water-cost.mjs
@@ -19,7 +19,7 @@
*/
import { chromium } from 'playwright';
import { spawnSync } from 'node:child_process';
-import { readFile, writeFile, mkdir } from 'node:fs/promises';
+import { readFile, writeFile, mkdir, readdir } from 'node:fs/promises';
import { existsSync } from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
@@ -40,6 +40,8 @@ const VIEW = Number(flag('view', '0'));
const ONLY = flag('only', '') ? new Set(flag('only', '').split(',')) : null;
const OUT = flag('out', path.join(ROOT, 'output', 'perf', 'terrain-water-cost.json'));
const NO_EXPORT = argv.includes('--no-export');
+/** A folder to write each variant's last frame to, as `<id>-view<n>.png`. */
+const SHOTS = flag('shots', '');
/** Where the example's other viewpoints are (the same poses as src/main.ts); null leaves the scene's camera. */
const VIEWS = [
@@ -61,6 +63,10 @@ const effect = (doc, type) => volume(doc).effects.find((e) => e.type === type);
const dropEntities = (...names) => (doc) => { doc.entities = doc.entities.filter((e) => !names.includes(e.name)); };
const WATER = ['Water', 'Sea', 'Lake', 'River In', 'River Out', 'Crate 1', 'Crate 2', 'Crate 3', 'Crate 4', 'Crate 5', 'Crate 6', 'Crate 7', 'Crate 8', 'Crate 9'];
const PLANTS = ['Plants', 'Flower sea'];
+const noLayer = (layer) => (w) => { for (const b of w.biomes) b.recipes = b.recipes.filter((r) => r.layer !== layer); };
+const forParts = (fn) => (w) => { for (const p of Object.values(w.plants)) for (const part of [...p.parts, ...(p.far ?? [])]) fn(part); };
+const TREES = ['oak', 'beech', 'birch', 'willow', 'pine-ridge', 'pine-lakeside'];
+const trees = (fn) => (w) => { for (const k of TREES) fn(w.plants[k]); };
const quality = (level, profile) => (cfg) => { cfg.quality = { ...cfg.quality, mode: level, ...(profile ? { profiles: { [level]: profile } } : {}) }; };
/** Each variant: what to take away, relative to `base`. Edits to the scene, or to the package's quality config. */
@@ -82,6 +88,19 @@ const VARIANTS = [
{ id: 'lensflare-off', label: 'lens flare off', scene: dropEffects('lensFlare') },
{ id: 'grade-off', label: 'colour grade + display LUT off', scene: dropEffects('colorGrade', 'displayLut') },
{ id: 'fxaa-off', label: 'fxaa off', scene: dropEffects('fxaa') },
+ // The plants, a layer at a time (what the world rules lay down), and with shadows taken off them
+ { id: 'plants-noshadow', label: 'plants cast no shadow', world: forParts((part) => { part.castShadows = false; }) },
+ ...['groves', 'banks', 'stones', 'cover', 'drifts', 'reeds', 'sea', 'shoals'].map((l) => ({ id: `layer-${l}-off`, label: `plant layer ${l} off`, world: noLayer(l) })),
+ { id: 'trees-no-lod2', label: 'trees without their third mesh (what the example drew before it)', world: trees((p) => { p.lod2Distance = 0; }) },
+ { id: 'trees-lod2-80', label: 'trees: lod1 from 60 m, lod2 from 80 m', world: trees((p) => { p.lod2Distance = 8000; }) },
+ { id: 'trees-lod2-70', label: 'trees: lod1 from 60 m, lod2 from 70 m', world: trees((p) => { p.lod2Distance = 7000; }) },
+ { id: 'trees-lod-tight', label: 'trees: lod1 from 30 m, lod2 from 60 m', world: trees((p) => { p.lodDistance = 3000; p.lod2Distance = 6000; }) },
+ { id: 'trees-lod-mid', label: 'trees: lod1 from 40 m, lod2 from 80 m', world: trees((p) => { p.lodDistance = 4000; p.lod2Distance = 8000; }) },
+ { id: 'trees-lod-quarter', label: 'trees change to their lod1 mesh at a quarter of the distance', world: trees((p) => { p.lodDistance *= 0.25; }) },
+ { id: 'trees-draw-quarter', label: 'trees give way to cards at a quarter of the distance', world: trees((p) => { p.drawDistance *= 0.25; p.lodDistance = Math.min(p.lodDistance, p.drawDistance); p.lod2Distance = 0; }) },
+ { id: 'trees-cards-only', label: 'trees are only ever cards', world: trees((p) => { p.drawDistance = 1; p.lodDistance = 0; p.lod2Distance = 0; }) },
+ { id: 'trees-noshadow', label: 'trees cast no shadow', world: trees((p) => { for (const part of [...p.parts, ...(p.far ?? [])]) part.castShadows = false; }) },
+ { id: 'trees-nofar', label: 'no far cards (trees fade out at their draw distance)', world: (w) => { for (const p of Object.values(w.plants)) p.farDistance = 0; } },
// Quality knobs, one at a time from high
{ id: 'msaa-1', label: 'no multisampling', config: quality('high', { msaaSamples: 1 }) },
{ id: 'msaa-2', label: 'msaa 2x', config: quality('high', { msaaSamples: 2 }) },
@@ -103,6 +122,9 @@ async function measure(server, original, variant, browser) {
const cfg = JSON.parse(original.config);
variant.scene?.(doc);
variant.config?.(cfg);
+ const worldDoc = JSON.parse(original.world);
+ variant.world?.(worldDoc);
+ await writeFile(worldFile, JSON.stringify(worldDoc));
const view = VIEWS[VIEW];
if (view) {
const cam = doc.entities.find((e) => e.name === 'Camera').components.find((c) => c.type === 'Transform');
@@ -116,6 +138,7 @@ async function measure(server, original, variant, browser) {
const page = await context.newPage();
const errors = [];
page.on('pageerror', (e) => errors.push(String(e).slice(0, 200)));
+ if (argv.includes('--logs')) page.on('console', (m) => { if (['warning', 'error'].includes(m.type())) console.log(` [${m.type()}] ${m.text().slice(0, 200)}`); });
try {
await page.goto(`http://127.0.0.1:${server.address().port}/?headless`, { waitUntil: 'load', timeout: 120000 });
await page.waitForFunction(() => window.__estellaCooked?.facts && window.__estellaCooked.bakes, null, { timeout: 120000 });
@@ -148,6 +171,7 @@ async function measure(server, original, variant, browser) {
const cpu = costs.systems.reduce((a, x) => a + x.ms, 0);
return { ms, counters: c.render(), cpu, native: costs.native, size: [document.querySelector('canvas').width, document.querySelector('canvas').height], gl: !!gl };
}, { frames: FRAMES, samples: SAMPLES });
+ if (SHOTS) { await mkdir(SHOTS, { recursive: true }); await page.screenshot({ path: path.join(SHOTS, `${variant.id}-view${VIEW}.png`) }); }
return { ms: median(result.ms), cpu: result.cpu, native: result.native, min: Math.min(...result.ms), max: Math.max(...result.ms), settled, counters: result.counters, size: result.size, errors };
} finally {
await context.close();
@@ -164,6 +188,8 @@ const original = {
scene: await readFile(path.join(DIR, 'assets/scenes/main.esscene'), 'utf8'),
config: await readFile(path.join(DIR, 'game.config.json'), 'utf8'),
};
+const worldFile = (await readdir(path.join(DIR, 'assets'))).filter((f) => f.endsWith('.esworld')).map((f) => path.join(DIR, 'assets', f))[0];
+original.world = await readFile(worldFile, 'utf8');
const server = await serveHost(DIR);
const browser = await chromium.launch({
headless: true,
@@ -189,11 +215,12 @@ try {
}
if (!r) { table[v.id] = { label: v.label, failed: true }; continue; }
table[v.id] = { label: v.label, ...r };
- console.log(`${v.id.padEnd(17)} ${r.ms.toFixed(2).padStart(7)} ms [${r.min.toFixed(2)}..${r.max.toFixed(2)}] cpu ${r.cpu.toFixed(2)} draws ${r.counters['batch.draws'] ?? '?'} shadow ${r.counters['render.shadow.draws'] ?? '?'} tris ${((r.counters['render.triangles'] ?? 0) / 1e6).toFixed(2)}M ${r.errors.length ? 'ERRORS ' + r.errors[0] : ''}`);
+ console.log(`${v.id.padEnd(17)} ${r.ms.toFixed(2).padStart(7)} ms [${r.min.toFixed(2)}..${r.max.toFixed(2)}] cpu ${r.cpu.toFixed(2)} draws ${r.counters['batch.draws'] ?? '?'} shadow ${r.counters['render.shadow.draws'] ?? '?'} tris ${((r.counters['render.triangles'] ?? 0) / 1e6).toFixed(2)}M placed ${r.counters['render.placements.seen'] ?? '?'}/coarse ${r.counters['render.placements.coarse'] ?? '?'}/far ${r.counters['render.placements.tooFar'] ?? '?'} ${r.errors.length ? 'ERRORS ' + r.errors[0] : ''}`);
}
} finally {
await writeFile(path.join(DIR, 'assets/scenes/main.esscene'), original.scene);
await writeFile(path.join(DIR, 'game.config.json'), original.config);
+ await writeFile(worldFile, original.world);
await browser.close();
await new Promise((r) => server.close(r));
}