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): PlacedFoliage keeps hand-placed plants as data in one entity, grown a cell at a time

yhh719357042fc6
diff --git a/docs/astro/src/content/docs/graphics/foliage.mdx b/docs/astro/src/content/docs/graphics/foliage.mdx
index 941b5287e..2f1e6a0c0 100644
--- a/docs/astro/src/content/docs/graphics/foliage.mdx
+++ b/docs/astro/src/content/docs/graphics/foliage.mdx
@@ -46,9 +46,29 @@ Each cell is built twice. Near, grass is a bent, tapered blade for every plant;
copied in full near, and far is two crossed cards a plant. The engine's own [level of detail](/docs/performance/level-of-detail/) picks between
them by how much of the screen the cell covers, and drops the cell past `drawDistance`.
+## Placed plants
+
+`Foliage` scatters plants by rule. A scene an artist composed has every plant where the artist put it, tens of thousands of them, and as entities that is a
+transform, a renderer and a draw each. **`PlacedFoliage`** keeps them as data in one entity: a table of `kinds` and a list of `records`.
+
+| Field | What it does |
+|---|---|
+| `sizeX`, `sizeZ`, `cellSize` | The area, centred on the entity, and the side of the cells it is cut into. |
+| `kinds` | What each kind is made of: its `parts` (a `mesh`, a cheaper `lod1Mesh`, a `material`, a `texture`, a `tint` and whether it is `opaque`), the `lodDistance` past which the cheaper mesh stands in and the `drawDistance` past which it is not drawn, and a far version, `far` parts drawn from `drawDistance` out to `farDistance`. |
+| `records` | Where each plant stands: six numbers a plant, the kind's index, x, y, z in the entity's space, the turn about the vertical in radians, and the scale. |
+
+The cells round the streaming sources (or the eye) are grown, each as one mesh for every kind in it and part of that kind, and let go with their meshes past the
+distance. A cell appears at once and fills in over the frames after it, each mesh a few milliseconds of the frame's budget, nearest first. A mesh keeps every channel
+the artist made (a normal map, a second uv, a vertex colour); nothing is painted over it, so a plant is drawn with an ordinary material, not the wind's.
+
+The far version is the hierarchical level of detail: a tree's crossed cards, baked to an atlas of their own, merged a cell at a time, shown where the eye is past
+what the kind draws as itself. It is cheap enough that the whole area stands at once. A kind with no far version is not drawn past `drawDistance`.
+
+Plants stand upright and are scaled uniformly; the records carry no tilt. The paths in `kinds` are the project's, listed so a package carries them.
+
## In a package
-Foliage is an optional module, like terrain: a package carries it when a scene has a `Foliage` component or a script imports `esengine/foliage`. It stands on a `Terrain` when the scene has one and needs no terrain module to stand on a flat floor.
+Foliage is an optional module, like terrain: a package carries it when a scene has a `Foliage` or `PlacedFoliage` component or a script imports `esengine/foliage`. It stands on a `Terrain` when the scene has one and needs no terrain module to stand on a flat floor.
## Limits
diff --git a/docs/astro/src/content/docs/zh-cn/graphics/foliage.mdx b/docs/astro/src/content/docs/zh-cn/graphics/foliage.mdx
index 195f06296..701303a59 100644
--- a/docs/astro/src/content/docs/zh-cn/graphics/foliage.mdx
+++ b/docs/astro/src/content/docs/zh-cn/graphics/foliage.mdx
@@ -33,9 +33,25 @@ description: 一个 Foliage 组件,把草或网格散布到一片区域或地形
每个格子构建两次。近处,草是每棵植物一根弯曲、渐细的草叶;远处,是三分之一的草叶,更宽而且更平。网格近处是完整的拷贝,远处是每棵植物两张交叉的卡片。引擎自己的[细节层级](/docs/zh-cn/performance/level-of-detail/)按格子覆盖多少屏幕在它们之间选择,超过 `drawDistance` 就把格子丢掉。
+## 手摆植物
+
+`Foliage` 按规则撒植物。美术搭好的场景里,每一棵都在美术放的位置,常常有几万棵,做成实体就是每棵一个变换、一个渲染器、一次绘制。**`PlacedFoliage`** 把它们当作数据存在一个实体里:一张 `kinds` 种类表和一份 `records` 记录。
+
+| 字段 | 作用 |
+|---|---|
+| `sizeX`、`sizeZ`、`cellSize` | 区域(以实体为中心)和切成的格子边长。 |
+| `kinds` | 每种植物由什么组成:`parts` 部件(`mesh` 网格、更省的 `lod1Mesh`、`material` 材质、`texture` 贴图、`tint` 色调、是否 `opaque`);超过 `lodDistance` 换成更省的网格,超过 `drawDistance` 不再绘制;以及远景版本 `far` 部件,从 `drawDistance` 一直画到 `farDistance`。 |
+| `records` | 每棵植物的位置:每棵六个数,种类序号、x、y、z(在实体空间里)、绕竖直轴的转角(弧度)、缩放。 |
+
+镜头(或流式加载源)周围的格子会被生长出来,每格里每种植物的每个部件合成一个网格,离开距离就连同网格一起释放。格子会立刻出现,之后的几帧里逐步填满:每个网格只占帧预算里的几毫秒,由近到远。网格保留美术做的所有通道(法线贴图、第二套 uv、顶点色),不会被覆盖,所以植物用普通材质绘制,而不是带风的材质。
+
+远景版本就是层级细节(HLOD):树的交叉卡片烘到自己的图集上,按格子合并,镜头比该种类自身的绘制距离更远时显示。它便宜到整个区域可以一次全部长出。没有远景版本的种类,超过 `drawDistance` 就不画。
+
+植物是直立、等比缩放的,记录里没有倾斜。`kinds` 里的路径是项目路径,列出来是为了让包带上它们。
+
## 在包里
-植被和地形一样是可选模块:场景里有 `Foliage` 组件,或脚本导入了 `esengine/foliage`,包里才会带上它。场景里有 `Terrain` 时植被立在地形上;平地上不需要地形模块。
+植被和地形一样是可选模块:场景里有 `Foliage` 或 `PlacedFoliage` 组件,或脚本导入了 `esengine/foliage`,包里才会带上它。场景里有 `Terrain` 时植被立在地形上;平地上不需要地形模块。
## 限制
diff --git a/pipeline/src/project/targetSupport.ts b/pipeline/src/project/targetSupport.ts
index 335329636..0ad0ab52b 100644
--- a/pipeline/src/project/targetSupport.ts
+++ b/pipeline/src/project/targetSupport.ts
@@ -45,7 +45,7 @@ export const SUBSYSTEM_COMPONENTS: Readonly<Record<Subsystem, readonly string[]>
fxBasic: [],
fxAtmosphere: ['Weather', 'TimeOfDay'],
fxLighting: [],
- foliage: ['Foliage'],
+ foliage: ['Foliage', 'PlacedFoliage'],
worldgen: ['WorldGen', 'WorldZone'],
water: ['WaterBody', 'WaterZone', 'Floating'],
spline: ['Spline'],
diff --git a/sdk/src/foliage/builder.ts b/sdk/src/foliage/builder.ts
index 45a280160..b6c6e0632 100644
--- a/sdk/src/foliage/builder.ts
+++ b/sdk/src/foliage/builder.ts
@@ -241,6 +241,58 @@ export function buildInstancedMesh(source: MeshData, plants: readonly Plant[], p
return pack(b);
}
+/**
+ * Copies of an authored mesh, one per plant, as one mesh, with every channel of the source kept: the colour, the second uv and the tangent that a
+ * normal map reads are what the artist made, and the wind's painted weights do not replace them (see buildInstancedMesh for a mesh that is painted).
+ * Each copy is turned about the vertical, scaled and placed; positions, normals and tangents are carried, other channels are copied as they are.
+ */
+export function buildPlacedMesh(source: MeshData, plants: readonly Plant[]): MeshData {
+ const stride = source.vertexStride, count = source.vertexCount;
+ const vertices = new Uint8Array(Math.max(1, count * plants.length) * stride);
+ const indices = new Uint32Array(source.indices.length * plants.length);
+ const at = (semantic: number) => source.channels.find((c) => c.semantic === semantic && c.type === MeshChannelType.Float32 && c.components >= 3)?.offset ?? -1;
+ const posAt = at(MeshChannel.Position), normalAt = at(MeshChannel.Normal), tangentAt = at(MeshChannel.Tangent);
+ const min: [number, number, number] = [Infinity, Infinity, Infinity];
+ const max: [number, number, number] = [-Infinity, -Infinity, -Infinity];
+ // The vertices are read and written as 32-bit words: a vertex is `stride / 4` of them and a channel starts at a whole word, which the packed
+ // format guarantees. This is the hot loop of growing a cell (a cell of grass is a hundred thousand vertices), so no DataView, no calls in it.
+ const words = stride >> 2, p = posAt >> 2, nr = normalAt >> 2, tg = tangentAt >> 2;
+ const f32 = new Float32Array(vertices.buffer), raw = new Uint32Array(vertices.buffer);
+ // The source once, as aligned words: read as floats for the channels that move, copied whole for the rest.
+ const own = new Uint8Array(count * stride);
+ own.set(source.vertices.subarray(0, count * stride));
+ const base = new Float32Array(own.buffer), rawBase = new Uint32Array(own.buffer);
+ const hasNormal = normalAt >= 0, hasTangent = tangentAt >= 0;
+ plants.forEach((plant, n) => {
+ const cos = Math.cos(plant.yaw), sin = Math.sin(plant.yaw), scale = plant.scale;
+ const first = n * count * words;
+ // Every channel copied as it is; the three that move are then rewritten.
+ raw.set(rawBase, first);
+ for (let v = 0, o = first; v < count; v++, o += words) {
+ if (posAt >= 0) {
+ const x = base[v * words + p]! * scale, y = base[v * words + p + 1]! * scale, z = base[v * words + p + 2]! * scale;
+ const wx = x * cos + z * sin + plant.x, wy = y + plant.y, wz = -x * sin + z * cos + plant.z;
+ f32[o + p] = wx; f32[o + p + 1] = wy; f32[o + p + 2] = wz;
+ if (wx < min[0]) min[0] = wx; if (wx > max[0]) max[0] = wx;
+ if (wy < min[1]) min[1] = wy; if (wy > max[1]) max[1] = wy;
+ if (wz < min[2]) min[2] = wz; if (wz > max[2]) max[2] = wz;
+ }
+ if (hasNormal) {
+ const x = base[v * words + nr]!, z = base[v * words + nr + 2]!;
+ f32[o + nr] = x * cos + z * sin; f32[o + nr + 2] = -x * sin + z * cos;
+ }
+ if (hasTangent) {
+ const x = base[v * words + tg]!, z = base[v * words + tg + 2]!;
+ f32[o + tg] = x * cos + z * sin; f32[o + tg + 2] = -x * sin + z * cos;
+ }
+ }
+ const firstIndex = n * source.indices.length, shift = n * count;
+ for (let i = 0; i < source.indices.length; i++) indices[firstIndex + i] = source.indices[i]! + shift;
+ });
+ if (plants.length === 0) { min.fill(0); max.fill(0); }
+ return { channels: source.channels, vertexStride: stride, vertexCount: count * plants.length, vertices, indices, aabbMin: min, aabbMax: max };
+}
+
/** 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;
diff --git a/sdk/src/foliage/foliageSupport.ts b/sdk/src/foliage/foliageSupport.ts
index 82542094c..f57363703 100644
--- a/sdk/src/foliage/foliageSupport.ts
+++ b/sdk/src/foliage/foliageSupport.ts
@@ -9,8 +9,10 @@ import { addEntryPlugin } from '../runtime/entryPlugins';
import { registerBuiltinShaderTemplate } from '../render/builtinShaders';
import { FOLIAGE_SHADER_TEMPLATE } from './foliageShader';
import { FoliagePlugin } from './foliagePlugin';
+import { PlacedFoliagePlugin } from './placedFoliage';
export function registerFoliageSupport(): void {
registerBuiltinShaderTemplate(FOLIAGE_SHADER_TEMPLATE);
addEntryPlugin('foliage', () => new FoliagePlugin());
+ addEntryPlugin('placedFoliage', () => new PlacedFoliagePlugin());
}
diff --git a/sdk/src/foliage/index.ts b/sdk/src/foliage/index.ts
index a7bda1c8b..a4fc6f388 100644
--- a/sdk/src/foliage/index.ts
+++ b/sdk/src/foliage/index.ts
@@ -4,7 +4,13 @@ export {
Foliage, FoliageField, FoliageRes, FoliagePlugin, foliagePlugin, type FoliageData,
} from './foliagePlugin';
export {
- scatterCell, buildGrassMesh, buildInstancedMesh, buildBillboardMesh, rng,
+ PlacedFoliage, PlacedFoliageField, PlacedFoliageRes, PlacedFoliagePlugin, placedFoliagePlugin,
+ type PlacedFoliageData,
+} from './placedFoliage';
+export { PlantGrowth, PlantGrowthRes, plantGrowthOf } from './plantGrowth';
+export { PLACED_STRIDE, type PlacedKind, type PlacedPart, type PlantKind } from './plantKind';
+export {
+ scatterCell, buildGrassMesh, buildInstancedMesh, buildPlacedMesh, buildBillboardMesh, rng,
type Plant, type Ground, type ScatterParams, type BladeParams, type CardRect,
} from './builder';
diff --git a/sdk/src/foliage/placedFoliage.ts b/sdk/src/foliage/placedFoliage.ts
new file mode 100644
index 000000000..04a54aed4
--- /dev/null
+++ b/sdk/src/foliage/placedFoliage.ts
@@ -0,0 +1,260 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file placedFoliage.ts
+ * @brief Everything an artist placed by hand, in one entity: a table of kinds and a list of records, grown a cell at a time near the eye.
+ *
+ * @details A region the artist composed is tens of thousands of placements: trees, shrubs, stones, tufts of grass. As entities that is a
+ * Transform, a MeshRenderer and a draw for each, which no frame holds. Here they are DATA: `kinds` says what each is made of
+ * (its parts: a mesh, its cheaper mesh, a material, a texture, a tint, and how far it is worth drawing), `records` says where
+ * each stands, six numbers a plant. The ground is cut into cells; the cells round the streaming sources (or the eye) are grown,
+ * each as ONE mesh per part and kind with all the plants of that kind in it, and let go with their meshes past the distance. The
+ * scene holds one entity; a frame holds the few hundred draws near the eye. Nothing is baked into the scene.
+ *
+ * A mesh keeps every channel the artist made (see buildPlacedMesh), so a normal map, a second uv or a vertex colour survives;
+ * nothing is painted over it. A plant stands upright, turned about the vertical, and uniformly scaled.
+ */
+import type { App, Plugin } from '../app/app';
+import { defineSystem, Schedule } from '../ecs/system';
+import { defineResource } from '../ecs/resource';
+import { defineComponent, RuntimeOnly, Transform, type ComponentDef, type TransformData } from '../ecs/component';
+import { Assets } from '../asset/AssetPlugin';
+import { log } from '../util/logger';
+import { chunksOf, ProceduralChunksRes } from '../residency/chunks';
+import type { Entity } from '../types';
+import type { Plant } from './builder';
+import { PLACED_STRIDE, type PlacedKind, type PlacedPart } from './plantKind';
+import { plantGrowthOf, prepareKinds, type GrownCell, type ReadyKinds } from './plantGrowth';
+
+export { PLACED_STRIDE, type PlacedKind, type PlacedPart };
+
+/** The fields of the `PlacedFoliage` component. @experimental */
+export interface PlacedFoliageData {
+ sizeX: number;
+ sizeZ: number;
+ cellSize: number;
+ kinds: PlacedKind[];
+ records: number[];
+}
+
+/**
+ * Plants placed by hand. Presence is the opt-in; its children are the cells near the eye.
+ *
+ * @experimental
+ */
+export const PlacedFoliage: ComponentDef<PlacedFoliageData> = defineComponent<PlacedFoliageData>('PlacedFoliage', {
+ sizeX: 256, sizeZ: 256, cellSize: 32, kinds: [] as PlacedKind[], records: [] as number[],
+}, {
+ // The kinds name meshes, materials and textures inside a list, which the component's own fields cannot declare; they are listed here
+ // so a package carries them, and loaded by path when a cell is grown.
+ discoverAssets: (data) => {
+ const refs: { type: 'mesh' | 'material' | 'texture'; path: string }[] = [];
+ for (const kind of (data.kinds as PlacedKind[] | undefined) ?? []) {
+ 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.material) refs.push({ type: 'material', path: p.material });
+ if (p.texture) refs.push({ type: 'texture', path: p.texture });
+ }
+ for (const p of kind.far ?? []) {
+ if (p.mesh) refs.push({ type: 'mesh', path: p.mesh });
+ if (p.material) refs.push({ type: 'material', path: p.material });
+ if (p.texture) refs.push({ type: 'texture', path: p.texture });
+ }
+ }
+ return refs;
+ },
+ fields: {
+ sizeX: { min: 1, category: 'Area', tooltip: 'World size along x, centred on this entity.' },
+ sizeZ: { min: 1, category: 'Area', tooltip: 'World size along z, centred on this entity.' },
+ cellSize: { min: 4, category: 'Area', tooltip: 'Side of the cells the area is cut into. Each kind in a cell is one mesh a part, culled whole.' },
+ kinds: { category: 'Plants', tooltip: 'What each kind of plant is made of: its parts (mesh, cheaper mesh, material, texture, tint) and how far it is drawn.' },
+ records: { category: 'Plants', tooltip: 'Where each plant stands: kind index, x, y, z, turn about the vertical in radians and scale, six numbers a plant, in this entity\'s space.' },
+ },
+});
+
+interface BuiltPlaced {
+ signature: string;
+ data: PlacedFoliageData;
+ /** The kinds' parts once their assets are in hand. */
+ ready: ReadyKinds | null;
+ /** The records sorted into cells (`cz * 1000 + cx`), by kind, the first time a cell asks. */
+ cells: Map<number, Map<number, Plant[]>> | null;
+ epoch: number;
+}
+
+const layerOf = (entity: Entity): string => `placed:${entity}`;
+
+/** Told by its sizes and a strided sample of the records, so a frame does not hash tens of thousands of numbers. */
+function signatureOf(data: PlacedFoliageData): string {
+ const { records, kinds, ...rest } = data;
+ let sample = 0;
+ const n = records.length, step = Math.max(1, Math.floor(n / 127));
+ for (let i = 0; i < n; i += step) sample = (Math.imul(sample, 31) + Math.round(records[i]! * 64)) | 0;
+ return `${JSON.stringify(rest)}|${JSON.stringify(kinds)}|${n}|${sample}`;
+}
+
+/** Run-time facts about the placed foliage. */
+export class PlacedFoliageField {
+ /** @internal */ readonly built_ = new Map<Entity, BuiltPlaced>();
+ /** @internal */ app_: App | null = null;
+
+ /** How many meshes are still waiting to be made, across every plant in the app. */
+ get pending(): number { return this.app_ ? plantGrowthOf(this.app_).pending : 0; }
+
+ /** How many cells are grown and standing now, across every entity. */
+ get cellCount(): number {
+ const app = this.app_;
+ if (!app?.hasResource(ProceduralChunksRes)) return 0;
+ let n = 0;
+ for (const entity of this.built_.keys()) {
+ for (const id of [layerOf(entity), `${layerOf(entity)}:far`]) {
+ const s = app.getResource(ProceduralChunksRes).status(id);
+ if (s) n += s.ready + s.stale;
+ }
+ }
+ return n;
+ }
+}
+
+export class PlacedFoliagePlugin implements Plugin {
+ name = 'placedFoliage';
+
+ build(app: App): void {
+ const field = new PlacedFoliageField();
+ field.app_ = app;
+ app.insertResource(PlacedFoliageRes, field);
+ plantGrowthOf(app);
+
+ app.addSystemToSchedule(Schedule.Update, defineSystem([], () => {
+ if (!app.hasResource(Assets)) return;
+ for (const entity of field.built_.keys()) {
+ if (app.world.valid(entity) && app.world.has(entity, PlacedFoliage)) continue;
+ if (app.hasResource(ProceduralChunksRes)) {
+ app.getResource(ProceduralChunksRes).remove(layerOf(entity));
+ app.getResource(ProceduralChunksRes).remove(`${layerOf(entity)}:far`);
+ }
+ field.built_.delete(entity);
+ }
+ for (const entity of app.world.getEntitiesWithComponents([PlacedFoliage, Transform])) {
+ const data = app.world.get(entity, PlacedFoliage) as PlacedFoliageData;
+ const signature = signatureOf(data);
+ let built = field.built_.get(entity);
+ if (!built || built.signature !== signature) {
+ built = { signature, data: { ...data }, ready: null, cells: null, epoch: (built?.epoch ?? 0) + 1 };
+ field.built_.set(entity, built);
+ void this.start(app, built);
+ }
+ this.layers(app, entity, built);
+ }
+ }, { name: 'PlacedFoliageSystem' }));
+ }
+
+ cleanup(app?: App): void {
+ if (!app?.hasResource(PlacedFoliageRes)) return;
+ const field = app.getResource(PlacedFoliageRes);
+ for (const entity of field.built_.keys()) {
+ if (app.hasResource(ProceduralChunksRes)) {
+ app.getResource(ProceduralChunksRes).remove(layerOf(entity));
+ app.getResource(ProceduralChunksRes).remove(`${layerOf(entity)}:far`);
+ }
+ }
+ field.built_.clear();
+ }
+
+ /** Reads the geometry and makes the handles of every part of every kind; the cells wait for it. */
+ private async start(app: App, built: BuiltPlaced): Promise<void> {
+ const epoch = built.epoch;
+ try {
+ const ready = await prepareKinds(app.getResource(Assets), built.data.kinds);
+ if (built.epoch === epoch) built.ready = ready;
+ } catch (e) {
+ log.error('foliage', 'preparing the placed plants failed', e);
+ }
+ }
+
+ private cellsAcross(data: PlacedFoliageData): { x: number; z: number } {
+ const side = Math.max(1, data.cellSize);
+ return { x: Math.min(200, Math.max(1, Math.ceil(data.sizeX / side))), z: Math.min(200, Math.max(1, Math.ceil(data.sizeZ / side))) };
+ }
+
+ /**
+ * The cells as two layers of chunks: the near one, wanted out to the furthest `drawDistance` and grown a few milliseconds a piece, and the far one
+ * (the hierarchical level of detail), wanted out to the furthest `farDistance` and cheap enough that the whole area stands at once.
+ */
+ private layers(app: App, entity: Entity, built: BuiltPlaced): void {
+ const data = built.data, t = app.world.get(entity, Transform) as TransformData;
+ const cells = this.cellsAcross(data);
+ const sx = t.worldScale.x || 1, sz = t.worldScale.z || 1;
+ const growth = plantGrowthOf(app), chunks = chunksOf(app);
+ let reach = 1, farReach = 0;
+ for (const kind of data.kinds) { reach = Math.max(reach, kind.drawDistance); if ((kind.far?.length ?? 0) > 0) farReach = Math.max(farReach, kind.farDistance); }
+ const generation = `${built.epoch}:${t.worldPosition.x}:${t.worldPosition.y}:${t.worldPosition.z}:${sx}:${sz}`;
+ const area = {
+ originX: t.worldPosition.x - data.sizeX / 2 * sx, originZ: t.worldPosition.z - data.sizeZ / 2 * sz,
+ sizeX: data.sizeX / cells.x * sx, sizeZ: data.sizeZ / cells.z * sz, extent: [0, 0, cells.x, cells.z] as [number, number, number, number], generation,
+ };
+ /** A cell's entity at its centre, and where its plants stand relative to it. */
+ const spawn = (cx: number, cz: number, name: string): { cell: GrownCell; by: Map<number, Plant[]> | null; at: { x: number; z: number } } | null => {
+ const by = this.sort(built, cells).get(cz * 1000 + cx) ?? null;
+ if (!by) return { cell: { entity: null, handles: [], dead: false }, by: null, at: { x: 0, z: 0 } };
+ const lx = -data.sizeX / 2 + (cx + 0.5) * (data.sizeX / cells.x), lz = -data.sizeZ / 2 + (cz + 0.5) * (data.sizeZ / cells.z);
+ const e = app.world.spawn(`${name} ${cx},${cz}`);
+ app.world.insert(e, Transform, { position: { x: lx, y: 0, z: lz } });
+ app.world.insert(e, RuntimeOnly);
+ const relative = new Map<number, Plant[]>();
+ for (const [k, list] of by) relative.set(k, list.map((p) => ({ ...p, x: p.x - lx, z: p.z - lz })));
+ return { cell: { entity: e, handles: [], dead: false }, by: relative, at: { x: t.worldPosition.x + lx * sx, z: t.worldPosition.z + lz * sz } };
+ };
+ chunks.set<GrownCell>(layerOf(entity), {
+ label: 'Growing the placed plants', ...area, loadRadius: reach, unloadRadius: reach + Math.max(1, data.cellSize) * 1.5,
+ make: (cx, cz) => {
+ if (!built.ready) return null;
+ const made = spawn(cx, cz, 'PlacedCell');
+ if (made?.by) growth.growCell(app, made.cell, data.kinds, built.ready, made.by);
+ return made?.cell ?? null;
+ },
+ publish: (_cx, _cz, cell) => { if (cell.entity !== null) app.world.setParent(cell.entity, entity); },
+ release: (_cx, _cz, cell) => growth.release(app, cell),
+ });
+ const farId = `${layerOf(entity)}:far`;
+ if (farReach <= 0) { chunks.remove(farId); return; }
+ chunks.set<GrownCell>(farId, {
+ label: 'Growing the far plants', ...area, loadRadius: farReach, unloadRadius: farReach + Math.max(1, data.cellSize) * 1.5,
+ make: (cx, cz) => {
+ if (!built.ready) return null;
+ const made = spawn(cx, cz, 'FarCell');
+ if (made?.by) growth.growFar(app, made.cell, data.kinds, built.ready, made.by, made.at);
+ return made?.cell ?? null;
+ },
+ publish: (_cx, _cz, cell) => { if (cell.entity !== null) app.world.setParent(cell.entity, entity); },
+ release: (_cx, _cz, cell) => growth.release(app, cell),
+ });
+ }
+
+ /** Sorts the records into cells and kinds, once. */
+ private sort(built: BuiltPlaced, cells: { x: number; z: number }): Map<number, Map<number, Plant[]>> {
+ if (built.cells) return built.cells;
+ const data = built.data, a = data.records;
+ const w = data.sizeX / cells.x, d = data.sizeZ / cells.z;
+ const sorted = new Map<number, Map<number, Plant[]>>();
+ for (let i = 0; i + PLACED_STRIDE <= a.length; i += PLACED_STRIDE) {
+ const kind = a[i]!, x = a[i + 1]!, z = a[i + 3]!;
+ const ix = Math.floor((x + data.sizeX / 2) / w), iz = Math.floor((z + data.sizeZ / 2) / d);
+ if (ix < 0 || iz < 0 || ix >= cells.x || iz >= cells.z) continue;
+ const key = iz * 1000 + ix;
+ let byKind = sorted.get(key);
+ if (!byKind) sorted.set(key, byKind = new Map());
+ let list = byKind.get(kind);
+ if (!list) byKind.set(kind, list = []);
+ list.push({ x, y: a[i + 2]!, z, yaw: a[i + 4]!, scale: a[i + 5]!, phase: 0, shade: 1 });
+ }
+ built.cells = sorted;
+ return sorted;
+ }
+}
+
+/** The resource the plugin installs. @experimental */
+export const PlacedFoliageRes = defineResource<PlacedFoliageField>(new PlacedFoliageField(), 'PlacedFoliage');
+
+export const placedFoliagePlugin: Plugin = new PlacedFoliagePlugin();
diff --git a/sdk/src/foliage/plantGrowth.ts b/sdk/src/foliage/plantGrowth.ts
new file mode 100644
index 000000000..6f6d5ad05
--- /dev/null
+++ b/sdk/src/foliage/plantGrowth.ts
@@ -0,0 +1,245 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file plantGrowth.ts
+ * @brief Growing plants a cell at a time inside the frame's budget: what `PlacedFoliage` and a generated world's plants share.
+ *
+ * @details A cell is an entity that stands at once, empty, and fills in over the frames after it: every kind in it and every part of that kind is
+ * one mesh (a batch of plants no bigger than a few milliseconds of work), made from the plants' own meshes with every channel kept (see
+ * buildPlacedMesh). Past the kind's distance a cheaper mesh stands in (a `LODGroup`), and past that its far version (a tree's crossed
+ * cards, merged a cell at a time) is shown where the eye is: the hierarchical level of detail. The pieces wait in one queue for the whole
+ * app and are made while the frame's budget lasts, nearest asked first; a cell let go first leaves its pieces unmade.
+ *
+ * The thresholds are made from the sphere of each piece's own mesh, as the engine measures a renderer, and not from the cell's: a tree's crown
+ * and its trunk have spheres of their own, and a cell's radius would hand over, and cull, a third as far as the kind says.
+ */
+import type { App } from '../app/app';
+import { defineSystem, Schedule } from '../ecs/system';
+import { defineResource } from '../ecs/resource';
+import {
+ Camera, getComponent, MeshRenderer, RuntimeOnly, Transform,
+ type CameraData, type MeshRendererData, type TransformData,
+} from '../ecs/component';
+import { Assets } from '../asset/AssetPlugin';
+import type { Assets as AssetsApi } from '../asset/Assets';
+import type { MeshData } from '../asset/meshFormat';
+import { log } from '../util/logger';
+import { bakesOf } from '../runtime/bakes';
+import type { Entity } from '../types';
+import { buildPlacedMesh, type Plant } from './builder';
+import type { PlacedKind, PlacedPart } from './plantKind';
+
+/** A part with what it needs in hand: its geometry read, its handles made. */
+export interface ReadyPart { part: PlacedPart; source: MeshData; lod1: MeshData | null; material: number; texture: number }
+
+/** Every kind's parts in hand, and the parts that stand for each far off. */
+export interface ReadyKinds { kinds: ReadyPart[][]; far: ReadyPart[][] }
+
+/** One grown cell: its entity (none where nothing stands), the meshes it owns so far, and whether it has been let go. */
+export interface GrownCell { entity: Entity | null; handles: number[]; dead: boolean }
+
+/** The most vertices one mesh of a cell takes: a piece of work of a few milliseconds, which a frame's budget can fit between others. */
+const BATCH_VERTICES = 24000;
+
+interface FarCell {
+ /** Where the cell is, in the world's x and z. */
+ x: number;
+ z: number;
+ owner: Entity;
+ kinds: readonly PlacedKind[];
+ children: { entity: Entity; kind: number; shown: boolean }[];
+}
+
+/** Reads the geometry and makes the handles of every part of every kind. */
+export async function prepareKinds(assets: AssetsApi, kinds: readonly PlacedKind[]): Promise<ReadyKinds> {
+ const ready = async (part: PlacedPart, withLod: boolean): Promise<ReadyPart | null> => {
+ const source = await assets.readMeshData((await assets.load<{ handle: number }>('mesh', part.mesh)).handle);
+ if (!source) { log.warn('foliage', `the geometry of ${part.mesh} cannot be read, so its plants are left out`); return null; }
+ let lod1: MeshData | null = null;
+ if (withLod && part.lod1Mesh) lod1 = await assets.readMeshData((await assets.load<{ handle: number }>('mesh', part.lod1Mesh)).handle);
+ return {
+ part, source, lod1,
+ material: part.material ? (await assets.loadMaterial(part.material)).handle : 0,
+ texture: part.texture ? (await assets.loadTexture(part.texture)).handle : 0,
+ };
+ };
+ const out: ReadyKinds = { kinds: [], far: [] };
+ for (const kind of kinds) {
+ const parts: ReadyPart[] = [], far: ReadyPart[] = [];
+ for (const part of kind.parts) { const r = await ready(part, true); if (r) parts.push(r); }
+ for (const part of kind.far ?? []) { const r = await ready(part, false); if (r) far.push(r); }
+ out.kinds.push(parts);
+ out.far.push(far);
+ }
+ return out;
+}
+
+/** The growth of every plant in an app: the pieces waiting, and the far cells standing. */
+export class PlantGrowth {
+ /** The pieces not yet made, in the order they were asked. */
+ readonly queue: { cell: GrownCell; run: () => void }[] = [];
+ private readonly far_ = new Set<FarCell>();
+ app_: App | null = null;
+
+ /** How many meshes are still waiting to be made. */
+ get pending(): number { return this.queue.length; }
+
+ /** Pieces made so far, and the milliseconds spent making them: what the growth has cost, for a profile to read. */
+ made = 0;
+ spentMs = 0;
+
+ /**
+ * Grows `cell`, whose entity the caller has made and stands at the cell's centre: the plants of each kind in `byKind` (relative to that centre),
+ * as pieces of work. `side` is the cell's side, for where the far version is shown from.
+ */
+ growCell(app: App, cell: GrownCell, kinds: readonly PlacedKind[], ready: ReadyKinds, byKind: ReadonlyMap<number, readonly Plant[]>): void {
+ const world = app.world, entity = cell.entity;
+ if (entity === null) return;
+ const assets = app.getResource(Assets);
+ const lodDef = getComponent('LODGroup');
+ const sphereOf = (m: MeshData): number => 0.5 * Math.hypot(m.aabbMax[0] - m.aabbMin[0], m.aabbMax[1] - m.aabbMin[1], m.aabbMax[2] - m.aabbMin[2]);
+ const sizeAt = (radius: number, distance: number): number => radius / (Math.max(1, distance) * 0.577);
+ const made = (mesh: MeshData): number => {
+ const handle = assets.createMesh(mesh);
+ if (handle === 0) throw new Error('the engine refused the geometry of a cell of plants');
+ cell.handles.push(handle);
+ return handle;
+ };
+ for (const [kindIndex, plants] of byKind) {
+ const kind = kinds[kindIndex], parts = ready.kinds[kindIndex];
+ if (!kind || !parts) continue;
+ parts.forEach((r, j) => {
+ const per = Math.max(1, Math.floor(BATCH_VERTICES / Math.max(1, r.source.vertexCount)));
+ for (let from = 0; from < plants.length; from += per) {
+ const batch = plants.slice(from, from + per);
+ this.queue.push({ cell, run: () => {
+ if (!world.valid(entity)) return;
+ try {
+ const near = buildPlacedMesh(r.source, batch);
+ const e = world.spawn(`${kindIndex}:${j}`);
+ world.insert(e, RuntimeOnly);
+ world.insert(e, Transform, {});
+ world.insert(e, MeshRenderer, {
+ mesh: made(near), material: r.material, texture: r.texture, lit: true, opaque: r.part.opaque !== false, cullBackfaces: false,
+ color: { r: r.part.tint[0], g: r.part.tint[1], b: r.part.tint[2], a: r.part.tint[3] },
+ } as Partial<MeshRendererData>);
+ if (lodDef) {
+ const coarse = r.lod1 ? buildPlacedMesh(r.lod1, batch) : null;
+ const far = coarse ? made(coarse) : 0;
+ // The engine's bounds for the group are the union of its levels, so the sphere is the union's.
+ const radius = sphereOf(coarse ? {
+ ...near,
+ aabbMin: near.aabbMin.map((v, i) => Math.min(v, coarse.aabbMin[i]!)) as [number, number, number],
+ aabbMax: near.aabbMax.map((v, i) => Math.max(v, coarse.aabbMax[i]!)) as [number, number, number],
+ } : near);
+ world.insert(e, lodDef, {
+ lod1: far, lod2: 0, lod3: 0, lod1Size: far ? sizeAt(radius, kind.lodDistance) : 0, lod2Size: 0, lod3Size: 0,
+ cullSize: sizeAt(radius, kind.drawDistance + radius), hysteresis: 0.1, enabled: true,
+ });
+ }
+ world.setParent(e, entity);
+ } catch (error) {
+ log.error('foliage', 'growing a piece of a cell of plants failed', error);
+ }
+ } });
+ }
+ });
+ }
+ }
+
+ /**
+ * Grows the far version of `cell`: each kind with one, its plants as one mesh a far part, hidden until the eye is far enough (`kind.drawDistance`
+ * to `kind.farDistance` from the cell's centre, at world x and z `at`). Cheap enough (a tree is two cards) to be made at once.
+ */
+ growFar(app: App, cell: GrownCell, kinds: readonly PlacedKind[], ready: ReadyKinds, byKind: ReadonlyMap<number, readonly Plant[]>, at: { x: number; z: number }): void {
+ const world = app.world, entity = cell.entity;
+ if (entity === null) return;
+ const assets = app.getResource(Assets);
+ const children: FarCell['children'] = [];
+ for (const [kindIndex, plants] of byKind) {
+ const parts = ready.far[kindIndex];
+ if (!parts || parts.length === 0) continue;
+ for (const r of parts) {
+ const handle = assets.createMesh(buildPlacedMesh(r.source, plants));
+ if (handle === 0) continue;
+ cell.handles.push(handle);
+ const e = world.spawn(`far ${kindIndex}`);
+ world.insert(e, RuntimeOnly);
+ world.insert(e, Transform, {});
+ world.insert(e, MeshRenderer, {
+ mesh: handle, material: r.material, texture: r.texture, lit: true, opaque: r.part.opaque !== false, cullBackfaces: false, enabled: false,
+ color: { r: r.part.tint[0], g: r.part.tint[1], b: r.part.tint[2], a: r.part.tint[3] },
+ } as Partial<MeshRendererData>);
+ world.setParent(e, entity);
+ children.push({ entity: e, kind: kindIndex, shown: false });
+ }
+ }
+ if (children.length > 0) this.far_.add({ x: at.x, z: at.z, owner: entity, kinds, children });
+ }
+
+ /** Lets a cell go: what it made is despawned and given back, and what it had not yet made is left unmade. */
+ release(app: App, cell: GrownCell): void {
+ cell.dead = true;
+ for (const f of this.far_) if (f.owner === cell.entity) this.far_.delete(f);
+ if (cell.entity !== null && app.world.valid(cell.entity)) app.world.despawn(cell.entity);
+ const assets = app.getResource(Assets);
+ for (const handle of cell.handles) assets.releaseBuiltMesh(handle);
+ cell.handles.length = 0;
+ }
+
+ /** Shows a far part where the eye is past what its kind draws as itself, and hides it nearer and further. */
+ private showFar(app: App): void {
+ if (this.far_.size === 0) return;
+ const world = app.world;
+ let eye: { x: number; z: number } | null = null;
+ for (const e of world.getEntitiesWithComponents([Camera, Transform])) {
+ if (!(world.get(e, Camera) as CameraData).isActive) continue;
+ const w = (world.get(e, Transform) as TransformData).worldPosition;
+ eye = { x: w.x, z: w.z };
+ break;
+ }
+ if (!eye) return;
+ for (const cell of this.far_) {
+ const d = Math.hypot(cell.x - eye.x, cell.z - eye.z);
+ for (const child of cell.children) {
+ const kind = cell.kinds[child.kind];
+ if (!kind) continue;
+ const show = d > kind.drawDistance && d < kind.farDistance;
+ if (show === child.shown || !world.valid(child.entity)) continue;
+ child.shown = show;
+ world.insert(child.entity, MeshRenderer, { ...(world.get(child.entity, MeshRenderer) as MeshRendererData), enabled: show });
+ }
+ }
+ }
+
+ /** One frame of it: the far versions shown where they should be, and the queue worked through while the frame's budget lasts, one piece at least. */
+ step(app: App): void {
+ this.showFar(app);
+ const bakes = bakesOf(app);
+ let first = true;
+ while (this.queue.length > 0 && (first || bakes.hasTime())) {
+ first = false;
+ const piece = this.queue.shift()!;
+ if (piece.cell.dead) continue;
+ const t0 = performance.now();
+ piece.run();
+ this.spentMs += performance.now() - t0;
+ this.made++;
+ }
+ bakes.mark(this, 'Growing the plants', this.queue.length === 0 ? 1 : 0.5);
+ }
+}
+
+/** The resource every plant's growth shares. @experimental */
+export const PlantGrowthRes = defineResource<PlantGrowth>(new PlantGrowth(), 'PlantGrowth');
+
+/** The App's plant growth, installed (with the system that steps it) on first use. */
+export function plantGrowthOf(app: App): PlantGrowth {
+ if (!app.hasResource(PlantGrowthRes)) {
+ const growth = new PlantGrowth();
+ growth.app_ = app;
+ app.insertResource(PlantGrowthRes, growth);
+ app.addSystemToSchedule(Schedule.Update, defineSystem([], () => { if (app.hasResource(Assets)) growth.step(app); }, { name: 'PlantGrowthSystem' }));
+ }
+ return app.getResource(PlantGrowthRes);
+}
diff --git a/sdk/src/foliage/plantKind.ts b/sdk/src/foliage/plantKind.ts
new file mode 100644
index 000000000..5ae62f9e3
--- /dev/null
+++ b/sdk/src/foliage/plantKind.ts
@@ -0,0 +1,53 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file plantKind.ts
+ * @brief What a kind of plant is made of, as data: the shape both a `PlacedFoliage` and a world's recipes name plants by.
+ *
+ * @details Types and a constant only, so the world-generation module can describe a plant without carrying the code that grows it.
+ */
+
+/** One part of a kind: what is drawn, and with what. Paths are the project's. */
+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;
+ material: string;
+ texture: string;
+ tint: [number, number, number, number];
+ /** False for a part that is blended (glass, a decal): it is drawn after what is solid. */
+ opaque: boolean;
+}
+
+/** A kind of plant: its parts, and how far it is drawn. */
+export interface PlacedKind {
+ parts: PlacedPart[];
+ /** Past this the cheaper mesh stands in. */
+ lodDistance: number;
+ /** Past this the kind is not drawn as itself. */
+ drawDistance: number;
+ /**
+ * The hierarchical level of detail: what stands for the kind from `drawDistance` out to `farDistance`, once the plants themselves are too small to
+ * draw: parts of their own (a tree's crossed cards, with the atlas they were baked to), merged a cell at a time like the plants are. Empty has none.
+ */
+ far: PlacedPart[];
+ farDistance: number;
+}
+
+/**
+ * A kind a world's recipes name (`WorldRules.plants`): the same, with the colourings the art gives it and how far it is sunk into the ground.
+ *
+ * `tints` are linear multipliers on the parts' colour, which a place takes one of by a slow noise (`tintScale` world units to a stand), so a wood has
+ * warm and cool stands and not a speckle. Absent, the kind is as made.
+ */
+export interface PlantKind extends PlacedKind {
+ tints?: [number, number, number][];
+ tintScale?: number;
+ /** How far a plant is sunk into the ground, in world units: a stone's buried underside. */
+ sink?: number;
+ /** World units to a unit of the plant's mesh: 100 for plants modelled in metres in a world of centimetres. A recipe's `scale` is then a size relative to the model. Default 1. */
+ unit?: number;
+}
+
+/** Numbers a record takes in `PlacedFoliage.records`: the kind's index, x, y, z in the entity's space, the turn about the vertical in radians, and the scale. */
+export const PLACED_STRIDE = 6;
diff --git a/sdk/tests/foliage-builder.test.ts b/sdk/tests/foliage-builder.test.ts
index 375d534ba..8abe99144 100644
--- a/sdk/tests/foliage-builder.test.ts
+++ b/sdk/tests/foliage-builder.test.ts
@@ -1,8 +1,8 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
import { describe, it, expect } from 'vitest';
-import { MeshChannel } from '../src/asset/meshFormat';
-import { buildBillboardMesh, buildGrassMesh, buildInstancedMesh, rng, scatterCell, type Ground, type Plant } from '../src/foliage/builder';
+import { MeshChannel, MeshChannelType, packChannels, type MeshData } from '../src/asset/meshFormat';
+import { buildBillboardMesh, buildGrassMesh, buildInstancedMesh, buildPlacedMesh, rng, scatterCell, type Ground, type Plant } from '../src/foliage/builder';
const flat: Ground = () => ({ y: 2, up: 1 });
const params = {
@@ -133,3 +133,60 @@ describe('instanced meshes and billboards', () => {
expect(mesh.indices.length).toBe(0);
});
});
+
+describe('placed meshes', () => {
+ // One triangle with every channel an authored plant has: position, uv, colour, normal and a tangent.
+ const { channels, vertexStride } = packChannels([
+ { semantic: MeshChannel.Position, components: 3, type: MeshChannelType.Float32 },
+ { semantic: MeshChannel.TexCoord0, components: 2, type: MeshChannelType.Float32 },
+ { semantic: MeshChannel.Color, components: 4, type: MeshChannelType.UNorm8 },
+ { semantic: MeshChannel.Normal, components: 3, type: MeshChannelType.Float32 },
+ { semantic: MeshChannel.Tangent, components: 4, type: MeshChannelType.Float32 },
+ ]);
+ const vertices = new Uint8Array(3 * vertexStride);
+ const view = new DataView(vertices.buffer);
+ const at = (s: number) => channels.find((c) => c.semantic === s)!.offset;
+ [[1, 0, 0], [0, 2, 0], [0, 0, 1]].forEach((p, v) => {
+ p.forEach((x, k) => view.setFloat32(v * vertexStride + at(MeshChannel.Position) + k * 4, x, true));
+ view.setFloat32(v * vertexStride + at(MeshChannel.Normal), 1, true);
+ view.setFloat32(v * vertexStride + at(MeshChannel.Tangent), 1, true);
+ view.setFloat32(v * vertexStride + at(MeshChannel.Tangent) + 12, -1, true);
+ view.setFloat32(v * vertexStride + at(MeshChannel.TexCoord0), 0.25 * (v + 1), true);
+ vertices.set([10, 20, 30, 255], v * vertexStride + at(MeshChannel.Color));
+ });
+ const source: MeshData = { channels, vertexStride, vertexCount: 3, vertices, indices: new Uint32Array([0, 1, 2]), aabbMin: [0, 0, 0], aabbMax: [1, 2, 1] };
+ const readF = (m: MeshData, v: number, semantic: number, k: number) =>
+ new DataView(m.vertices.buffer).getFloat32(v * m.vertexStride + m.channels.find((c) => c.semantic === semantic)!.offset + k * 4, true);
+
+ it('keeps every channel and places, turns and scales a copy a plant', () => {
+ const plants: Plant[] = [
+ { x: 5, y: 1, z: 0, yaw: 0, scale: 2, phase: 0, shade: 1 },
+ { x: 0, y: 0, z: 0, yaw: Math.PI / 2, scale: 1, phase: 0, shade: 1 },
+ ];
+ const m = buildPlacedMesh(source, plants);
+ expect(m.channels).toEqual(source.channels);
+ expect(m.vertexCount).toBe(6);
+ expect([...m.indices]).toEqual([0, 1, 2, 3, 4, 5]);
+ // First copy: the point (1, 0, 0) scaled by two, then moved by (5, 1, 0).
+ expect(positionOf(m, 0)).toEqual([7, 1, 0]);
+ // Second copy: a quarter turn about the vertical takes (1, 0, 0) to (0, 0, -1).
+ const p = positionOf(m, 3);
+ expect(p[0]).toBeCloseTo(0, 5);
+ expect(p[2]).toBeCloseTo(-1, 5);
+ // The normal and the tangent turn with it, the tangent's handedness and the uv and colour are copied as they are.
+ expect(readF(m, 3, MeshChannel.Normal, 2)).toBeCloseTo(-1, 5);
+ expect(readF(m, 3, MeshChannel.Tangent, 2)).toBeCloseTo(-1, 5);
+ expect(readF(m, 3, MeshChannel.Tangent, 3)).toBe(-1);
+ expect(readF(m, 4, MeshChannel.TexCoord0, 0)).toBeCloseTo(0.5, 5);
+ expect(colorOf(m as never, 5)).toEqual([10, 20, 30, 255]);
+ });
+
+ it('bounds what it placed, and is an empty mesh for no plants', () => {
+ const m = buildPlacedMesh(source, [{ x: 5, y: 1, z: 0, yaw: 0, scale: 2, phase: 0, shade: 1 }]);
+ expect(m.aabbMin).toEqual([5, 1, 0]);
+ expect(m.aabbMax).toEqual([7, 5, 2]);
+ const none = buildPlacedMesh(source, []);
+ expect(none.vertexCount).toBe(0);
+ expect(none.indices.length).toBe(0);
+ });
+});
diff --git a/tools/check-corpus-authoring.mjs b/tools/check-corpus-authoring.mjs
index 8867a77e6..7b60e3ff1 100644
--- a/tools/check-corpus-authoring.mjs
+++ b/tools/check-corpus-authoring.mjs
@@ -122,6 +122,7 @@ const DISPOSITION = {
// — derived: a system writes them; authored, they would be a bug —
RuntimeOnly: ['derived', 'tags a world-only entity a system re-derives; scene serialization skips tagged entities, so authoring one would delete it on save'],
NetGhost: ['derived', 'replication tags a remote proxy with it; the authority writes it, never the scene'],
+ PlacedFoliage: ['derived', 'a generated world grows its plants through the same machinery without the component, and a project that places plants by hand writes the kinds and records with a script from its own rules; the lists are generated data, not something a scene is authored by hand with'],
PlacedObject: ['derived', 'a generated world writes it on what it places for the game to interact with; authored, it would name a placement no rule made'],
SceneOwner: ['derived', 'scene loading records which scene an entity came from; authoring it would claim an ownership the loader never granted'],