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(2d): a generated world on the screen plane, laid out by the worldgen rules and published in chunks

yhh62b0f3f08f65
diff --git a/docs/astro/src/content/docs/world/generation.mdx b/docs/astro/src/content/docs/world/generation.mdx
index 0ce6ea769..269a8ec06 100644
--- a/docs/astro/src/content/docs/world/generation.mdx
+++ b/docs/astro/src/content/docs/world/generation.mdx
@@ -176,6 +176,36 @@ always included, in `.esengine/asset-groups.json`:
{ "version": "1.0", "groups": { "recipes": { "folder": "assets/models", "mode": "local", "alwaysInclude": true } } }
```
+## A 2D world
+
+The same rules lay out a 2D world: no terrain, the plan read flat over **x and y**, published in chunks round the camera. Nothing is drawn by the engine; what a
+placement looks like (a sprite, a prefab) and how the ground is painted (a tile layer, a shader) are yours, said in `publish`.
+
+```typescript
+import { registerWorldRules, createWorld2D } from 'esengine/worldgen';
+
+registerWorldRules(rules); // biomes, recipes and layers, as above
+const world = createWorld2D(app, 'island', {
+ rules: rules.id, seed: 11, chunkSize: 512, cellSize: 32,
+ publish(chunk) {
+ // chunk.placements: what stands here (id, recipe, member, biome, x, y, scale, interactive, footprint...)
+ // chunk.biomeGrid: the biome of each cell of the ground, indexes chunk.biomes
+ const spawned = spawnTilesAndSprites(chunk);
+ return () => despawn(spawned); // taking the chunk away
+ },
+});
+
+world.diffs.remove(tree.id); // felled: only that chunk is made again, and it stays felled
+```
+
+- **Chunks follow the camera** (or the streaming sources), nearest first within the frame's budget, and are released past `unloadRadius`; it is `ProceduralChunks` on the
+ `'xy'` plane, so a world of any size holds a bounded number of them.
+- **The same whatever is asked first.** A chunk is a function of the seed, the rules and its place, so a neighbour made earlier or later agrees, a server and a client agree, and a
+ placement's id is stable across loads. A group (an anchor and its members) belongs to the chunk its anchor stands in.
+- **What players changed** is a `PlacementDiffs`, laid over the plan before a chunk is shown; `diffs.toJSON()` and `diffs.load()` are the save.
+- **Zones are planned by hand**: a `ZoneDef` whose `z` is world y keeps an area clear or holds it to a biome (a camp the player built).
+- A recipe's `ring` is in world units and `arc` in degrees from +x toward +y. `mesh`, `material`, `attach` and `minUp` are 3D things and are not read.
+
## Limits
- **Decoration is merged a chunk at a time, not GPU-instanced.** The renderer's instance records are written each frame, which for a
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 60ca1fc7e..49bac35eb 100644
--- a/docs/astro/src/content/docs/zh-cn/world/generation.mdx
+++ b/docs/astro/src/content/docs/zh-cn/world/generation.mdx
@@ -144,6 +144,33 @@ gens.diffs().load(saved); // 以及读回
{ "version": "1.0", "groups": { "recipes": { "folder": "assets/models", "mode": "local", "alwaysInclude": true } } }
```
+## 2D 世界
+
+同一套规则也能生成 2D 世界:没有地形,把规划按 **x 和 y** 平铺来读,围绕相机分块发布。引擎不画任何东西;放置物长什么样(精灵、预制体)、地面怎么画(瓦片层、着色器)由你在 `publish` 里决定。
+
+```typescript
+import { registerWorldRules, createWorld2D } from 'esengine/worldgen';
+
+registerWorldRules(rules); // 群系、配方和层,与上文相同
+const world = createWorld2D(app, 'island', {
+ rules: rules.id, seed: 11, chunkSize: 512, cellSize: 32,
+ publish(chunk) {
+ // chunk.placements:这里立着什么(id、recipe、member、biome、x、y、scale、interactive、footprint……)
+ // chunk.biomeGrid:地面每个格子的群系,是 chunk.biomes 的下标
+ const spawned = spawnTilesAndSprites(chunk);
+ return () => despawn(spawned); // 撤掉这个区块
+ },
+});
+
+world.diffs.remove(tree.id); // 砍倒了:只有那个区块重做,并且一直保持砍倒
+```
+
+- **区块跟着相机走**(或跟着流送源),在帧预算内由近及远生成,超过 `unloadRadius` 就释放;它是 `'xy'` 平面上的 `ProceduralChunks`,所以无论世界多大,同时存在的区块数都有上限。
+- **先问谁都一样。** 一个区块只取决于种子、规则和位置,所以邻居早做晚做结果都一致,服务器和客户端一致,放置物的 id 在多次加载间稳定。一组(锚点和它的成员)属于锚点所在的区块。
+- **玩家改过的东西**是 `PlacementDiffs`,在区块显示前盖在规划上;`diffs.toJSON()` 和 `diffs.load()` 就是存档。
+- **区域手工规划**:`ZoneDef` 的 `z` 是世界 y,用来让一片区域保持空旷或固定为某个群系(玩家搭的营地)。
+- 配方的 `ring` 是世界单位,`arc` 是从 +x 转向 +y 的角度。`mesh`、`material`、`attach` 和 `minUp` 是 3D 的东西,这里不读。
+
## 限制
- **装饰按区块合并绘制,而不是 GPU 实例化。** 渲染器的实例记录每帧重写,成千上万株植物每帧要上传数兆字节;合并的静态网格每帧不上传任何东西,内存由区块驻留限制住。
diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.json
index 3820423a8..dc4794afb 100644
--- a/docs/astro/src/data/apiStability.generated.json
+++ b/docs/astro/src/data/apiStability.generated.json
@@ -3,10 +3,10 @@
"counts": {
"public": 115,
"beta": 171,
- "experimental": 2689,
+ "experimental": 2697,
"deprecated": 3
},
- "total": 2975,
+ "total": 2983,
"subsystems": [
{
"id": "mobile-controls",
diff --git a/sdk/etc/worldgen.api.md b/sdk/etc/worldgen.api.md
index cc7584b20..e8537eb1a 100644
--- a/sdk/etc/worldgen.api.md
+++ b/sdk/etc/worldgen.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/worldgen
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 0 public · 0 beta · 54 experimental · 0 deprecated
+Symbols: 0 public · 0 beta · 62 experimental · 0 deprecated
## BiomeCondition — interface @experimental
```
@@ -124,6 +124,25 @@ z: number
zone: string | null
```
+## Placement2D — interface @experimental
+```
+biome: string
+canopy: number
+footprint: number
+group: string
+id: string
+interactive: string | null
+layer: string
+member: string
+plant: string | null
+recipe: string
+scale: number
+x: number
+y: number
+yaw: number
+zone: string | null
+```
+
## PlacementChange — interface @experimental
```
scale: number | undefined
@@ -228,6 +247,44 @@ waterDepth: number | undefined
'noBiome' | 'density' | 'noGround' | 'slope' | 'water' | 'zone' | 'occupied' | 'conflict'
```
+## World2D — interface @experimental
+```
+biomeAt: (x: number, y: number) => string | null
+diffs: PlacementDiffs
+dispose: () => void
+plan: WorldPlan
+status: () => { ready: number; pending: number; failed: number; }
+```
+
+## World2DChunk — interface @experimental
+```
+biomeGrid: Uint8Array<ArrayBufferLike>
+biomes: readonly string[]
+cellSize: number
+cells: number
+cx: number
+cy: number
+placements: Placement2D[]
+size: number
+x0: number
+y0: number
+```
+
+## World2DOptions — interface @experimental
+```
+cellSize: number | undefined
+chunkSize: number | undefined
+diffs: PlacementDiffs | undefined
+loadRadius: number | undefined
+publish: (chunk: World2DChunk) => (() => void) | void
+rules: string | WorldRules
+seed: number | undefined
+sources: (() => Iterable<{ x: number; y: number; }>) | undefined
+unloadRadius: number | undefined
+world: string | undefined
+zones: readonly ZoneDef[] | undefined
+```
+
## WorldGen — const @experimental
```
ComponentDef<WorldGenData>
@@ -389,6 +446,11 @@ static prototype: Zones
(c: BiomeCondition, v: number): number
```
+## createWorld2D — function @experimental
+```
+(app: App, id: string, options: World2DOptions): World2D
+```
+
## faceHalf — const @experimental
```
(radius: number) => number
@@ -429,6 +491,11 @@ static prototype: Zones
(json: unknown, file?: string): WorldRules
```
+## placement2D — function @experimental
+```
+(p: Placement): Placement2D
+```
+
## planetFaces — function @experimental
```
(planet: () => PlanetFacts | null): PlanetFace[]
@@ -439,6 +506,16 @@ static prototype: Zones
(rules: WorldRules): void
```
+## streamingPoints2D — function @experimental
+```
+(app: App): { x: number; y: number; }[]
+```
+
+## world2dChunk — function @experimental
+```
+(plan: WorldPlan, diffs: PlacementDiffs, cx: number, cy: number, size: number, cells: number): { chunk: World2DChunk; ids: string[]; }
+```
+
## worldGenPlugin — const @experimental
```
Plugin
diff --git a/sdk/src/worldgen/index.ts b/sdk/src/worldgen/index.ts
index 61ababeb0..ace020e58 100644
--- a/sdk/src/worldgen/index.ts
+++ b/sdk/src/worldgen/index.ts
@@ -11,6 +11,7 @@ export {
export { parseWorldRules, isRulesFile, WorldRulesAssetLoader } from './rulesAsset';
export { WorldPlan, type Placement, type Group, type Rejection } from './plan';
export { Zones, zoneDistance, zoneWeight, zoneBounds, type ZoneDef, type ZoneShape } from './zones';
+export { createWorld2D, world2dChunk, placement2D, streamingPoints2D, type World2D, type World2DOptions, type World2DChunk, type Placement2D } from './world2d';
export { PlacementDiffs, type PlacementChange, type PlacementDiffsData } from './diffs';
export {
Environment, fbm, fbm3, hash01, hashString, type FieldValues, type FieldFn, type NoiseField, type EnvironmentInputs,
diff --git a/sdk/src/worldgen/world2d.ts b/sdk/src/worldgen/world2d.ts
new file mode 100644
index 000000000..0b25ed153
--- /dev/null
+++ b/sdk/src/worldgen/world2d.ts
@@ -0,0 +1,238 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file world2d.ts
+ * @brief A generated world on the screen plane: the rules a 3D world is laid out by, read flat over x and y, and published in chunks round the camera.
+ *
+ * @details The plan (plan.ts) is a function of position, seed and rules and asks nothing of the ground but a height, so a world with no
+ * terrain is a flat plan, and a 2D world is that plan with its second axis read as world y. Nothing is drawn here: what the plan
+ * places is a list of things standing at points (a recipe, a member of it, a biome, a footprint), and what a thing looks like
+ * (a sprite, a prefab, a tile of the ground) is the game's, said in `publish`.
+ *
+ * - A chunk is a square of the world, `chunkSize` a side. Each frame the ones near a streaming source (or the camera) are made,
+ * nearest first within the frame's budget, and the ones left behind are released with whatever `publish` handed back to undo them.
+ * - What `publish` is given: the placements of the chunk, and the biome of each cell of a grid across it, for painting the ground.
+ * - What a player changed (a tree felled) is a {@link PlacementDiffs}: laid over the plan before a chunk is shown, so it stays felled
+ * when its chunk is let go and made again, and after a save is read back. Only the chunk the thing stood in is made again.
+ * - A group (an anchor and the members placed round it) belongs to the chunk its anchor stands in, so one across a chunk's edge is neither
+ * cut nor placed twice.
+ *
+ * The rules are the 3D ones: a recipe's `mesh`, `material`, `attach` and `minUp` mean nothing here and are not read, and its `ring` is in world
+ * units with `arc` in degrees from +x toward +y.
+ */
+import type { App } from '../app/app';
+import { chunksOf, streamingSourcesOf, type ChunkSource } from '../residency/chunks';
+import { makePlanePlan } from './planePlan';
+import { worldRules, type WorldRules } from './rules';
+import { Zones, type ZoneDef } from './zones';
+import { PlacementDiffs } from './diffs';
+import type { Placement, WorldPlan } from './plan';
+
+/** One thing the plan placed, on the screen plane. */
+export interface Placement2D {
+ /** Stable across loads and load orders: what a save records and `remove` takes. */
+ id: string;
+ group: string;
+ layer: string;
+ recipe: string;
+ member: string;
+ biome: string;
+ /** The zone it stands in, if any. */
+ zone: string | null;
+ x: number;
+ y: number;
+ /** Turn, in radians, and size. */
+ yaw: number;
+ scale: number;
+ /** What a game interacts with it as (a tree to fell); null for scenery. */
+ interactive: string | null;
+ /** The kind of plant the rules name, or null. */
+ plant: string | null;
+ /** What it takes on the ground, and how far it spreads overhead, in world units. */
+ footprint: number;
+ canopy: number;
+}
+
+/** One chunk, as `publish` is given it. */
+export interface World2DChunk {
+ /** The chunk's place on the grid of chunks, and the world corner (lowest x and y) it starts at. */
+ cx: number;
+ cy: number;
+ x0: number;
+ y0: number;
+ size: number;
+ /** The things standing in it, with what a player changed laid over them. */
+ placements: Placement2D[];
+ /** The ground: `cells` by `cells` squares across the chunk, row 0 at the lowest y, each the index into `biomes` of the biome that holds most there (255: none). */
+ cells: number;
+ cellSize: number;
+ biomeGrid: Uint8Array;
+ /** The rules' biome ids, in the order the grid indexes them. */
+ biomes: readonly string[];
+}
+
+export interface World2DOptions {
+ /** The rules, or the id of rules the game registered with `registerWorldRules`. */
+ rules: WorldRules | string;
+ seed?: number;
+ /** The world as the game names it: another name lays out another world by the same rules and seed. */
+ world?: string;
+ /** The side of a chunk, in world units (default 512). */
+ chunkSize?: number;
+ /** The side of one cell of the ground grid, in world units (default 32). */
+ cellSize?: number;
+ /** Chunks within this of a source are made, and one is released past `unloadRadius`. Defaults: a chunk and a half, and two and a half. */
+ loadRadius?: number;
+ unloadRadius?: number;
+ /** Where the world is wanted round, in world x and y; absent, the streaming sources, or else the camera. */
+ sources?: () => Iterable<{ x: number; y: number }>;
+ /** Areas planned by hand: kept clear, or held to a biome. A zone's `z` is world y. */
+ zones?: readonly ZoneDef[];
+ /** What players changed; absent, the world keeps its own. */
+ diffs?: PlacementDiffs;
+ /** Shows one chunk. Returns how to take what it showed away (despawn what it spawned); `release` calls it. */
+ publish(chunk: World2DChunk): (() => void) | void;
+}
+
+/** A generated 2D world: ask it, change it, let it go. */
+export interface World2D {
+ /** The plan, for the questions a game asks about the world itself. */
+ readonly plan: WorldPlan;
+ /** What players changed. Remove a felled tree's id here and its chunk is made again without it. */
+ readonly diffs: PlacementDiffs;
+ /** The biome that holds most at a world point, or null. */
+ biomeAt(x: number, y: number): string | null;
+ /** The chunks counted: ready, pending, failed. */
+ status(): { ready: number; pending: number; failed: number };
+ /** Takes the world away, releasing every chunk. */
+ dispose(): void;
+}
+
+/** A placement as a 2D game reads it: the plan's second axis is world y. */
+export function placement2D(p: Placement): Placement2D {
+ return {
+ id: p.id, group: p.group, layer: p.layer, recipe: p.recipe, member: p.member, biome: p.biome, zone: p.zone,
+ x: p.x, y: p.z, yaw: p.yaw, scale: p.scale, interactive: p.interactive, plant: p.plant, footprint: p.footprint, canopy: p.canopy,
+ };
+}
+
+/**
+ * One chunk of a plan: what stands in the square [cx * size, (cx + 1) * size) by [cy * size, (cy + 1) * size), with what players changed laid over
+ * it, and the biome of each cell of a `cells` by `cells` grid across it. `ids` is every placement the plan made there, removed ones too, which is
+ * what a change to one of them is looked up by.
+ */
+export function world2dChunk(
+ plan: WorldPlan, diffs: PlacementDiffs, cx: number, cy: number, size: number, cells: number,
+): { chunk: World2DChunk; ids: string[] } {
+ const biomes = plan.rules.biomes.map((b) => b.id);
+ const biomeIndex = new Map(biomes.map((b, i) => [b, i]));
+ const x0 = cx * size, y0 = cy * size;
+ const placements: Placement2D[] = [];
+ const ids: string[] = [];
+ for (const p of plan.placementsIn(x0, y0, x0 + size, y0 + size)) {
+ ids.push(p.id);
+ if (diffs.isRemoved(p.id)) continue;
+ const out = placement2D(p);
+ const change = diffs.changeOf(p.id);
+ if (change) {
+ if (change.x !== undefined) out.x = change.x;
+ if (change.z !== undefined) out.y = change.z;
+ if (change.yaw !== undefined) out.yaw = change.yaw;
+ if (change.scale !== undefined) out.scale = change.scale;
+ }
+ placements.push(out);
+ }
+ const biomeGrid = new Uint8Array(cells * cells).fill(255);
+ const step = size / cells;
+ for (let gy = 0; gy < cells; gy++) {
+ for (let gx = 0; gx < cells; gx++) {
+ const biome = plan.biomeAt(x0 + (gx + 0.5) * step, y0 + (gy + 0.5) * step);
+ const index = biome === null ? undefined : biomeIndex.get(biome);
+ if (index !== undefined) biomeGrid[gy * cells + gx] = index;
+ }
+ }
+ return { chunk: { cx, cy, x0, y0, size, placements, cells, cellSize: step, biomeGrid, biomes }, ids };
+}
+
+interface Made {
+ chunk: World2DChunk;
+ ids: string[];
+}
+
+interface Published {
+ dispose: (() => void) | null;
+}
+
+/** Lays out a world by `rules` over the screen plane and publishes it in chunks round the camera, as `id`. */
+export function createWorld2D(app: App, id: string, options: World2DOptions): World2D {
+ const rules = typeof options.rules === 'string' ? worldRules(options.rules) : options.rules;
+ if (!rules) throw new Error(`createWorld2D("${id}"): there are no rules registered as "${String(options.rules)}"`);
+ const seed = options.seed ?? 1;
+ const world = options.world ?? id;
+ const size = Math.max(options.chunkSize ?? 512, 8);
+ const cellSize = Math.min(Math.max(options.cellSize ?? 32, 1), size);
+ const cells = Math.max(Math.round(size / cellSize), 1);
+ const loadRadius = options.loadRadius ?? size * 1.5;
+ const unloadRadius = Math.max(options.unloadRadius ?? size * 2.5, loadRadius);
+ const diffs = options.diffs ?? new PlacementDiffs();
+ const zones = new Zones();
+ for (const zone of options.zones ?? []) zones.set(zone);
+ const { plan } = makePlanePlan({ rules, farRules: null, seed, world, ground: null, flatY: 0, water: null, layers: [], zones });
+
+ const chunks = chunksOf(app);
+ /** The chunk each placement id was last made into, so a change to it makes only that chunk again. */
+ const ownerOf = new Map<string, { cx: number; cy: number }>();
+
+ const sources = options.sources
+ ? (): Iterable<ChunkSource> => [...options.sources!()].map((s) => ({ x: s.x, z: s.y }))
+ : undefined;
+
+ chunks.set<Made & Published>(id, {
+ label: `World ${id}`,
+ plane: 'xy',
+ originX: 0, originZ: 0, sizeX: size, sizeZ: size, extent: null,
+ loadRadius, unloadRadius,
+ generation: `${rules.id}:${seed}:${world}`,
+ ...(sources ? { sources } : {}),
+ make: (cx, cy) => ({ ...world2dChunk(plan, diffs, cx, cy, size, cells), dispose: null }),
+ publish: (cx, cy, made) => {
+ for (const placed of made.ids) ownerOf.set(placed, { cx, cy });
+ made.dispose = options.publish(made.chunk) ?? null;
+ },
+ release: (cx, cy, made) => {
+ made.dispose?.();
+ made.dispose = null;
+ for (const placed of made.ids) {
+ const owner = ownerOf.get(placed);
+ if (owner && owner.cx === cx && owner.cy === cy) ownerOf.delete(placed);
+ }
+ },
+ });
+
+ // A change to one placement makes only the chunk it stood in again.
+ diffs.onChange = (changed) => {
+ const owner = ownerOf.get(changed);
+ if (!owner) return;
+ const x = owner.cx * size, y = owner.cy * size;
+ chunks.invalidate(id, x + 1, y + 1, x + size - 1, y + size - 1);
+ };
+
+ return {
+ plan, diffs,
+ biomeAt: (x, y) => plan.biomeAt(x, y),
+ status: () => {
+ const s = chunks.status(id);
+ return s ? { ready: s.ready, pending: s.pending, failed: s.failed } : { ready: 0, pending: 0, failed: 0 };
+ },
+ dispose: () => {
+ diffs.onChange = null;
+ chunks.remove(id);
+ ownerOf.clear();
+ },
+ };
+}
+
+/** The world's streaming sources as 2D points, for a game that wants to add its own. */
+export function streamingPoints2D(app: App): { x: number; y: number }[] {
+ return streamingSourcesOf(app).map((s) => ({ x: s.x, y: s.y ?? 0 }));
+}
diff --git a/sdk/tests/world2d.test.ts b/sdk/tests/world2d.test.ts
new file mode 100644
index 000000000..50bd76577
--- /dev/null
+++ b/sdk/tests/world2d.test.ts
@@ -0,0 +1,108 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file A 2D generated world: the 3D plan read flat over x and y, cut into chunks that agree, with what players changed laid over them.
+ */
+import { describe, expect, it } from 'vitest';
+import { makePlanePlan } from '../src/worldgen/planePlan';
+import { Zones } from '../src/worldgen/zones';
+import { PlacementDiffs } from '../src/worldgen/diffs';
+import { world2dChunk, placement2D } from '../src/worldgen/world2d';
+import type { WorldRules } from '../src/worldgen/rules';
+
+const rules: WorldRules = {
+ id: 'test:2d', versions: [1],
+ biomes: [
+ { id: 'forest', conditions: [{ field: 'moisture', min: 0.5, blend: 0.1 }], transition: 30, recipes: [{ recipe: 'grove', layer: 'trees', density: 0.8 }] },
+ { id: 'meadow', conditions: [{ field: 'moisture', max: 0.5, blend: 0.1 }], transition: 30, recipes: [{ recipe: 'rock', layer: 'trees', density: 0.4 }] },
+ ],
+ recipes: [
+ { id: 'grove', version: 1, tags: ['tree'], anchor: { id: 'oak', footprint: 14, interactive: 'tree' },
+ members: [{ id: 'sapling', count: [1, 3], ring: [30, 60], footprint: 6 }] },
+ { id: 'rock', version: 1, anchor: { id: 'boulder', footprint: 10 } },
+ ],
+ layers: [{ id: 'trees', spacing: 90, drawDistance: 600 }],
+};
+
+const plan = (zones = new Zones()) => makePlanePlan({
+ rules, farRules: null, seed: 7, world: 'w', ground: null, flatY: 0, water: null, layers: [], zones,
+}).plan;
+
+const SIZE = 512;
+
+describe('a chunk of a 2D world', () => {
+ it('is the same whenever it is asked for, and whatever was asked first', () => {
+ const a = world2dChunk(plan(), new PlacementDiffs(), 2, -1, SIZE, 16);
+ const p = plan();
+ world2dChunk(p, new PlacementDiffs(), 9, 9, SIZE, 16);
+ const b = world2dChunk(p, new PlacementDiffs(), 2, -1, SIZE, 16);
+ expect(b.chunk.placements).toEqual(a.chunk.placements);
+ expect(b.chunk.biomeGrid).toEqual(a.chunk.biomeGrid);
+ expect(a.chunk.placements.length).toBeGreaterThan(5);
+ });
+
+ it('stands things on the plane by x and y, anchors inside the chunk and no id in two chunks', () => {
+ const diffs = new PlacementDiffs();
+ const p = plan();
+ const seen = new Map<string, string>();
+ let anchors = 0;
+ for (let cy = -2; cy <= 1; cy++) for (let cx = -2; cx <= 1; cx++) {
+ const { chunk } = world2dChunk(p, diffs, cx, cy, SIZE, 16);
+ for (const t of chunk.placements) {
+ expect(seen.has(t.id)).toBe(false);
+ seen.set(t.id, `${cx},${cy}`);
+ if (t.member === 'oak' || t.member === 'boulder') {
+ anchors++;
+ expect(t.x).toBeGreaterThanOrEqual(chunk.x0);
+ expect(t.x).toBeLessThan(chunk.x0 + SIZE);
+ expect(t.y).toBeGreaterThanOrEqual(chunk.y0);
+ expect(t.y).toBeLessThan(chunk.y0 + SIZE);
+ }
+ }
+ }
+ expect(anchors).toBeGreaterThan(20);
+ });
+
+ it('paints its ground by the biome that holds each cell, indexed into the rules', () => {
+ const { chunk } = world2dChunk(plan(), new PlacementDiffs(), 0, 0, SIZE, 8);
+ expect(chunk.biomes).toEqual(['forest', 'meadow']);
+ expect(chunk.biomeGrid.length).toBe(64);
+ for (const cell of chunk.biomeGrid) expect([0, 1, 255]).toContain(cell);
+ const p = plan();
+ const step = SIZE / 8;
+ const expected = p.biomeAt(0.5 * step, 0.5 * step);
+ expect(chunk.biomes[chunk.biomeGrid[0]!]).toBe(expected);
+ });
+
+ it('lays what players changed over the plan: a felled thing is gone, a moved one is where it was put, and both are still listed by id', () => {
+ const diffs = new PlacementDiffs();
+ const first = world2dChunk(plan(), diffs, 1, 1, SIZE, 8);
+ const tree = first.chunk.placements.find((t) => t.interactive === 'tree')!;
+ const other = first.chunk.placements.find((t) => t.id !== tree.id && t.member === 'oak')!;
+ diffs.remove(tree.id);
+ diffs.change(other.id, { x: 5000, z: -3, scale: 2 });
+ const next = world2dChunk(plan(), diffs, 1, 1, SIZE, 8);
+ expect(next.chunk.placements.some((t) => t.id === tree.id)).toBe(false);
+ expect(next.ids).toContain(tree.id);
+ const moved = next.chunk.placements.find((t) => t.id === other.id)!;
+ expect(moved.x).toBe(5000);
+ expect(moved.y).toBe(-3);
+ expect(moved.scale).toBe(2);
+ diffs.restore(tree.id);
+ expect(world2dChunk(plan(), diffs, 1, 1, SIZE, 8).chunk.placements.some((t) => t.id === tree.id)).toBe(true);
+ });
+
+ it('keeps out of a zone planned by hand, whose z is world y', () => {
+ const zones = new Zones();
+ zones.set({ id: 'camp', kind: 'home', shape: { type: 'circle', x: 700, z: 700, radius: 250 }, falloff: 0, priority: 1, excludes: ['*'] });
+ const { chunk } = world2dChunk(plan(zones), new PlacementDiffs(), 1, 1, SIZE, 8);
+ for (const t of chunk.placements) expect(Math.hypot(t.x - 700, t.y - 700)).toBeGreaterThan(250 - t.footprint);
+ expect(world2dChunk(plan(), new PlacementDiffs(), 1, 1, SIZE, 8).chunk.placements.length).toBeGreaterThan(chunk.placements.length);
+ });
+
+ it('reads a placement as the screen plane does', () => {
+ const t = placement2D({ id: 'i', group: 'g', layer: 'l', recipe: 'r', recipeVersion: 1, member: 'm', biome: 'b', zone: null, x: 3, y: 99, z: 4, yaw: 1, scale: 2, normal: [0, 1, 0],
+ attach: 'upright', mesh: 0, material: 0, plant: null, interactive: null, footprint: 1, canopy: 2, far: null });
+ expect(t).toMatchObject({ x: 3, y: 4, yaw: 1, scale: 2 });
+ });
+});