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(worldgen): decoration has a far version past its layer's lodDistance, and leans with the ground when it is aligned

yhhce5e6684781f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 396fce8ee..201c48bcf 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -29,6 +29,7 @@ published separately; it ships inside the editor.
- **Which water a place is.** The sea fills only low ground joined to the open sea past the water zone's edge: a hollow below its level walled off by higher ground stays dry (or holds a lake of its own). A lake or a river is water only where its surface is over its ground, so a hill inside its outline is land, for what is drawn and what `Waters.sample` answers, whatever order the bodies were added in. `WaterBody.bodyId` names a body the same in every session; `Waters.sample` carries it and `Waters.bodyAt(x, z)` says which body a place belongs to. `findBasins` gives a game the ground's basins (each filled to the lowest point of its rim, with its outlet), the drainage down to the edge and the sea's reach, for deciding where its lakes and rivers go; `drainPath` follows the water from a point.
- **An area without a heightmap is a window on its provider's ground.** Its noise is read from `Terrain.provider` where the area stands in the world, over the provider's height range, instead of being made in the area's own space and stretched to fill it: two areas of the same size side by side join, an area is the same ground its provider gives without end, and a game's own provider can make an area. Ground read from a provider is read again when its terrain is moved, so it stays the world's ground.
- **Rays against the terrain, anywhere.** `Terrains.raycast(origin, direction, maxDistance)` meets the ground's triangles exactly (the ones collision and `heightAt` use) wherever the ray goes, with no physics world and no collision tile there, for a line of sight, a pick or a landing spot.
+- **Far versions for generated decoration.** A recipe member can name its far version (`far`: crossed cards, or a tent for a conifer, showing a rectangle of its texture), drawn past its layer's `lodDistance`, and decoration that leans with the ground (`attach: 'align'`) now leans in its merged mesh too.
- **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.md
index ab929320b..ec688cd57 100644
--- a/docs/WORLD_GENERATION_PLAN.md
+++ b/docs/WORLD_GENERATION_PLAN.md
@@ -33,7 +33,7 @@
### T-03 程序化区块的驻留与统一预算
- 需要:由 WorldStreamer 调度程序化地形、碰撞、植被、交互实体的准备与发布;距离/视野优先级、取消过期任务、全局帧预算、卸载释放、可查询的 ready/pending/failure;一个地块只有一个生命周期所有者。
-- 当前状态:已完成主体。`ProceduralChunks`(`sdk/src/residency/chunks.ts`)是程序化区块的唯一生命周期所有者,与 WorldStreamer 共用 `WorldStreamingSource`(无源时退回视点);各"层"登记切分、范围、加载/卸载半径、代次与 make/publish/release。每帧跨层按距离排序,源所在区块立即生成,其余在统一帧预算(`Bakes.budgetMs` 与 `Bakes.hasTime`,与烘焙作业、地形页共享,被挤占时作业让出一半)内生成;异步结果按代次丢弃并中止 `AbortSignal`(快速传送不发布旧结果);代次变化时旧版本保留到新版本替换;超出卸载半径即释放其发布的一切;`status`/`stateAt` 可查询 ready/stale/pending/making/failed 与原因,进度并入状态栏。已迁入:地形碰撞块(跟随运动刚体与角色)、植被格(跟随视点,到 `drawDistance`)。测试 `sdk/tests/procedural-chunks.test.ts`。仍欠:植被 GPU 实例化(目前每格合并网格,内存已随驻留有上限);地形页仍由四叉树 + 图集 LRU 自管(已共用帧预算并限制异步并发);远景与正交俯视 LOD 需在目标设备实测;交互实体待 T-04 作为层接入。
+- 当前状态:已完成主体。`ProceduralChunks`(`sdk/src/residency/chunks.ts`)是程序化区块的唯一生命周期所有者,与 WorldStreamer 共用 `WorldStreamingSource`(无源时退回视点);各"层"登记切分、范围、加载/卸载半径、代次与 make/publish/release。每帧跨层按距离排序,源所在区块立即生成,其余在统一帧预算(`Bakes.budgetMs` 与 `Bakes.hasTime`,与烘焙作业、地形页共享,被挤占时作业让出一半)内生成;异步结果按代次丢弃并中止 `AbortSignal`(快速传送不发布旧结果);代次变化时旧版本保留到新版本替换;超出卸载半径即释放其发布的一切;`status`/`stateAt` 可查询 ready/stale/pending/making/failed 与原因,进度并入状态栏。已迁入:地形碰撞块(跟随运动刚体与角色)、植被格(跟随视点,到 `drawDistance`)。测试 `sdk/tests/procedural-chunks.test.ts`。植被 GPU 实例化评估结论:暂不采用。渲染器的实例记录是每帧重写上传的瞬时纹理,5 万片草叶约 6MB/帧;按格合并的静态网格每帧零上传、GPU 顶点量相同,内存已由驻留限制;真正的实例化需要持久实例缓冲(UE HISM 式),作为渲染器功能另立。仍欠:地形页仍由四叉树 + 图集 LRU 自管(已共用帧预算并限制异步并发);远景与正交俯视 LOD 需在目标设备实测;交互实体待 T-04 作为层接入。
- 验收:连续走过大量区块内存和实体有上限;折返不重复;快速传送不把旧请求结果发布到新星球;卸载同时移除渲染、碰撞、资产引用;远景与正交俯视 LOD 在目标设备实测。
### T-04 群落、建造排除区与持久变化
@@ -57,7 +57,8 @@
- 发布:T-03 区块层;装饰按区块按种类合并网格;可交互物为独立实体带 `PlacedObject{id, kind}`,`objectOf(id)`;生成实体带 `RuntimeOnly` 不进存档;服务端只生成可交互实体。
- 调试:`explain(x,z)`(场、群落权重、区域、各层候选与拒绝原因)、`stats`、`biomeWeights`、`placementsIn`。
- 测试:`sdk/tests/worldgen-plan.test.ts`、`worldgen-plugin.test.ts`。
- - 仍欠:有限整地(区域压平地面)、陆地离岸距离场、装饰远景版本与 GPU 实例化、贴地装饰合并时按直立绘制、配方编辑器、可达性/安全落点等验收由游戏用查询接口实现(引擎可后续提供寻路连通查询)。
+ - 后续已补:装饰远景版本(成员 `far` 卡片 + 层 `lodDistance`,LODGroup 切换);贴地装饰合并时随法线倾斜。
+ - 仍欠:有限整地(区域压平地面)、陆地离岸距离场、配方编辑器、可达性/安全落点等验收由游戏用查询接口实现(引擎可后续提供寻路连通查询)。
- 验收:林地建房后草木不穿地板;采集后卸载重进不重生;同种子不同加载顺序结果相同;安全落点、早期资源、入口可达。
## 水域补充
diff --git a/docs/astro/src/content/docs/world/generation.mdx b/docs/astro/src/content/docs/world/generation.mdx
index d432bf218..f7f26f692 100644
--- a/docs/astro/src/content/docs/world/generation.mdx
+++ b/docs/astro/src/content/docs/world/generation.mdx
@@ -72,7 +72,8 @@ with the layer it is placed in and the share of that layer's candidates it takes
A recipe is a group: an **anchor** and **members** placed round it. Each member says its mesh and material (asset paths, or handles
already loaded), how many (`count`), how far from the anchor and at what angles (`ring`, `arc`), its `scale`, the ground it takes
(`footprint`: a trunk) apart from how far it spreads overhead (`canopy`: a crown), whether it stands upright or leans with the
-ground (`attach`), how steep (`minUp`) and how deep in water (`waterDepth`) it may stand, and the `chance` it is placed at all. A
+ground (`attach`), how steep (`minUp`) and how deep in water (`waterDepth`) it may stand, the `chance` it is placed at all, and its far
+version (`far`: the rectangle of its texture two crossed cards show, or a tent of them for a conifer, drawn past its layer's `lodDistance`). A
member that cannot stand (no ground, too steep, under water, kept out by a zone, on something placed before it) is left out; the
group stands.
@@ -152,7 +153,8 @@ Declare the folders they live in always included, in `.esengine/asset-groups.jso
- **No terraforming yet.** A zone keeps generation out of its ground; it does not flatten it.
- **No distance from the shore on land.** `waterDepth` says how deep water stands; a field of how far a dry place is from water is a
game's own for now.
-- **Decoration is drawn whole to `drawDistance`.** It has no far version, and aligned decoration is drawn upright.
+- **Decoration is merged a chunk at a time, not GPU-instanced.** The renderer's instance records are written each frame, which for a
+ field of thousands of plants would upload megabytes a frame; merged static meshes upload nothing, and the chunks bound their memory.
- **Rules are code.** Recipes are plain data and can be read from JSON, but there is no editor for them yet.
See the **Generated World** example (`examples/worldgen`).
diff --git a/docs/astro/src/content/docs/zh-cn/world/generation.mdx b/docs/astro/src/content/docs/zh-cn/world/generation.mdx
index 0bc1d6797..787cf7b40 100644
--- a/docs/astro/src/content/docs/zh-cn/world/generation.mdx
+++ b/docs/astro/src/content/docs/zh-cn/world/generation.mdx
@@ -57,7 +57,7 @@ registerWorldRules({
### 配方
-配方是一个组:一个**锚点**和围绕它放置的**成员**。每个成员说明它的网格和材质(资源路径,或已加载的句柄)、数量(`count`)、离锚点多远和在什么角度(`ring`、`arc`)、`scale`、它在地面上占的范围(`footprint`:树干),与它在头顶伸展的范围(`canopy`:树冠)分开记录;它是直立还是随地面倾斜(`attach`)、允许多陡(`minUp`)和多深的水里站立(`waterDepth`),以及被放置的概率 `chance`。站不住的成员(没有地面、太陡、在水下、被区域排除、压在先放的东西上)会被省去,组仍然成立。
+配方是一个组:一个**锚点**和围绕它放置的**成员**。每个成员说明它的网格和材质(资源路径,或已加载的句柄)、数量(`count`)、离锚点多远和在什么角度(`ring`、`arc`)、`scale`、它在地面上占的范围(`footprint`:树干),与它在头顶伸展的范围(`canopy`:树冠)分开记录;它是直立还是随地面倾斜(`attach`)、允许多陡(`minUp`)和多深的水里站立(`waterDepth`)、被放置的概率 `chance`,以及它的远景版本(`far`:两张十字交叉卡片显示的贴图矩形,针叶树可用帐篷形,在所在层的 `lodDistance` 之外绘制)。站不住的成员(没有地面、太陡、在水下、被区域排除、压在先放的东西上)会被省去,组仍然成立。
`version` 是每个放置物 ID 的一部分:配方放置的东西变了就把它加一。
@@ -126,7 +126,7 @@ gens.diffs().load(saved); // 以及读回
- **还不能整地。** 区域让生成避开它的地面,但不会把地面压平。
- **陆地上没有离岸距离。** `waterDepth` 说明水有多深;干燥的地方离水多远,目前由游戏自己提供场。
-- **装饰完整绘制到 `drawDistance`。** 它没有远景版本,随地面倾斜的装饰按直立绘制。
+- **装饰按区块合并绘制,而不是 GPU 实例化。** 渲染器的实例记录每帧重写,成千上万株植物每帧要上传数兆字节;合并的静态网格每帧不上传任何东西,内存由区块驻留限制住。
- **规则是代码。** 配方是普通数据,可以从 JSON 读取,但还没有编辑器。
参见 **Generated World** 示例(`examples/worldgen`)。
diff --git a/examples/worldgen/src/main.ts b/examples/worldgen/src/main.ts
index 4ca0bb0dc..52a9f8cbf 100644
--- a/examples/worldgen/src/main.ts
+++ b/examples/worldgen/src/main.ts
@@ -6,6 +6,8 @@ import { addPlugin, defineSystem, GetWorld, Res, Query, Mut, Input, Time, Transf
import { registerWorldRules, WorldGenRes, type WorldRules } from 'esengine/worldgen';
const PINE = 'assets/models/pine.esmesh', ROCK = 'assets/models/rock.esmesh';
+/** A pine far off: a tent of cards showing the tree's part of its colour strip. */
+const PINE_FAR = { u0: 0.2, v0: 0.22, u1: 0.8, v1: 0.95, tent: true };
/**
* Three biomes by the fields (moisture, rock, how steep), each with its recipes: groves of pines with saplings round a tall one in
@@ -27,14 +29,14 @@ const rules: WorldRules = {
],
recipes: [
{ id: 'grove', version: 1, tags: ['tree'],
- anchor: { id: 'elder', mesh: PINE, material: 'assets/materials/pine.esmaterial', scale: [1.4, 1.8], footprint: 10, canopy: 35, minUp: 0.82 },
+ anchor: { id: 'elder', mesh: PINE, material: 'assets/materials/pine.esmaterial', scale: [1.4, 1.8], footprint: 10, canopy: 35, minUp: 0.82, far: PINE_FAR },
members: [
- { id: 'pine', mesh: PINE, material: 'assets/materials/pine.esmaterial', count: [3, 6], ring: [45, 110], scale: [0.9, 1.3], footprint: 8, canopy: 25, minUp: 0.8 },
- { id: 'sapling', mesh: PINE, material: 'assets/materials/pine.esmaterial', count: [2, 5], ring: [110, 170], scale: [0.35, 0.6], footprint: 4, minUp: 0.8, chance: 0.8 },
+ { id: 'pine', mesh: PINE, material: 'assets/materials/pine.esmaterial', count: [3, 6], ring: [45, 110], scale: [0.9, 1.3], footprint: 8, canopy: 25, minUp: 0.8, far: PINE_FAR },
+ { id: 'sapling', mesh: PINE, material: 'assets/materials/pine.esmaterial', count: [2, 5], ring: [110, 170], scale: [0.35, 0.6], footprint: 4, minUp: 0.8, chance: 0.8, far: PINE_FAR },
{ id: 'stone', mesh: ROCK, material: 'assets/materials/stone.esmaterial', count: [0, 2], ring: [20, 60], scale: [0.8, 1.6], footprint: 6, tags: ['rock'] },
] },
{ id: 'lone pine', version: 1, tags: ['tree'],
- anchor: { id: 'pine', mesh: PINE, material: 'assets/materials/pine.esmaterial', scale: [0.8, 1.4], footprint: 8, minUp: 0.8 } },
+ anchor: { id: 'pine', mesh: PINE, material: 'assets/materials/pine.esmaterial', scale: [0.8, 1.4], footprint: 8, minUp: 0.8, far: PINE_FAR } },
{ id: 'outcrop', version: 1, tags: ['rock'],
anchor: { id: 'boulder', mesh: ROCK, material: 'assets/materials/stone.esmaterial', scale: [4, 6.5], footprint: 26, attach: 'align' },
members: [
@@ -47,9 +49,9 @@ const rules: WorldRules = {
anchor: { id: 'vein', mesh: ROCK, material: 'assets/materials/copper.esmaterial', interactive: 'copper', scale: [1.2, 1.8], footprint: 10, attach: 'align' } },
],
layers: [
- { id: 'groups', spacing: 260, drawDistance: 4200, chunkSize: 512 },
+ { id: 'groups', spacing: 260, drawDistance: 4200, lodDistance: 1400, chunkSize: 512 },
{ id: 'resources', spacing: 220, drawDistance: 2400, chunkSize: 512 },
- { id: 'detail', spacing: 90, drawDistance: 2400, chunkSize: 384 },
+ { id: 'detail', spacing: 90, drawDistance: 2400, lodDistance: 1200, chunkSize: 384 },
],
};
registerWorldRules(rules);
diff --git a/sdk/etc/foliage.api.md b/sdk/etc/foliage.api.md
index 3266ba7d9..16390faee 100644
--- a/sdk/etc/foliage.api.md
+++ b/sdk/etc/foliage.api.md
@@ -86,6 +86,7 @@ ResourceDef<FoliageField>
phase: number
scale: number
shade: number
+up: readonly [number, number, number] | undefined
x: number
y: number
yaw: number
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 444bfbd63..3fc0e4f8b 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -6576,6 +6576,7 @@ kind: string
attach: "upright" | "align"
biome: string
canopy: number
+far: { u0: number; v0: number; u1: number; v1: number; tent?: boolean; } | null | undefined
footprint: number
group: string
id: string
@@ -6631,6 +6632,7 @@ version: 1
chunkSize: number | undefined
drawDistance: number
id: string
+lodDistance: number | undefined
occupies: boolean | undefined
spacing: number
version: number | undefined
@@ -6671,6 +6673,7 @@ width: number | undefined
phase: number
scale: number
shade: number
+up: readonly [number, number, number] | undefined
x: number
y: number
yaw: number
@@ -7650,6 +7653,7 @@ attach: "upright" | "align" | undefined
canopy: number | undefined
chance: number | undefined
count: readonly [number, number] | undefined
+far: { u0: number; v0: number; u1: number; v1: number; tent?: boolean; } | undefined
footprint: number
id: string
interactive: string | undefined
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index cf12abf8a..4ab4699ac 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -6779,6 +6779,7 @@ kind: string
attach: "upright" | "align"
biome: string
canopy: number
+far: { u0: number; v0: number; u1: number; v1: number; tent?: boolean; } | null | undefined
footprint: number
group: string
id: string
@@ -6834,6 +6835,7 @@ version: 1
chunkSize: number | undefined
drawDistance: number
id: string
+lodDistance: number | undefined
occupies: boolean | undefined
spacing: number
version: number | undefined
@@ -6874,6 +6876,7 @@ width: number | undefined
phase: number
scale: number
shade: number
+up: readonly [number, number, number] | undefined
x: number
y: number
yaw: number
@@ -7863,6 +7866,7 @@ attach: "upright" | "align" | undefined
canopy: number | undefined
chance: number | undefined
count: readonly [number, number] | undefined
+far: { u0: number; v0: number; u1: number; v1: number; tent?: boolean; } | undefined
footprint: number
id: string
interactive: string | undefined
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index fae35eac4..fc6059217 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -6571,6 +6571,7 @@ kind: string
attach: "upright" | "align"
biome: string
canopy: number
+far: { u0: number; v0: number; u1: number; v1: number; tent?: boolean; } | null | undefined
footprint: number
group: string
id: string
@@ -6626,6 +6627,7 @@ version: 1
chunkSize: number | undefined
drawDistance: number
id: string
+lodDistance: number | undefined
occupies: boolean | undefined
spacing: number
version: number | undefined
@@ -6666,6 +6668,7 @@ width: number | undefined
phase: number
scale: number
shade: number
+up: readonly [number, number, number] | undefined
x: number
y: number
yaw: number
@@ -7645,6 +7648,7 @@ attach: "upright" | "align" | undefined
canopy: number | undefined
chance: number | undefined
count: readonly [number, number] | undefined
+far: { u0: number; v0: number; u1: number; v1: number; tent?: boolean; } | undefined
footprint: number
id: string
interactive: string | undefined
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 4fd385477..2419d79b1 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -6864,6 +6864,7 @@ kind: string
attach: "upright" | "align"
biome: string
canopy: number
+far: { u0: number; v0: number; u1: number; v1: number; tent?: boolean; } | null | undefined
footprint: number
group: string
id: string
@@ -6919,6 +6920,7 @@ version: 1
chunkSize: number | undefined
drawDistance: number
id: string
+lodDistance: number | undefined
occupies: boolean | undefined
spacing: number
version: number | undefined
@@ -6959,6 +6961,7 @@ width: number | undefined
phase: number
scale: number
shade: number
+up: readonly [number, number, number] | undefined
x: number
y: number
yaw: number
@@ -7938,6 +7941,7 @@ attach: "upright" | "align" | undefined
canopy: number | undefined
chance: number | undefined
count: readonly [number, number] | undefined
+far: { u0: number; v0: number; u1: number; v1: number; tent?: boolean; } | undefined
footprint: number
id: string
interactive: string | undefined
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index b4492e306..291b7d2c0 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -6578,6 +6578,7 @@ kind: string
attach: "upright" | "align"
biome: string
canopy: number
+far: { u0: number; v0: number; u1: number; v1: number; tent?: boolean; } | null | undefined
footprint: number
group: string
id: string
@@ -6633,6 +6634,7 @@ version: 1
chunkSize: number | undefined
drawDistance: number
id: string
+lodDistance: number | undefined
occupies: boolean | undefined
spacing: number
version: number | undefined
@@ -6673,6 +6675,7 @@ width: number | undefined
phase: number
scale: number
shade: number
+up: readonly [number, number, number] | undefined
x: number
y: number
yaw: number
@@ -7652,6 +7655,7 @@ attach: "upright" | "align" | undefined
canopy: number | undefined
chance: number | undefined
count: readonly [number, number] | undefined
+far: { u0: number; v0: number; u1: number; v1: number; tent?: boolean; } | undefined
footprint: number
id: string
interactive: string | undefined
diff --git a/sdk/etc/worldgen.api.md b/sdk/etc/worldgen.api.md
index a1d49b715..ad95ca466 100644
--- a/sdk/etc/worldgen.api.md
+++ b/sdk/etc/worldgen.api.md
@@ -91,6 +91,7 @@ kind: string
attach: "upright" | "align"
biome: string
canopy: number
+far: { u0: number; v0: number; u1: number; v1: number; tent?: boolean; } | null | undefined
footprint: number
group: string
id: string
@@ -146,6 +147,7 @@ version: 1
chunkSize: number | undefined
drawDistance: number
id: string
+lodDistance: number | undefined
occupies: boolean | undefined
spacing: number
version: number | undefined
@@ -167,6 +169,7 @@ attach: "upright" | "align" | undefined
canopy: number | undefined
chance: number | undefined
count: readonly [number, number] | undefined
+far: { u0: number; v0: number; u1: number; v1: number; tent?: boolean; } | undefined
footprint: number
id: string
interactive: string | undefined
diff --git a/sdk/src/foliage/builder.ts b/sdk/src/foliage/builder.ts
index 7e77a74cf..45a280160 100644
--- a/sdk/src/foliage/builder.ts
+++ b/sdk/src/foliage/builder.ts
@@ -28,6 +28,8 @@ export interface Plant {
/** 0 to 1: its own phase in the wind, and how dark its roots are. */
phase: number;
shade: number;
+ /** The ground's normal it leans with (a stone on a slope), after its turn; upright when absent. */
+ up?: readonly [number, number, number];
}
/** What a place is, as the ground answers: how high it is and how much it faces up. */
@@ -220,6 +222,8 @@ export function buildInstancedMesh(source: MeshData, plants: readonly Plant[], p
for (const plant of plants) {
const base = b.pos.length / 3;
const cos = Math.cos(plant.yaw), sin = Math.sin(plant.yaw);
+ const lean = plant.up ? leanTo(plant.up) : null;
+ const q = [0, 0, 0], m = [0, 0, 0];
for (let v = 0; v < source.vertexCount; v++) {
readPosition(v, p3);
if (!readNormal(v, n3)) { n3[0] = 0; n3[1] = 1; n3[2] = 0; }
@@ -227,14 +231,34 @@ export function buildInstancedMesh(source: MeshData, plants: readonly Plant[], p
const t = Math.min(Math.max((p3[1]! - minY) / span, 0), 1);
const x = p3[0]! * plant.scale, y = p3[1]! * plant.scale, z = p3[2]! * plant.scale;
const color = paint ? paintColor(paint, t, plant.shade) : [t, plant.phase, plant.shade * (0.6 + 0.4 * t)] as const;
- vertex(b, plant.x + x * cos + z * sin, plant.y + y, plant.z - x * sin + z * cos, uv2[0]!, uv2[1]!,
- color[0], color[1], color[2], n3[0]! * cos + n3[2]! * sin, n3[1]!, -n3[0]! * sin + n3[2]! * cos);
+ q[0] = x * cos + z * sin; q[1] = y; q[2] = -x * sin + z * cos;
+ m[0] = n3[0]! * cos + n3[2]! * sin; m[1] = n3[1]!; m[2] = -n3[0]! * sin + n3[2]! * cos;
+ if (lean) { lean(q); lean(m); }
+ vertex(b, plant.x + q[0]!, plant.y + q[1]!, plant.z + q[2]!, uv2[0]!, uv2[1]!, color[0], color[1], color[2], m[0]!, m[1]!, m[2]!);
}
for (const i of source.indices) b.idx.push(base + i);
}
return pack(b);
}
+/** The turn that takes up (0, 1, 0) to `n` the shortest way, applied to a vector in place; null when `n` is up. */
+function leanTo(n: readonly [number, number, number]): ((v: number[]) => void) | null {
+ const len = Math.hypot(n[0], n[1], n[2]) || 1;
+ const nx = n[0] / len, ny = n[1] / len, nz = n[2] / len;
+ // The axis is up crossed with n, (nz, 0, -nx); its length the sine of the angle, ny its cosine.
+ const s = Math.hypot(nz, nx);
+ if (s < 1e-6) return null;
+ const ax = nz / s, az = -nx / s, c = ny, k = 1 - c;
+ return (v) => {
+ const [x, y, z] = v as [number, number, number];
+ // Rodrigues: v cos + (axis x v) sin + axis (axis . v)(1 - cos), with the axis in the ground plane.
+ const dot = ax * x + az * z;
+ v[0] = x * c + (-az * y) * s + ax * dot * k;
+ v[1] = y * c + (az * x - ax * z) * s;
+ v[2] = z * c + (ax * y) * s + az * dot * k;
+ };
+}
+
/** The rectangle of the plant's texture a card shows, in uv. */
export interface CardRect {
u0: number;
diff --git a/sdk/src/worldgen/plan.ts b/sdk/src/worldgen/plan.ts
index 29186128d..e1ba41e26 100644
--- a/sdk/src/worldgen/plan.ts
+++ b/sdk/src/worldgen/plan.ts
@@ -48,6 +48,8 @@ export interface Placement {
interactive: string | null;
footprint: number;
canopy: number;
+ /** The far version it is drawn as past its layer's lodDistance, when its recipe gives one. */
+ far: RecipeMember['far'] | null;
}
/** Why a candidate or a member did not stand. */
@@ -285,7 +287,7 @@ export class WorldPlan {
x, y: f.height!, z, yaw: (turn || h) * Math.PI * 2, scale: lerp(m.scale, hash01(this.worldHash_, hashString(group), k, 11), 1),
normal: n, attach: m.attach ?? 'upright', mesh: typeof m.mesh === 'number' ? m.mesh : 0,
material: typeof m.material === 'number' ? m.material : 0, interactive: m.interactive ?? null,
- footprint: m.footprint, canopy: m.canopy ?? m.footprint,
+ footprint: m.footprint, canopy: m.canopy ?? m.footprint, far: m.far ?? null,
};
}
diff --git a/sdk/src/worldgen/rules.ts b/sdk/src/worldgen/rules.ts
index cea2d8d73..339fc9a92 100644
--- a/sdk/src/worldgen/rules.ts
+++ b/sdk/src/worldgen/rules.ts
@@ -67,6 +67,11 @@ export interface RecipeMember {
chance?: number;
/** Tags a zone may keep it out by, beside its recipe's. */
tags?: readonly string[];
+ /**
+ * Decoration's far version past its layer's `lodDistance`: two crossed cards (or a tent, for a conifer) showing this rectangle of its
+ * texture. Absent, it is drawn whole out to `drawDistance`.
+ */
+ far?: { u0: number; v0: number; u1: number; v1: number; tent?: boolean };
}
export interface Recipe {
@@ -86,6 +91,8 @@ export interface PlacementLayer {
spacing: number;
/** How far from the streaming sources the layer is published, and the side of its chunks. */
drawDistance: number;
+ /** Past this, decoration that has a far version is drawn as it; the layer's draw distance when absent. */
+ lodDistance?: number;
chunkSize?: number;
/** Whether later layers keep clear of its footprints (default true). */
occupies?: boolean;
diff --git a/sdk/src/worldgen/worldgenPlugin.ts b/sdk/src/worldgen/worldgenPlugin.ts
index 2c640d05b..81d6cb610 100644
--- a/sdk/src/worldgen/worldgenPlugin.ts
+++ b/sdk/src/worldgen/worldgenPlugin.ts
@@ -21,7 +21,7 @@ import type { App, Plugin } from '../app/app';
import { defineSystem, Schedule } from '../ecs/system';
import { defineResource } from '../ecs/resource';
import {
- defineComponent, MeshRenderer, RuntimeOnly, Transform,
+ defineComponent, getComponent, MeshRenderer, RuntimeOnly, Transform,
type ComponentDef, type MeshRendererData, type TransformData,
} from '../ecs/component';
import { Assets } from '../asset/AssetPlugin';
@@ -29,11 +29,11 @@ import type { MeshData } from '../asset/meshFormat';
import { log } from '../util/logger';
import type { Entity } from '../types';
import { TerrainsRes } from '../terrain/terrainPlugin';
-import { buildInstancedMesh, type Plant } from '../foliage/builder';
+import { buildBillboardMesh, buildInstancedMesh, type Plant } from '../foliage/builder';
import { chunksOf, ProceduralChunksRes, type ChunkLayerStatus } from '../residency/chunks';
import { Environment } from './fields';
import { WorldPlan, type Placement } from './plan';
-import { worldRules, worldRulesRevision, type RecipeMember, type WorldRules } from './rules';
+import { worldRules, worldRulesRevision, type PlacementLayer, type RecipeMember, type WorldRules } from './rules';
import { Zones, type ZoneDef } from './zones';
import { PlacementDiffs } from './diffs';
@@ -144,7 +144,8 @@ interface BuiltWorld {
/** A chunk of a layer: what it places (its decoration merged by mesh, its interactive placements), and what it put in the world. */
interface PlacedChunk {
- decor: { mesh: number; material: number; data: MeshData; origin: [number, number, number] }[];
+ /** A kind of decoration: its near mesh and, when it has one, its far cards; drawn near out to `lodDistance`, out to `drawDistance`. */
+ decor: { mesh: number; material: number; data: MeshData; far: MeshData | null; origin: [number, number, number]; radius: number; lodDistance: number; drawDistance: number }[];
objects: Placement[];
entities: Entity[];
meshes: number[];
@@ -403,7 +404,7 @@ export class WorldGenPlugin implements Plugin {
make: (cx, cz) => {
const x0 = cx * size, z0 = cz * size;
if (waiting || (terrains && ![[x0, z0], [x0 + size, z0], [x0, z0 + size], [x0 + size, z0 + size]].every(([x, z]) => terrains.groundKnownAt(x!, z!)))) return null;
- return this.chunk(app, plan, diffs, layer.id, x0, z0, size, rendering);
+ return this.chunk(app, plan, diffs, layer, x0, z0, size, rendering);
},
publish: (_cx, _cz, value) => this.place(app, gens, entity, value),
release: (_cx, _cz, value) => this.unplace(app, gens, value),
@@ -412,10 +413,10 @@ export class WorldGenPlugin implements Plugin {
}
/** What one chunk of a layer places: its decoration merged by mesh, and its interactive placements, with the changes laid over. */
- private chunk(app: App, plan: WorldPlan, diffs: PlacementDiffs, layer: string, x0: number, z0: number, size: number,
+ private chunk(app: App, plan: WorldPlan, diffs: PlacementDiffs, layer: PlacementLayer, x0: number, z0: number, size: number,
rendering: boolean): PlacedChunk | Promise<PlacedChunk> {
const placements: Placement[] = [];
- for (const p of plan.placementsIn(x0, z0, x0 + size, z0 + size, [layer])) {
+ for (const p of plan.placementsIn(x0, z0, x0 + size, z0 + size, [layer.id])) {
if (diffs.isRemoved(p.id)) continue;
const c = diffs.changeOf(p.id);
placements.push(c ? { ...p, ...c } : p);
@@ -438,8 +439,15 @@ export class WorldGenPlugin implements Plugin {
if (!source || source instanceof Promise) continue;
const plants: Plant[] = list.map((p, i) => ({
x: p.x - origin[0], y: p.y, z: p.z - origin[2], yaw: p.yaw, scale: p.scale, phase: (i * 0.618) % 1, shade: 1,
+ ...(p.attach === 'align' ? { up: p.normal } : {}),
}));
- out.decor.push({ mesh: list[0]!.mesh, material: list[0]!.material, data: buildInstancedMesh(source, plants), origin });
+ const far = list[0]!.far;
+ const width = Math.max(source.aabbMax[0] - source.aabbMin[0], source.aabbMax[2] - source.aabbMin[2]);
+ out.decor.push({
+ mesh: list[0]!.mesh, material: list[0]!.material, data: buildInstancedMesh(source, plants), origin,
+ far: far ? buildBillboardMesh(plants, width, source.aabbMax[1] - source.aabbMin[1], far, undefined, far.tent === true) : null,
+ radius: Math.SQRT2 * size / 2, lodDistance: layer.lodDistance ?? layer.drawDistance, drawDistance: layer.drawDistance,
+ });
}
return out;
};
@@ -471,6 +479,8 @@ export class WorldGenPlugin implements Plugin {
const handle = assets?.createMesh(d.data) ?? 0;
if (!handle) continue;
chunk.meshes.push(handle);
+ const farHandle = d.far ? assets?.createMesh(d.far) ?? 0 : 0;
+ if (farHandle) chunk.meshes.push(farHandle);
const e = world.spawn('WorldGenDecor');
// Made again from the rules whenever its chunk is: a scene or a save never holds it.
world.insert(e, RuntimeOnly);
@@ -478,6 +488,15 @@ export class WorldGenPlugin implements Plugin {
world.insert(e, MeshRenderer, {
mesh: handle, material: d.material, lit: true, opaque: true, cullBackfaces: false, color: { r: 1, g: 1, b: 1, a: 1 },
} as Partial<MeshRendererData>);
+ const lodDef = getComponent('LODGroup');
+ if (lodDef) {
+ // Measured as the engine measures it, by the share of the screen the chunk's sphere covers, for a 60 degree view.
+ const sizeAt = (distance: number): number => d.radius / (Math.max(1, distance) * 0.577);
+ world.insert(e, lodDef, {
+ lod1: farHandle, lod2: 0, lod3: 0, lod1Size: farHandle ? sizeAt(d.lodDistance) : 0, lod2Size: 0, lod3Size: 0,
+ cullSize: sizeAt(d.drawDistance + d.radius), hysteresis: 0.1, enabled: true,
+ });
+ }
world.setParent(e, parent);
chunk.entities.push(e);
}
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index 5a683507c..6c78bd6af 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -2790,4 +2790,6 @@ export const NOTED = {
{"note":"A river runs into a lake cleanly, and water casts no shadow."},
"feat(terrain): a ray meets the ground's triangles anywhere, with no physics and no collision tile there":
{"note":"Rays against the terrain, anywhere."},
+ "feat(worldgen): decoration has a far version past its layer's lodDistance, and leans with the ground when it is aligned":
+ {"note":"Far versions for generated decoration."},
};