A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat: fit procedural buildings and reserve roads from foliage
yhh4e79689e1075
diff --git a/desktop b/desktopindex bd0e3d761..6b69b1b29 160000--- a/desktop+++ b/desktop@@ -1 +1 @@-Subproject commit bd0e3d761446d07d454c4838d925765770bdd7a6+Subproject commit 6b69b1b298968d99498933ac9245136bb21d0f08diff --git a/docs/astro/src/content/docs/graphics/foliage.mdx b/docs/astro/src/content/docs/graphics/foliage.mdxindex 38e398232..46c4bb604 100644--- a/docs/astro/src/content/docs/graphics/foliage.mdx+++ b/docs/astro/src/content/docs/graphics/foliage.mdx@@ -31,6 +31,22 @@ replaces it. Nothing is baked.If the scene has a [Terrain](/docs/graphics/terrain/), plants stand on it, keep off what is too steep, and wait for it to be built; with none, thearea is flat at the entity's height.+## Budget and reservations++`count` is **per cell**, not for the whole area. Before distance and terrain rejection, a 700 × 700 field with 35-unit cells and+750 plants per cell has 400 cells and up to 300,000 plants. Review density (`count / cellSize²`), cell count, near/far distance and+shadow passes together. Larger cells reduce submissions but cull more coarsely. Short grass can set `castShadows: false`; it still+receives light and shadows. Existing scenes keep casting unless this option is changed.++When a WorldGen exists, Foliage respects its exclusion zones. `zoneWorld` selects the world by name (empty uses the first),+`zoneTags` adds comma-separated tags to `foliage` and `grass` (or `tree` for a mesh), and `zonePadding` adds clearance in world units.+Reserve building floors, steps and entrances with `WorldZone` boxes and roads with zones from `roadZones` / `setRoad` in+`esengine/worldgen`. Moving or deleting a zone regenerates the field. Without WorldGen the field grows as before.++The MCP `audit_vegetation` tool reports authored upper bounds and live counters. Warm generation with `step` before measuring;+`gpuDraws` includes shadow and other passes, while `drawCalls` counts scene lists. Background-window idle time is not a foreground+frame-rate benchmark. For large forests, `WorldRules.plants` and `PlacedFoliage` share geometry and support per-instance LOD.+## WindThe **Foliage** shader (`builtin:foliage`) bends each vertex by a weight painted in its colour (red is how far up the plant it is, so the rootdiff --git a/docs/astro/src/content/docs/world/generation.mdx b/docs/astro/src/content/docs/world/generation.mdxindex ed6696e74..7d78312e3 100644--- a/docs/astro/src/content/docs/world/generation.mdx+++ b/docs/astro/src/content/docs/world/generation.mdx@@ -145,6 +145,32 @@ Only the chunks the zone reaches are made again, each keeping its old version un*A **World Zone**: a circle that tells the generator which biome to grow inside it.*+## Building bases and roads++An upright recipe member can set `grounding: { size: [width, depth], samples: 5, mode: 'highest', maxRelief: 2 }`.+The base dimensions are model units; yaw and scale are applied before sampling the corners, edges and interior. The grid side may be+3, 5, 7 or 9. Every sample must have ground and satisfy `minUp` and `waterDepth`; `maxRelief` rejects excessive height variation in+world units. The base chooses `highest` (default), `lowest`, `mean` or `center`, then adds `offset` in scaled model units.+`Placement.grounding` reports the range, support depth and burial depth. This is finite-grid support checking, not a terrain flattening+operation: use a foundation deep enough for the accepted relief, or a flattening WorldZone for an authored site.++The reservation always contains the whole fitted base. `scaleFootprint: true` also treats `footprint` and `canopy` as model-unit radii;+omitting it preserves the existing world-unit behavior. The planner settles overlaps after choosing deterministic scale and base height.+`stats` / `explain` report `relief` alongside slope, water, zone and overlap rejection. The World Rules editor exposes these settings.++```ts+import { setRoad } from 'esengine/worldgen';+setRoad(worlds.zones('valley'), {+ id: 'camp-trail', points: [[0, 0], [40, -20], [80, -10]],+ width: 6, clearance: 2, falloff: 3, excludes: ['tree', 'grass', 'building'],+});+```++`roadZones` returns serializable rectangle and circle zones with continuous bends and round end caps. `setRoad` replaces just one+road's reservations, removing obsolete segments, and `removeRoad` releases them. These reserve space; mesh construction and road+grading are separate. A 2D world uses the same helpers with its y coordinate in the second point slot. Place the building layer before+forest layers so trees respect its footprints, and reserve authored building floors and entrances with WorldZones for Foliage.+## Interactive placements and changesA member with `interactive` (`'ore'`, `'tree'`) is an entity of its own, carrying a `PlacedObject` with its placement id and kind;diff --git a/docs/astro/src/content/docs/zh-cn/graphics/foliage.mdx b/docs/astro/src/content/docs/zh-cn/graphics/foliage.mdxindex bc3f2a96c..e8b382752 100644--- a/docs/astro/src/content/docs/zh-cn/graphics/foliage.mdx+++ b/docs/astro/src/content/docs/zh-cn/graphics/foliage.mdx@@ -24,6 +24,21 @@ description: 一个 Foliage 组件,把草或网格散布到一片区域或地形如果场景里有 [Terrain](/docs/zh-cn/graphics/terrain/),植物就站在它上面,避开太陡的地方,并等它构建完;没有地形时,区域是实体所在高度的平地。+## 预算与禁植区域++`count` 是**每块**植物数量。700 × 700 的区域使用 35 单位的区块、每块 750 株,在距离和地形筛选前最多有 400 块、30 万株。+密度约为 `count / cellSize²`,需要和区块数、LOD、绘制距离、阴影一起设置。增大区块可以减少提交,但裁剪会更粗。+短草可设置 `castShadows: false`,仍然接受光照和阴影。旧场景默认保持投影。++存在 WorldGen 时,Foliage 会读取它的禁植区域。`zoneWorld` 选择世界名称,留空使用第一个世界;`zoneTags` 为逗号分隔的额外标签,+默认已包含 `foliage` 和 `grass`(使用网格时为 `tree`);`zonePadding` 是额外的世界单位留白。+用 WorldZone 方框预留建筑地基、台阶和门前通道,用 `esengine/worldgen` 的 `roadZones` 或 `setRoad` 预留连续道路。+区域移动或删除后草地会重新生成。没有 WorldGen 的场景保持原有行为。++MCP 的 `audit_vegetation` 会给出配置上限和当前绘制统计。先用 `step` 完成预热,再测量;`gpuDraws` 包含阴影等全部 pass,+`drawCalls` 是场景列表的绘制数。后台窗口的空闲时间和 1 FPS 不能代表前台游戏帧率。大型森林优先使用支持共享网格和逐实例 LOD 的+`WorldRules.plants` 或 `PlacedFoliage`。+## 风**Foliage** 着色器(`builtin:foliage`)按顶点颜色里画好的权重弯曲每个顶点(红色是它在植物上多高,所以根不动、尖端动;绿色是植物自己的相位,所以一片草地不会整体一起摆),再加一阵在世界上传播的阵风和叠在上面的颤动。参数在材质里:`u_windStrength`、`u_windSpeed`、`u_windDirection`(度)、`u_gustScale`(越小阵风越长)和 `u_flutter`。植物是双面的,并且让光透过(`u_translucency`);带 alpha 通道的叶子纹理(`u_albedo`、`u_useTexture`、`u_alphaCutoff`)能从一张卡片里抠出叶子的轮廓。diff --git a/docs/astro/src/content/docs/zh-cn/world/generation.mdx b/docs/astro/src/content/docs/zh-cn/world/generation.mdxindex 8665878cc..ca80d08e5 100644--- a/docs/astro/src/content/docs/zh-cn/world/generation.mdx+++ b/docs/astro/src/content/docs/zh-cn/world/generation.mdx@@ -119,6 +119,23 @@ gens.zones().set({ id: 'house 1', kind: 'building', shape: { type: 'rect', x, z,*一个 **World Zone**:一个圆,告诉生成器在其中生长哪种群落。*+## 建筑底面与道路++直立建筑的成员可以设置 `grounding: { size: [宽, 深], samples: 5, mode: 'highest', maxRelief: 2 }`。+宽深使用模型单位,应用旋转和缩放后,对角点、边缘和内部的网格采样;网格边长可以为 3、5、7 或 9。+每个采样点都要有地面并满足 `minUp`、`waterDepth`,`maxRelief` 按世界单位限制最大高差。+标高可选最高点(默认)、最低点、平均值或中心点:`highest`、`lowest`、`mean`、`center`,再叠加随模型缩放的 `offset`。+`Placement.grounding` 提供高度范围、所需支撑深度和埋入深度。它是有限网格检测,不会自动削平地形;+模型地基需要覆盖允许的高差,手工场地也可以使用 WorldZone 的 `flatten`。++避让范围至少覆盖整块旋转缩放后的底面。`scaleFootprint: true` 将占地和树冠半径视为模型单位;+留空则保留原有的世界单位含义。`stats` 和 `explain` 用 `relief` 区分高差拒绝,世界规则编辑器中可以直接编辑这些字段。++`esengine/worldgen` 导出的 `roadZones({ id, points, width, clearance, falloff, excludes })` 将折线路径转为矩形段和圆形接头,+转弯和端点不会留下禁植缺口;`setRoad(zones, options)` 替换一条路并清理旧段,`removeRoad(zones, id)` 释放它。+这些函数预留空间,路面网格和道路整地另行制作。2D 世界也可以使用,把 y 写在每个点的第二个坐标。+建筑层放在森林层之前,树木就会避开建筑的占地;Foliage 的建筑底面与门前通道使用 WorldZone 预留。+## 可交互的放置物与变化带 `interactive`(如 `'ore'`、`'tree'`)的成员是独立的实体,带有记录放置 ID 与类型的 `PlacedObject`;其余都是装饰,按区块、按种类合并成一个网格绘制。`gens.objectOf(id)` 找到某个放置物对应的实体。diff --git a/sdk/etc/foliage.api.md b/sdk/etc/foliage.api.mdindex 58f9311e8..f6e14883c 100644--- a/sdk/etc/foliage.api.md+++ b/sdk/etc/foliage.api.md@@ -34,6 +34,7 @@ cardU0: numbercardU1: numbercardV0: numbercardV1: number+castShadows: booleancellSize: numbercount: numberdrawDistance: number@@ -49,6 +50,9 @@ seed: numbersizeX: numbersizeZ: numberwaterDepth: number+zonePadding: number+zoneTags: string+zoneWorld: string```## FoliageField — class @experimentaldiff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex aedaf576a..d785a73f7 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -4541,6 +4541,7 @@ cardU0: numbercardU1: numbercardV0: numbercardV1: number+castShadows: booleancellSize: numbercount: numberdrawDistance: number@@ -4556,6 +4557,9 @@ seed: numbersizeX: numbersizeZ: numberwaterDepth: number+zonePadding: number+zoneTags: string+zoneWorld: string```## FoliageField — class @experimental@@ -7170,6 +7174,7 @@ biome: stringcanopy: numberfar: { u0: number; v0: number; u1: number; v1: number; tent?: boolean; } | null | undefinedfootprint: number+grounding: GroundFit | undefinedgroup: stringid: stringinteractive: string | null@@ -8470,6 +8475,7 @@ chance: number | undefinedcount: readonly [number, number] | undefinedfar: { u0: number; v0: number; u1: number; v1: number; tent?: boolean; } | undefinedfootprint: number+grounding: GroundingOptions | undefinedid: stringinteractive: string | undefinedmaterial: string | number | undefined@@ -8478,6 +8484,7 @@ minUp: number | undefinedplant: string | undefinedring: readonly [number, number] | undefinedscale: readonly [number, number] | undefined+scaleFootprint: boolean | undefinedtags: readonly string[] | undefinedwaterDepth: number | undefined```@@ -8541,7 +8548,7 @@ OnDemand = 2## Rejection — type @experimental```-'noBiome' | 'density' | 'noGround' | 'slope' | 'water' | 'zone' | 'occupied' | 'conflict'+'noBiome' | 'density' | 'noGround' | 'slope' | 'water' | 'relief' | 'zone' | 'occupied' | 'conflict'```## ReliableOrderedTransport — interface @experimentaldiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex 80f8bbed0..7d6525301 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -4549,6 +4549,7 @@ cardU0: numbercardU1: numbercardV0: numbercardV1: number+castShadows: booleancellSize: numbercount: numberdrawDistance: number@@ -4564,6 +4565,9 @@ seed: numbersizeX: numbersizeZ: numberwaterDepth: number+zonePadding: number+zoneTags: string+zoneWorld: string```## FoliageField — class @experimental@@ -7376,6 +7380,7 @@ biome: stringcanopy: numberfar: { u0: number; v0: number; u1: number; v1: number; tent?: boolean; } | null | undefinedfootprint: number+grounding: GroundFit | undefinedgroup: stringid: stringinteractive: string | null@@ -8686,6 +8691,7 @@ chance: number | undefinedcount: readonly [number, number] | undefinedfar: { u0: number; v0: number; u1: number; v1: number; tent?: boolean; } | undefinedfootprint: number+grounding: GroundingOptions | undefinedid: stringinteractive: string | undefinedmaterial: string | number | undefined@@ -8694,6 +8700,7 @@ minUp: number | undefinedplant: string | undefinedring: readonly [number, number] | undefinedscale: readonly [number, number] | undefined+scaleFootprint: boolean | undefinedtags: readonly string[] | undefinedwaterDepth: number | undefined```@@ -8757,7 +8764,7 @@ OnDemand = 2## Rejection — type @experimental```-'noBiome' | 'density' | 'noGround' | 'slope' | 'water' | 'zone' | 'occupied' | 'conflict'+'noBiome' | 'density' | 'noGround' | 'slope' | 'water' | 'relief' | 'zone' | 'occupied' | 'conflict'```## ReliableOrderedTransport — interface @experimentaldiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex 25ec7db5a..d22b5007b 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -4536,6 +4536,7 @@ cardU0: numbercardU1: numbercardV0: numbercardV1: number+castShadows: booleancellSize: numbercount: numberdrawDistance: number@@ -4551,6 +4552,9 @@ seed: numbersizeX: numbersizeZ: numberwaterDepth: number+zonePadding: number+zoneTags: string+zoneWorld: string```## FoliageField — class @experimental@@ -7165,6 +7169,7 @@ biome: stringcanopy: numberfar: { u0: number; v0: number; u1: number; v1: number; tent?: boolean; } | null | undefinedfootprint: number+grounding: GroundFit | undefinedgroup: stringid: stringinteractive: string | null@@ -8465,6 +8470,7 @@ chance: number | undefinedcount: readonly [number, number] | undefinedfar: { u0: number; v0: number; u1: number; v1: number; tent?: boolean; } | undefinedfootprint: number+grounding: GroundingOptions | undefinedid: stringinteractive: string | undefinedmaterial: string | number | undefined@@ -8473,6 +8479,7 @@ minUp: number | undefinedplant: string | undefinedring: readonly [number, number] | undefinedscale: readonly [number, number] | undefined+scaleFootprint: boolean | undefinedtags: readonly string[] | undefinedwaterDepth: number | undefined```@@ -8536,7 +8543,7 @@ OnDemand = 2## Rejection — type @experimental```-'noBiome' | 'density' | 'noGround' | 'slope' | 'water' | 'zone' | 'occupied' | 'conflict'+'noBiome' | 'density' | 'noGround' | 'slope' | 'water' | 'relief' | 'zone' | 'occupied' | 'conflict'```## ReliableOrderedTransport — interface @experimentaldiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex 892b944a7..040f1645a 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -4536,6 +4536,7 @@ cardU0: numbercardU1: numbercardV0: numbercardV1: number+castShadows: booleancellSize: numbercount: numberdrawDistance: number@@ -4551,6 +4552,9 @@ seed: numbersizeX: numbersizeZ: numberwaterDepth: number+zonePadding: number+zoneTags: string+zoneWorld: string```## FoliageField — class @experimental@@ -7461,6 +7465,7 @@ biome: stringcanopy: numberfar: { u0: number; v0: number; u1: number; v1: number; tent?: boolean; } | null | undefinedfootprint: number+grounding: GroundFit | undefinedgroup: stringid: stringinteractive: string | null@@ -8761,6 +8766,7 @@ chance: number | undefinedcount: readonly [number, number] | undefinedfar: { u0: number; v0: number; u1: number; v1: number; tent?: boolean; } | undefinedfootprint: number+grounding: GroundingOptions | undefinedid: stringinteractive: string | undefinedmaterial: string | number | undefined@@ -8769,6 +8775,7 @@ minUp: number | undefinedplant: string | undefinedring: readonly [number, number] | undefinedscale: readonly [number, number] | undefined+scaleFootprint: boolean | undefinedtags: readonly string[] | undefinedwaterDepth: number | undefined```@@ -8832,7 +8839,7 @@ OnDemand = 2## Rejection — type @experimental```-'noBiome' | 'density' | 'noGround' | 'slope' | 'water' | 'zone' | 'occupied' | 'conflict'+'noBiome' | 'density' | 'noGround' | 'slope' | 'water' | 'relief' | 'zone' | 'occupied' | 'conflict'```## ReliableOrderedTransport — interface @experimentaldiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 8afc6efbd..62941351b 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -4536,6 +4536,7 @@ cardU0: numbercardU1: numbercardV0: numbercardV1: number+castShadows: booleancellSize: numbercount: numberdrawDistance: number@@ -4551,6 +4552,9 @@ seed: numbersizeX: numbersizeZ: numberwaterDepth: number+zonePadding: number+zoneTags: string+zoneWorld: string```## FoliageField — class @experimental@@ -7172,6 +7176,7 @@ biome: stringcanopy: numberfar: { u0: number; v0: number; u1: number; v1: number; tent?: boolean; } | null | undefinedfootprint: number+grounding: GroundFit | undefinedgroup: stringid: stringinteractive: string | null@@ -8472,6 +8477,7 @@ chance: number | undefinedcount: readonly [number, number] | undefinedfar: { u0: number; v0: number; u1: number; v1: number; tent?: boolean; } | undefinedfootprint: number+grounding: GroundingOptions | undefinedid: stringinteractive: string | undefinedmaterial: string | number | undefined@@ -8480,6 +8486,7 @@ minUp: number | undefinedplant: string | undefinedring: readonly [number, number] | undefinedscale: readonly [number, number] | undefined+scaleFootprint: boolean | undefinedtags: readonly string[] | undefinedwaterDepth: number | undefined```@@ -8543,7 +8550,7 @@ OnDemand = 2## Rejection — type @experimental```-'noBiome' | 'density' | 'noGround' | 'slope' | 'water' | 'zone' | 'occupied' | 'conflict'+'noBiome' | 'density' | 'noGround' | 'slope' | 'water' | 'relief' | 'zone' | 'occupied' | 'conflict'```## ReliableOrderedTransport — interface @experimentaldiff --git a/sdk/etc/worldgen.api.md b/sdk/etc/worldgen.api.mdindex e8537eb1a..8c835f0a0 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 · 62 experimental · 0 deprecated+Symbols: 0 public · 0 beta · 71 experimental · 0 deprecated## BiomeCondition — interface @experimental```@@ -68,6 +68,32 @@ static prototype: FaceZonesRecord<string, number>```+## GroundFit — interface @experimental+```+buriedDepth: number+max: number+mean: number+min: number+relief: number+samples: number+supportDepth: number+y: number+```++## GroundFitResult — type @experimental+```+{ ok: true; fit: GroundFit } | { ok: false; reason: 'noGround' | 'slope' | 'water' | 'relief' }+```++## GroundingOptions — interface @experimental+```+maxRelief: number | undefined+mode: "highest" | "lowest" | "mean" | "center" | undefined+offset: number | undefined+samples: number | undefined+size: readonly [number, number]+```+## Group — interface @experimental```anchor: Placement@@ -104,6 +130,7 @@ biome: stringcanopy: numberfar: { u0: number; v0: number; u1: number; v1: number; tent?: boolean; } | null | undefinedfootprint: number+grounding: GroundFit | undefinedgroup: stringid: stringinteractive: string | null@@ -230,6 +257,7 @@ chance: number | undefinedcount: readonly [number, number] | undefinedfar: { u0: number; v0: number; u1: number; v1: number; tent?: boolean; } | undefinedfootprint: number+grounding: GroundingOptions | undefinedid: stringinteractive: string | undefinedmaterial: string | number | undefined@@ -238,13 +266,27 @@ minUp: number | undefinedplant: string | undefinedring: readonly [number, number] | undefinedscale: readonly [number, number] | undefined+scaleFootprint: boolean | undefinedtags: readonly string[] | undefinedwaterDepth: number | undefined```## Rejection — type @experimental```-'noBiome' | 'density' | 'noGround' | 'slope' | 'water' | 'zone' | 'occupied' | 'conflict'+'noBiome' | 'density' | 'noGround' | 'slope' | 'water' | 'relief' | 'zone' | 'occupied' | 'conflict'+```++## RoadOptions — interface @experimental+```+biome: string | undefined+clearance: number | undefined+excludes: readonly string[] | undefined+falloff: number | undefined+fields: Readonly<Record<string, number>> | undefined+id: string+points: readonly (readonly [number, number])[]+priority: number | undefined+width: number```## World2D — interface @experimental@@ -471,6 +513,11 @@ static prototype: Zones(x: number, y: number, z: number, seed: number, octaves: number): number```+## fitGroundFootprint — function @experimental+```+(inputs: Pick<EnvironmentInputs, "ground" | "waterDepth">, x: number, z: number, yaw: number, scale: number, options: GroundingOptions, limits?: { minUp?: number; waterDepth?: number; }): GroundFitResult+```+## hash01 — function @experimental```(...v: number[]): number@@ -506,11 +553,31 @@ static prototype: Zones(rules: WorldRules): void```+## removeRoad — function @experimental+```+(zones: Zones, id: string): void+```++## roadZones — function @experimental+```+(options: RoadOptions): ZoneDef[]+```++## setRoad — function @experimental+```+(zones: Zones, options: RoadOptions): void+```+## streamingPoints2D — function @experimental```(app: App): { x: number; y: number; }[]```+## validateGrounding — function @experimental+```+(options: GroundingOptions): void+```+## world2dChunk — function @experimental```(plan: WorldPlan, diffs: PlacementDiffs, cx: number, cy: number, size: number, cells: number): { chunk: World2DChunk; ids: string[]; }diff --git a/sdk/src/foliage/foliagePlugin.ts b/sdk/src/foliage/foliagePlugin.tsindex e3ffd7c7f..62dd26526 100644--- a/sdk/src/foliage/foliagePlugin.ts+++ b/sdk/src/foliage/foliagePlugin.ts@@ -27,6 +27,7 @@ import { TerrainsRes } from '../terrain/terrainPlugin';import { Material } from '../render/material';import { currentWeather, currentWeatherDrive, WeatherDrive } from '../postprocess/weather';import { isEditor, isPlayMode } from '../ecs/env';+import type { Zones } from '../worldgen/zones';import {buildBillboardMesh, buildGrassMesh, buildInstancedMesh, scatterCell,type Ground, type Plant,@@ -60,6 +61,14 @@ export interface FoliageData {/** Distance past which a cell is drawn as its far version, and past which it is not drawn. */lodDistance: number;drawDistance: number;+ /** Whether the generated cells cast shadows. Disable for dense short grass; it still receives lighting and shadows. */+ castShadows: boolean;+ /** WorldGen world whose zones reserve roads and buildings. Empty uses its first world; no WorldGen leaves the field unchanged. */+ zoneWorld: string;+ /** Extra comma-separated exclusion tags, in addition to foliage and grass/tree. */+ zoneTags: string;+ /** Additional world-space clearance from a zone's boundary. */+ zonePadding: number;/** A tree's far version is two crossed cards showing this rectangle of its texture, as uv: left, bottom, right, top. */cardU0: number;cardV0: number;@@ -78,7 +87,8 @@ export const Foliage: ComponentDef<FoliageData> = defineComponent<FoliageData>('mesh: 0, material: 0,sizeX: 400, sizeZ: 400, cellSize: 40, count: 500, seed: 1,minScale: 0.8, maxScale: 1.25, minUp: 0.7, heightMin: -100000, heightMax: 100000, waterDepth: 0,- bladeHeight: 14, bladeWidth: 1.6, lodDistance: 140, drawDistance: 420,+ bladeHeight: 14, bladeWidth: 1.6, lodDistance: 140, drawDistance: 420, castShadows: true,+ zoneWorld: '', zoneTags: '', zonePadding: 0,cardU0: 0, cardV0: 0, cardU1: 1, cardV1: 1, cardTent: 0,}, {assetFields: [{ field: 'mesh', type: 'mesh' }, { field: 'material', type: 'material' }],@@ -100,6 +110,10 @@ export const Foliage: ComponentDef<FoliageData> = defineComponent<FoliageData>('bladeWidth: { min: 0.01, category: 'Grass', tooltip: 'Width of a blade at its base, at scale 1.' },lodDistance: { min: 1, category: 'Distance', tooltip: 'Past this a cell is drawn as its far version: fewer, broader blades, or a tree as crossed cards.' },drawDistance: { min: 1, category: 'Distance', tooltip: 'Past this a cell is not drawn.' },+ castShadows: { category: 'Distance', tooltip: 'Generated cells cast shadows. Turn off for dense short grass to avoid drawing every cell again into each shadow cascade. Lighting and received shadows remain.' },+ zoneWorld: { category: 'Placement', tooltip: 'WorldGen world whose building and road exclusion zones this field respects. Empty uses the first world.' },+ zoneTags: { category: 'Placement', tooltip: 'Extra comma-separated tags used by zone exclusions. foliage and grass (or tree for a mesh) are included automatically.' },+ zonePadding: { min: 0, category: 'Placement', tooltip: 'Extra world-space clearance from building and road zones.' },cardU0: { label: 'Card left', category: 'Far version', tooltip: 'The part of the plant\'s texture a far tree shows (left, bottom, right, top).' },cardV0: { label: 'Card bottom', category: 'Far version' },cardU1: { label: 'Card right', category: 'Far version' },@@ -127,6 +141,12 @@ function waterOf(app: App): WaterQuery | null {return w && typeof w.depthAt === 'function' ? w as WaterQuery : null;}+/** Optional world generation: querying zones must not pull that module into a foliage-only game. */+function zonesOf(app: App, world: string | undefined): Zones | null {+ const gens = app.getResourceByName?.('WorldGens') as { zones?(world?: string): Zones } | undefined;+ return gens?.zones?.(world || undefined) ?? null;+}+/** The chunk layer a Foliage's cells are. */const layerOf = (entity: Entity): string => `foliage:${entity}`;@@ -193,7 +213,8 @@ export class FoliagePlugin implements Plugin {field.built_.set(entity, built);void this.start(app, built);}- this.layer(app, entity, built, revision, waiting);+ const zones = zonesOf(app, data.zoneWorld);+ this.layer(app, entity, built, `${revision}:${zones?.revision ?? 0}`, waiting);}}, { name: 'FoliageSystem' }));}@@ -260,7 +281,7 @@ export class FoliagePlugin implements Plugin {* The field's cells as a layer of chunks: the area's grid, wanted out to `drawDistance` round the streaming sources, grown again* (each old cell kept till its new one stands) when a field, the ground or the water changes.*/- private layer(app: App, entity: Entity, built: BuiltFoliage, revision: number, waiting: boolean): void {+ private layer(app: App, entity: Entity, built: BuiltFoliage, revision: string, waiting: boolean): void {const t = app.world.get(entity, Transform) as TransformData;const data = built.data, cells = this.cellsAcross(data);const sx = t.worldScale.x || 1, sz = t.worldScale.z || 1;@@ -306,7 +327,10 @@ export class FoliagePlugin implements Plugin {const worldX = t.worldPosition.x + localX * sx, worldZ = t.worldPosition.z + localZ * sz;const hasTerrain = !!terrains && terrains.built_.size > 0;const water = waterOf(app);+ const zones = zonesOf(app, data.zoneWorld);+ const tags = ['foliage', data.mesh ? 'tree' : 'grass', ...(data.zoneTags ?? '').split(',').map((s) => s.trim()).filter(Boolean)];const ground: Ground = (x, z) => {+ if (zones?.excluding(x, z, Math.max(0, data.zonePadding ?? 0), tags, data.seed)) return null;// With a terrain, a plant stands where there is ground and nowhere else; with none, the area is flat at the entity's height.const y = hasTerrain ? terrains!.heightAt(x, z) : t.worldPosition.y;if (y === null) return null;@@ -356,6 +380,7 @@ export class FoliagePlugin implements Plugin {world.insert(cell, Transform, { position: { x: localX, y: 0, z: localZ } });world.insert(cell, MeshRenderer, {mesh: handles[0]!, material: data.material, lit: true, opaque: true, cullBackfaces: false,+ castShadows: data.castShadows !== false,color: { r: 1, g: 1, b: 1, a: 1 },} as Partial<MeshRendererData>);const lodDef = getComponent('LODGroup');diff --git a/sdk/src/runtime/planWorkerBundle.generated.ts b/sdk/src/runtime/planWorkerBundle.generated.tsindex 0f8680857..bfa84be36 100644--- a/sdk/src/runtime/planWorkerBundle.generated.ts+++ b/sdk/src/runtime/planWorkerBundle.generated.ts@@ -2,4 +2,4 @@// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team// Generated by sdk/scripts/build-worker.mjs from src/worldgen/planWorker.ts: do not edit./** The planning worker's script: what a pool of planning workers is started from. */-export const PLAN_WORKER_SOURCE = "(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});let t=(e,t,n)=>{let r=Math.min(Math.max((n-e)/(t-e||1e-6),0),1);return r*r*(3-2*r)};function n(e,n,r){let i=t(r.rockSlope-.08,r.rockSlope+.08,1-n),a=t(r.snowHeight-.06,r.snowHeight+.06,e)*(1-i*.85),o=t(r.dirtHeight-.15,r.dirtHeight+.15,e)*(1-a)*(1-i),s=(1-i)*(1-a)*(1-o),c=s+o+a+i||1;return[s/c,o/c,a/c,i/c]}function r(e,t,n){let r=Math.min(Math.max(t,0),1)*(e.width-1),i=Math.min(Math.max(n,0),1)*(e.height-1),a=Math.min(Math.floor(r),e.width-2),o=Math.min(Math.floor(i),e.height-2),s=r-a,c=i-o,l=(t,n)=>e.data[n*e.width+t],u=l(a,o)+(l(a+1,o)-l(a,o))*s;return u+(l(a,o+1)+(l(a+1,o+1)-l(a,o+1))*s-u)*c}function i(e,t,n,i,a,o){let s=1/(e.width-1),c=1/(e.height-1),l=(r(e,t+s,n)-r(e,t-s,n))*o/(2*s*i),u=(r(e,t,n+c)-r(e,t,n-c))*o/(2*c*a),d=Math.hypot(l,1,u);return[-l/d,1/d,-u/d]}var a=class e{constructor(e,t,n,r,i=[0,t.height],a=null){this.field=e,this.data=t,this.splat=n,this.flow=r,this.splat2=a,this.infinite=!1,this.bounds=[-t.sizeX/2,-t.sizeZ/2,t.sizeX/2,t.sizeZ/2],[this.minHeight,this.maxHeight]=i}ensureSplats(e){let t=this.field,r=Math.min(t.width,1024),i=Math.min(t.height,1024);if(!this.splat){let e=new Uint8Array(r*i*4),t=this.data.sizeX,a=this.data.sizeZ;for(let o=0;o<i;o++)for(let s=0;s<r;s++){let c=(s/(r-1)-.5)*t,l=(o/(i-1)-.5)*a,u=this.height(c,l)??this.minHeight,d=this.normal(c,l),f=n((u-this.minHeight)/this.span,d?d[1]:1,this.data);for(let t=0;t<4;t++)e[(o*r+s)*4+t]=Math.round(f[t]*255)}this.splat={width:r,height:i,pixels:e}}return e&&!this.splat2&&(this.splat2={width:this.splat.width,height:this.splat.height,pixels:new Uint8Array(this.splat.width*this.splat.height*4)}),{a:this.splat,b:this.splat2}}splats(){return{a:this.splat,b:this.splat2}}get span(){return Math.max(this.maxHeight-this.minHeight,1e-6)}toData(){let e=this.data;return{field:this.field,params:{sizeX:e.sizeX,sizeZ:e.sizeZ,height:e.height,rockSlope:e.rockSlope,dirtHeight:e.dirtHeight,snowHeight:e.snowHeight},splat:this.splat,splat2:this.splat2,flow:this.flow,range:[this.minHeight,this.maxHeight]}}static fromData(t){return new e(t.field,t.params,t.splat,t.flow,t.range,t.splat2)}height(e,t){let n=e/this.data.sizeX+.5,i=t/this.data.sizeZ+.5;return n<0||n>1||i<0||i>1?null:this.minHeight+r(this.field,n,i)*this.span}normal(e,t){let n=e/this.data.sizeX+.5,r=t/this.data.sizeZ+.5;return n<0||n>1||r<0||r>1?null:i(this.field,n,r,this.data.sizeX,this.data.sizeZ,this.span)}paint(e,t,r,i){let a=Math.min(Math.max(e/this.data.sizeX+.5,0),1),o=Math.min(Math.max(t/this.data.sizeZ+.5,0),1),s=[...n((r-this.minHeight)/this.span,i,this.data)],c=e=>{if(!e)return[0,0,0,0];let t=Math.round(a*(e.width-1)),n=(Math.round(o*(e.height-1))*e.width+t)*4;return[e.pixels[n]/255,e.pixels[n+1]/255,e.pixels[n+2]/255,e.pixels[n+3]/255]};if(this.splat||this.splat2){let e=[...c(this.splat),...this.splat2?c(this.splat2):[]],t=e.reduce((e,t)=>e+t,0);t>.001&&(s=e.map(e=>e/t))}if(this.flow){let e=Math.round(a*(this.field.width-1)),t=Math.round(o*(this.field.height-1)),n=d(.45,.85,this.flow[t*this.field.width+e])*.8*s[0];s[0]-=n,s[1]+=n}return s}},o=class e{constructor(e){this.p=e,this.infinite=!0,this.bounds=null,this.minHeight=0,this.maxHeight=e.height}toData(){return{...this.p}}static fromData(t){return new e(t)}height(e,t){return this.sample(e,t)[0]*this.p.height}normal(e,t){let[,n,r]=this.sample(e,t),i=n*this.p.height,a=r*this.p.height,o=Math.hypot(i,1,a);return[-i/o,1/o,-a/o]}paint(e,t,r,i){return n(r/Math.max(this.p.height,1e-6),i,this.p)}sample(e,t){let n=this.p,r=Math.max(n.frequency,1e-6)/Math.max(n.sizeX,1e-6),i=e*r,a=t*r,o=Math.min(Math.max(n.warp,0),1);o>0&&(i+=(u(i+5.2,a+1.3,n.seed+7001)[0]*2-1)*o*.5,a+=(u(i+8.3,a+2.8,n.seed+7003)[0]*2-1)*o*.5);let l=Math.max(1,Math.min(8,Math.floor(n.octaves))),d=Math.min(Math.max(n.erosion,0),4),f=1,p=1,m=0,h=0,g=0,_=0,v=0,y=0;for(let e=0;e<l;e++){let[t,r,o]=u(i*p,a*p,n.seed+e*101),l=t,b=r*p,x=o*p;if(n.ridged>0){let e=t*2-1,r=Math.sqrt(e*e+s*s),i=(r-s)/c,a=e/r/c*2;l=t*(1-n.ridged)+(1-i)*n.ridged,b=b*(1-n.ridged)-a*b*n.ridged,x=x*(1-n.ridged)-a*x*n.ridged}v+=b*f,y+=x*f;let S=d>0?1/(1+d*(v*v+y*y)*.25):1;m+=l*f*S,g+=b*f*S,_+=x*f*S,h+=f,f*=n.persistence,p*=2}return[m/h,g/h*r,_/h*r]}};let s=.06,c=Math.sqrt(1.0036)-s;function l(e,t,n){let r=Math.imul(e,374761393)+Math.imul(t,668265263)+Math.imul(n|0,2147483647)|0;return r=Math.imul(r^r>>>13,1274126177),r=(r^r>>>16)>>>0,r/4294967295}function u(e,t,n){let r=Math.floor(e),i=Math.floor(t),a=e-r,o=t-i,s=a*a*(3-2*a),c=o*o*(3-2*o),u=6*a*(1-a),d=6*o*(1-o),f=l(r,i,n),p=l(r+1,i,n),m=l(r,i+1,n),h=l(r+1,i+1,n),g=p-f,_=m-f,v=f-p-m+h;return[f+g*s+_*c+v*s*c,(g+v*c)*u,(_+v*s)*d]}function d(e,t,n){let r=Math.min(Math.max((n-e)/(t-e||1e-6),0),1);return r*r*(3-2*r)}let f={moisture:{scale:900,octaves:4},temperature:{scale:2400,octaves:3},rock:{scale:500,octaves:4}};function p(...e){let t=-1640531527;for(let n of e)t=Math.imul(t^(n|0),2246822507),t=t^t>>>13|0,t=Math.imul(t,3266489909),t=t^t>>>16|0;return(t>>>0)/4294967296}function m(e){let t=-2128831035;for(let n=0;n<e.length;n++)t=Math.imul(t^e.charCodeAt(n),16777619);return t|0}function h(e,t,n,r,i){let a=0,o=0,s=1,c=1;for(let l=0;l<i;l++)a+=_(e*c,t*c,n*c,r+l*131)*s,o+=s,s*=.5,c*=2;return a/o}function g(e,t,n,r){return p(e,t,n,r)}function _(e,t,n,r){let i=Math.floor(e),a=Math.floor(t),o=Math.floor(n),s=e-i,c=t-a,l=n-o,u=s*s*(3-2*s),d=c*c*(3-2*c),f=l*l*(3-2*l),p=(e,t,n)=>g(i+e,a+t,o+n,r),m=p(0,0,0)+(p(1,0,0)-p(0,0,0))*u,h=p(0,1,0)+(p(1,1,0)-p(0,1,0))*u,_=p(0,0,1)+(p(1,0,1)-p(0,0,1))*u,v=p(0,1,1)+(p(1,1,1)-p(0,1,1))*u,y=m+(h-m)*d;return y+(_+(v-_)*d-y)*f}function v(e,t,n,r){let i=0,a=0,o=1,s=1;for(let c=0;c<r;c++)i+=u(e*s,t*s,n+c*131)[0]*o,a+=o,o*=.5,s*=2;return i/a}var y=class{constructor(e){this.inputs=e,this.seeds_={},this.noise_={...f};for(let[t,n]of Object.entries(e.noise??{}))n&&(this.noise_[t]=n);for(let t of Object.keys(this.noise_))this.seeds_[t]=e.seed*7919^m(t)}sample(e,t){let n={},r=(e,t)=>{let r=!1,i=0;Object.defineProperty(n,e,{enumerable:!0,configurable:!0,get:()=>(r||=(i=t(),!0),i),set:e=>{i=e,r=!0}})},i,a=()=>i===void 0?i=this.inputs.ground(e,t):i;r(`height`,()=>a()?.y??NaN),r(`up`,()=>a()?.up??1),r(`slope`,()=>1-(a()?.up??1)),r(`waterDepth`,()=>{let n=a();return n&&this.inputs.waterDepth?this.inputs.waterDepth(e,t,n.y)??-1/0:-1/0}),r(`shoreDistance`,()=>this.inputs.shoreDistance?.(e,t)??1/0);for(let[n,i]of Object.entries(this.noise_)){let a=Math.max(i.scale,1e-6),o=Math.max(1,i.octaves??3);this.inputs.space?r(n,()=>{let r=this.inputs.space(e,t);return h(r[0]/a,r[1]/a,r[2]/a,this.seeds_[n],o)}):r(n,()=>v(e/a,t/a,this.seeds_[n],o))}for(let[i,a]of Object.entries(this.inputs.fields??{}))r(i,()=>a(e,t,n));for(let r of this.inputs.overrides?.(e,t)??[]){let e=n[r.field]??r.value;n[r.field]=e+(r.value-e)*Math.min(Math.max(r.weight,0),1)}return n}};function b(e,t,n){if(e.type===`circle`)return Math.hypot(t-e.x,n-e.z)-e.radius;let r=Math.cos(-(e.yaw??0)),i=Math.sin(-(e.yaw??0)),a=t-e.x,o=n-e.z,s=Math.abs(a*r-o*i)-e.halfX,c=Math.abs(a*i+o*r)-e.halfZ;return Math.hypot(Math.max(s,0),Math.max(c,0))+Math.min(Math.max(s,c),0)}function x(e,t){if(t<=0)return 1;if(e.falloff<=0||t>=e.falloff)return 0;let n=1-t/e.falloff;return n*n*(3-2*n)}function S(e){let t=e.shape,n=(t.type===`circle`?t.radius:Math.hypot(t.halfX,t.halfZ))+Math.max(e.falloff,0);return[t.x-n,t.z-n,t.x+n,t.z+n]}var C=class{constructor(){this.zones_=new Map,this.revision=0,this.onChange=null}set(e){let t=this.zones_.get(e.id);t&&JSON.stringify(t)===JSON.stringify(e)||(this.zones_.set(e.id,e),this.revision++,t&&this.onChange?.(S(t),t),this.onChange?.(S(e),e))}delete(e){let t=this.zones_.get(e);t&&(this.zones_.delete(e),this.revision++,this.onChange?.(S(t),t))}get(e){return this.zones_.get(e)}all(){return this.zones_.values()}at(e,t,n=0){let r=[];for(let i of this.zones_.values()){let a=x(i,b(i.shape,e,t)-n);a>0&&r.push({zone:i,weight:a})}return r.sort((e,t)=>t.zone.priority-e.zone.priority||(e.zone.id<t.zone.id?-1:1))}excluding(e,t,n,r,i){for(let{zone:a,weight:o}of this.at(e,t,n))if(a.excludes.some(e=>e===`*`||r.includes(e))&&(o>=1||p(i,m(a.id),Math.floor(e*16),Math.floor(t*16))<o))return a;return null}};let w=[{normal:[1,0,0],a:[0,0,-1],b:[0,1,0]},{normal:[-1,0,0],a:[0,0,1],b:[0,1,0]},{normal:[0,1,0],a:[1,0,0],b:[0,0,-1]},{normal:[0,-1,0],a:[1,0,0],b:[0,0,1]},{normal:[0,0,1],a:[1,0,0],b:[0,1,0]},{normal:[0,0,-1],a:[-1,0,0],b:[0,1,0]}],T=Math.PI/4;function E(e,t,n,r=[0,0,0]){let i=w[e],a=Math.tan(t*T),o=Math.tan(n*T),s=i.normal[0]+a*i.a[0]+o*i.b[0],c=i.normal[1]+a*i.a[1]+o*i.b[1],l=i.normal[2]+a*i.a[2]+o*i.b[2],u=Math.hypot(s,c,l);return r[0]=s/u,r[1]=c/u,r[2]=l/u,r}function D(e,t,n){let r=Math.abs(e),i=Math.abs(t),a=Math.abs(n),o;o=r>=i&&r>=a?e>=0?0:1:i>=a?t>=0?2:3:n>=0?4:5;let s=w[o],c=e*s.normal[0]+t*s.normal[1]+n*s.normal[2],l=e*s.a[0]+t*s.a[1]+n*s.a[2],u=e*s.b[0]+t*s.b[1]+n*s.b[2];return{face:o,u:Math.atan(l/c)/T,v:Math.atan(u/c)/T}}function O(e,t,n,r){let i=w[e],a=t*i.normal[0]+n*i.normal[1]+r*i.normal[2];if(a<=1e-6)return null;let o=t*i.a[0]+n*i.a[1]+r*i.a[2],s=t*i.b[0]+n*i.b[1]+r*i.b[2];return{u:Math.atan(o/a)/T,v:Math.atan(s/a)/T}}let k=(e,t)=>2/2**(e-1-t);function A(e,t){let n=k(e,t.level);return{u0:-1+t.ix*n,v0:-1+t.iz*n,span:n}}function j(e,t,n,r){let i=w[e];for(let[e,a]of[[i.a,n],[i.b,r]]){let n=e[0]*t[0]+e[1]*t[1]+e[2]*t[2],r=e[0]-t[0]*n,i=e[1]-t[1]*n,o=e[2]-t[2]*n,s=Math.hypot(r,i,o)||1;a[0]=r/s,a[1]=i/s,a[2]=o/s}}function M(e,t){let{u0:n,v0:r,span:i}=A(e.levels,t),a=i/64,o=new Float32Array(13467),s=[0,0,0];for(let e=0;e<67;e++)for(let i=0;i<67;i++){E(t.face,n+(i-1)*a,r+(e-1)*a,s);let c=(e*67+i)*3;o[c]=s[0],o[c+1]=s[1],o[c+2]=s[2]}let c=e.provider.sample({world:e.world,seed:e.seed,version:e.version,radius:e.radius,directions:o,count:4489});return c instanceof Promise?c.then(n=>N(e,t,o,n.heights,n.paint)):N(e,t,o,c.heights,c.paint)}function N(e,t,n,r,i){let a=1/0,o=-1/0;for(let e=1;e<=65;e++)for(let t=1;t<=65;t++){let n=r[e*67+t];a=Math.min(a,n),o=Math.max(o,n)}let s=Math.max(e.maxHeight-e.minHeight,1e-6),c=new Uint8Array(17956),l=new Uint8Array(17956),u=new Uint8Array(17956),d=(t,i,a)=>{let o=Math.min(Math.max(t,0),66),s=Math.min(Math.max(i,0),66)*67+o,c=e.radius+r[s];a[0]=n[s*3]*c,a[1]=n[s*3+1]*c,a[2]=n[s*3+2]*c},f=[0,0,0],p=[0,0,0],m=[0,0,0],h=[0,0,0],g=[0,0,0],_=[0,0,0],v=e.paint?.()??null,y=v?P(v,n,i):null;for(let a=0;a<67;a++)for(let o=0;o<67;o++){let u=a*67+o,v=Math.round(Math.min(Math.max((r[u]-e.minHeight)/s,0),1)*65535);d(o-1,a,f),d(o+1,a,p),d(o,a-1,m),d(o,a+1,h);let b=[p[0]-f[0],p[1]-f[1],p[2]-f[2]],x=[h[0]-m[0],h[1]-m[1],h[2]-m[2]],S=b[1]*x[2]-b[2]*x[1],C=b[2]*x[0]-b[0]*x[2],w=b[0]*x[1]-b[1]*x[0],T=[n[u*3],n[u*3+1],n[u*3+2]],E=Math.hypot(S,C,w)||1;S/=E,C/=E,w/=E,S*T[0]+C*T[1]+w*T[2]<0&&(S=-S,C=-C,w=-w),j(t.face,T,g,_);let D=S*g[0]+C*g[1]+w*g[2],O=S*_[0]+C*_[1]+w*_[2],k=S*T[0]+C*T[1]+w*T[2];E=Math.hypot(D,k,O)||1,c[u*4]=v>>8,c[u*4+1]=v&255,c[u*4+2]=Math.round((D/E*.5+.5)*255),c[u*4+3]=Math.round((O/E*.5+.5)*255);let A=0,M=0,N=0,P=0;if(y){let e=y(o,a);A=e[0],M=e[1],N=e[2],P=e[3]}else if(i)A=i[u*4],M=i[u*4+1],N=i[u*4+2],P=i[u*4+3];else{let e=Math.min(Math.max((.9-k/E)*6,0),1);A=1-e,P=e}l[u*4]=Math.round(Math.min(Math.max(A,0),1)*255),l[u*4+1]=Math.round(Math.min(Math.max(M,0),1)*255),l[u*4+2]=Math.round(Math.min(Math.max(N,0),1)*255),l[u*4+3]=Math.round(Math.min(Math.max(P,0),1)*255)}return{heights:c,paint:l,paint2:u,min:Number.isFinite(a)?a:e.minHeight,max:Number.isFinite(o)?o:e.maxHeight}}function P(e,t,n){let r=Array(81);for(let i=0;i<9;i++)for(let a=0;a<9;a++){let o=1+a*8,s=(1+i*8)*67+o,c=n?[n[s*4],n[s*4+1],n[s*4+2],n[s*4+3]]:[1,0,0,0],l=e(t[s*3],t[s*3+1],t[s*3+2],c);r[i*9+a]=[l[0]??0,l[1]??0,l[2]??0,l[3]??0]}return(e,t)=>{let n=Math.min(Math.max((e-1)/8,0),8),i=Math.min(Math.max((t-1)/8,0),8),a=Math.min(Math.floor(n),7),o=Math.min(Math.floor(i),7),s=n-a,c=i-o,l=r[o*9+a],u=r[o*9+a+1],d=r[(o+1)*9+a],f=r[(o+1)*9+a+1],p=[0,0,0,0];for(let e=0;e<4;e++)p[e]=(l[e]*(1-s)+u[e]*s)*(1-c)+(d[e]*(1-s)+f[e]*s)*c;return p}}let F=e=>e*Math.PI/4,I=e=>F(e),L=1.5;var R=class{constructor(e,t){this.face=e,this.planet=t,this.tiles_=new Map}facts(){return this.planet()}directionAt(e,t){let n=this.facts(),r=F(n?.radius??1);return E(this.face,e/r,t/r)}planeOf(e,t,n){let r=this.facts(),i=O(this.face,e,t,n);if(!r||!i)return null;let a=F(r.radius);return{x:i.u*a,z:i.v*a}}frameAt(e,t){let n=this.directionAt(e,t),r=[0,0,0],i=[0,0,0];return j(this.face,n,r,i),{dir:n,eu:r,ev:i}}world(e,t,n){let r=this.facts(),i=this.directionAt(e,n),a=r.radius+t;return[r.centre[0]+i[0]*a,r.centre[1]+i[1]*a,r.centre[2]+i[2]*a]}tile(e,t){let n=Math.floor(e/48),r=Math.floor(t/48),i=`${n},${r}`,a=this.tiles_.get(i);if(a)return this.tiles_.delete(i),this.tiles_.set(i,a),a;let o=this.facts();if(!o?.sampleMany)return null;let s=new Float32Array(3675);for(let e=0;e<35;e++)for(let t=0;t<35;t++){let i=this.directionAt(n*48+(t-1)*L,r*48+(e-1)*L);s[(e*35+t)*3]=i[0],s[(e*35+t)*3+1]=i[1],s[(e*35+t)*3+2]=i[2]}let c=o.sampleMany(s,1225);if(!c)return null;let l={x0:n*48-L,z0:r*48-L,n:35,heights:c.heights,paint:c.paint,fields:c.fields,fieldCount:o.fieldNames.length};return this.tiles_.set(i,l),this.tiles_.size>6e3&&this.tiles_.delete(this.tiles_.keys().next().value),l}cellOf(e,t,n){let r=(t-e.x0)/L,i=(n-e.z0)/L,a=Math.min(Math.max(Math.floor(r),0),e.n-2),o=Math.min(Math.max(Math.floor(i),0),e.n-2);return{i:a,j:o,fx:Math.min(Math.max(r-a,0),1),fz:Math.min(Math.max(i-o,0),1)}}heightAt(e,t){let n=this.tile(e,t);if(!n)return null;let{i:r,j:i,fx:a,fz:o}=this.cellOf(n,e,t),s=n.n,c=n.heights,l=c[i*s+r],u=c[i*s+r+1],d=c[(i+1)*s+r],f=c[(i+1)*s+r+1];return(l+(u-l)*a)*(1-o)+(d+(f-d)*a)*o}paintAt(e,t){let n=this.tile(e,t);if(!n?.paint)return null;let{i:r,j:i,fx:a,fz:o}=this.cellOf(n,e,t),s=(i+ +(o>.5))*n.n+r+ +(a>.5);return[n.paint[s*4],n.paint[s*4+1],n.paint[s*4+2],n.paint[s*4+3]]}fieldsAt(e,t){let n=this.tile(e,t);if(!n?.fields||n.fieldCount===0)return null;let{i:r,j:i,fx:a,fz:o}=this.cellOf(n,e,t),s=n.fieldCount,c=n.n,l=[];for(let e=0;e<s;e++){let t=n.fields[(i*c+r)*s+e],u=n.fields[(i*c+r+1)*s+e],d=n.fields[((i+1)*c+r)*s+e],f=n.fields[((i+1)*c+r+1)*s+e];l.push((t+(u-t)*a)*(1-o)+(d+(f-d)*a)*o)}return l}ground(e,t){let n=this.heightAt(e,t);if(n===null)return null;let r=L,i=this.heightAt(e-r,t),a=this.heightAt(e+r,t),o=this.heightAt(e,t-r),s=this.heightAt(e,t+r);if(i===null||a===null||o===null||s===null)return{y:n,up:1,normal:[0,1,0]};let c=-(a-i)/3,l=-(s-o)/3,u=Math.hypot(c,1,l);return{y:n,up:1/u,normal:[c/u,1/u,l/u]}}worldNormal(e,t,n){let r=this.frameAt(t,n);return[e[0]*r.eu[0]+e[1]*r.dir[0]+e[2]*r.ev[0],e[0]*r.eu[1]+e[1]*r.dir[1]+e[2]*r.ev[1],e[0]*r.eu[2]+e[1]*r.dir[2]+e[2]*r.ev[2]]}environment(){return{ground:(e,t)=>this.ground(e,t),space:(e,t)=>{let n=this.facts(),r=this.directionAt(e,t);return[r[0]*n.radius,r[1]*n.radius,r[2]*n.radius]}}}zoneOnFace(e){let t=this.facts(),n=e.shape;if(!t||n.y===void 0)return null;let r=n.x-t.centre[0],i=n.y-t.centre[1],a=n.z-t.centre[2],o=Math.hypot(r,i,a);if(o<1e-9)return null;let s=this.planeOf(r/o,i/o,a/o),c=I(t.radius),l=(n.type===`circle`?n.radius:Math.hypot(n.halfX,n.halfZ))+e.falloff;if(!s||Math.abs(s.x)>c+l||Math.abs(s.z)>c+l)return null;if(n.type===`circle`)return{...e,shape:{type:`circle`,x:s.x,z:s.z,radius:n.radius}};let u=this.frameAt(s.x,s.z),d=n.facing??[Math.cos(n.yaw??0),0,Math.sin(n.yaw??0)],f=Math.atan2(d[0]*u.ev[0]+d[1]*u.ev[1]+d[2]*u.ev[2],d[0]*u.eu[0]+d[1]*u.eu[1]+d[2]*u.eu[2]);return{...e,shape:{type:`rect`,x:s.x,z:s.z,halfX:n.halfX,halfZ:n.halfZ,yaw:f}}}sourcesOnFace(e,t){let n=this.facts(),r=[];if(!n)return r;let i=I(n.radius);for(let a of e){let e=a.x-n.centre[0],o=(a.y??0)-n.centre[1],s=a.z-n.centre[2],c=Math.hypot(e,o,s);if(c<1e-9)continue;let l=this.planeOf(e/c,o/c,s/c);l&&Math.abs(l.x)<=i+t&&Math.abs(l.z)<=i+t&&r.push(l)}return r}};function z(e,t){if(!Number.isFinite(t))return 0;let n=Math.max(e.blend??0,1e-9),r=e=>{if(e<=0)return 1;if(e>=n)return 0;let t=1-e/n;return t*t*(3-2*t)};return r(e.min===void 0?-1:e.min-t)*r(e.max===void 0?-1:t-e.max)}let B=4e4;function V(e){let t=e.anchor.footprint;for(let n of e.members??[])t=Math.max(t,(n.ring?.[1]??0)+n.footprint);return t}let H=(e,t,n)=>e?e[0]+(e[1]-e[0])*t:n;var U=class{constructor(e,t,n,r,i){this.rules=e,this.env=t,this.zones=n,this.seed=r,this.world=i,this.recipes_=new Map,this.layers_=[],this.viable_=new Map,this.groups_=new Map,this.worldHash_=m(i)^r;for(let t of e.recipes)this.recipes_.set(t.id,t);for(let t of e.layers){let n=new Set;for(let r of e.biomes)for(let e of r.recipes)e.layer===t.id&&n.add(e.recipe);let r=0;for(let e of n){let t=this.recipes_.get(e);t&&(r=Math.max(r,V(t)))}this.layers_.push({def:t,hash:m(t.id),maxRadius:r,recipes:n})}}invalidate(){this.viable_.clear(),this.groups_.clear()}layerIndex(e){return this.layers_.findIndex(t=>t.def.id===e)}biomeWeights(e,t){let n=[],r=0;for(let i of this.rules.biomes){let a=this.biomeWeight(i,e,t);a>0&&(n.push({biome:i.id,weight:a}),r+=a)}for(let{zone:i,weight:a}of this.zones.at(e,t)){if(!i.biome)continue;for(let e of n)e.weight*=1-a;r=r*(1-a)+a;let e=n.find(e=>e.biome===i.biome);e?e.weight+=a:n.push({biome:i.biome,weight:a});break}if(r<=0)return[];for(let e of n)e.weight/=r;return n.filter(e=>e.weight>0).sort((e,t)=>t.weight-e.weight||(e.biome<t.biome?-1:1))}biomeAt(e,t){return this.biomeWeights(e,t)[0]?.biome??null}paint(e,t,n){let r=n.length,i=this.biomeWeights(e,t);for(let{biome:e}of i)r=Math.max(r,this.rules.biomes.find(t=>t.id===e)?.paint?.length??0);let a=Array.from({length:r},(e,t)=>n[t]??0);for(let{biome:e,weight:t}of i){let i=this.rules.biomes.find(t=>t.id===e);if(!i?.paint)continue;let o=t*Math.min(Math.max(i.paintStrength??1,0),1);for(let e=0;e<r;e++)a[e]=a[e]+((i.paint[e]??0)-(n[e]??0))*o}let o=a.reduce((e,t)=>e+t,0)||1;return a.map(e=>e/o)}groupsIn(e,t,n,r,i){let a=this.layerIndex(e);if(a<0)return[];let o=this.layers_[a].def.spacing,s=[];for(let e=Math.floor(n/o);e<=Math.floor(i/o);e++)for(let c=Math.floor(t/o);c<=Math.floor(r/o);c++){let o=this.group(a,c,e);typeof o!=`string`&&o.x>=t&&o.x<r&&o.z>=n&&o.z<i&&s.push(o)}return s}placementsIn(e,t,n,r,i){let a=[];for(let o of this.layers_)if(!(i&&!i.includes(o.def.id)))for(let i of this.groupsIn(o.def.id,e,t,n,r))a.push(i.anchor,...i.members);return a}stats(e,t,n,r,i){let a={placed:0,noBiome:0,density:0,noGround:0,slope:0,water:0,zone:0,occupied:0,conflict:0},o=this.layerIndex(e);if(o<0)return a;let s=this.layers_[o].def.spacing;for(let e=Math.floor(n/s);e<Math.ceil(i/s);e++)for(let n=Math.floor(t/s);n<Math.ceil(r/s);n++){let t=this.group(o,n,e);typeof t==`string`?a[t]++:a.placed++}return a}explain(e,t){let n=this.layers_.map((n,r)=>{let i=Math.floor(e/n.def.spacing),a=Math.floor(t/n.def.spacing),o=this.group(r,i,a),s=this.viable(r,i,a);return{layer:n.def.id,cell:[i,a],group:typeof o==`string`?null:o.id,rejected:typeof o==`string`?o:null,detail:s.ok?void 0:s.detail}});return{fields:this.env.sample(e,t),biomes:this.biomeWeights(e,t),zones:this.zones.at(e,t).map(({zone:e,weight:t})=>({id:e.id,kind:e.kind,weight:t})),layers:n}}group(e,t,n){let r=`${e}:${t},${n}`,i=this.groups_.get(r);if(i!==void 0)return i;this.groups_.size>B&&this.groups_.clear();let a=this.makeGroup(e,t,n);return this.groups_.set(r,a),a}makeGroup(e,t,n){let r=this.viable(e,t,n);if(!r.ok)return r.reason;let i=r.candidate,a=this.layers_[e],o=a.def.spacing,s=Math.ceil((i.radius+a.maxRadius)/o);for(let r=-s;r<=s;r++)for(let a=-s;a<=s;a++){if(a===0&&r===0)continue;let o=this.viable(e,t+a,n+r);if(!o.ok)continue;let s=o.candidate;if((s.priority>i.priority||s.priority===i.priority&&(s.gz<n||s.gz===n&&s.gx<t))&&Math.hypot(s.x-i.x,s.z-i.z)<i.radius+s.radius)return`conflict`}let c=`${a.def.id}@${a.def.version??1}:${t},${n}`,l=i.recipe,u=this.place(c,a.def,l,l.anchor,0,i.x,i.z,i.biome,i.fields,0),d=[],f=[u];for(let[r,o]of(l.members??[]).entries()){let s=(e,i)=>p(this.worldHash_,a.hash,t,n,1e3+r*37+e,i),u=o.count?o.count[0]+Math.floor(s(0,0)*(o.count[1]-o.count[0]+1)):1;for(let t=0;t<u;t++){if(o.chance!==void 0&&s(1,t)>=o.chance)continue;let n=H(o.arc,s(2,t),s(2,t)*360)*Math.PI/180,r=H(o.ring,s(3,t),0),u=i.x+Math.cos(n)*r,p=i.z+Math.sin(n)*r,m=this.env.sample(u,p);if(this.standing(m,o)!==null||this.zones.excluding(u,p,o.footprint,this.tagsOf(a.def,l,o),this.seed)!==null||this.occupied(e,u,p,o.footprint)!==null||f.some(e=>Math.hypot(e.x-u,e.z-p)<e.footprint+o.footprint))continue;let h=this.place(c,a.def,l,o,t,u,p,i.biome,m,s(4,t));h&&(d.push(h),f.push(h))}}return{id:c,layer:a.def.id,x:i.x,z:i.z,radius:i.radius,priority:i.priority,anchor:u,members:d}}place(e,t,n,r,i,a,o,s,c,l){if(!Number.isFinite(c.height))return null;let u=p(this.worldHash_,m(e),m(r.id),i,7),d=this.env.inputs.ground(a,o),f=d?.up??1,h=d?.normal??[0,f,Math.sqrt(Math.max(0,1-f*f))];return{id:`${e}/${n.id}@${n.version}/${r.id}.${i}`,group:e,layer:t.id,recipe:n.id,recipeVersion:n.version,member:r.id,biome:s,zone:this.zones.at(a,o)[0]?.zone.id??null,x:a,y:c.height,z:o,yaw:(l||u)*Math.PI*2,scale:H(r.scale,p(this.worldHash_,m(e),i,11),1),normal:h,attach:r.attach??`upright`,mesh:typeof r.mesh==`number`?r.mesh:0,material:typeof r.material==`number`?r.material:0,plant:r.plant??null,interactive:r.interactive??null,footprint:r.footprint,canopy:r.canopy??r.footprint,far:r.far??null}}standing(e,t){return Number.isFinite(e.height)?e.up<(t.minUp??0)?`slope`:e.waterDepth>(t.waterDepth??0)?`water`:null:`noGround`}tagsOf(e,t,n){return[e.id,t.id,n.interactive?`interactive`:`decor`,...t.tags??[],...n.tags??[]]}viable(e,t,n){let r=`${e}:${t},${n}`,i=this.viable_.get(r);if(i)return i;this.viable_.size>B&&this.viable_.clear();let a=this.makeViable(e,t,n);return this.viable_.set(r,a),a}makeViable(e,t,n){let r=this.layers_[e],i=r.def.spacing,a=e=>p(this.worldHash_,r.hash,t,n,e),o=(t+a(1))*i,s=(n+a(2))*i,c=this.biomeWeights(o,s);if(c.length===0)return{ok:!1,reason:`noBiome`};let l=a(3),u=c[c.length-1].biome;for(let e of c){if(l<e.weight){u=e.biome;break}l-=e.weight}let d=(this.rules.biomes.find(e=>e.id===u)?.recipes??[]).filter(e=>e.layer===r.def.id&&this.recipes_.has(e.recipe)),f=a(4),m=null;for(let e of d){if(f<e.density){m=this.recipes_.get(e.recipe);break}f-=e.density}if(!m)return{ok:!1,reason:`density`};let h=this.env.sample(o,s),g=this.standing(h,m.anchor);if(g)return{ok:!1,reason:g};let _=this.zones.excluding(o,s,m.anchor.footprint,this.tagsOf(r.def,m,m.anchor),this.seed);if(_)return{ok:!1,reason:`zone`,detail:_.id};let v=this.occupied(e,o,s,m.anchor.footprint);return v?{ok:!1,reason:`occupied`,detail:v}:{ok:!0,candidate:{gx:t,gz:n,x:o,z:s,priority:a(5),biome:u,recipe:m,radius:V(m),fields:h}}}occupied(e,t,n,r){for(let i=0;i<e;i++){let e=this.layers_[i];if(e.def.occupies===!1)continue;let a=e.def.spacing,o=r+e.maxRadius;for(let e=Math.floor((n-o)/a);e<=Math.floor((n+o)/a);e++)for(let s=Math.floor((t-o)/a);s<=Math.floor((t+o)/a);s++){let a=this.group(i,s,e);if(typeof a!=`string`){for(let e of[a.anchor,...a.members])if(Math.hypot(e.x-t,e.z-n)<e.footprint+r)return e.id}}}return null}biomeWeight(e,t,n){let r=e.transition??0,i=t,a=n;if(r>0){let o=m(e.id)^this.worldHash_;i+=(v(t/r,n/r,o,2)-.5)*2*r,a+=(v(t/r,n/r,o+1,2)-.5)*2*r}let o=this.env.sample(i,a),s=e.weight??1;for(let t of e.conditions)if(s*=z(t,o[t.field]??NaN),s<=0)return 0;return s}};function W(e){return e.layers.some(e=>(e.farSpacing??1)>1)?{...e,layers:e.layers.map(e=>(e.farSpacing??1)>1?{...e,spacing:e.spacing*e.farSpacing}:e)}:null}function G(e,t){let n={};t.layers.forEach((t,r)=>{n[`paint.${t}`]=(t,n)=>e.paintAt(t,n)?.[r]??0}),t.fieldNames.forEach((t,r)=>{n[t]=(t,n)=>e.fieldsAt(t,n)?.[r]??0});let r=new y({seed:t.seed,noise:t.rules.noise,fields:{...n,...t.rules.fields},...e.environment(),waterDepth:(e,n,r)=>t.seaLevel-r,overrides:(e,n)=>{let r=[];for(let{zone:i,weight:a}of t.zones.at(e,n))for(let[e,t]of Object.entries(i.fields??{}))r.push({field:e,value:t,weight:a});return r}}),i=`${t.world}#${e.face}`;return{plan:new U(t.rules,r,t.zones,t.seed,i),farPlan:t.farRules?new U(t.farRules,r,t.zones,t.seed,i):null}}function K(e){let t={};e.ground&&e.layers.forEach((n,r)=>{t[`paint.${n}`]=(t,n)=>e.ground.paintAt(t,n)?.[r]??0});let n=new y({seed:e.seed,noise:e.rules.noise,fields:{...t,...e.rules.fields},ground:(t,n)=>{if(e.ground){let r=e.ground.heightAt(t,n);if(r===null)return null;let i=e.ground.normalAt(t,n)??[0,1,0];return{y:r,up:i[1],normal:i}}return{y:e.flatY,up:1,normal:[0,1,0]}},waterDepth:(t,n,r)=>e.water?.depthAt(t,n,r)??null,shoreDistance:(t,n)=>e.water?.shoreAt(t,n)??null,overrides:(t,n)=>{let r=[];for(let{zone:i,weight:a}of e.zones.at(t,n))for(let[e,t]of Object.entries(i.fields??{}))r.push({field:e,value:t,weight:a});return r}});return{plan:new U(e.rules,n,e.zones,e.seed,e.world),farPlan:e.farRules?new U(e.farRules,n,e.zones,e.seed,e.world):null}}var ee=class{constructor(e,t){this.source=e,this.cell=t}node(e,t){let n=e*this.cell,r=t*this.cell,i=this.source.bounds;return i&&(n=Math.min(Math.max(n,i[0]),i[2]),r=Math.min(Math.max(r,i[1]),i[3])),this.source.height(n,r)}covers(e,t){let n=this.source.bounds;return!n||e>=n[0]&&e<=n[2]&&t>=n[1]&&t<=n[3]}height(e,t){let n=this.corners(e,t);if(!n)return null;let[r,i,a,o,s,c]=n;return s+c<=1?r+(i-r)*s+(a-r)*c:o+(a-o)*(1-s)+(i-o)*(1-c)}normal(e,t){let n=this.corners(e,t);if(!n)return null;let[r,i,a,o,s,c]=n,l=(s+c<=1?i-r:o-a)/this.cell,u=(s+c<=1?a-r:o-i)/this.cell,d=Math.hypot(l,1,u);return[-l/d,1/d,-u/d]}tile(e,t){let n=new Float32Array(3267);for(let r=0;r<=32;r++)for(let i=0;i<=32;i++){let a=this.node(e*32+i,t*32+r);if(a===null)return null;let o=(r*33+i)*3;n[o]=i*this.cell,n[o+1]=a,n[o+2]=r*this.cell}let r=new Uint32Array(6144),i=0;for(let e=0;e<32;e++)for(let t=0;t<32;t++){let n=e*33+t,a=n+1,o=n+33,s=o+1;r.set([n,o,a,a,o,s],i),i+=6}return{x0:e*32*this.cell,z0:t*32*this.cell,positions:n,indices:r}}raycast(e,t,n,r,i,a,o){let s=Math.hypot(r,i,a);if(s<=0)return null;r/=s,i/=s,a/=s;let c=this.cell,l=Math.floor(e/c),u=Math.floor(n/c),d=r>0?1:-1,f=a>0?1:-1,p=r===0?1/0:Math.abs(c/r),m=a===0?1/0:Math.abs(c/a),h=r===0?1/0:((r>0?(l+1)*c:l*c)-e)/r,g=a===0?1/0:((a>0?(u+1)*c:u*c)-n)/a,_=0;for(let s=0;s<1e6&&_<=o;s++){let s=this.node(l,u),v=this.node(l+1,u),y=this.node(l,u+1),b=this.node(l+1,u+1);if(s===null||v===null||y===null||b===null)return null;let x=l*c,S=u*c;for(let l of[[[x,s,S],[x,y,S+c],[x+c,v,S]],[[x+c,v,S],[x,y,S+c],[x+c,b,S+c]]]){let s=te(e,t,n,r,i,a,l[0],l[1],l[2]);if(s&&s.t<=o&&this.covers(e+r*s.t,n+a*s.t))return{distance:s.t,point:[e+r*s.t,t+i*s.t,n+a*s.t],normal:s.n}}if(h<g?(_=h,h+=p,l+=d):(_=g,g+=m,u+=f),r===0&&a===0)break}return null}corners(e,t){if(!this.covers(e,t))return null;let n=e/this.cell,r=t/this.cell,i=Math.floor(n),a=Math.floor(r),o=this.node(i,a),s=this.node(i+1,a),c=this.node(i,a+1),l=this.node(i+1,a+1);return o===null||s===null||c===null||l===null?null:[o,s,c,l,n-i,r-a]}};function te(e,t,n,r,i,a,o,s,c){let l=s[0]-o[0],u=s[1]-o[1],d=s[2]-o[2],f=c[0]-o[0],p=c[1]-o[1],m=c[2]-o[2],h=i*m-a*p,g=a*f-r*m,_=r*p-i*f,v=l*h+u*g+d*_;if(Math.abs(v)<1e-12)return null;let y=1/v,b=e-o[0],x=t-o[1],S=n-o[2],C=(b*h+x*g+S*_)*y;if(C<-1e-9||C>1+1e-9)return null;let w=x*d-S*u,T=S*l-b*d,E=b*u-x*l,D=(r*w+i*T+a*E)*y;if(D<-1e-9||C+D>1+1e-9)return null;let O=(f*w+p*T+m*E)*y;if(O<0)return null;let k=u*m-d*p,A=d*f-l*m,j=l*p-u*f;A<0&&(k=-k,A=-A,j=-j);let M=Math.hypot(k,A,j)||1;return{t:O,n:[k/M,A/M,j/M]}}function ne(e,t,n,r){let i=e.height(n-t.x,r-t.z);return i===null?null:t.y+i}function re(e,t,n,r){return e.normal(n-t.x,r-t.z)}function ie(e,t,n,r,i){let a=r-n.x,o=i-n.z,s=t.height(a,o),c=t.normal(a,o);return s===null||!c?null:e.paint(a,o,s,c[1])}var ae=class{constructor(e){this.source_=e.source.kind===`field`?a.fromData(e.source.data):o.fromData(e.source.data),this.surface_=new ee(this.source_,e.cell),this.origin_=e.origin}heightAt(e,t){return ne(this.surface_,this.origin_,e,t)}normalAt(e,t){return re(this.surface_,this.origin_,e,t)}paintAt(e,t){return ie(this.source_,this.surface_,this.origin_,e,t)}},oe=class{constructor(e){this.data=e}lerp(e,t){let{minX:n,minZ:r,sizeX:i,sizeZ:a,nx:o,nz:s}=this.data.grid;if(o<2||s<2)return null;let c=(e-n)/i,l=(t-r)/a;if(c<0||c>1||l<0||l>1)return null;let u=c*(o-1),d=l*(s-1),f=Math.min(Math.floor(u),o-2),p=Math.min(Math.floor(d),s-2),m=u-f,h=d-p,g=p*o+f,_=e=>(e[g]*(1-m)+e[g+1]*m)*(1-h)+(e[g+o]*(1-m)+e[g+o+1]*m)*h;return{height:_(this.data.height),shore:_(this.data.shore)}}depthAt(e,t,n){let r=this.lerp(e,t);return r?r.shore>0?r.height-n:null:this.data.ocean?this.data.ocean.level-n:null}shoreAt(e,t){let n=this.lerp(e,t);return n?-n.shore:this.data.ocean?-1e6:null}};let q=new Map,J=new Map,Y=e=>{let t=URL.createObjectURL(new Blob([e],{type:`text/javascript`}));return import(t).then(e=>e.default).finally(()=>URL.revokeObjectURL(t))};function X(e,t){let n=J.get(e);return n||(n=t(e),J.set(e,n)),n}function se(e){let t=new C;for(let n of e.zones)t.set(n);return{face:null,...K({rules:e.rules,farRules:W(e.rules),seed:e.seed,world:e.world,zones:t,ground:e.ground?new ae(e.ground):null,flatY:e.flatY,water:e.water?new oe(e.water):null,layers:e.layers})}}async function ce(e,t){let n=await X(e.provider.source,t),r={centre:e.centre,radius:e.radius,gravity:0,height:null,paint:null,layers:e.layers,fieldNames:e.fieldNames,fieldsAt:null,sampleMany:(t,r)=>{let i=n.sample({world:e.provider.world,seed:e.provider.seed,version:e.provider.version,radius:e.radius,directions:t,count:r});if(i instanceof Promise)throw Error(`a provider used in a worker must answer at once`);return i}},i=new R(e.face,()=>r),a=new C;for(let t of e.zones)a.set(t);return{face:i,...G(i,{rules:e.rules,farRules:W(e.rules),seed:e.seed,world:e.world,seaLevel:e.seaLevel,layers:e.layers,fieldNames:e.fieldNames,zones:a})}}async function Z(e,t,n){let r=q.get(e);if(!r){if(!t)throw Error(`the plan ${e} is not known to this worker`);r=`plane`in t?se(t):await ce(t,n),q.set(e,r),q.size>24&&q.delete(q.keys().next().value)}return r}async function Q(e,t=Y){let n=await Z(e.key,e.spec,t);return(e.far&&n.farPlan?n.farPlan:n.plan).placementsIn(e.x0,e.z0,e.x1,e.z1,[e.layer])}async function $(e,t=Y){let n=await X(e.provider.source,t),r=null;if(e.paintKeys){let n=e.paintKeys,i=await Promise.all(n.map((n,r)=>Z(n,e.specs[r],t)));r=(e,t,n,r)=>{let a=i[D(e,t,n).face],o=a.face.planeOf(e,t,n);return o?a.plan.paint(o.x,o.z,r):r}}let i=await M({provider:n,world:e.provider.world,seed:e.provider.seed,version:e.provider.version,radius:e.radius,levels:e.levels,minHeight:e.minHeight,maxHeight:e.maxHeight,...r?{paint:()=>r}:{}},e.node);return{result:i,transfer:[i.heights.buffer,i.paint.buffer,i.paint2.buffer]}}return typeof self<`u`&&typeof self.importScripts==`function`&&(self.onmessage=e=>{let t=e.data,n=e=>self.postMessage({id:t.id,error:e instanceof Error?e.message:String(e)});t.type===`page`?$(t).then(e=>self.postMessage({id:t.id,result:e.result},e.transfer),n):Q(t).then(e=>self.postMessage({id:t.id,result:e}),n)}),e.page=$,e.placements=Q,e})({});";+export const PLAN_WORKER_SOURCE = "(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});let t=(e,t,n)=>{let r=Math.min(Math.max((n-e)/(t-e||1e-6),0),1);return r*r*(3-2*r)};function n(e,n,r){let i=t(r.rockSlope-.08,r.rockSlope+.08,1-n),a=t(r.snowHeight-.06,r.snowHeight+.06,e)*(1-i*.85),o=t(r.dirtHeight-.15,r.dirtHeight+.15,e)*(1-a)*(1-i),s=(1-i)*(1-a)*(1-o),c=s+o+a+i||1;return[s/c,o/c,a/c,i/c]}function r(e,t,n){let r=Math.min(Math.max(t,0),1)*(e.width-1),i=Math.min(Math.max(n,0),1)*(e.height-1),a=Math.min(Math.floor(r),e.width-2),o=Math.min(Math.floor(i),e.height-2),s=r-a,c=i-o,l=(t,n)=>e.data[n*e.width+t],u=l(a,o)+(l(a+1,o)-l(a,o))*s;return u+(l(a,o+1)+(l(a+1,o+1)-l(a,o+1))*s-u)*c}function i(e,t,n,i,a,o){let s=1/(e.width-1),c=1/(e.height-1),l=(r(e,t+s,n)-r(e,t-s,n))*o/(2*s*i),u=(r(e,t,n+c)-r(e,t,n-c))*o/(2*c*a),d=Math.hypot(l,1,u);return[-l/d,1/d,-u/d]}var a=class e{constructor(e,t,n,r,i=[0,t.height],a=null){this.field=e,this.data=t,this.splat=n,this.flow=r,this.splat2=a,this.infinite=!1,this.bounds=[-t.sizeX/2,-t.sizeZ/2,t.sizeX/2,t.sizeZ/2],[this.minHeight,this.maxHeight]=i}ensureSplats(e){let t=this.field,r=Math.min(t.width,1024),i=Math.min(t.height,1024);if(!this.splat){let e=new Uint8Array(r*i*4),t=this.data.sizeX,a=this.data.sizeZ;for(let o=0;o<i;o++)for(let s=0;s<r;s++){let c=(s/(r-1)-.5)*t,l=(o/(i-1)-.5)*a,u=this.height(c,l)??this.minHeight,d=this.normal(c,l),f=n((u-this.minHeight)/this.span,d?d[1]:1,this.data);for(let t=0;t<4;t++)e[(o*r+s)*4+t]=Math.round(f[t]*255)}this.splat={width:r,height:i,pixels:e}}return e&&!this.splat2&&(this.splat2={width:this.splat.width,height:this.splat.height,pixels:new Uint8Array(this.splat.width*this.splat.height*4)}),{a:this.splat,b:this.splat2}}splats(){return{a:this.splat,b:this.splat2}}get span(){return Math.max(this.maxHeight-this.minHeight,1e-6)}toData(){let e=this.data;return{field:this.field,params:{sizeX:e.sizeX,sizeZ:e.sizeZ,height:e.height,rockSlope:e.rockSlope,dirtHeight:e.dirtHeight,snowHeight:e.snowHeight},splat:this.splat,splat2:this.splat2,flow:this.flow,range:[this.minHeight,this.maxHeight]}}static fromData(t){return new e(t.field,t.params,t.splat,t.flow,t.range,t.splat2)}height(e,t){let n=e/this.data.sizeX+.5,i=t/this.data.sizeZ+.5;return n<0||n>1||i<0||i>1?null:this.minHeight+r(this.field,n,i)*this.span}normal(e,t){let n=e/this.data.sizeX+.5,r=t/this.data.sizeZ+.5;return n<0||n>1||r<0||r>1?null:i(this.field,n,r,this.data.sizeX,this.data.sizeZ,this.span)}paint(e,t,r,i){let a=Math.min(Math.max(e/this.data.sizeX+.5,0),1),o=Math.min(Math.max(t/this.data.sizeZ+.5,0),1),s=[...n((r-this.minHeight)/this.span,i,this.data)],c=e=>{if(!e)return[0,0,0,0];let t=Math.round(a*(e.width-1)),n=(Math.round(o*(e.height-1))*e.width+t)*4;return[e.pixels[n]/255,e.pixels[n+1]/255,e.pixels[n+2]/255,e.pixels[n+3]/255]};if(this.splat||this.splat2){let e=[...c(this.splat),...this.splat2?c(this.splat2):[]],t=e.reduce((e,t)=>e+t,0);t>.001&&(s=e.map(e=>e/t))}if(this.flow){let e=Math.round(a*(this.field.width-1)),t=Math.round(o*(this.field.height-1)),n=d(.45,.85,this.flow[t*this.field.width+e])*.8*s[0];s[0]-=n,s[1]+=n}return s}},o=class e{constructor(e){this.p=e,this.infinite=!0,this.bounds=null,this.minHeight=0,this.maxHeight=e.height}toData(){return{...this.p}}static fromData(t){return new e(t)}height(e,t){return this.sample(e,t)[0]*this.p.height}normal(e,t){let[,n,r]=this.sample(e,t),i=n*this.p.height,a=r*this.p.height,o=Math.hypot(i,1,a);return[-i/o,1/o,-a/o]}paint(e,t,r,i){return n(r/Math.max(this.p.height,1e-6),i,this.p)}sample(e,t){let n=this.p,r=Math.max(n.frequency,1e-6)/Math.max(n.sizeX,1e-6),i=e*r,a=t*r,o=Math.min(Math.max(n.warp,0),1);o>0&&(i+=(u(i+5.2,a+1.3,n.seed+7001)[0]*2-1)*o*.5,a+=(u(i+8.3,a+2.8,n.seed+7003)[0]*2-1)*o*.5);let l=Math.max(1,Math.min(8,Math.floor(n.octaves))),d=Math.min(Math.max(n.erosion,0),4),f=1,p=1,m=0,h=0,g=0,_=0,v=0,y=0;for(let e=0;e<l;e++){let[t,r,o]=u(i*p,a*p,n.seed+e*101),l=t,b=r*p,x=o*p;if(n.ridged>0){let e=t*2-1,r=Math.sqrt(e*e+s*s),i=(r-s)/c,a=e/r/c*2;l=t*(1-n.ridged)+(1-i)*n.ridged,b=b*(1-n.ridged)-a*b*n.ridged,x=x*(1-n.ridged)-a*x*n.ridged}v+=b*f,y+=x*f;let S=d>0?1/(1+d*(v*v+y*y)*.25):1;m+=l*f*S,g+=b*f*S,_+=x*f*S,h+=f,f*=n.persistence,p*=2}return[m/h,g/h*r,_/h*r]}};let s=.06,c=Math.sqrt(1.0036)-s;function l(e,t,n){let r=Math.imul(e,374761393)+Math.imul(t,668265263)+Math.imul(n|0,2147483647)|0;return r=Math.imul(r^r>>>13,1274126177),r=(r^r>>>16)>>>0,r/4294967295}function u(e,t,n){let r=Math.floor(e),i=Math.floor(t),a=e-r,o=t-i,s=a*a*(3-2*a),c=o*o*(3-2*o),u=6*a*(1-a),d=6*o*(1-o),f=l(r,i,n),p=l(r+1,i,n),m=l(r,i+1,n),h=l(r+1,i+1,n),g=p-f,_=m-f,v=f-p-m+h;return[f+g*s+_*c+v*s*c,(g+v*c)*u,(_+v*s)*d]}function d(e,t,n){let r=Math.min(Math.max((n-e)/(t-e||1e-6),0),1);return r*r*(3-2*r)}let f={moisture:{scale:900,octaves:4},temperature:{scale:2400,octaves:3},rock:{scale:500,octaves:4}};function p(...e){let t=-1640531527;for(let n of e)t=Math.imul(t^(n|0),2246822507),t=t^t>>>13|0,t=Math.imul(t,3266489909),t=t^t>>>16|0;return(t>>>0)/4294967296}function m(e){let t=-2128831035;for(let n=0;n<e.length;n++)t=Math.imul(t^e.charCodeAt(n),16777619);return t|0}function h(e,t,n,r,i){let a=0,o=0,s=1,c=1;for(let l=0;l<i;l++)a+=_(e*c,t*c,n*c,r+l*131)*s,o+=s,s*=.5,c*=2;return a/o}function g(e,t,n,r){return p(e,t,n,r)}function _(e,t,n,r){let i=Math.floor(e),a=Math.floor(t),o=Math.floor(n),s=e-i,c=t-a,l=n-o,u=s*s*(3-2*s),d=c*c*(3-2*c),f=l*l*(3-2*l),p=(e,t,n)=>g(i+e,a+t,o+n,r),m=p(0,0,0)+(p(1,0,0)-p(0,0,0))*u,h=p(0,1,0)+(p(1,1,0)-p(0,1,0))*u,_=p(0,0,1)+(p(1,0,1)-p(0,0,1))*u,v=p(0,1,1)+(p(1,1,1)-p(0,1,1))*u,y=m+(h-m)*d;return y+(_+(v-_)*d-y)*f}function v(e,t,n,r){let i=0,a=0,o=1,s=1;for(let c=0;c<r;c++)i+=u(e*s,t*s,n+c*131)[0]*o,a+=o,o*=.5,s*=2;return i/a}var y=class{constructor(e){this.inputs=e,this.seeds_={},this.noise_={...f};for(let[t,n]of Object.entries(e.noise??{}))n&&(this.noise_[t]=n);for(let t of Object.keys(this.noise_))this.seeds_[t]=e.seed*7919^m(t)}sample(e,t){let n={},r=(e,t)=>{let r=!1,i=0;Object.defineProperty(n,e,{enumerable:!0,configurable:!0,get:()=>(r||=(i=t(),!0),i),set:e=>{i=e,r=!0}})},i,a=()=>i===void 0?i=this.inputs.ground(e,t):i;r(`height`,()=>a()?.y??NaN),r(`up`,()=>a()?.up??1),r(`slope`,()=>1-(a()?.up??1)),r(`waterDepth`,()=>{let n=a();return n&&this.inputs.waterDepth?this.inputs.waterDepth(e,t,n.y)??-1/0:-1/0}),r(`shoreDistance`,()=>this.inputs.shoreDistance?.(e,t)??1/0);for(let[n,i]of Object.entries(this.noise_)){let a=Math.max(i.scale,1e-6),o=Math.max(1,i.octaves??3);this.inputs.space?r(n,()=>{let r=this.inputs.space(e,t);return h(r[0]/a,r[1]/a,r[2]/a,this.seeds_[n],o)}):r(n,()=>v(e/a,t/a,this.seeds_[n],o))}for(let[i,a]of Object.entries(this.inputs.fields??{}))r(i,()=>a(e,t,n));for(let r of this.inputs.overrides?.(e,t)??[]){let e=n[r.field]??r.value;n[r.field]=e+(r.value-e)*Math.min(Math.max(r.weight,0),1)}return n}};function b(e,t,n){if(e.type===`circle`)return Math.hypot(t-e.x,n-e.z)-e.radius;let r=Math.cos(-(e.yaw??0)),i=Math.sin(-(e.yaw??0)),a=t-e.x,o=n-e.z,s=Math.abs(a*r-o*i)-e.halfX,c=Math.abs(a*i+o*r)-e.halfZ;return Math.hypot(Math.max(s,0),Math.max(c,0))+Math.min(Math.max(s,c),0)}function x(e,t){if(t<=0)return 1;if(e.falloff<=0||t>=e.falloff)return 0;let n=1-t/e.falloff;return n*n*(3-2*n)}function S(e){let t=e.shape,n=(t.type===`circle`?t.radius:Math.hypot(t.halfX,t.halfZ))+Math.max(e.falloff,0);return[t.x-n,t.z-n,t.x+n,t.z+n]}var C=class{constructor(){this.zones_=new Map,this.revision=0,this.onChange=null}set(e){let t=this.zones_.get(e.id);t&&JSON.stringify(t)===JSON.stringify(e)||(this.zones_.set(e.id,e),this.revision++,t&&this.onChange?.(S(t),t),this.onChange?.(S(e),e))}delete(e){let t=this.zones_.get(e);t&&(this.zones_.delete(e),this.revision++,this.onChange?.(S(t),t))}get(e){return this.zones_.get(e)}all(){return this.zones_.values()}at(e,t,n=0){let r=[];for(let i of this.zones_.values()){let a=x(i,b(i.shape,e,t)-n);a>0&&r.push({zone:i,weight:a})}return r.sort((e,t)=>t.zone.priority-e.zone.priority||(e.zone.id<t.zone.id?-1:1))}excluding(e,t,n,r,i){for(let{zone:a,weight:o}of this.at(e,t,n))if(a.excludes.some(e=>e===`*`||r.includes(e))&&(o>=1||p(i,m(a.id),Math.floor(e*16),Math.floor(t*16))<o))return a;return null}};let w=[{normal:[1,0,0],a:[0,0,-1],b:[0,1,0]},{normal:[-1,0,0],a:[0,0,1],b:[0,1,0]},{normal:[0,1,0],a:[1,0,0],b:[0,0,-1]},{normal:[0,-1,0],a:[1,0,0],b:[0,0,1]},{normal:[0,0,1],a:[1,0,0],b:[0,1,0]},{normal:[0,0,-1],a:[-1,0,0],b:[0,1,0]}],T=Math.PI/4;function E(e,t,n,r=[0,0,0]){let i=w[e],a=Math.tan(t*T),o=Math.tan(n*T),s=i.normal[0]+a*i.a[0]+o*i.b[0],c=i.normal[1]+a*i.a[1]+o*i.b[1],l=i.normal[2]+a*i.a[2]+o*i.b[2],u=Math.hypot(s,c,l);return r[0]=s/u,r[1]=c/u,r[2]=l/u,r}function D(e,t,n){let r=Math.abs(e),i=Math.abs(t),a=Math.abs(n),o;o=r>=i&&r>=a?e>=0?0:1:i>=a?t>=0?2:3:n>=0?4:5;let s=w[o],c=e*s.normal[0]+t*s.normal[1]+n*s.normal[2],l=e*s.a[0]+t*s.a[1]+n*s.a[2],u=e*s.b[0]+t*s.b[1]+n*s.b[2];return{face:o,u:Math.atan(l/c)/T,v:Math.atan(u/c)/T}}function O(e,t,n,r){let i=w[e],a=t*i.normal[0]+n*i.normal[1]+r*i.normal[2];if(a<=1e-6)return null;let o=t*i.a[0]+n*i.a[1]+r*i.a[2],s=t*i.b[0]+n*i.b[1]+r*i.b[2];return{u:Math.atan(o/a)/T,v:Math.atan(s/a)/T}}let k=(e,t)=>2/2**(e-1-t);function A(e,t){let n=k(e,t.level);return{u0:-1+t.ix*n,v0:-1+t.iz*n,span:n}}function j(e,t,n,r){let i=w[e];for(let[e,a]of[[i.a,n],[i.b,r]]){let n=e[0]*t[0]+e[1]*t[1]+e[2]*t[2],r=e[0]-t[0]*n,i=e[1]-t[1]*n,o=e[2]-t[2]*n,s=Math.hypot(r,i,o)||1;a[0]=r/s,a[1]=i/s,a[2]=o/s}}function M(e,t){let{u0:n,v0:r,span:i}=A(e.levels,t),a=i/64,o=new Float32Array(13467),s=[0,0,0];for(let e=0;e<67;e++)for(let i=0;i<67;i++){E(t.face,n+(i-1)*a,r+(e-1)*a,s);let c=(e*67+i)*3;o[c]=s[0],o[c+1]=s[1],o[c+2]=s[2]}let c=e.provider.sample({world:e.world,seed:e.seed,version:e.version,radius:e.radius,directions:o,count:4489});return c instanceof Promise?c.then(n=>N(e,t,o,n.heights,n.paint)):N(e,t,o,c.heights,c.paint)}function N(e,t,n,r,i){let a=1/0,o=-1/0;for(let e=1;e<=65;e++)for(let t=1;t<=65;t++){let n=r[e*67+t];a=Math.min(a,n),o=Math.max(o,n)}let s=Math.max(e.maxHeight-e.minHeight,1e-6),c=new Uint8Array(17956),l=new Uint8Array(17956),u=new Uint8Array(17956),d=(t,i,a)=>{let o=Math.min(Math.max(t,0),66),s=Math.min(Math.max(i,0),66)*67+o,c=e.radius+r[s];a[0]=n[s*3]*c,a[1]=n[s*3+1]*c,a[2]=n[s*3+2]*c},f=[0,0,0],p=[0,0,0],m=[0,0,0],h=[0,0,0],g=[0,0,0],_=[0,0,0],v=e.paint?.()??null,y=v?P(v,n,i):null;for(let a=0;a<67;a++)for(let o=0;o<67;o++){let u=a*67+o,v=Math.round(Math.min(Math.max((r[u]-e.minHeight)/s,0),1)*65535);d(o-1,a,f),d(o+1,a,p),d(o,a-1,m),d(o,a+1,h);let b=[p[0]-f[0],p[1]-f[1],p[2]-f[2]],x=[h[0]-m[0],h[1]-m[1],h[2]-m[2]],S=b[1]*x[2]-b[2]*x[1],C=b[2]*x[0]-b[0]*x[2],w=b[0]*x[1]-b[1]*x[0],T=[n[u*3],n[u*3+1],n[u*3+2]],E=Math.hypot(S,C,w)||1;S/=E,C/=E,w/=E,S*T[0]+C*T[1]+w*T[2]<0&&(S=-S,C=-C,w=-w),j(t.face,T,g,_);let D=S*g[0]+C*g[1]+w*g[2],O=S*_[0]+C*_[1]+w*_[2],k=S*T[0]+C*T[1]+w*T[2];E=Math.hypot(D,k,O)||1,c[u*4]=v>>8,c[u*4+1]=v&255,c[u*4+2]=Math.round((D/E*.5+.5)*255),c[u*4+3]=Math.round((O/E*.5+.5)*255);let A=0,M=0,N=0,P=0;if(y){let e=y(o,a);A=e[0],M=e[1],N=e[2],P=e[3]}else if(i)A=i[u*4],M=i[u*4+1],N=i[u*4+2],P=i[u*4+3];else{let e=Math.min(Math.max((.9-k/E)*6,0),1);A=1-e,P=e}l[u*4]=Math.round(Math.min(Math.max(A,0),1)*255),l[u*4+1]=Math.round(Math.min(Math.max(M,0),1)*255),l[u*4+2]=Math.round(Math.min(Math.max(N,0),1)*255),l[u*4+3]=Math.round(Math.min(Math.max(P,0),1)*255)}return{heights:c,paint:l,paint2:u,min:Number.isFinite(a)?a:e.minHeight,max:Number.isFinite(o)?o:e.maxHeight}}function P(e,t,n){let r=Array(81);for(let i=0;i<9;i++)for(let a=0;a<9;a++){let o=1+a*8,s=(1+i*8)*67+o,c=n?[n[s*4],n[s*4+1],n[s*4+2],n[s*4+3]]:[1,0,0,0],l=e(t[s*3],t[s*3+1],t[s*3+2],c);r[i*9+a]=[l[0]??0,l[1]??0,l[2]??0,l[3]??0]}return(e,t)=>{let n=Math.min(Math.max((e-1)/8,0),8),i=Math.min(Math.max((t-1)/8,0),8),a=Math.min(Math.floor(n),7),o=Math.min(Math.floor(i),7),s=n-a,c=i-o,l=r[o*9+a],u=r[o*9+a+1],d=r[(o+1)*9+a],f=r[(o+1)*9+a+1],p=[0,0,0,0];for(let e=0;e<4;e++)p[e]=(l[e]*(1-s)+u[e]*s)*(1-c)+(d[e]*(1-s)+f[e]*s)*c;return p}}let F=e=>e*Math.PI/4,I=e=>F(e),L=1.5;var R=class{constructor(e,t){this.face=e,this.planet=t,this.tiles_=new Map}facts(){return this.planet()}directionAt(e,t){let n=this.facts(),r=F(n?.radius??1);return E(this.face,e/r,t/r)}planeOf(e,t,n){let r=this.facts(),i=O(this.face,e,t,n);if(!r||!i)return null;let a=F(r.radius);return{x:i.u*a,z:i.v*a}}frameAt(e,t){let n=this.directionAt(e,t),r=[0,0,0],i=[0,0,0];return j(this.face,n,r,i),{dir:n,eu:r,ev:i}}world(e,t,n){let r=this.facts(),i=this.directionAt(e,n),a=r.radius+t;return[r.centre[0]+i[0]*a,r.centre[1]+i[1]*a,r.centre[2]+i[2]*a]}tile(e,t){let n=Math.floor(e/48),r=Math.floor(t/48),i=`${n},${r}`,a=this.tiles_.get(i);if(a)return this.tiles_.delete(i),this.tiles_.set(i,a),a;let o=this.facts();if(!o?.sampleMany)return null;let s=new Float32Array(3675);for(let e=0;e<35;e++)for(let t=0;t<35;t++){let i=this.directionAt(n*48+(t-1)*L,r*48+(e-1)*L);s[(e*35+t)*3]=i[0],s[(e*35+t)*3+1]=i[1],s[(e*35+t)*3+2]=i[2]}let c=o.sampleMany(s,1225);if(!c)return null;let l={x0:n*48-L,z0:r*48-L,n:35,heights:c.heights,paint:c.paint,fields:c.fields,fieldCount:o.fieldNames.length};return this.tiles_.set(i,l),this.tiles_.size>6e3&&this.tiles_.delete(this.tiles_.keys().next().value),l}cellOf(e,t,n){let r=(t-e.x0)/L,i=(n-e.z0)/L,a=Math.min(Math.max(Math.floor(r),0),e.n-2),o=Math.min(Math.max(Math.floor(i),0),e.n-2);return{i:a,j:o,fx:Math.min(Math.max(r-a,0),1),fz:Math.min(Math.max(i-o,0),1)}}heightAt(e,t){let n=this.tile(e,t);if(!n)return null;let{i:r,j:i,fx:a,fz:o}=this.cellOf(n,e,t),s=n.n,c=n.heights,l=c[i*s+r],u=c[i*s+r+1],d=c[(i+1)*s+r],f=c[(i+1)*s+r+1];return(l+(u-l)*a)*(1-o)+(d+(f-d)*a)*o}paintAt(e,t){let n=this.tile(e,t);if(!n?.paint)return null;let{i:r,j:i,fx:a,fz:o}=this.cellOf(n,e,t),s=(i+ +(o>.5))*n.n+r+ +(a>.5);return[n.paint[s*4],n.paint[s*4+1],n.paint[s*4+2],n.paint[s*4+3]]}fieldsAt(e,t){let n=this.tile(e,t);if(!n?.fields||n.fieldCount===0)return null;let{i:r,j:i,fx:a,fz:o}=this.cellOf(n,e,t),s=n.fieldCount,c=n.n,l=[];for(let e=0;e<s;e++){let t=n.fields[(i*c+r)*s+e],u=n.fields[(i*c+r+1)*s+e],d=n.fields[((i+1)*c+r)*s+e],f=n.fields[((i+1)*c+r+1)*s+e];l.push((t+(u-t)*a)*(1-o)+(d+(f-d)*a)*o)}return l}ground(e,t){let n=this.heightAt(e,t);if(n===null)return null;let r=L,i=this.heightAt(e-r,t),a=this.heightAt(e+r,t),o=this.heightAt(e,t-r),s=this.heightAt(e,t+r);if(i===null||a===null||o===null||s===null)return{y:n,up:1,normal:[0,1,0]};let c=-(a-i)/3,l=-(s-o)/3,u=Math.hypot(c,1,l);return{y:n,up:1/u,normal:[c/u,1/u,l/u]}}worldNormal(e,t,n){let r=this.frameAt(t,n);return[e[0]*r.eu[0]+e[1]*r.dir[0]+e[2]*r.ev[0],e[0]*r.eu[1]+e[1]*r.dir[1]+e[2]*r.ev[1],e[0]*r.eu[2]+e[1]*r.dir[2]+e[2]*r.ev[2]]}environment(){return{ground:(e,t)=>this.ground(e,t),space:(e,t)=>{let n=this.facts(),r=this.directionAt(e,t);return[r[0]*n.radius,r[1]*n.radius,r[2]*n.radius]}}}zoneOnFace(e){let t=this.facts(),n=e.shape;if(!t||n.y===void 0)return null;let r=n.x-t.centre[0],i=n.y-t.centre[1],a=n.z-t.centre[2],o=Math.hypot(r,i,a);if(o<1e-9)return null;let s=this.planeOf(r/o,i/o,a/o),c=I(t.radius),l=(n.type===`circle`?n.radius:Math.hypot(n.halfX,n.halfZ))+e.falloff;if(!s||Math.abs(s.x)>c+l||Math.abs(s.z)>c+l)return null;if(n.type===`circle`)return{...e,shape:{type:`circle`,x:s.x,z:s.z,radius:n.radius}};let u=this.frameAt(s.x,s.z),d=n.facing??[Math.cos(n.yaw??0),0,Math.sin(n.yaw??0)],f=Math.atan2(d[0]*u.ev[0]+d[1]*u.ev[1]+d[2]*u.ev[2],d[0]*u.eu[0]+d[1]*u.eu[1]+d[2]*u.eu[2]);return{...e,shape:{type:`rect`,x:s.x,z:s.z,halfX:n.halfX,halfZ:n.halfZ,yaw:f}}}sourcesOnFace(e,t){let n=this.facts(),r=[];if(!n)return r;let i=I(n.radius);for(let a of e){let e=a.x-n.centre[0],o=(a.y??0)-n.centre[1],s=a.z-n.centre[2],c=Math.hypot(e,o,s);if(c<1e-9)continue;let l=this.planeOf(e/c,o/c,s/c);l&&Math.abs(l.x)<=i+t&&Math.abs(l.z)<=i+t&&r.push(l)}return r}};function z(e,t){if(!Number.isFinite(t))return 0;let n=Math.max(e.blend??0,1e-9),r=e=>{if(e<=0)return 1;if(e>=n)return 0;let t=1-e/n;return t*t*(3-2*t)};return r(e.min===void 0?-1:e.min-t)*r(e.max===void 0?-1:t-e.max)}function ee(e){if(!e||!Array.isArray(e.size)||e.size.length!==2||e.size.some(e=>!Number.isFinite(e)||e<=0))throw Error(`grounding.size: two positive model dimensions`);if(![3,5,7,9].includes(e.samples??5))throw Error(`grounding.samples: 3, 5, 7 or 9`);if(![`highest`,`lowest`,`mean`,`center`].includes(e.mode??`highest`))throw Error(`grounding.mode: highest, lowest, mean or center`);if(e.maxRelief!==void 0&&(!Number.isFinite(e.maxRelief)||e.maxRelief<0))throw Error(`grounding.maxRelief: a nonnegative world distance`);if(e.offset!==void 0&&!Number.isFinite(e.offset))throw Error(`grounding.offset: a finite model distance`)}function te(e,t,n,r,i,a,o={}){if(ee(a),![t,n,r,i].every(Number.isFinite)||i<=0)throw Error(`grounding transform: finite position, yaw and positive scale`);let s=a.samples??5,c=Math.cos(r),l=Math.sin(r),u=1/0,d=-1/0,f=0,p=0;for(let r=0;r<s;r++)for(let m=0;m<s;m++){let h=(m/(s-1)-.5)*a.size[0]*i,g=(r/(s-1)-.5)*a.size[1]*i,_=t+h*c+g*l,v=n-h*l+g*c,y=e.ground(_,v);if(!y||!Number.isFinite(y.y)||!Number.isFinite(y.up))return{ok:!1,reason:`noGround`};if(y.up<(o.minUp??0))return{ok:!1,reason:`slope`};let b=e.waterDepth?.(_,v,y.y)??0;if(!Number.isFinite(b))return{ok:!1,reason:`noGround`};if(b>(o.waterDepth??0))return{ok:!1,reason:`water`};u=Math.min(u,y.y),d=Math.max(d,y.y),f+=y.y,m===(s-1)/2&&r===(s-1)/2&&(p=y.y)}let m=d-u,h=f/(s*s);if(m>(a.maxRelief??1/0))return{ok:!1,reason:`relief`};let g={highest:d,lowest:u,mean:h,center:p}[a.mode??`highest`]+(a.offset??0)*i;return{ok:!0,fit:{y:g,min:u,max:d,mean:h,relief:m,supportDepth:Math.max(0,g-u),buriedDepth:Math.max(0,d-g),samples:s*s}}}let B=4e4;function V(e){let t=H(e.anchor,e.anchor.scale?.[1]??1);for(let n of e.members??[])t=Math.max(t,(n.ring?.[1]??0)+H(n,n.scale?.[1]??1));return t}function H(e,t){return Math.max(e.footprint*(e.scaleFootprint?Math.abs(t):1),e.grounding?Math.hypot(...e.grounding.size)*Math.abs(t)/2:0)}let U=(e,t,n)=>e?e[0]+(e[1]-e[0])*t:n;var W=class{constructor(e,t,n,r,i){this.rules=e,this.env=t,this.zones=n,this.seed=r,this.world=i,this.recipes_=new Map,this.layers_=[],this.viable_=new Map,this.groups_=new Map,this.worldHash_=m(i)^r;for(let t of e.recipes)this.recipes_.set(t.id,t);for(let t of e.layers){let n=new Set;for(let r of e.biomes)for(let e of r.recipes)e.layer===t.id&&n.add(e.recipe);let r=0;for(let e of n){let t=this.recipes_.get(e);t&&(r=Math.max(r,V(t)))}this.layers_.push({def:t,hash:m(t.id),maxRadius:r,recipes:n})}}invalidate(){this.viable_.clear(),this.groups_.clear()}layerIndex(e){return this.layers_.findIndex(t=>t.def.id===e)}biomeWeights(e,t){let n=[],r=0;for(let i of this.rules.biomes){let a=this.biomeWeight(i,e,t);a>0&&(n.push({biome:i.id,weight:a}),r+=a)}for(let{zone:i,weight:a}of this.zones.at(e,t)){if(!i.biome)continue;for(let e of n)e.weight*=1-a;r=r*(1-a)+a;let e=n.find(e=>e.biome===i.biome);e?e.weight+=a:n.push({biome:i.biome,weight:a});break}if(r<=0)return[];for(let e of n)e.weight/=r;return n.filter(e=>e.weight>0).sort((e,t)=>t.weight-e.weight||(e.biome<t.biome?-1:1))}biomeAt(e,t){return this.biomeWeights(e,t)[0]?.biome??null}paint(e,t,n){let r=n.length,i=this.biomeWeights(e,t);for(let{biome:e}of i)r=Math.max(r,this.rules.biomes.find(t=>t.id===e)?.paint?.length??0);let a=Array.from({length:r},(e,t)=>n[t]??0);for(let{biome:e,weight:t}of i){let i=this.rules.biomes.find(t=>t.id===e);if(!i?.paint)continue;let o=t*Math.min(Math.max(i.paintStrength??1,0),1);for(let e=0;e<r;e++)a[e]=a[e]+((i.paint[e]??0)-(n[e]??0))*o}let o=a.reduce((e,t)=>e+t,0)||1;return a.map(e=>e/o)}groupsIn(e,t,n,r,i){let a=this.layerIndex(e);if(a<0)return[];let o=this.layers_[a].def.spacing,s=[];for(let e=Math.floor(n/o);e<=Math.floor(i/o);e++)for(let c=Math.floor(t/o);c<=Math.floor(r/o);c++){let o=this.group(a,c,e);typeof o!=`string`&&o.x>=t&&o.x<r&&o.z>=n&&o.z<i&&s.push(o)}return s}placementsIn(e,t,n,r,i){let a=[];for(let o of this.layers_)if(!(i&&!i.includes(o.def.id)))for(let i of this.groupsIn(o.def.id,e,t,n,r))a.push(i.anchor,...i.members);return a}stats(e,t,n,r,i){let a={placed:0,noBiome:0,density:0,noGround:0,slope:0,water:0,relief:0,zone:0,occupied:0,conflict:0},o=this.layerIndex(e);if(o<0)return a;let s=this.layers_[o].def.spacing;for(let e=Math.floor(n/s);e<Math.ceil(i/s);e++)for(let n=Math.floor(t/s);n<Math.ceil(r/s);n++){let t=this.group(o,n,e);typeof t==`string`?a[t]++:a.placed++}return a}explain(e,t){let n=this.layers_.map((n,r)=>{let i=Math.floor(e/n.def.spacing),a=Math.floor(t/n.def.spacing),o=this.group(r,i,a),s=this.viable(r,i,a);return{layer:n.def.id,cell:[i,a],group:typeof o==`string`?null:o.id,rejected:typeof o==`string`?o:null,detail:s.ok?void 0:s.detail}});return{fields:this.env.sample(e,t),biomes:this.biomeWeights(e,t),zones:this.zones.at(e,t).map(({zone:e,weight:t})=>({id:e.id,kind:e.kind,weight:t})),layers:n}}group(e,t,n){let r=`${e}:${t},${n}`,i=this.groups_.get(r);if(i!==void 0)return i;this.groups_.size>B&&this.groups_.clear();let a=this.makeGroup(e,t,n);return this.groups_.set(r,a),a}makeGroup(e,t,n){let r=this.viable(e,t,n);if(!r.ok)return r.reason;let i=r.candidate,a=this.layers_[e],o=a.def.spacing,s=Math.ceil((i.radius+a.maxRadius)/o);for(let r=-s;r<=s;r++)for(let a=-s;a<=s;a++){if(a===0&&r===0)continue;let o=this.viable(e,t+a,n+r);if(!o.ok)continue;let s=o.candidate;if((s.priority>i.priority||s.priority===i.priority&&(s.gz<n||s.gz===n&&s.gx<t))&&Math.hypot(s.x-i.x,s.z-i.z)<i.radius+s.radius)return`conflict`}let c=`${a.def.id}@${a.def.version??1}:${t},${n}`,l=i.recipe,u=i.anchor,d=[],f=[u];for(let[r,o]of(l.members??[]).entries()){let s=(e,i)=>p(this.worldHash_,a.hash,t,n,1e3+r*37+e,i),u=o.count?o.count[0]+Math.floor(s(0,0)*(o.count[1]-o.count[0]+1)):1;for(let t=0;t<u;t++){if(o.chance!==void 0&&s(1,t)>=o.chance)continue;let n=U(o.arc,s(2,t),s(2,t)*360)*Math.PI/180,r=U(o.ring,s(3,t),0),u=i.x+Math.cos(n)*r,p=i.z+Math.sin(n)*r,m=this.env.sample(u,p),h=this.place(c,a.def,l,o,t,u,p,i.biome,m,s(4,t));typeof h!=`string`&&this.zones.excluding(u,p,h.footprint,this.tagsOf(a.def,l,o),this.seed)===null&&this.occupied(e,u,p,h.footprint)===null&&(f.some(e=>Math.hypot(e.x-u,e.z-p)<e.footprint+h.footprint)||(d.push(h),f.push(h)))}}return{id:c,layer:a.def.id,x:i.x,z:i.z,radius:i.radius,priority:i.priority,anchor:u,members:d}}place(e,t,n,r,i,a,o,s,c,l){let u=this.standing(c,r);if(u)return u;let d=p(this.worldHash_,m(e),m(r.id),i,7),f=(l||d)*Math.PI*2,h=U(r.scale,p(this.worldHash_,m(e),i,11),1),g;if(r.grounding){let e=te(this.env.inputs,a,o,f,h,r.grounding,r);if(!e.ok)return e.reason;g=e.fit}let _=this.env.inputs.ground(a,o),v=_?.up??1,y=_?.normal??[0,v,Math.sqrt(Math.max(0,1-v*v))];return{id:`${e}/${n.id}@${n.version}/${r.id}.${i}`,group:e,layer:t.id,recipe:n.id,recipeVersion:n.version,member:r.id,biome:s,zone:this.zones.at(a,o)[0]?.zone.id??null,x:a,y:g?.y??c.height,z:o,yaw:f,scale:h,normal:y,attach:r.attach??`upright`,mesh:typeof r.mesh==`number`?r.mesh:0,material:typeof r.material==`number`?r.material:0,plant:r.plant??null,interactive:r.interactive??null,footprint:H(r,h),canopy:(r.canopy??r.footprint)*(r.scaleFootprint?Math.abs(h):1),far:r.far??null,...g?{grounding:g}:{}}}standing(e,t){return Number.isFinite(e.height)?e.up<(t.minUp??0)?`slope`:e.waterDepth>(t.waterDepth??0)?`water`:null:`noGround`}tagsOf(e,t,n){return[e.id,t.id,n.interactive?`interactive`:`decor`,...t.tags??[],...n.tags??[]]}viable(e,t,n){let r=`${e}:${t},${n}`,i=this.viable_.get(r);if(i)return i;this.viable_.size>B&&this.viable_.clear();let a=this.makeViable(e,t,n);return this.viable_.set(r,a),a}makeViable(e,t,n){let r=this.layers_[e],i=r.def.spacing,a=e=>p(this.worldHash_,r.hash,t,n,e),o=(t+a(1))*i,s=(n+a(2))*i,c=this.biomeWeights(o,s);if(c.length===0)return{ok:!1,reason:`noBiome`};let l=a(3),u=c[c.length-1].biome;for(let e of c){if(l<e.weight){u=e.biome;break}l-=e.weight}let d=(this.rules.biomes.find(e=>e.id===u)?.recipes??[]).filter(e=>e.layer===r.def.id&&this.recipes_.has(e.recipe)),f=a(4),m=null;for(let e of d){if(f<e.density){m=this.recipes_.get(e.recipe);break}f-=e.density}if(!m)return{ok:!1,reason:`density`};let h=this.env.sample(o,s),g=`${r.def.id}@${r.def.version??1}:${t},${n}`,_=this.place(g,r.def,m,m.anchor,0,o,s,u,h,0);if(typeof _==`string`)return{ok:!1,reason:_};let v=this.zones.excluding(o,s,_.footprint,this.tagsOf(r.def,m,m.anchor),this.seed);if(v)return{ok:!1,reason:`zone`,detail:v.id};let y=this.occupied(e,o,s,_.footprint);return y?{ok:!1,reason:`occupied`,detail:y}:{ok:!0,candidate:{gx:t,gz:n,x:o,z:s,priority:a(5),biome:u,recipe:m,radius:V(m),anchor:_}}}occupied(e,t,n,r){for(let i=0;i<e;i++){let e=this.layers_[i];if(e.def.occupies===!1)continue;let a=e.def.spacing,o=r+e.maxRadius;for(let e=Math.floor((n-o)/a);e<=Math.floor((n+o)/a);e++)for(let s=Math.floor((t-o)/a);s<=Math.floor((t+o)/a);s++){let a=this.group(i,s,e);if(typeof a!=`string`){for(let e of[a.anchor,...a.members])if(Math.hypot(e.x-t,e.z-n)<e.footprint+r)return e.id}}}return null}biomeWeight(e,t,n){let r=e.transition??0,i=t,a=n;if(r>0){let o=m(e.id)^this.worldHash_;i+=(v(t/r,n/r,o,2)-.5)*2*r,a+=(v(t/r,n/r,o+1,2)-.5)*2*r}let o=this.env.sample(i,a),s=e.weight??1;for(let t of e.conditions)if(s*=z(t,o[t.field]??NaN),s<=0)return 0;return s}};function G(e){return e.layers.some(e=>(e.farSpacing??1)>1)?{...e,layers:e.layers.map(e=>(e.farSpacing??1)>1?{...e,spacing:e.spacing*e.farSpacing}:e)}:null}function K(e,t){let n={};t.layers.forEach((t,r)=>{n[`paint.${t}`]=(t,n)=>e.paintAt(t,n)?.[r]??0}),t.fieldNames.forEach((t,r)=>{n[t]=(t,n)=>e.fieldsAt(t,n)?.[r]??0});let r=new y({seed:t.seed,noise:t.rules.noise,fields:{...n,...t.rules.fields},...e.environment(),waterDepth:(e,n,r)=>t.seaLevel-r,overrides:(e,n)=>{let r=[];for(let{zone:i,weight:a}of t.zones.at(e,n))for(let[e,t]of Object.entries(i.fields??{}))r.push({field:e,value:t,weight:a});return r}}),i=`${t.world}#${e.face}`;return{plan:new W(t.rules,r,t.zones,t.seed,i),farPlan:t.farRules?new W(t.farRules,r,t.zones,t.seed,i):null}}function ne(e){let t={};e.ground&&e.layers.forEach((n,r)=>{t[`paint.${n}`]=(t,n)=>e.ground.paintAt(t,n)?.[r]??0});let n=new y({seed:e.seed,noise:e.rules.noise,fields:{...t,...e.rules.fields},ground:(t,n)=>{if(e.ground){let r=e.ground.heightAt(t,n);if(r===null)return null;let i=e.ground.normalAt(t,n)??[0,1,0];return{y:r,up:i[1],normal:i}}return{y:e.flatY,up:1,normal:[0,1,0]}},waterDepth:(t,n,r)=>e.water?.depthAt(t,n,r)??null,shoreDistance:(t,n)=>e.water?.shoreAt(t,n)??null,overrides:(t,n)=>{let r=[];for(let{zone:i,weight:a}of e.zones.at(t,n))for(let[e,t]of Object.entries(i.fields??{}))r.push({field:e,value:t,weight:a});return r}});return{plan:new W(e.rules,n,e.zones,e.seed,e.world),farPlan:e.farRules?new W(e.farRules,n,e.zones,e.seed,e.world):null}}var re=class{constructor(e,t){this.source=e,this.cell=t}node(e,t){let n=e*this.cell,r=t*this.cell,i=this.source.bounds;return i&&(n=Math.min(Math.max(n,i[0]),i[2]),r=Math.min(Math.max(r,i[1]),i[3])),this.source.height(n,r)}covers(e,t){let n=this.source.bounds;return!n||e>=n[0]&&e<=n[2]&&t>=n[1]&&t<=n[3]}height(e,t){let n=this.corners(e,t);if(!n)return null;let[r,i,a,o,s,c]=n;return s+c<=1?r+(i-r)*s+(a-r)*c:o+(a-o)*(1-s)+(i-o)*(1-c)}normal(e,t){let n=this.corners(e,t);if(!n)return null;let[r,i,a,o,s,c]=n,l=(s+c<=1?i-r:o-a)/this.cell,u=(s+c<=1?a-r:o-i)/this.cell,d=Math.hypot(l,1,u);return[-l/d,1/d,-u/d]}tile(e,t){let n=new Float32Array(3267);for(let r=0;r<=32;r++)for(let i=0;i<=32;i++){let a=this.node(e*32+i,t*32+r);if(a===null)return null;let o=(r*33+i)*3;n[o]=i*this.cell,n[o+1]=a,n[o+2]=r*this.cell}let r=new Uint32Array(6144),i=0;for(let e=0;e<32;e++)for(let t=0;t<32;t++){let n=e*33+t,a=n+1,o=n+33,s=o+1;r.set([n,o,a,a,o,s],i),i+=6}return{x0:e*32*this.cell,z0:t*32*this.cell,positions:n,indices:r}}raycast(e,t,n,r,i,a,o){let s=Math.hypot(r,i,a);if(s<=0)return null;r/=s,i/=s,a/=s;let c=this.cell,l=Math.floor(e/c),u=Math.floor(n/c),d=r>0?1:-1,f=a>0?1:-1,p=r===0?1/0:Math.abs(c/r),m=a===0?1/0:Math.abs(c/a),h=r===0?1/0:((r>0?(l+1)*c:l*c)-e)/r,g=a===0?1/0:((a>0?(u+1)*c:u*c)-n)/a,_=0;for(let s=0;s<1e6&&_<=o;s++){let s=this.node(l,u),v=this.node(l+1,u),y=this.node(l,u+1),b=this.node(l+1,u+1);if(s===null||v===null||y===null||b===null)return null;let x=l*c,S=u*c;for(let l of[[[x,s,S],[x,y,S+c],[x+c,v,S]],[[x+c,v,S],[x,y,S+c],[x+c,b,S+c]]]){let s=ie(e,t,n,r,i,a,l[0],l[1],l[2]);if(s&&s.t<=o&&this.covers(e+r*s.t,n+a*s.t))return{distance:s.t,point:[e+r*s.t,t+i*s.t,n+a*s.t],normal:s.n}}if(h<g?(_=h,h+=p,l+=d):(_=g,g+=m,u+=f),r===0&&a===0)break}return null}corners(e,t){if(!this.covers(e,t))return null;let n=e/this.cell,r=t/this.cell,i=Math.floor(n),a=Math.floor(r),o=this.node(i,a),s=this.node(i+1,a),c=this.node(i,a+1),l=this.node(i+1,a+1);return o===null||s===null||c===null||l===null?null:[o,s,c,l,n-i,r-a]}};function ie(e,t,n,r,i,a,o,s,c){let l=s[0]-o[0],u=s[1]-o[1],d=s[2]-o[2],f=c[0]-o[0],p=c[1]-o[1],m=c[2]-o[2],h=i*m-a*p,g=a*f-r*m,_=r*p-i*f,v=l*h+u*g+d*_;if(Math.abs(v)<1e-12)return null;let y=1/v,b=e-o[0],x=t-o[1],S=n-o[2],C=(b*h+x*g+S*_)*y;if(C<-1e-9||C>1+1e-9)return null;let w=x*d-S*u,T=S*l-b*d,E=b*u-x*l,D=(r*w+i*T+a*E)*y;if(D<-1e-9||C+D>1+1e-9)return null;let O=(f*w+p*T+m*E)*y;if(O<0)return null;let k=u*m-d*p,A=d*f-l*m,j=l*p-u*f;A<0&&(k=-k,A=-A,j=-j);let M=Math.hypot(k,A,j)||1;return{t:O,n:[k/M,A/M,j/M]}}function ae(e,t,n,r){let i=e.height(n-t.x,r-t.z);return i===null?null:t.y+i}function oe(e,t,n,r){return e.normal(n-t.x,r-t.z)}function se(e,t,n,r,i){let a=r-n.x,o=i-n.z,s=t.height(a,o),c=t.normal(a,o);return s===null||!c?null:e.paint(a,o,s,c[1])}var ce=class{constructor(e){this.source_=e.source.kind===`field`?a.fromData(e.source.data):o.fromData(e.source.data),this.surface_=new re(this.source_,e.cell),this.origin_=e.origin}heightAt(e,t){return ae(this.surface_,this.origin_,e,t)}normalAt(e,t){return oe(this.surface_,this.origin_,e,t)}paintAt(e,t){return se(this.source_,this.surface_,this.origin_,e,t)}},le=class{constructor(e){this.data=e}lerp(e,t){let{minX:n,minZ:r,sizeX:i,sizeZ:a,nx:o,nz:s}=this.data.grid;if(o<2||s<2)return null;let c=(e-n)/i,l=(t-r)/a;if(c<0||c>1||l<0||l>1)return null;let u=c*(o-1),d=l*(s-1),f=Math.min(Math.floor(u),o-2),p=Math.min(Math.floor(d),s-2),m=u-f,h=d-p,g=p*o+f,_=e=>(e[g]*(1-m)+e[g+1]*m)*(1-h)+(e[g+o]*(1-m)+e[g+o+1]*m)*h;return{height:_(this.data.height),shore:_(this.data.shore)}}depthAt(e,t,n){let r=this.lerp(e,t);return r?r.shore>0?r.height-n:null:this.data.ocean?this.data.ocean.level-n:null}shoreAt(e,t){let n=this.lerp(e,t);return n?-n.shore:this.data.ocean?-1e6:null}};let q=new Map,J=new Map,Y=e=>{let t=URL.createObjectURL(new Blob([e],{type:`text/javascript`}));return import(t).then(e=>e.default).finally(()=>URL.revokeObjectURL(t))};function X(e,t){let n=J.get(e);return n||(n=t(e),J.set(e,n)),n}function ue(e){let t=new C;for(let n of e.zones)t.set(n);return{face:null,...ne({rules:e.rules,farRules:G(e.rules),seed:e.seed,world:e.world,zones:t,ground:e.ground?new ce(e.ground):null,flatY:e.flatY,water:e.water?new le(e.water):null,layers:e.layers})}}async function de(e,t){let n=await X(e.provider.source,t),r={centre:e.centre,radius:e.radius,gravity:0,height:null,paint:null,layers:e.layers,fieldNames:e.fieldNames,fieldsAt:null,sampleMany:(t,r)=>{let i=n.sample({world:e.provider.world,seed:e.provider.seed,version:e.provider.version,radius:e.radius,directions:t,count:r});if(i instanceof Promise)throw Error(`a provider used in a worker must answer at once`);return i}},i=new R(e.face,()=>r),a=new C;for(let t of e.zones)a.set(t);return{face:i,...K(i,{rules:e.rules,farRules:G(e.rules),seed:e.seed,world:e.world,seaLevel:e.seaLevel,layers:e.layers,fieldNames:e.fieldNames,zones:a})}}async function Z(e,t,n){let r=q.get(e);if(!r){if(!t)throw Error(`the plan ${e} is not known to this worker`);r=`plane`in t?ue(t):await de(t,n),q.set(e,r),q.size>24&&q.delete(q.keys().next().value)}return r}async function Q(e,t=Y){let n=await Z(e.key,e.spec,t);return(e.far&&n.farPlan?n.farPlan:n.plan).placementsIn(e.x0,e.z0,e.x1,e.z1,[e.layer])}async function $(e,t=Y){let n=await X(e.provider.source,t),r=null;if(e.paintKeys){let n=e.paintKeys,i=await Promise.all(n.map((n,r)=>Z(n,e.specs[r],t)));r=(e,t,n,r)=>{let a=i[D(e,t,n).face],o=a.face.planeOf(e,t,n);return o?a.plan.paint(o.x,o.z,r):r}}let i=await M({provider:n,world:e.provider.world,seed:e.provider.seed,version:e.provider.version,radius:e.radius,levels:e.levels,minHeight:e.minHeight,maxHeight:e.maxHeight,...r?{paint:()=>r}:{}},e.node);return{result:i,transfer:[i.heights.buffer,i.paint.buffer,i.paint2.buffer]}}return typeof self<`u`&&typeof self.importScripts==`function`&&(self.onmessage=e=>{let t=e.data,n=e=>self.postMessage({id:t.id,error:e instanceof Error?e.message:String(e)});t.type===`page`?$(t).then(e=>self.postMessage({id:t.id,result:e.result},e.transfer),n):Q(t).then(e=>self.postMessage({id:t.id,result:e}),n)}),e.page=$,e.placements=Q,e})({});";diff --git a/sdk/src/worldgen/grounding.ts b/sdk/src/worldgen/grounding.tsnew file mode 100644index 000000000..2c0585efa--- /dev/null+++ b/sdk/src/worldgen/grounding.ts@@ -0,0 +1,76 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import type { EnvironmentInputs } from './fields';++/** Fit an upright building's base to a grid over its entire rotated footprint. */+export interface GroundingOptions {+ /** Width and depth in model units, centred on the model's origin. */+ size: readonly [number, number];+ /** Odd grid side, including corners, edges and centre (3, 5, 7 or 9; default 5). */+ samples?: number;+ /** Base elevation before offset; highest avoids embedding the base (default). */+ mode?: 'highest' | 'lowest' | 'mean' | 'center';+ /** Reject sites with more height variation than this, in world units. */+ maxRelief?: number;+ /** Vertical offset in model units, scaled with the model. */+ offset?: number;+}++/** Measurements a foundation builder or a placement diagnostic can use. */+export interface GroundFit {+ y: number;+ min: number;+ max: number;+ mean: number;+ relief: number;+ /** Distance from the base to the lowest sampled ground, in world units. */+ supportDepth: number;+ /** Distance from the base to the highest sampled ground, in world units. */+ buriedDepth: number;+ samples: number;+}++export type GroundFitResult = { ok: true; fit: GroundFit } | { ok: false; reason: 'noGround' | 'slope' | 'water' | 'relief' };++/** Shared by file validation and direct callers; bad grids must never cause unbounded sampling. */+export function validateGrounding(options: GroundingOptions): void {+ if (!options || !Array.isArray(options.size) || options.size.length !== 2+ || options.size.some((v) => !Number.isFinite(v) || v <= 0)) throw new Error('grounding.size: two positive model dimensions');+ if (![3, 5, 7, 9].includes(options.samples ?? 5)) throw new Error('grounding.samples: 3, 5, 7 or 9');+ if (!['highest', 'lowest', 'mean', 'center'].includes(options.mode ?? 'highest')) throw new Error('grounding.mode: highest, lowest, mean or center');+ if (options.maxRelief !== undefined && (!Number.isFinite(options.maxRelief) || options.maxRelief < 0)) throw new Error('grounding.maxRelief: a nonnegative world distance');+ if (options.offset !== undefined && !Number.isFinite(options.offset)) throw new Error('grounding.offset: a finite model distance');+}++/**+ * Samples the same ground used by the plan, without changing it. Positive yaw follows the engine's +Y quaternion rotation.+ * A supported site is a finite grid test, not a proof about features smaller than its sample spacing. Use maxRelief no greater+ * than the model's foundation depth, or level the accepted site with a WorldZone before placing an authored building.+ */+export function fitGroundFootprint(+ inputs: Pick<EnvironmentInputs, 'ground' | 'waterDepth'>, x: number, z: number, yaw: number, scale: number,+ options: GroundingOptions, limits: { minUp?: number; waterDepth?: number } = {},+): GroundFitResult {+ validateGrounding(options);+ if (![x, z, yaw, scale].every(Number.isFinite) || scale <= 0) throw new Error('grounding transform: finite position, yaw and positive scale');+ const n = options.samples ?? 5, c = Math.cos(yaw), s = Math.sin(yaw);+ let min = Infinity, max = -Infinity, sum = 0, center = 0;+ for (let iz = 0; iz < n; iz++) for (let ix = 0; ix < n; ix++) {+ const lx = (ix / (n - 1) - 0.5) * options.size[0] * scale;+ const lz = (iz / (n - 1) - 0.5) * options.size[1] * scale;+ const wx = x + lx * c + lz * s, wz = z - lx * s + lz * c;+ const g = inputs.ground(wx, wz);+ if (!g || !Number.isFinite(g.y) || !Number.isFinite(g.up)) return { ok: false, reason: 'noGround' };+ if (g.up < (limits.minUp ?? 0)) return { ok: false, reason: 'slope' };+ const water = inputs.waterDepth?.(wx, wz, g.y) ?? 0;+ if (!Number.isFinite(water)) return { ok: false, reason: 'noGround' };+ if (water > (limits.waterDepth ?? 0)) return { ok: false, reason: 'water' };+ min = Math.min(min, g.y); max = Math.max(max, g.y); sum += g.y;+ if (ix === (n - 1) / 2 && iz === (n - 1) / 2) center = g.y;+ }+ const relief = max - min, mean = sum / (n * n);+ if (relief > (options.maxRelief ?? Infinity)) return { ok: false, reason: 'relief' };+ const levels = { highest: max, lowest: min, mean, center };+ const y = levels[options.mode ?? 'highest'] + (options.offset ?? 0) * scale;+ return { ok: true, fit: { y, min, max, mean, relief, supportDepth: Math.max(0, y - min), buriedDepth: Math.max(0, max - y), samples: n * n } };+}diff --git a/sdk/src/worldgen/index.ts b/sdk/src/worldgen/index.tsindex ace020e58..343f9330b 100644--- a/sdk/src/worldgen/index.ts+++ b/sdk/src/worldgen/index.ts@@ -11,6 +11,8 @@ 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 { fitGroundFootprint, validateGrounding, type GroundingOptions, type GroundFit, type GroundFitResult } from './grounding';+export { roadZones, setRoad, removeRoad, type RoadOptions } from './roads';export { createWorld2D, world2dChunk, placement2D, streamingPoints2D, type World2D, type World2DOptions, type World2DChunk, type Placement2D } from './world2d';export { PlacementDiffs, type PlacementChange, type PlacementDiffsData } from './diffs';export {diff --git a/sdk/src/worldgen/plan.ts b/sdk/src/worldgen/plan.tsindex a1a1888e7..0a72a1db4 100644--- a/sdk/src/worldgen/plan.ts+++ b/sdk/src/worldgen/plan.ts@@ -21,6 +21,7 @@import { Environment, fbm, hash01, hashString, type FieldValues } from './fields';import { bandWeight, type BiomeDef, type PlacementLayer, type Recipe, type RecipeMember, type WorldRules } from './rules';import type { Zones } from './zones';+import { fitGroundFootprint, type GroundFit } from './grounding';/** One thing placed. */export interface Placement {@@ -52,12 +53,14 @@ export interface Placement {interactive: string | null;footprint: number;canopy: number;+ /** Full-footprint measurements when the recipe asks for ground fitting. */+ grounding?: GroundFit;/** 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. */-export type Rejection = 'noBiome' | 'density' | 'noGround' | 'slope' | 'water' | 'zone' | 'occupied' | 'conflict';+export type Rejection = 'noBiome' | 'density' | 'noGround' | 'slope' | 'water' | 'relief' | 'zone' | 'occupied' | 'conflict';export interface Group {id: string;@@ -80,7 +83,7 @@ interface Candidate {biome: string;recipe: Recipe;radius: number;- fields: FieldValues;+ anchor: Placement;}type Viable = { ok: true; candidate: Candidate } | { ok: false; reason: Rejection; detail?: string };@@ -89,11 +92,17 @@ type Viable = { ok: true; candidate: Candidate } | { ok: false; reason: Rejectioconst CACHE_LIMIT = 40000;function groupRadius(recipe: Recipe): number {- let r = recipe.anchor.footprint;- for (const m of recipe.members ?? []) r = Math.max(r, (m.ring?.[1] ?? 0) + m.footprint);+ let r = footprintOf(recipe.anchor, recipe.anchor.scale?.[1] ?? 1);+ for (const m of recipe.members ?? []) r = Math.max(r, (m.ring?.[1] ?? 0) + footprintOf(m, m.scale?.[1] ?? 1));return r;}+/** A fitted base cannot reach beyond its reservation, even if the authored radius is smaller. */+function footprintOf(m: RecipeMember, scale: number): number {+ return Math.max(m.footprint * (m.scaleFootprint ? Math.abs(scale) : 1),+ m.grounding ? Math.hypot(...m.grounding.size) * Math.abs(scale) / 2 : 0);+}+const lerp = (range: readonly [number, number] | undefined, t: number, fallback: number): number =>range ? range[0] + (range[1] - range[0]) * t : fallback;@@ -197,7 +206,7 @@ export class WorldPlan {/** How many candidates of a layer in the square stood, and why the rest did not. */stats(layer: string, x0: number, z0: number, x1: number, z1: number): Record<'placed' | Rejection, number> {- const counts = { placed: 0, noBiome: 0, density: 0, noGround: 0, slope: 0, water: 0, zone: 0, occupied: 0, conflict: 0 };+ const counts = { placed: 0, noBiome: 0, density: 0, noGround: 0, slope: 0, water: 0, relief: 0, zone: 0, occupied: 0, conflict: 0 };const li = this.layerIndex(layer);if (li < 0) return counts;const s = this.layers_[li]!.def.spacing;@@ -257,7 +266,7 @@ export class WorldPlan {}const groupId = `${layer.def.id}@${layer.def.version ?? 1}:${gx},${gz}`;const r = c.recipe;- const anchor = this.place(groupId, layer.def, r, r.anchor, 0, c.x, c.z, c.biome, c.fields, 0)!;+ const anchor = c.anchor;const members: Placement[] = [];const taken: Placement[] = [anchor];for (const [mi, m] of (r.members ?? []).entries()) {@@ -269,12 +278,11 @@ export class WorldPlan {const dist = lerp(m.ring, h(3, k), 0);const x = c.x + Math.cos(angle) * dist, z = c.z + Math.sin(angle) * dist;const f = this.env.sample(x, z);- if (this.standing(f, m) !== null) continue;- if (this.zones.excluding(x, z, m.footprint, this.tagsOf(layer.def, r, m), this.seed) !== null) continue;- if (this.occupied(li, x, z, m.footprint) !== null) continue;- if (taken.some((t) => Math.hypot(t.x - x, t.z - z) < t.footprint + m.footprint)) continue;const p = this.place(groupId, layer.def, r, m, k, x, z, c.biome, f, h(4, k));- if (!p) continue;+ if (typeof p === 'string') continue;+ if (this.zones.excluding(x, z, p.footprint, this.tagsOf(layer.def, r, m), this.seed) !== null) continue;+ if (this.occupied(li, x, z, p.footprint) !== null) continue;+ if (taken.some((t) => Math.hypot(t.x - x, t.z - z) < t.footprint + p.footprint)) continue;members.push(p);taken.push(p);}@@ -283,19 +291,28 @@ export class WorldPlan {}private place(group: string, layer: PlacementLayer, r: Recipe, m: RecipeMember, k: number, x: number, z: number,- biome: string, f: FieldValues, turn: number): Placement | null {- if (!Number.isFinite(f.height!)) return null;+ biome: string, f: FieldValues, turn: number): Placement | Rejection {+ const why = this.standing(f, m);+ if (why) return why;const h = hash01(this.worldHash_, hashString(group), hashString(m.id), k, 7);+ const yaw = (turn || h) * Math.PI * 2, scale = lerp(m.scale, hash01(this.worldHash_, hashString(group), k, 11), 1);+ let grounding: GroundFit | undefined;+ if (m.grounding) {+ const result = fitGroundFootprint(this.env.inputs, x, z, yaw, scale, m.grounding, m);+ if (!result.ok) return result.reason;+ grounding = result.fit;+ }const g = this.env.inputs.ground(x, z);const up = g?.up ?? 1;const n = g?.normal ?? [0, up, Math.sqrt(Math.max(0, 1 - up * up))];return {id: `${group}/${r.id}@${r.version}/${m.id}.${k}`, group, layer: layer.id, recipe: r.id, recipeVersion: r.version, member: m.id,biome, zone: this.zones.at(x, z)[0]?.zone.id ?? null,- x, y: f.height!, z, yaw: (turn || h) * Math.PI * 2, scale: lerp(m.scale, hash01(this.worldHash_, hashString(group), k, 11), 1),+ x, y: grounding?.y ?? f.height!, z, yaw, scale,normal: n, attach: m.attach ?? 'upright', mesh: typeof m.mesh === 'number' ? m.mesh : 0,material: typeof m.material === 'number' ? m.material : 0, plant: m.plant ?? null, interactive: m.interactive ?? null,- footprint: m.footprint, canopy: m.canopy ?? m.footprint, far: m.far ?? null,+ footprint: footprintOf(m, scale), canopy: (m.canopy ?? m.footprint) * (m.scaleFootprint ? Math.abs(scale) : 1), far: m.far ?? null,+ ...(grounding ? { grounding } : {}),};}@@ -338,13 +355,14 @@ export class WorldPlan {for (const br of choices) { if (v < br.density) { recipe = this.recipes_.get(br.recipe)!; break; } v -= br.density; }if (!recipe) return { ok: false, reason: 'density' };const f = this.env.sample(x, z);- const why = this.standing(f, recipe.anchor);- if (why) return { ok: false, reason: why };- const zone = this.zones.excluding(x, z, recipe.anchor.footprint, this.tagsOf(layer.def, recipe, recipe.anchor), this.seed);+ const groupId = `${layer.def.id}@${layer.def.version ?? 1}:${gx},${gz}`;+ const anchor = this.place(groupId, layer.def, recipe, recipe.anchor, 0, x, z, biome, f, 0);+ if (typeof anchor === 'string') return { ok: false, reason: anchor };+ const zone = this.zones.excluding(x, z, anchor.footprint, this.tagsOf(layer.def, recipe, recipe.anchor), this.seed);if (zone) return { ok: false, reason: 'zone', detail: zone.id };- const blocker = this.occupied(li, x, z, recipe.anchor.footprint);+ const blocker = this.occupied(li, x, z, anchor.footprint);if (blocker) return { ok: false, reason: 'occupied', detail: blocker };- return { ok: true, candidate: { gx, gz, x, z, priority: h(5), biome, recipe, radius: groupRadius(recipe), fields: f } };+ return { ok: true, candidate: { gx, gz, x, z, priority: h(5), biome, recipe, radius: groupRadius(recipe), anchor } };}/** The id of a placement of an earlier layer whose footprint a footprint of `radius` at (x, z) would overlap, or null. */diff --git a/sdk/src/worldgen/roads.ts b/sdk/src/worldgen/roads.tsnew file mode 100644index 000000000..f999c760d--- /dev/null+++ b/sdk/src/worldgen/roads.ts@@ -0,0 +1,68 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import type { ZoneDef } from './zones';+import { Zones } from './zones';++/** A path's reserved corridor, usable on a 3D ground plane or a 2D world's x/y plane. */+export interface RoadOptions {+ id: string;+ /** World [x, z] points (read z as y in a 2D world). Repeat the first point to close a loop. */+ points: readonly (readonly [number, number])[];+ /** Full width of the travelled surface. */+ width: number;+ /** Extra clearance on each side, before the soft edge (default 0). */+ clearance?: number;+ falloff?: number;+ priority?: number;+ /** Default ['*']; use tags such as tree/building to keep small ground cover. */+ excludes?: readonly string[];+ biome?: string;+ fields?: Readonly<Record<string, number>>;+}++const prefixOf = (id: string): string => `road:${encodeURIComponent(id)}/`;++/**+ * Turns a polyline into ordinary zones: rectangles with round joins and end caps, so bends leave no holes.+ * These serialize into worker plans and use the normal footprint-aware exclusion and terrain-paint paths.+ * It reserves a corridor; it does not make a road mesh or flatten a sloping road to one height.+ */+export function roadZones(options: RoadOptions): ZoneDef[] {+ const { id, points, width } = options;+ if (typeof id !== 'string' || !id.trim()) throw new Error('road.id: a nonempty name');+ if (!Number.isFinite(width) || width <= 0) throw new Error('road.width: a positive distance');+ for (const key of ['clearance', 'falloff'] as const) if (options[key] !== undefined+ && (!Number.isFinite(options[key]) || options[key]! < 0)) throw new Error(`road.${key}: a nonnegative distance`);+ if (options.priority !== undefined && !Number.isFinite(options.priority)) throw new Error('road.priority: a finite number');+ if (!Array.isArray(points) || points.length < 2 || points.some((p) => !Array.isArray(p) || p.length !== 2 || !p.every(Number.isFinite))) {+ throw new Error('road.points: at least two finite [x, z] points');+ }+ const radius = width / 2 + (options.clearance ?? 0), prefix = prefixOf(id);+ const common = { kind: 'road', falloff: options.falloff ?? 0, priority: options.priority ?? 10,+ excludes: [...(options.excludes ?? ['*'])], ...(options.biome ? { biome: options.biome } : {}),+ ...(options.fields ? { fields: { ...options.fields } } : {}) };+ const zones: ZoneDef[] = [];+ points.forEach(([x, z], i) => {+ zones.push({ ...common, id: `${prefix}join:${i}`, shape: { type: 'circle', x, z, radius } });+ if (i === 0) return;+ const [px, pz] = points[i - 1]!, dx = x - px, dz = z - pz, length = Math.hypot(dx, dz);+ if (length === 0) return;+ // Zone rectangles use the 2D distance function's rotation convention, with local +X along the segment.+ zones.push({ ...common, id: `${prefix}segment:${i - 1}`, shape: { type: 'rect', x: (x + px) / 2, z: (z + pz) / 2,+ halfX: length / 2, halfZ: radius, yaw: Math.atan2(dz, dx) } });+ });+ return zones;+}++/** Replace just this road's zones, including removing obsolete segments after shortening the path. Validates before changing anything. */+export function setRoad(zones: Zones, options: RoadOptions): void {+ const next = roadZones(options), ids = new Set(next.map((z) => z.id)), prefix = prefixOf(options.id);+ for (const zone of [...zones.all()]) if (zone.id.startsWith(prefix) && !ids.has(zone.id)) zones.delete(zone.id);+ for (const zone of next) zones.set(zone);+}++/** Remove a road's reservation; unrelated zones are preserved. */+export function removeRoad(zones: Zones, id: string): void {+ const prefix = prefixOf(id);+ for (const zone of [...zones.all()]) if (zone.id.startsWith(prefix)) zones.delete(zone.id);+}diff --git a/sdk/src/worldgen/rules.ts b/sdk/src/worldgen/rules.tsindex cac7aab86..2438d1789 100644--- a/sdk/src/worldgen/rules.ts+++ b/sdk/src/worldgen/rules.ts@@ -19,6 +19,7 @@*/import type { FieldFn, NoiseField } from './fields';import type { PlantKind } from '../foliage/plantKind';+import type { GroundingOptions } from './grounding';/** A band of one field with soft edges: full weight between `min` and `max`, fading to none over `blend` past each. */export interface BiomeCondition { field: string; min?: number; max?: number; blend?: number }@@ -59,8 +60,12 @@ export interface RecipeMember {ring?: readonly [number, number];arc?: readonly [number, number];scale?: readonly [number, number];- /** What it takes on the ground (a trunk): nothing else stands within it. */+ /** Radius it takes on the ground: world units by default, model units with scaleFootprint. */footprint: number;+ /** Scale footprint and canopy with the model. Omitted preserves existing world-unit rules. */+ scaleFootprint?: boolean;+ /** Fit an upright building over its whole base; also reserves at least the scaled base's circumcircle. */+ grounding?: GroundingOptions;/** How far it spreads overhead (a crown), for what is kept clear of view; the footprint when absent. */canopy?: number;/** Upright, or leaning with the ground. */diff --git a/sdk/src/worldgen/rulesAsset.ts b/sdk/src/worldgen/rulesAsset.tsindex c91970287..6b78cfad3 100644--- a/sdk/src/worldgen/rulesAsset.ts+++ b/sdk/src/worldgen/rulesAsset.ts@@ -13,6 +13,7 @@import type { AssetLoader, LoadContext } from '../asset/AssetLoader';import type { PlantKind } from '../foliage/plantKind';import type { BiomeDef, PlacementLayer, Recipe, RecipeMember, WorldRules } from './rules';+import { validateGrounding, type GroundingOptions } from './grounding';/** Whether a WorldGen's `rules` names a file rather than rules registered by code. */export function isRulesFile(ref: string): boolean {@@ -43,6 +44,14 @@ function member(v: unknown, where: string): RecipeMember {if (!v || typeof v !== 'object') fail(where, 'a member, an object');const m = v as Record<string, unknown>;const mesh = m.mesh;+ if (m.scaleFootprint !== undefined && typeof m.scaleFootprint !== 'boolean') fail(`${where}.scaleFootprint`, 'a boolean');+ if (m.grounding !== undefined) {+ try { validateGrounding(m.grounding as GroundingOptions); }+ catch (error) { fail(where, error instanceof Error ? error.message : String(error)); }+ if (m.attach === 'align') fail(`${where}.grounding`, 'footprint fitting requires an upright member');+ }+ const scale = range(m.scale, `${where}.scale`);+ if ((m.grounding || m.scaleFootprint) && scale && scale[0] <= 0) fail(`${where}.scale`, 'positive scales for fitted or scaled footprints');if (m.plant !== undefined) str(m.plant, `${where}.plant`);else if (typeof mesh !== 'string' && typeof mesh !== 'number') fail(`${where}.mesh`, 'a mesh path, or a plant');return {@@ -53,7 +62,7 @@ function member(v: unknown, where: string): RecipeMember {count: range(m.count, `${where}.count`),ring: range(m.ring, `${where}.ring`),arc: range(m.arc, `${where}.arc`),- scale: range(m.scale, `${where}.scale`),+ scale,} as RecipeMember;}diff --git a/sdk/tests/foliage-zones.test.ts b/sdk/tests/foliage-zones.test.tsnew file mode 100644index 000000000..03edbce1e--- /dev/null+++ b/sdk/tests/foliage-zones.test.ts@@ -0,0 +1,47 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { describe, expect, it } from 'vitest';+import { App } from '../src/app/app';+import { AppContext, setDefaultContext } from '../src/ecs/context';+import { setEditorMode, setPlayMode } from '../src/ecs/env';+import { Transform, MeshRenderer } from '../src/ecs/component';+import { Assets } from '../src/asset/AssetPlugin';+import { Foliage, FoliagePlugin } from '../src/foliage/foliagePlugin';+import { WorldGens, WorldGenRes } from '../src/worldgen/worldgenPlugin';+import { WorldStreamingSource } from '../src/residency/components';+import { createMockModule } from './mocks/wasm';++const tick = async (app: App) => { for (let i = 0; i < 16; i++) { app.tick(1 / 60); await new Promise((r) => setTimeout(r, 0)); } };+const boot = () => {+ setDefaultContext(new AppContext()); setEditorMode(false); setPlayMode(false);+ const app = App.new(), module = createMockModule(); app.connectCpp(module.getRegistry(), module);+ let handle = 1;+ app.insertResource(Assets, { createMesh: () => handle++, releaseBuiltMesh: () => {} } as any);+ app.addPlugin(new FoliagePlugin());+ const source = app.world.spawn();+ app.world.insert(source, Transform); app.world.insert(source, WorldStreamingSource, { ...WorldStreamingSource._default });+ const entity = app.world.spawn(); app.world.insert(entity, Transform);+ app.world.insert(entity, Foliage, { ...Foliage._default, sizeX: 40, sizeZ: 40, cellSize: 20, count: 12, drawDistance: 100,+ castShadows: false, zoneWorld: 'parcel' });+ return { app, entity };+};+const cells = (app: App) => app.world.getEntitiesWithComponents([MeshRenderer]);++describe('grass reservations and shadows', () => {+ it('grows without worldgen and applies the authored shadow policy to generated cells', async () => {+ const { app, entity } = boot(); await tick(app);+ expect(cells(app)).toHaveLength(4);+ for (const e of cells(app)) expect(app.world.get(e, MeshRenderer).castShadows).toBe(false);+ app.world.insert(entity, Foliage, { ...app.world.get(entity, Foliage), castShadows: true }); await tick(app);+ for (const e of cells(app)) expect(app.world.get(e, MeshRenderer).castShadows).toBe(true);+ });+ it('regenerates when a building exclusion is added or removed, with unrelated tags left alone', async () => {+ const { app } = boot(); const gens = new WorldGens(); app.insertResource(WorldGenRes, gens);+ const zones = gens.zones('parcel'); await tick(app); expect(cells(app)).toHaveLength(4);+ const building = { id: 'house', kind: 'building', shape: { type: 'rect' as const, x: 0, z: 0, halfX: 50, halfZ: 50, yaw: 0.3 }, falloff: 0, priority: 10, excludes: ['tree'] };+ zones.set(building); await tick(app); expect(cells(app)).toHaveLength(4);+ zones.set({ ...building, excludes: ['grass'] }); await tick(app); expect(cells(app)).toHaveLength(0);+ zones.delete('house'); await tick(app); expect(cells(app)).toHaveLength(4);+ zones.set({ ...building, excludes: ['*'] }); await tick(app); expect(cells(app)).toHaveLength(0);+ });+});diff --git a/sdk/tests/worldgen-pcg.test.ts b/sdk/tests/worldgen-pcg.test.tsnew file mode 100644index 000000000..d03af9820--- /dev/null+++ b/sdk/tests/worldgen-pcg.test.ts@@ -0,0 +1,118 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { describe, expect, it } from 'vitest';+import { Environment, type EnvironmentInputs } from '../src/worldgen/fields';+import { fitGroundFootprint, type GroundingOptions } from '../src/worldgen/grounding';+import { roadZones, setRoad, removeRoad } from '../src/worldgen/roads';+import { WorldPlan } from '../src/worldgen/plan';+import { Zones, zoneDistance } from '../src/worldgen/zones';+import { parseWorldRules } from '../src/worldgen/rulesAsset';+import type { WorldRules } from '../src/worldgen/rules';+import { placements, type PlaneSpec } from '../src/worldgen/planWorker';++const flat: EnvironmentInputs = { seed: 7, ground: () => ({ y: 10, up: 1 }) };+const base: GroundingOptions = { size: [8, 4], maxRelief: 4 };+const rules = (): WorldRules => ({+ id: 'pcg', versions: [1],+ biomes: [{ id: 'plain', conditions: [], recipes: [{ recipe: 'house', layer: 'buildings', density: 1 }, { recipe: 'pine', layer: 'forest', density: 1 }] }],+ recipes: [+ { id: 'house', version: 1, anchor: { id: 'base', mesh: 1, footprint: 1, scale: [1.1, 1.8], grounding: base } },+ { id: 'pine', version: 1, tags: ['tree'], anchor: { id: 'tree', mesh: 2, footprint: 1, scale: [1, 3], scaleFootprint: true } },+ ],+ layers: [{ id: 'buildings', spacing: 30, drawDistance: 200 }, { id: 'forest', spacing: 8, drawDistance: 200 }],+});+const plan = (r = rules(), zones = new Zones(), inputs = flat) => new WorldPlan(r, new Environment(inputs), zones, 7, 'world');++describe('building ground fit', () => {+ it('rotates and scales the entire base with the engine yaw convention', () => {+ const inputs = { ground: (x: number, z: number) => ({ y: x + 2 * z, up: 1 }) };+ const r = fitGroundFootprint(inputs, 10, 20, Math.PI / 2, 2, { size: [8, 4], samples: 5, offset: 0.5 });+ expect(r.ok).toBe(true);+ if (!r.ok) return;+ expect(r.fit).toMatchObject({ min: 30, max: 70, mean: 50, relief: 40, y: 71, supportDepth: 41, buriedDepth: 0, samples: 25 });+ });+ it('checks edges for missing ground, steep slopes and water even when the centre is safe', () => {+ const edge = (x: number, z: number) => Math.abs(x) >= 4 && Math.abs(z) >= 2;+ const fit = (inputs: Pick<EnvironmentInputs, 'ground' | 'waterDepth'>) => fitGroundFootprint(inputs, 0, 0, 0, 1, base, { minUp: 0.8 });+ expect(fit({ ground: (x, z) => edge(x, z) ? null : { y: 10, up: 1 } })).toEqual({ ok: false, reason: 'noGround' });+ expect(fit({ ground: (x, z) => ({ y: 10, up: edge(x, z) ? 0.4 : 1 }) })).toEqual({ ok: false, reason: 'slope' });+ expect(fit({ ...flat, waterDepth: (x, z) => edge(x, z) ? 1 : 0 })).toEqual({ ok: false, reason: 'water' });+ });+ it('rejects excessive relief and reports foundation support and burial separately', () => {+ const slope = { ground: (x: number) => ({ y: x, up: 1 }) };+ expect(fitGroundFootprint(slope, 0, 0, 0, 1, base)).toEqual({ ok: false, reason: 'relief' });+ for (const [mode, y, supportDepth, buriedDepth] of [['highest', 4, 8, 0], ['lowest', -4, 0, 8], ['mean', 0, 4, 4], ['center', 0, 4, 4]] as const) {+ const r = fitGroundFootprint(slope, 0, 0, 0, 1, { size: [8, 4], mode });+ expect(r).toMatchObject({ ok: true, fit: { y, supportDepth, buriedDepth } });+ }+ });+ it('rejects invalid dimensions, unbounded grids, modes and offsets before sampling', () => {+ for (const patch of [{ size: [0, 4] }, { samples: 100000 }, { samples: 4 }, { mode: 'bad' }, { offset: Infinity }, { maxRelief: -1 }]) {+ expect(() => fitGroundFootprint(flat, 0, 0, 0, 1, { ...base, ...patch } as GroundingOptions)).toThrow(/grounding/);+ }+ });+});++describe('PCG road reservations', () => {+ it('covers diagonal segments, sharp joins and round ends, without reserving distant land', () => {+ const zs = roadZones({ id: 'trail', points: [[0, 0], [20, 20], [40, 0]], width: 4, clearance: 1 });+ const inside = (x: number, z: number) => zs.some((q) => zoneDistance(q.shape, x, z) <= 0);+ for (const [x, z] of [[0, -2.9], [10, 10], [20, 22.9], [30, 10], [42.9, 0]]) expect(inside(x!, z!)).toBe(true);+ expect(inside(20, 0)).toBe(false);+ expect(inside(0, 5)).toBe(false);+ });+ it('replaces shortened roads idempotently, removes stale joins and preserves other roads', () => {+ const z = new Zones();+ setRoad(z, { id: 'a', points: [[0, 0], [20, 0], [40, 0]], width: 4 });+ setRoad(z, { id: 'a/b', points: [[100, 0], [120, 0]], width: 4 });+ const short = { id: 'a', points: [[0, 0], [10, 0]] as [number, number][], width: 4 };+ setRoad(z, short); const rev = z.revision; setRoad(z, short);+ expect(z.revision).toBe(rev);+ expect(z.at(40, 0)).toHaveLength(0);+ expect(z.at(100, 0).length).toBeGreaterThan(0);+ const before = [...z.all()];+ expect(() => setRoad(z, { ...short, width: -1 })).toThrow(/width/);+ expect([...z.all()]).toEqual(before);+ removeRoad(z, 'a');+ expect(z.at(0, 0)).toHaveLength(0);+ expect(z.at(100, 0).length).toBeGreaterThan(0);+ });+ it('keeps scaled trees and whole building bases clear of roads and one another', () => {+ const z = new Zones(); setRoad(z, { id: 'main', points: [[-100, 0], [100, 0]], width: 6 });+ const ps = plan(rules(), z).placementsIn(-90, -90, 90, 90);+ expect(ps.some((p) => p.grounding)).toBe(true);+ expect(ps.some((p) => p.recipe === 'pine')).toBe(true);+ for (const p of ps) {+ expect(Math.abs(p.z)).toBeGreaterThanOrEqual(3 + p.footprint);+ if (p.grounding) expect(p.footprint).toBeCloseTo(Math.hypot(8, 4) * p.scale / 2);+ else expect(p.footprint).toBe(p.scale);+ for (const q of ps) if (p !== q) expect(Math.hypot(p.x - q.x, p.z - q.z) + 1e-9).toBeGreaterThanOrEqual(p.footprint + q.footprint);+ }+ });+ it('preserves existing world-space footprints unless model scaling is requested', () => {+ const r = rules(); delete r.recipes[1]!.anchor.scaleFootprint;+ expect(plan(r).placementsIn(-60, -60, 60, 60, ['forest']).every((p) => p.footprint === 1)).toBe(true);+ });+ it('is independent of chunk order and identical in a worker plan', async () => {+ const r = rules(), z = new Zones(); setRoad(z, { id: 'r', points: [[-70, -20], [0, 30], [70, -20]], width: 7 });+ const a = plan(r, z), b = plan(r, z);+ const cells = [[-64, -64], [0, -64], [-64, 0], [0, 0]] as const;+ const sort = (ps: ReturnType<WorldPlan['placementsIn']>) => ps.sort((x, y) => x.id.localeCompare(y.id));+ const forward = cells.flatMap(([x, z]) => a.placementsIn(x, z, x + 64, z + 64));+ const reverse = [...cells].reverse().flatMap(([x, z]) => b.placementsIn(x, z, x + 64, z + 64));+ expect(sort(forward)).toEqual(sort(reverse));+ const spec: PlaneSpec = { plane: true, rules: r, seed: 7, world: 'world', ground: null, flatY: 10, water: null, layers: [], zones: [...z.all()] };+ const remote = (await Promise.all(r.layers.map((l) => placements({ id: 1, key: 'pcg-test', spec, layer: l.id, far: false, x0: -64, z0: -64, x1: 64, z1: 64 })))).flat();+ expect(sort(remote)).toEqual(sort(forward));+ });+ it('exposes relief rejections and validates new fields when loading files', () => {+ const r = rules(), p = plan(r, new Zones(), { seed: 7, ground: (x) => ({ y: x * 4, up: 1 }) });+ expect(p.stats('buildings', -60, -60, 60, 60).relief).toBe(16);+ const roundtrip = parseWorldRules(JSON.parse(JSON.stringify(r)), 'pcg.esworld');+ expect(roundtrip.recipes[0]!.anchor.grounding).toEqual(base);+ r.recipes[0]!.anchor.grounding = { ...base, samples: 4 };+ expect(() => parseWorldRules(r, 'pcg.esworld')).toThrow(/pcg.esworld.recipes\[0\].anchor.*grounding.samples/);+ r.recipes[0]!.anchor.grounding = base; r.recipes[0]!.anchor.attach = 'align';+ expect(() => parseWorldRules(r)).toThrow(/upright/);+ });+});