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(residency): procedural chunks have one owner and the frame one budget; terrain collision and foliage cells are chunk layers
yhhbcbfa1202208
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 60bf00943..3aa0d671a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -24,6 +24,7 @@ published separately; it ships inside the editor.- **Terrain without cracks, and without end.** The ground is now a CDLOD quadtree round the eye: every node is the same small patch drawn as instances of one mesh, its heights and normals read on the GPU from pages of a height atlas, and its vertices slide onto the coarser grid toward the end of their level's range, so levels meet without cracks or skirts and nothing pops as the camera moves. `Terrain.extent` Infinite makes ground that goes on for ever from seeded noise read anywhere (worn by the noise's own erosion), drawn out to `drawDistance`; `cellSize` is the finest cell near the eye. Pages are made a few a frame, coarse and near first, and shown as progress.- **Terrain from a generator the game names, versioned.** Infinite ground is now made by a terrain provider: a function of the world position that samples whole regions (heights, and paint if it has its own), the same on every machine, and that may answer later from a worker or a server. `Terrain.provider`, `world` and `generatorVersion` name it; `registerTerrainProvider` adds a game's own, and the engine's noise is `estella:noise` version 1. A terrain whose provider is missing, whose version its provider no longer has, or whose heightmap cannot be read fails with a reason in `Terrains.status` and answers nothing, instead of growing noise in its place.- **Terrain collision, the same ground that is drawn.** 3D bodies and characters now collide with a `Terrain`: it is built in tiles round everything that moves on it (`collision`, `collisionDistance`, `collisionLayer`, `friction`), the tile under a body at once, and kept through a rebuild until the new ground replaces it. What is collided with, what `Terrains.heightAt` and `normalAt` answer and the finest level drawn near the eye are now one set of triangles, so a ray, a query and the picture agree wherever the camera is; `Terrains.collisionReadyAt` says when the ground under a point is ready. Any system that makes static geometry while the game runs can hand it to the 3D world through the new `CollisionGeometry` resource.+- **Procedural chunks, with one owner and one budget.** What a game makes as it runs is now chunks of layers in `ProceduralChunks` (`chunksOf(app)`): each layer says how it is cut, how far round the streaming sources it is wanted and how a chunk is made, published and released, and the chunks are made nearest first within the frame's budget (the one `Bakes.budgetMs`, shared with the bakes and the terrain's pages), released with everything they published past the unload radius, and made again when the layer's generation changes, the old version staying until the new one replaces it; an answer for an older generation is thrown away. `status` and `stateAt` say where they stand. Terrain collision and foliage cells are layers: plants now grow round the eye out to `drawDistance` and are let go past it, and a changed field or ground regrows them without blinking out.- **A vertex hook can hand the fragment a colour.** What a material's vertex hook leaves in `es_vertexColor` is now the colour its fragment receives (times the instance's tint), on both backends.- **Bakes run over frames, with progress.** Work that used to hold a frame until it was done (a terrain worn by rain, a water zone baked, terrain chunks built, plants grown) is now spread over frames within a budget, and listed with its progress in the new `Bakes` resource (`bakesOf(app).active`). The editor's status bar shows it as a bar, for the edit world and for the game running in Play, and a game can show it on a loading screen. Plants wait for the ground and the water they stand on instead of being grown twice.- **Eroded and warped terrain.** `Terrain.erosion` wears the ground with rain (a heightmap's as well as the noise's): gullies down the slopes, sharper ridges, silt in the valleys, and dirt painted where the water ran; the same seed wears the same ground. `Terrain.warp` bends the noise by noise of its own for winding valleys and bent ridges. `erodeHeightfield` and `erosionJob` do the same for a tool.diff --git a/docs/WORLD_GENERATION_PLAN.md b/docs/WORLD_GENERATION_PLAN.mdindex 4573cfce5..575ca2acd 100644--- a/docs/WORLD_GENERATION_PLAN.md+++ b/docs/WORLD_GENERATION_PLAN.md@@ -33,7 +33,7 @@### T-03 程序化区块的驻留与统一预算- 需要:由 WorldStreamer 调度程序化地形、碰撞、植被、交互实体的准备与发布;距离/视野优先级、取消过期任务、全局帧预算、卸载释放、可查询的 ready/pending/failure;一个地块只有一个生命周期所有者。-- 当前状态:地形渲染已改为按需页(四叉树选择 + 图集 LRU 淘汰,常驻有上限),分帧作业与进度(`Bakes`)已有;植被仍遍历整个区域且按格子合并网格(非 GPU 实例化);尚未接入 WorldStreamer,尚无统一预算与取消。+- 当前状态:已完成主体。`ProceduralChunks`(`sdk/src/residency/chunks.ts`)是程序化区块的唯一生命周期所有者,与 WorldStreamer 共用 `WorldStreamingSource`(无源时退回视点);各"层"登记切分、范围、加载/卸载半径、代次与 make/publish/release。每帧跨层按距离排序,源所在区块立即生成,其余在统一帧预算(`Bakes.budgetMs` 与 `Bakes.hasTime`,与烘焙作业、地形页共享,被挤占时作业让出一半)内生成;异步结果按代次丢弃并中止 `AbortSignal`(快速传送不发布旧结果);代次变化时旧版本保留到新版本替换;超出卸载半径即释放其发布的一切;`status`/`stateAt` 可查询 ready/stale/pending/making/failed 与原因,进度并入状态栏。已迁入:地形碰撞块(跟随运动刚体与角色)、植被格(跟随视点,到 `drawDistance`)。测试 `sdk/tests/procedural-chunks.test.ts`。仍欠:植被 GPU 实例化(目前每格合并网格,内存已随驻留有上限);地形页仍由四叉树 + 图集 LRU 自管(已共用帧预算并限制异步并发);远景与正交俯视 LOD 需在目标设备实测;交互实体待 T-04 作为层接入。- 验收:连续走过大量区块内存和实体有上限;折返不重复;快速传送不把旧请求结果发布到新星球;卸载同时移除渲染、碰撞、资产引用;远景与正交俯视 LOD 在目标设备实测。### T-04 群落、建造排除区与持久变化diff --git a/docs/astro/src/content/docs/graphics/foliage.mdx b/docs/astro/src/content/docs/graphics/foliage.mdxindex 7310e31a3..941b5287e 100644--- a/docs/astro/src/content/docs/graphics/foliage.mdx+++ b/docs/astro/src/content/docs/graphics/foliage.mdx@@ -9,8 +9,11 @@ hundred draws that culling can drop whole, and each cell is built at the detail## The component-Add a `Foliage` component to an entity. The area is centred on it, and its children are the cells, made when the scene runs (and in the-editor's scene view) and made again when a field changes. Nothing is baked.+Add a `Foliage` component to an entity. The area is centred on it, and its children are the cells. They are+[procedural chunks](/docs/world/streaming/#procedural-chunks): grown round the streaming sources (or the eye, in a game without any, and in+the editor's scene view) out to `drawDistance`, nearest first, and let go with their meshes past it, so a large area holds only the cells+near what looks at it. When a field, the ground or the water changes they are grown again, each old cell staying until its new one+replaces it. Nothing is baked.| Field | What it does ||---|---|@@ -53,4 +56,4 @@ Foliage is an optional module, like terrain: a package carries it when a scene h- **No collision and no interaction.** Plants do not bend away from a character; the wind is the only thing that moves them.- **The far version of a mesh is a card, not an impostor.** It shows the rectangle of the plant's texture you name, from every side the same; atree whose texture has no such picture shows its texture there.-- **Cells are built a few a frame**, so a large field appears over a moment.+- **Cells are grown within the frame's budget**, nearest first, so the distance fills in over a moment.diff --git a/docs/astro/src/content/docs/world/streaming.mdx b/docs/astro/src/content/docs/world/streaming.mdxindex 8730566cf..8c2f756c1 100644--- a/docs/astro/src/content/docs/world/streaming.mdx+++ b/docs/astro/src/content/docs/world/streaming.mdx@@ -131,6 +131,39 @@ enemy at 25 health that you walk away from comes back at full health. What doessurvive is the entity's authored identity, which is what a save system will bebuilt on later.+## Procedural chunks++What a game makes as it runs (the ground's collision round what moves, plants round the eye, and whatever a game generates itself) is+not a cooked cell but a chunk of a **layer**, and `ProceduralChunks` is the one owner of their lifetime, as the streamer is of cells. A+layer says how it is cut, how far round its sources it is wanted and how one chunk is made, published and released:++```typescript+import { chunksOf } from 'esengine';++chunksOf(app).set('ruins', {+ label: 'Placing ruins',+ originX: 0, originZ: 0, sizeX: 64, sizeZ: 64, extent: null,+ loadRadius: 256, unloadRadius: 320,+ generation: `${planet}:${generatorVersion}`, // what the chunks are made from+ make: (cx, cz, signal) => generateRuins(cx, cz, signal), // a value, null for "not yet", or a promise+ publish: (cx, cz, ruins) => spawnRuins(ruins),+ release: (cx, cz, ruins) => despawnRuins(ruins),+});+```++- **One set of sources.** A layer is wanted round the same `WorldStreamingSource`s the streamer reads (or the eye, where there are+ none), unless it names its own: terrain collision follows every moving 3D body and character.+- **One budget.** Every frame the wanted chunks of every layer are made nearest first: the ones a source stands in at once, the rest+ while the frame's budget lasts. The budget is `Bakes.budgetMs`, shared with the bakes and the terrain's pages.+- **Bounded.** A chunk past every source's `unloadRadius` is released, with everything it published, so walking for ever holds a fixed+ number; stepping back and forth inside the band makes nothing again.+- **Generations.** `generation` names a layer's inputs. When it changes every chunk is made again, and its old version stays published+ until the new one replaces it, so nothing standing on it falls. An answer that arrives for an older generation (a teleport to another+ planet while a worker was still busy with the last) is thrown away, and the chunk's `AbortSignal` is aborted.+- **Readable.** `status(id)` counts a layer's chunks (ready, stale, pending, making, failed, with the first failure's reason), and+ `stateAt(id, x, z)` says where the chunk at a point stands. Layers still making chunks show with their progress in the editor's status+ bar, through the same list as the bakes.+## Reading what is resident```typescriptdiff --git a/docs/astro/src/content/docs/zh-cn/graphics/foliage.mdx b/docs/astro/src/content/docs/zh-cn/graphics/foliage.mdxindex afcf5a750..195f06296 100644--- a/docs/astro/src/content/docs/zh-cn/graphics/foliage.mdx+++ b/docs/astro/src/content/docs/zh-cn/graphics/foliage.mdx@@ -7,7 +7,7 @@ description: 一个 Foliage 组件,把草或网格散布到一片区域或地形## 组件-给某个实体加一个 `Foliage` 组件。区域以它为中心,它的子实体就是这些格子,在场景运行时(以及编辑器的场景视图里)生成,字段一变就重新生成。没有任何东西被烘焙。+给某个实体加一个 `Foliage` 组件。区域以它为中心,它的子实体就是这些格子。格子是[程序化区块](/docs/zh-cn/world/streaming/#程序化区块):围绕流送源(没有流送源的游戏里是视点,编辑器场景视图里也是视点)生长到 `drawDistance`,由近及远,超出后连同网格一起释放,所以大片区域只保留看着它的东西附近的格子。字段、地面或水变化时重新生长,每个旧格子保留到新格子替换它为止。没有任何东西被烘焙。| 字段 | 作用 ||---|---|@@ -42,4 +42,4 @@ description: 一个 Foliage 组件,把草或网格散布到一片区域或地形- **只有位置。** 区域被当作不旋转、不缩放;地形的位置和均匀缩放会被跟随,旋转不会。- **没有碰撞,也没有交互。** 植物不会被角色压弯;风是唯一能让它们动的东西。- **网格的远景版本是卡片,不是 impostor。** 它显示你指定的那个纹理矩形,从各个方向看都一样;纹理里没有这样一张图的树,卡片上就是它的纹理。-- **格子每帧构建几个**,所以大片区域会在一小会儿内出现。+- **格子在每帧预算内生长**,由近及远,所以远处会在一小会儿内填满。diff --git a/docs/astro/src/content/docs/zh-cn/world/streaming.mdx b/docs/astro/src/content/docs/zh-cn/world/streaming.mdxindex 0a6d5ff16..bc97af3c4 100644--- a/docs/astro/src/content/docs/zh-cn/world/streaming.mdx+++ b/docs/astro/src/content/docs/zh-cn/world/streaming.mdx@@ -112,6 +112,30 @@ main.esscene ──cook──▶ main.esscene 持久世界内容重建。你走开时只剩 25 点血的敌人,回来时是满血的。真正留下来的是实体的编排身份,以后的存档系统会建在它上面。+## 程序化区块++游戏在运行中生成的东西(运动物体周围的地面碰撞、视点周围的植被、游戏自己生成的任何东西)不是 cook 出来的格子,而是某个**层**的区块,`ProceduralChunks` 是它们生命周期的唯一所有者,就像流送器之于格子。一个层说明自己怎么切分、在它的源周围多远内需要、一个区块怎么生成、发布和释放:++```typescript+import { chunksOf } from 'esengine';++chunksOf(app).set('ruins', {+ label: 'Placing ruins',+ originX: 0, originZ: 0, sizeX: 64, sizeZ: 64, extent: null,+ loadRadius: 256, unloadRadius: 320,+ generation: `${planet}:${generatorVersion}`, // 区块由什么生成+ make: (cx, cz, signal) => generateRuins(cx, cz, signal), // 一个值、表示"还不行"的 null,或一个 Promise+ publish: (cx, cz, ruins) => spawnRuins(ruins),+ release: (cx, cz, ruins) => despawnRuins(ruins),+});+```++- **同一组源。** 层围绕流送器读取的同一批 `WorldStreamingSource`(没有时是视点)被需要,除非它指定自己的源:地形碰撞跟随每个运动的 3D 刚体和角色。+- **同一份预算。** 每帧所有层需要的区块由近及远生成:源所在的区块立刻生成,其余在本帧预算内生成。预算是 `Bakes.budgetMs`,与烘焙作业和地形页共用。+- **有上限。** 超出所有源 `unloadRadius` 的区块连同它发布的一切被释放,所以一直走下去持有的区块数是固定的;在带内来回走不会重复生成。+- **代次。** `generation` 标识层的输入。它变化时每个区块重新生成,旧版本保留发布直到新版本替换它,站在上面的东西不会掉下去。为旧代次返回的结果(worker 还在算上一个星球时就传送到了另一个星球)被丢弃,区块的 `AbortSignal` 被中止。+- **可查询。** `status(id)` 统计一个层的区块(ready、stale、pending、making、failed,以及第一个失败的原因),`stateAt(id, x, z)` 说明某点所在区块的状态。仍在生成区块的层会和烘焙作业一起、带着进度显示在编辑器状态栏里。+## 读取当前常驻状态```typescriptdiff --git a/docs/astro/src/data/components.generated.json b/docs/astro/src/data/components.generated.jsonindex 54626126d..a14bc9305 100644--- a/docs/astro/src/data/components.generated.json+++ b/docs/astro/src/data/components.generated.json@@ -5324,6 +5324,35 @@"doc": "How far ground without end is drawn.","range": "≥ 1"},+ {+ "key": "collision",+ "type": "boolean",+ "default": "true",+ "doc": "Whether 3D bodies and characters collide with the ground: the finest level's triangles, wherever the camera is."+ },+ {+ "key": "collisionDistance",+ "type": "number",+ "default": "64",+ "doc": "How far round each moving body and character the ground is built for collision, in world units.",+ "range": "≥ 1"+ },+ {+ "key": "collisionLayer",+ "type": "number",+ "default": "0",+ "doc": "The collision layer the ground is in (0 to 15).",+ "range": "0–15, step 1",+ "advanced": true+ },+ {+ "key": "friction",+ "type": "number",+ "default": "0.6",+ "doc": "How much the ground holds what slides on it.",+ "range": "≥ 0",+ "advanced": true+ },{"key": "seed","type": "number",@@ -5434,6 +5463,9 @@"cellSize","detail","drawDistance",+ "collisionDistance",+ "collisionLayer",+ "friction","seed","frequency","octaves",diff --git a/sdk/etc/foliage.api.md b/sdk/etc/foliage.api.mdindex 308d248b7..3266ba7d9 100644--- a/sdk/etc/foliage.api.md+++ b/sdk/etc/foliage.api.md@@ -53,6 +53,7 @@ waterDepth: number## FoliageField — class @experimental```+@internal app_: App | null@internal authoredWind_: Map<number, number>@internal built_: Map<number, BuiltFoliage>cellCount: numberdiff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex c6e2fb9c0..ac714ebef 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -1,7 +1,7 @@# API surface — esengine/index<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 159 beta · 1786 experimental · 3 deprecated+Symbols: 115 public · 159 beta · 1794 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -1550,6 +1550,7 @@ texelsPerUnit: numberactive: BakeProgress[]budgetMs: numberclear: (owner: object) => void+hasTime: () => booleanmark: (owner: object, label: string, progress: number) => voidrun: <T>(label: string, job: WorkJob<T>) => { done: Promise<T>; cancel: () => void; }step: (now?: () => number) => void@@ -2400,6 +2401,44 @@ BuiltinComponentDef<ChildrenData>entities: number[]```+## ChunkLayer — interface @experimental+```+extent: readonly [number, number, number, number] | null+generation: string | number+label: string+loadRadius: number+make: (cx: number, cz: number, signal: AbortSignal) => T | null | Promise<T | null>+originX: number+originZ: number+publish: (cx: number, cz: number, value: T) => void+release: (cx: number, cz: number, value: T) => void+sizeX: number+sizeZ: number+sources: (() => Iterable<ChunkSource>) | undefined+unloadRadius: number+```++## ChunkLayerStatus — interface @experimental+```+failed: number+making: number+pending: number+ready: number+reason: string | undefined+stale: number+```++## ChunkSource — interface @experimental+```+x: number+z: number+```++## ChunkState — type @experimental+```+'making' | 'ready' | 'stale' | 'failed'+```+## CircleCollider2D — const @experimental```BuiltinComponentDef<CircleCollider2DData>@@ -4168,6 +4207,7 @@ waterDepth: number## FoliageField — class @experimental```+@internal app_: App | null@internal authoredWind_: Map<number, number>@internal built_: Map<number, BuiltFoliage>cellCount: number@@ -7095,6 +7135,27 @@ fingerprint: stringpending: PendingSystemEntry[]```+## ProceduralChunks — class @experimental+```+@internal progress_: () => { label: string; progress: number; owner: object; }[]+@internal sources_: () => ChunkSource[]+clear: () => void+has: (id: string) => boolean+pending: number+remove: (id: string) => void+set: <T>(id: string, def: ChunkLayer<T>) => void+stateAt: (id: string, x: number, z: number) => ChunkState | null+status: (id: string) => ChunkLayerStatus | null+step: (hasTime: () => boolean) => void+static new (): ProceduralChunks+static prototype: ProceduralChunks+```++## ProceduralChunksRes — const @experimental+```+ResourceDef<ProceduralChunks>+```+## ProceduralParams — interface @experimental```frequency: number@@ -12485,6 +12546,11 @@ MotionDriver<AnimatorBlend2DMotion>(): string[]```+## chunksOf — function @experimental+```+(app: App): ProceduralChunks+```+## clearAnimatorControllerStore — function @experimental```(): void@@ -15160,6 +15226,11 @@ StatsPlugin(world: World, entity: Entity): void```+## streamingSourcesOf — function @experimental+```+(app: App): ChunkSource[]+```+## studioPreviewReport — function @experimental```(entities: readonly EnvironmentLightEntity[], exists: (ref: string) => boolean): StudioPreviewReportdiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex f27292627..8e2764eac 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.native<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 164 beta · 1805 experimental · 3 deprecated+Symbols: 115 public · 164 beta · 1813 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -1550,6 +1550,7 @@ texelsPerUnit: numberactive: BakeProgress[]budgetMs: numberclear: (owner: object) => void+hasTime: () => booleanmark: (owner: object, label: string, progress: number) => voidrun: <T>(label: string, job: WorkJob<T>) => { done: Promise<T>; cancel: () => void; }step: (now?: () => number) => void@@ -2400,6 +2401,44 @@ BuiltinComponentDef<ChildrenData>entities: number[]```+## ChunkLayer — interface @experimental+```+extent: readonly [number, number, number, number] | null+generation: string | number+label: string+loadRadius: number+make: (cx: number, cz: number, signal: AbortSignal) => T | null | Promise<T | null>+originX: number+originZ: number+publish: (cx: number, cz: number, value: T) => void+release: (cx: number, cz: number, value: T) => void+sizeX: number+sizeZ: number+sources: (() => Iterable<ChunkSource>) | undefined+unloadRadius: number+```++## ChunkLayerStatus — interface @experimental+```+failed: number+making: number+pending: number+ready: number+reason: string | undefined+stale: number+```++## ChunkSource — interface @experimental+```+x: number+z: number+```++## ChunkState — type @experimental+```+'making' | 'ready' | 'stale' | 'failed'+```+## CircleCollider2D — const @experimental```BuiltinComponentDef<CircleCollider2DData>@@ -4176,6 +4215,7 @@ waterDepth: number## FoliageField — class @experimental```+@internal app_: App | null@internal authoredWind_: Map<number, number>@internal built_: Map<number, BuiltFoliage>cellCount: number@@ -7298,6 +7338,27 @@ fingerprint: stringpending: PendingSystemEntry[]```+## ProceduralChunks — class @experimental+```+@internal progress_: () => { label: string; progress: number; owner: object; }[]+@internal sources_: () => ChunkSource[]+clear: () => void+has: (id: string) => boolean+pending: number+remove: (id: string) => void+set: <T>(id: string, def: ChunkLayer<T>) => void+stateAt: (id: string, x: number, z: number) => ChunkState | null+status: (id: string) => ChunkLayerStatus | null+step: (hasTime: () => boolean) => void+static new (): ProceduralChunks+static prototype: ProceduralChunks+```++## ProceduralChunksRes — const @experimental+```+ResourceDef<ProceduralChunks>+```+## ProceduralParams — interface @experimental```frequency: number@@ -12713,6 +12774,11 @@ MotionDriver<AnimatorBlend2DMotion>(): string[]```+## chunksOf — function @experimental+```+(app: App): ProceduralChunks+```+## clearAnimatorControllerStore — function @experimental```(): void@@ -15423,6 +15489,11 @@ StatsPlugin(world: World, entity: Entity): void```+## streamingSourcesOf — function @experimental+```+(app: App): ChunkSource[]+```+## studioPreviewReport — function @experimental```(entities: readonly EnvironmentLightEntity[], exists: (ref: string) => boolean): StudioPreviewReportdiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex e23f8c324..ab783d320 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.node<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 161 beta · 1785 experimental · 3 deprecated+Symbols: 115 public · 161 beta · 1793 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -1545,6 +1545,7 @@ texelsPerUnit: numberactive: BakeProgress[]budgetMs: numberclear: (owner: object) => void+hasTime: () => booleanmark: (owner: object, label: string, progress: number) => voidrun: <T>(label: string, job: WorkJob<T>) => { done: Promise<T>; cancel: () => void; }step: (now?: () => number) => void@@ -2395,6 +2396,44 @@ BuiltinComponentDef<ChildrenData>entities: number[]```+## ChunkLayer — interface @experimental+```+extent: readonly [number, number, number, number] | null+generation: string | number+label: string+loadRadius: number+make: (cx: number, cz: number, signal: AbortSignal) => T | null | Promise<T | null>+originX: number+originZ: number+publish: (cx: number, cz: number, value: T) => void+release: (cx: number, cz: number, value: T) => void+sizeX: number+sizeZ: number+sources: (() => Iterable<ChunkSource>) | undefined+unloadRadius: number+```++## ChunkLayerStatus — interface @experimental+```+failed: number+making: number+pending: number+ready: number+reason: string | undefined+stale: number+```++## ChunkSource — interface @experimental+```+x: number+z: number+```++## ChunkState — type @experimental+```+'making' | 'ready' | 'stale' | 'failed'+```+## CircleCollider2D — const @experimental```BuiltinComponentDef<CircleCollider2DData>@@ -4163,6 +4202,7 @@ waterDepth: number## FoliageField — class @experimental```+@internal app_: App | null@internal authoredWind_: Map<number, number>@internal built_: Map<number, BuiltFoliage>cellCount: number@@ -7090,6 +7130,27 @@ fingerprint: stringpending: PendingSystemEntry[]```+## ProceduralChunks — class @experimental+```+@internal progress_: () => { label: string; progress: number; owner: object; }[]+@internal sources_: () => ChunkSource[]+clear: () => void+has: (id: string) => boolean+pending: number+remove: (id: string) => void+set: <T>(id: string, def: ChunkLayer<T>) => void+stateAt: (id: string, x: number, z: number) => ChunkState | null+status: (id: string) => ChunkLayerStatus | null+step: (hasTime: () => boolean) => void+static new (): ProceduralChunks+static prototype: ProceduralChunks+```++## ProceduralChunksRes — const @experimental+```+ResourceDef<ProceduralChunks>+```+## ProceduralParams — interface @experimental```frequency: number@@ -12480,6 +12541,11 @@ MotionDriver<AnimatorBlend2DMotion>(): string[]```+## chunksOf — function @experimental+```+(app: App): ProceduralChunks+```+## clearAnimatorControllerStore — function @experimental```(): void@@ -15165,6 +15231,11 @@ StatsPlugin(world: World, entity: Entity): void```+## streamingSourcesOf — function @experimental+```+(app: App): ChunkSource[]+```+## studioPreviewReport — function @experimental```(entities: readonly EnvironmentLightEntity[], exists: (ref: string) => boolean): StudioPreviewReportdiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex 2834dfd18..c41486c82 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -1,7 +1,7 @@# API surface — esengine/minigame<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 159 beta · 1807 experimental · 3 deprecated+Symbols: 115 public · 159 beta · 1815 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -1545,6 +1545,7 @@ texelsPerUnit: numberactive: BakeProgress[]budgetMs: numberclear: (owner: object) => void+hasTime: () => booleanmark: (owner: object, label: string, progress: number) => voidrun: <T>(label: string, job: WorkJob<T>) => { done: Promise<T>; cancel: () => void; }step: (now?: () => number) => void@@ -2395,6 +2396,44 @@ BuiltinComponentDef<ChildrenData>entities: number[]```+## ChunkLayer — interface @experimental+```+extent: readonly [number, number, number, number] | null+generation: string | number+label: string+loadRadius: number+make: (cx: number, cz: number, signal: AbortSignal) => T | null | Promise<T | null>+originX: number+originZ: number+publish: (cx: number, cz: number, value: T) => void+release: (cx: number, cz: number, value: T) => void+sizeX: number+sizeZ: number+sources: (() => Iterable<ChunkSource>) | undefined+unloadRadius: number+```++## ChunkLayerStatus — interface @experimental+```+failed: number+making: number+pending: number+ready: number+reason: string | undefined+stale: number+```++## ChunkSource — interface @experimental+```+x: number+z: number+```++## ChunkState — type @experimental+```+'making' | 'ready' | 'stale' | 'failed'+```+## CircleCollider2D — const @experimental```BuiltinComponentDef<CircleCollider2DData>@@ -4163,6 +4202,7 @@ waterDepth: number## FoliageField — class @experimental```+@internal app_: App | null@internal authoredWind_: Map<number, number>@internal built_: Map<number, BuiltFoliage>cellCount: number@@ -7383,6 +7423,27 @@ fingerprint: stringpending: PendingSystemEntry[]```+## ProceduralChunks — class @experimental+```+@internal progress_: () => { label: string; progress: number; owner: object; }[]+@internal sources_: () => ChunkSource[]+clear: () => void+has: (id: string) => boolean+pending: number+remove: (id: string) => void+set: <T>(id: string, def: ChunkLayer<T>) => void+stateAt: (id: string, x: number, z: number) => ChunkState | null+status: (id: string) => ChunkLayerStatus | null+step: (hasTime: () => boolean) => void+static new (): ProceduralChunks+static prototype: ProceduralChunks+```++## ProceduralChunksRes — const @experimental+```+ResourceDef<ProceduralChunks>+```+## ProceduralParams — interface @experimental```frequency: number@@ -12779,6 +12840,11 @@ MotionDriver<AnimatorBlend2DMotion>(): string[]```+## chunksOf — function @experimental+```+(app: App): ProceduralChunks+```+## clearAnimatorControllerStore — function @experimental```(): void@@ -15469,6 +15535,11 @@ StatsPlugin(world: World, entity: Entity): void```+## streamingSourcesOf — function @experimental+```+(app: App): ChunkSource[]+```+## studioPreviewReport — function @experimental```(entities: readonly EnvironmentLightEntity[], exists: (ref: string) => boolean): StudioPreviewReportdiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 4562b8483..41583b60e 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -1,7 +1,7 @@# API surface — esengine/wechat<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 159 beta · 1798 experimental · 3 deprecated+Symbols: 115 public · 159 beta · 1806 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -1545,6 +1545,7 @@ texelsPerUnit: numberactive: BakeProgress[]budgetMs: numberclear: (owner: object) => void+hasTime: () => booleanmark: (owner: object, label: string, progress: number) => voidrun: <T>(label: string, job: WorkJob<T>) => { done: Promise<T>; cancel: () => void; }step: (now?: () => number) => void@@ -2395,6 +2396,44 @@ BuiltinComponentDef<ChildrenData>entities: number[]```+## ChunkLayer — interface @experimental+```+extent: readonly [number, number, number, number] | null+generation: string | number+label: string+loadRadius: number+make: (cx: number, cz: number, signal: AbortSignal) => T | null | Promise<T | null>+originX: number+originZ: number+publish: (cx: number, cz: number, value: T) => void+release: (cx: number, cz: number, value: T) => void+sizeX: number+sizeZ: number+sources: (() => Iterable<ChunkSource>) | undefined+unloadRadius: number+```++## ChunkLayerStatus — interface @experimental+```+failed: number+making: number+pending: number+ready: number+reason: string | undefined+stale: number+```++## ChunkSource — interface @experimental+```+x: number+z: number+```++## ChunkState — type @experimental+```+'making' | 'ready' | 'stale' | 'failed'+```+## CircleCollider2D — const @experimental```BuiltinComponentDef<CircleCollider2DData>@@ -4163,6 +4202,7 @@ waterDepth: number## FoliageField — class @experimental```+@internal app_: App | null@internal authoredWind_: Map<number, number>@internal built_: Map<number, BuiltFoliage>cellCount: number@@ -7097,6 +7137,27 @@ fingerprint: stringpending: PendingSystemEntry[]```+## ProceduralChunks — class @experimental+```+@internal progress_: () => { label: string; progress: number; owner: object; }[]+@internal sources_: () => ChunkSource[]+clear: () => void+has: (id: string) => boolean+pending: number+remove: (id: string) => void+set: <T>(id: string, def: ChunkLayer<T>) => void+stateAt: (id: string, x: number, z: number) => ChunkState | null+status: (id: string) => ChunkLayerStatus | null+step: (hasTime: () => boolean) => void+static new (): ProceduralChunks+static prototype: ProceduralChunks+```++## ProceduralChunksRes — const @experimental+```+ResourceDef<ProceduralChunks>+```+## ProceduralParams — interface @experimental```frequency: number@@ -12511,6 +12572,11 @@ MotionDriver<AnimatorBlend2DMotion>(): string[]```+## chunksOf — function @experimental+```+(app: App): ProceduralChunks+```+## clearAnimatorControllerStore — function @experimental```(): void@@ -15196,6 +15262,11 @@ StatsPlugin(world: World, entity: Entity): void```+## streamingSourcesOf — function @experimental+```+(app: App): ChunkSource[]+```+## studioPreviewReport — function @experimental```(entities: readonly EnvironmentLightEntity[], exists: (ref: string) => boolean): StudioPreviewReportdiff --git a/sdk/src/core-content.ts b/sdk/src/core-content.tsindex 464982390..f0991b43b 100644--- a/sdk/src/core-content.ts+++ b/sdk/src/core-content.ts@@ -348,6 +348,8 @@ export {type PrefabRoot,type WorldPartition,type CutWorld,+ ProceduralChunks, ProceduralChunksRes, chunksOf, streamingSourcesOf,+ type ChunkLayer, type ChunkSource, type ChunkState, type ChunkLayerStatus,} from './residency/index';export {diff --git a/sdk/src/foliage/foliagePlugin.ts b/sdk/src/foliage/foliagePlugin.tsindex 61d760201..f880aac12 100644--- a/sdk/src/foliage/foliagePlugin.ts+++ b/sdk/src/foliage/foliagePlugin.ts@@ -4,8 +4,10 @@* @file foliagePlugin.ts* @brief Grass and trees across an area, drawn a cell at a time and swaying in the wind.*- * @details The `Foliage` component says what grows where; this grows it. The entity stays as authored and the cells are its children,- * made when the scene runs (and in the editor's scene view) and made again when a field changes, so nothing is baked.+ * @details The `Foliage` component says what grows where; this grows it. The entity stays as authored and the cells are its children.+ * The cells are a layer of procedural chunks (residency/chunks.ts): grown round the streaming sources (or the eye) out to+ * `drawDistance`, nearest first within the frame's budget, let go with their meshes past it, and grown again when a field or+ * the ground changes, each old cell staying until its new one replaces it, so nothing is baked and nothing blinks out.* Each cell is a MeshRenderer with a LODGroup (see builder.ts for what each level is), so culling and the choice of level are* the engine's. If there is a Terrain, plants stand on it, avoid what is too steep and wait for it to be built.*/@@ -19,7 +21,7 @@ import {import { Assets } from '../asset/AssetPlugin';import type { MeshData } from '../asset/meshFormat';import { log } from '../util/logger';-import { bakesOf } from '../runtime/bakes';+import { chunksOf, ProceduralChunksRes, type ChunkLayerStatus } from '../residency/chunks';import type { Entity } from '../types';import { TerrainsRes } from '../terrain/terrainPlugin';import { Material } from '../render/material';@@ -109,18 +111,14 @@ export const Foliage: ComponentDef<FoliageData> = defineComponent<FoliageData>('interface BuiltFoliage {signature: string;data: FoliageData;- cells: Entity[];- handles: number[];- queue: [number, number][];source: MeshData | null;loading: boolean;epoch: number;- /** What the terrain was when this was grown. */- terrainRevision: number;- /** The cells to grow in all, for the progress shown while they are. */- total: number;}+/** One grown cell: its entity (none where nothing grew) and the meshes it owns. */+interface GrownCell { entity: Entity | null; handles: number[] }+/** The water, as foliage asks it (the water module is optional: read by name, not imported). */interface WaterQuery { depthAt(x: number, z: number, y: number): number | null; revision_: number; baking: boolean }@@ -129,8 +127,8 @@ function waterOf(app: App): WaterQuery | null {return w && typeof w.depthAt === 'function' ? w as WaterQuery : null;}-/** How long a frame may spend growing cells, in milliseconds; at least one is grown a frame. */-const CELL_BUDGET_MS = 5;+/** The chunk layer a Foliage's cells are. */+const layerOf = (entity: Entity): string => `foliage:${entity}`;/** Run-time facts about the foliage the plugin has grown. */export class FoliageField {@@ -138,19 +136,29 @@ export class FoliageField {/** @internal The u_windStrength each material had before the weather's wind scaled it, to put back. */readonly authoredWind_ = new Map<number, number>();- /** How many cells across every field are still waiting to be built. */+ /** @internal */ app_: App | null = null;++ /** How many cells near enough to be drawn, across every field, are still waiting to be grown. */get pending(): number {let n = 0;- for (const b of this.built_.values()) n += b.queue.length + (b.loading ? 1 : 0);+ for (const [entity, b] of this.built_) n += (this.statusOf_(entity)?.pending ?? 0) + (b.loading ? 1 : 0);return n;}- /** How many plants stand in the cells built so far, across every field. */+ /** How many cells are grown and standing now, across every field. */get cellCount(): number {let n = 0;- for (const b of this.built_.values()) n += b.cells.length;+ for (const entity of this.built_.keys()) {+ const s = this.statusOf_(entity);+ if (s) n += s.ready + s.stale;+ }return n;}++ private statusOf_(entity: Entity): ChunkLayerStatus | null {+ const app = this.app_;+ return app?.hasResource(ProceduralChunksRes) ? app.getResource(ProceduralChunksRes).status(layerOf(entity)) : null;+ }}/** The resource the plugin installs. @experimental */@@ -161,6 +169,7 @@ export class FoliagePlugin implements Plugin {build(app: App): void {const field = new FoliageField();+ field.app_ = app;app.insertResource(FoliageRes, field);app.addSystemToSchedule(Schedule.Update, defineSystem([], () => {@@ -168,37 +177,21 @@ export class FoliagePlugin implements Plugin {const terrains = app.hasResource(TerrainsRes) ? app.getResource(TerrainsRes) : null;this.sweep(app, field);this.blow(app, field);- // What stands on the ground waits for it: a plant placed before its terrain is read would stand on nothing.- if (terrains?.loading) return;- // Plants are grown again when the ground they stand on or the water they keep out of changes.+ // Plants are grown again when the ground they stand on or the water they keep out of changes, and wait while either is+ // being made: a plant placed before its terrain is read would stand on nothing.const water = waterOf(app);const revision = (terrains?.revision_ ?? 0) * 100003 + (water?.revision_ ?? 0);+ const waiting = !!terrains?.loading || !!water?.baking;for (const entity of app.world.getEntitiesWithComponents([Foliage, Transform])) {const data = app.world.get(entity, Foliage) as FoliageData;const signature = JSON.stringify(data);let built = field.built_.get(entity);- if (!built || built.signature !== signature || built.terrainRevision !== revision) {- if (built) this.destroy(app, built);- built = {- signature, data: { ...data }, cells: [], handles: [], queue: [], source: null, loading: true,- epoch: (built?.epoch ?? 0) + 1, terrainRevision: revision, total: 0,- };+ if (!built || built.signature !== signature) {+ built = { signature, data: { ...data }, source: null, loading: true, epoch: (built?.epoch ?? 0) + 1 };field.built_.set(entity, built);- void this.start(app, entity, built);- continue;- }- if (built.loading) continue;- // Plants stand on the ground: while a terrain's heights are still being made, growing them would be done again once they are.- const terrains = app.hasResource(TerrainsRes) ? app.getResource(TerrainsRes) : null;- if (terrains?.loading) continue;- if (water?.baking) continue;- const until = performance.now() + CELL_BUDGET_MS;- while (built.queue.length > 0) {- const [cx, cz] = built.queue.shift()!;- this.buildCell(app, entity, built, cx, cz);- if (performance.now() >= until) break;+ void this.start(app, built);}- bakesOf(app).mark(built, 'Growing the plants', built.total ? 1 - built.queue.length / built.total : 1);+ this.layer(app, entity, built, revision, waiting);}}, { name: 'FoliageSystem' }));}@@ -240,45 +233,68 @@ export class FoliagePlugin implements Plugin {cleanup(app?: App): void {if (!app?.hasResource(FoliageRes)) return;const field = app.getResource(FoliageRes);- for (const built of field.built_.values()) this.destroy(app, built);+ for (const entity of field.built_.keys()) {+ if (app.hasResource(ProceduralChunksRes)) app.getResource(ProceduralChunksRes).remove(layerOf(entity));+ }field.built_.clear();}- /** Reads the plant's geometry, if it has one, then queues the cells. */- private async start(app: App, entity: Entity, built: BuiltFoliage): Promise<void> {- const epoch = built.epoch;+ /** Reads the plant's geometry, if it has one; the cells wait for it. */+ private async start(app: App, built: BuiltFoliage): Promise<void> {const data = built.data;try {if (data.mesh) {- const source = await app.getResource(Assets).readMeshData(data.mesh);- if (built.epoch !== epoch) return;- built.source = source;- if (!source) log.warn('foliage', `the geometry of mesh ${data.mesh} cannot be read, so its plants are grass instead`);+ built.source = await app.getResource(Assets).readMeshData(data.mesh);+ if (!built.source) log.warn('foliage', `the geometry of mesh ${data.mesh} cannot be read, so its plants are grass instead`);}- if (!app.world.valid(entity)) return;- const cells = this.cellsAcross(data);- for (let cz = 0; cz < cells.z; cz++) for (let cx = 0; cx < cells.x; cx++) built.queue.push([cx, cz]);- built.total = built.queue.length;} catch (e) {log.error('foliage', 'growing the foliage failed', e);} finally {- if (built.epoch === epoch) built.loading = false;+ built.loading = false;}}+ /**+ * 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 {+ 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;+ const assets = app.getResource(Assets);+ chunksOf(app).set<GrownCell>(layerOf(entity), {+ label: 'Growing the plants',+ originX: t.worldPosition.x - data.sizeX / 2 * sx, originZ: t.worldPosition.z - data.sizeZ / 2 * sz,+ sizeX: data.sizeX / cells.x * sx, sizeZ: data.sizeZ / cells.z * sz,+ extent: [0, 0, cells.x, cells.z],+ loadRadius: data.drawDistance,+ unloadRadius: data.drawDistance + Math.max(1, data.cellSize) * 1.5,+ generation: `${built.epoch}:${revision}:${t.worldPosition.x}:${t.worldPosition.y}:${t.worldPosition.z}:${sx}:${sz}`,+ // Plants stand on the ground and keep out of the water: while either is still being made, they wait.+ make: (cx, cz) => (waiting || built.loading ? null : this.grow(app, entity, built, cx, cz)),+ publish: (_cx, _cz, cell) => { if (cell.entity !== null) app.world.setParent(cell.entity, entity); },+ release: (_cx, _cz, cell) => {+ if (cell.entity !== null && app.world.valid(cell.entity)) app.world.despawn(cell.entity);+ for (const handle of cell.handles) assets.releaseBuiltMesh(handle);+ },+ });+ }+private cellsAcross(data: FoliageData): { x: number; z: number } {const side = Math.max(1, data.cellSize);return { x: Math.min(200, Math.max(1, Math.ceil(data.sizeX / side))), z: Math.min(200, Math.max(1, Math.ceil(data.sizeZ / side))) };}- private buildCell(app: App, parent: Entity, built: BuiltFoliage, cx: number, cz: number): void {+ /** Grows cell (cx, cz): its plants, their meshes and the entity that draws them, not yet in the world (its parent is set on publishing). */+ private grow(app: App, parent: Entity, built: BuiltFoliage, cx: number, cz: number): GrownCell | null {const world = app.world;- if (!world.valid(parent)) return;+ if (!world.valid(parent)) return null;const data = built.data;const assets = app.getResource(Assets);const terrains = app.hasResource(TerrainsRes) ? app.getResource(TerrainsRes) : null;const t = world.tryGet(parent, Transform) as TransformData | null;- if (!t) return;+ if (!t) return null;const side = Math.max(1, data.cellSize);const cells = this.cellsAcross(data);// The cell's centre in the entity's own space, then in the world's (the ground is answered in the world's).@@ -306,7 +322,7 @@ export class FoliagePlugin implements Plugin {cellKey: cz * 1000 + cx, minScale: data.minScale, maxScale: data.maxScale, minUp: data.minUp,heightMin: data.heightMin, heightMax: data.heightMax,}, ground);- if (plants.length === 0) return;+ if (plants.length === 0) return { entity: null, handles: [] };// The cell stands at its centre, on the entity's own base height; the plants carry the ground's height relative to that.for (const p of plants) p.y -= t.worldPosition.y;@@ -329,11 +345,10 @@ export class FoliagePlugin implements Plugin {if (handle === 0) {log.warn('foliage', `the engine refused the geometry of cell ${cx},${cz}`);for (const h of handles) assets.releaseBuiltMesh(h);- return;+ throw new Error(`the engine refused the geometry of cell ${cx},${cz}`);}handles.push(handle);}- built.handles.push(...handles);const cell = world.spawn(`FoliageCell ${cx},${cz}`);world.insert(cell, Transform, { position: { x: localX, y: 0, z: localZ } });@@ -351,25 +366,13 @@ export class FoliagePlugin implements Plugin {lod1Size: sizeAt(data.lodDistance), lod2Size: 0, lod3Size: 0, cullSize: sizeAt(data.drawDistance), hysteresis: 0.1, enabled: true,});}- world.setParent(cell, parent);- built.cells.push(cell);- }-- private destroy(app: App, built: BuiltFoliage): void {- built.epoch++;- built.queue.length = 0;- bakesOf(app).clear(built);- const assets = app.hasResource(Assets) ? app.getResource(Assets) : null;- for (const cell of built.cells) if (app.world.valid(cell)) app.world.despawn(cell);- for (const handle of built.handles) assets?.releaseBuiltMesh(handle);- built.cells.length = 0;- built.handles.length = 0;+ return { entity: cell, handles };}private sweep(app: App, field: FoliageField): void {- for (const [entity, built] of field.built_) {+ for (const entity of field.built_.keys()) {if (app.world.valid(entity) && app.world.has(entity, Foliage)) continue;- this.destroy(app, built);+ if (app.hasResource(ProceduralChunksRes)) app.getResource(ProceduralChunksRes).remove(layerOf(entity));field.built_.delete(entity);}}diff --git a/sdk/src/residency/chunks.ts b/sdk/src/residency/chunks.tsnew file mode 100644index 000000000..470167bfe--- /dev/null+++ b/sdk/src/residency/chunks.ts@@ -0,0 +1,355 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file chunks.ts+ * @brief The one owner of procedural chunks: what is made round the streaming sources, in what order, within the frame's budget,+ * and when it is let go.+ *+ * @details A cooked world's cells are scenes, brought in by the WorldStreamer. What a game makes as it runs (the ground's collision+ * round what moves, plants round the eye, and later what stands in a biome) is chunks of layers, and this is the single+ * author of their lifetime, as the streamer is of cells. A layer says how it is cut, how far round its sources it is wanted+ * and how one chunk is made, published and released; the layer never decides on its own that a chunk exists.+ *+ * - Every frame the chunks within a layer's load radius of a source are wanted, nearest first across every layer; the+ * ones a source stands in are made at once, the rest while the frame's budget (Bakes) lasts.+ * - A chunk past every source's unload radius is released: whatever it published (meshes, colliders, entities) goes with+ * it, so a source walking for ever holds a bounded number of chunks.+ * - A layer's `generation` names its inputs. When it changes every chunk is made again; until a chunk's new version is+ * published its old one stays, so nothing standing on it falls, and an answer that arrives for an older generation (a+ * provider still working on the planet just left) is thrown away, never published.+ * - A chunk whose making throws is failed until the generation changes, and says why.+ */+import type { App } from '../app/app';+import { defineResource } from '../ecs/resource';+import { defineSystem, Schedule } from '../ecs/system';+import { Camera, Transform, type CameraData, type TransformData } from '../ecs/component';+import { EditorView, editorViewEye } from '../camera/EditorView';+import { WorldStreamingSource, type WorldStreamingSourceData } from './components';+import { bakesOf } from '../runtime/bakes';+import { log } from '../util/logger';++/** A place a layer is wanted round, on the ground plane, in world units. */+export interface ChunkSource { x: number; z: number }++/** One kind of chunk: how it is cut, where it is wanted and how it is made. */+export interface ChunkLayer<T> {+ /** What the layer is, for the progress shown while its chunks are made. */+ readonly label: string;+ /** The world position of chunk (0, 0)'s corner, and the side of a chunk along x and z. */+ originX: number;+ originZ: number;+ sizeX: number;+ sizeZ: number;+ /** The chunks there are, [x0, z0, x1, z1) in chunk coordinates; null for no end. */+ extent: readonly [number, number, number, number] | null;+ /** Chunks within this of a source are wanted; one is let go once past `unloadRadius` of every source. */+ loadRadius: number;+ unloadRadius: number;+ /** Names the layer's inputs: when it changes every chunk is made again, and answers for an older one are thrown away. */+ generation: number | string;+ /** Where the layer is wanted round; absent, the world's streaming sources (or the eye, where there are none). */+ sources?(): Iterable<ChunkSource>;+ /** Makes a chunk. Null is "not yet" (what it stands on is not ready) and is asked again later; a promise answers later. */+ make(cx: number, cz: number, signal: AbortSignal): T | null | Promise<T | null>;+ /** Puts a made chunk into the world. An older version of it, if one was published, has just been released. */+ publish(cx: number, cz: number, value: T): void;+ /** Takes a published chunk out of the world: everything it put there. */+ release(cx: number, cz: number, value: T): void;+}++/** Where one chunk stands: being made, published (for the layer's generation now, or an older one), or failed. */+export type ChunkState = 'making' | 'ready' | 'stale' | 'failed';++/** A layer's chunks, counted. */+export interface ChunkLayerStatus {+ /** Published for the generation now. */+ ready: number;+ /** Published for an older generation, waiting to be made again. */+ stale: number;+ /** Wanted and not published yet (including those being made). */+ pending: number;+ making: number;+ failed: number;+ /** Why the first failed chunk failed. */+ reason?: string;+}++interface Chunk<T> {+ cx: number;+ cz: number;+ /** What is published now, and for which generation. */+ value: T | null;+ publishedFor: number | string | null;+ /** Being made: for which generation, and how to stop it. */+ making: { generation: number | string; abort: AbortController } | null;+ failedFor: number | string | null;+ reason?: string;+}++interface Layer<T> {+ def: ChunkLayer<T>;+ chunks: Map<string, Chunk<T>>;+ /** The chunks within the load radius of a source, as of the last frame. */+ wanted: Set<string>;+}++/** At most this many chunks of a layer are answered later at once. */+const MAX_IN_FLIGHT = 8;++const keyOf = (cx: number, cz: number): string => `${cx},${cz}`;++/** The procedural chunks of every layer. Read {@link ProceduralChunks.status} for where they stand. */+export class ProceduralChunks {+ private readonly layers_ = new Map<string, Layer<unknown>>();+ /** @internal Set by the plugin: the world's own sources, sampled once a frame. */+ sources_: () => ChunkSource[] = () => [];++ /** Adds a layer under `id`, or takes the new definition of one already there (its chunks stay and follow the new generation). */+ set<T>(id: string, def: ChunkLayer<T>): void {+ const had = this.layers_.get(id);+ if (had) had.def = def as ChunkLayer<unknown>;+ else this.layers_.set(id, { def: def as ChunkLayer<unknown>, chunks: new Map(), wanted: new Set() });+ }++ /** Takes a layer away, releasing every chunk it published and stopping what is being made. */+ remove(id: string): void {+ const layer = this.layers_.get(id);+ if (!layer) return;+ for (const c of layer.chunks.values()) this.drop(layer, c);+ this.layers_.delete(id);+ }++ has(id: string): boolean {+ return this.layers_.has(id);+ }++ /** Where the chunk of layer `id` at world (x, z) stands, or null when it is not wanted, not made, or there is no such layer. */+ stateAt(id: string, x: number, z: number): ChunkState | null {+ const layer = this.layers_.get(id);+ if (!layer) return null;+ const d = layer.def;+ const c = layer.chunks.get(keyOf(Math.floor((x - d.originX) / d.sizeX), Math.floor((z - d.originZ) / d.sizeZ)));+ return c ? stateOf(c, d.generation) : null;+ }++ /** Layer `id`'s chunks counted, or null when there is no such layer. */+ status(id: string): ChunkLayerStatus | null {+ const layer = this.layers_.get(id);+ if (!layer) return null;+ const s: ChunkLayerStatus = { ready: 0, stale: 0, pending: pendingOf(layer), making: 0, failed: 0 };+ for (const c of layer.chunks.values()) {+ if (c.making) s.making++;+ if (stateOf(c, layer.def.generation) === 'failed') { s.failed++; s.reason ??= c.reason; }+ if (c.value !== null) { if (c.publishedFor === layer.def.generation) s.ready++; else s.stale++; }+ }+ return s;+ }++ /** How many chunks every layer still wants made. */+ get pending(): number {+ let n = 0;+ for (const layer of this.layers_.values()) n += pendingOf(layer);+ return n;+ }++ /** Lets go of every chunk of every layer. */+ clear(): void {+ for (const id of [...this.layers_.keys()]) this.remove(id);+ }++ /**+ * One frame: releases what no source is near, then makes what is wanted, nearest first across every layer, the chunks a source+ * stands in at once and the rest while `hasTime` says so.+ */+ step(hasTime: () => boolean): void {+ const world = this.sources_();+ const wanted: { layer: Layer<unknown>; cx: number; cz: number; dist: number }[] = [];+ for (const layer of this.layers_.values()) {+ const d = layer.def;+ const sources = d.sources ? [...d.sources()] : world;+ const near = new Map<string, number>();+ const keep = new Set<string>();+ for (const s of sources) {+ const reach = Math.max(d.loadRadius, d.unloadRadius);+ const x0 = Math.floor((s.x - reach - d.originX) / d.sizeX), x1 = Math.floor((s.x + reach - d.originX) / d.sizeX);+ const z0 = Math.floor((s.z - reach - d.originZ) / d.sizeZ), z1 = Math.floor((s.z + reach - d.originZ) / d.sizeZ);+ for (let cz = z0; cz <= z1; cz++) for (let cx = x0; cx <= x1; cx++) {+ if (d.extent && (cx < d.extent[0] || cz < d.extent[1] || cx >= d.extent[2] || cz >= d.extent[3])) continue;+ const mx = d.originX + cx * d.sizeX, mz = d.originZ + cz * d.sizeZ;+ const dist = Math.hypot(Math.max(mx - s.x, 0, s.x - mx - d.sizeX), Math.max(mz - s.z, 0, s.z - mz - d.sizeZ));+ const key = keyOf(cx, cz);+ if (dist <= d.unloadRadius) keep.add(key);+ if (dist <= d.loadRadius && dist < (near.get(key) ?? Infinity)) near.set(key, dist);+ }+ }+ for (const [key, c] of layer.chunks) {+ if (near.has(key) || keep.has(key)) continue;+ this.drop(layer, c);+ layer.chunks.delete(key);+ }+ layer.wanted = new Set(near.keys());+ for (const [key, dist] of near) {+ const c = layer.chunks.get(key);+ const state = c ? stateOf(c, d.generation) : null;+ if (state === 'ready' || state === 'failed' || c?.making) continue;+ const [cx, cz] = key.split(',').map(Number) as [number, number];+ wanted.push({ layer, cx, cz, dist });+ }+ }+ wanted.sort((a, b) => a.dist - b.dist);+ const inFlight = new Map<Layer<unknown>, number>();+ for (const layer of this.layers_.values()) {+ let n = 0;+ for (const c of layer.chunks.values()) if (c.making) n++;+ inFlight.set(layer, n);+ }+ for (const w of wanted) {+ if (w.dist > 0 && !hasTime()) break;+ if ((inFlight.get(w.layer) ?? 0) >= MAX_IN_FLIGHT) continue;+ if (this.make(w.layer, w.cx, w.cz)) inFlight.set(w.layer, (inFlight.get(w.layer) ?? 0) + 1);+ }+ }++ /** Makes one chunk; true when it is now being answered later. */+ private make(layer: Layer<unknown>, cx: number, cz: number): boolean {+ const key = keyOf(cx, cz);+ let c = layer.chunks.get(key);+ if (!c) {+ c = { cx, cz, value: null, publishedFor: null, making: null, failedFor: null };+ layer.chunks.set(key, c);+ }+ const chunk = c;+ const generation = layer.def.generation;+ const abort = new AbortController();+ let made: unknown;+ try {+ made = layer.def.make(cx, cz, abort.signal);+ } catch (e) {+ this.fail(layer, chunk, generation, e);+ return false;+ }+ if (!(made instanceof Promise)) {+ if (made !== null) this.publish(layer, chunk, made, generation);+ else if (chunk.value === null) layer.chunks.delete(key);+ return false;+ }+ chunk.making = { generation, abort };+ made.then((value) => {+ // Thrown away if the chunk was let go, made again, or the layer moved on while this was being made.+ if (chunk.making?.abort !== abort || abort.signal.aborted) return;+ chunk.making = null;+ if (layer.chunks.get(key) !== chunk || generation !== layer.def.generation) return;+ if (value !== null) this.publish(layer, chunk, value, generation);+ }, (e: unknown) => {+ if (chunk.making?.abort !== abort || abort.signal.aborted) return;+ chunk.making = null;+ if (generation === layer.def.generation) this.fail(layer, chunk, generation, e);+ });+ return true;+ }++ private publish(layer: Layer<unknown>, c: Chunk<unknown>, value: unknown, generation: number | string): void {+ if (c.value !== null) layer.def.release(c.cx, c.cz, c.value);+ c.value = value;+ c.publishedFor = generation;+ c.failedFor = null;+ c.reason = undefined;+ layer.def.publish(c.cx, c.cz, value);+ }++ private fail(layer: Layer<unknown>, c: Chunk<unknown>, generation: number | string, e: unknown): void {+ c.failedFor = generation;+ c.reason = e instanceof Error ? e.message : String(e);+ log.error('chunks', `making chunk ${c.cx},${c.cz} of ${layer.def.label} failed`, e);+ }++ /** Releases what a chunk published and stops what it is making. */+ private drop(layer: Layer<unknown>, c: Chunk<unknown>): void {+ c.making?.abort.abort();+ c.making = null;+ if (c.value !== null) layer.def.release(c.cx, c.cz, c.value);+ c.value = null;+ c.publishedFor = null;+ }++ /** @internal The labels and progress of the layers still making chunks, for the bakes list. */+ progress_(): { label: string; progress: number; owner: object }[] {+ const out: { label: string; progress: number; owner: object }[] = [];+ for (const layer of this.layers_.values()) {+ const pending = pendingOf(layer);+ if (pending === 0) continue;+ const ready = layer.wanted.size - pending;+ out.push({ label: layer.def.label, progress: ready / layer.wanted.size, owner: layer });+ }+ return out;+ }+}++/** The wanted chunks not yet published for the generation now (nor failed for it). */+function pendingOf(layer: Layer<unknown>): number {+ let n = 0;+ for (const key of layer.wanted) {+ const c = layer.chunks.get(key);+ const state = c ? stateOf(c, layer.def.generation) : null;+ if (state !== 'ready' && state !== 'failed') n++;+ }+ return n;+}++function stateOf(c: Chunk<unknown>, generation: number | string): ChunkState {+ if (c.failedFor === generation) return 'failed';+ if (c.value !== null) return c.publishedFor === generation ? 'ready' : 'stale';+ return 'making';+}++/** The resource; {@link chunksOf} installs it where it is missing. @experimental */+export const ProceduralChunksRes = defineResource<ProceduralChunks>(new ProceduralChunks(), 'ProceduralChunks');++/**+ * The places the world is wanted round: every enabled WorldStreamingSource and, when there is none, the editor's eye while it looks+ * at the scene in 3D, else the active cameras. The same sources the WorldStreamer reads cells by.+ */+export function streamingSourcesOf(app: App): ChunkSource[] {+ const world = app.world;+ world.ensureTransformsComposed();+ const out: ChunkSource[] = [];+ for (const e of world.getEntitiesWithComponents([WorldStreamingSource, Transform])) {+ if (!(world.get(e, WorldStreamingSource) as WorldStreamingSourceData).enabled) continue;+ const p = (world.get(e, Transform) as TransformData).worldPosition;+ out.push({ x: p.x, z: p.z });+ }+ if (out.length > 0) return out;+ if (app.hasResource(EditorView)) {+ const view = app.getResource(EditorView);+ if (view.active && view.perspective) {+ const eye = editorViewEye(view);+ return [{ x: eye.x, z: eye.z }];+ }+ }+ for (const e of world.getEntitiesWithComponents([Camera, Transform])) {+ if (!(world.get(e, Camera) as CameraData).isActive) continue;+ const p = (world.get(e, Transform) as TransformData).worldPosition;+ out.push({ x: p.x, z: p.z });+ }+ return out;+}++/** The App's procedural chunks, installed (with the system that steps them, after Update) on first use. */+export function chunksOf(app: App): ProceduralChunks {+ if (!app.hasResource(ProceduralChunksRes)) {+ const chunks = new ProceduralChunks();+ chunks.sources_ = () => streamingSourcesOf(app);+ app.insertResource(ProceduralChunksRes, chunks);+ const bakes = bakesOf(app);+ const shown = new Set<object>();+ app.addSystemToSchedule(Schedule.PostUpdate, defineSystem([], () => {+ chunks.step(() => bakes.hasTime());+ const now = new Set<object>();+ for (const p of chunks.progress_()) { bakes.mark(p.owner, p.label, p.progress); now.add(p.owner); }+ for (const owner of shown) if (!now.has(owner)) bakes.clear(owner);+ shown.clear();+ for (const owner of now) shown.add(owner);+ }, { name: 'ProceduralChunkSystem' }));+ }+ return app.getResource(ProceduralChunksRes);+}diff --git a/sdk/src/residency/index.ts b/sdk/src/residency/index.tsindex f5848f6b3..20236a05a 100644--- a/sdk/src/residency/index.ts+++ b/sdk/src/residency/index.ts@@ -29,3 +29,7 @@ export {prefabRootOf, resolvePrefabRoots, type CutWorld,} from './cutWorld';export { registryEntityFields } from './componentRefs';+export {+ ProceduralChunks, ProceduralChunksRes, chunksOf, streamingSourcesOf,+ type ChunkLayer, type ChunkSource, type ChunkState, type ChunkLayerStatus,+} from './chunks';diff --git a/sdk/src/runtime/bakes.ts b/sdk/src/runtime/bakes.tsindex 31952acfd..7adb6d6ee 100644--- a/sdk/src/runtime/bakes.ts+++ b/sdk/src/runtime/bakes.ts@@ -8,6 +8,10 @@* can say what for. So such work is a job: a generator that yields how far along it is, stepped each frame for as long as* the frame can spare. Every job running is listed with its label and progress, which the editor shows in its status bar* and a game can put on a loading screen.+ *+ * The frame's budget is one, and it is here: the jobs and the work stepped elsewhere (pages made, chunks of the world built)+ * spend the same milliseconds. The jobs run first each frame; when the rest could not finish the frame before, the jobs leave+ * them half of it.*/import type { App } from '../app/app';import { defineResource } from '../ecs/resource';@@ -32,8 +36,14 @@ interface Running {/** The jobs an App is running. Read {@link Bakes.active} for what to show. */export class Bakes {- /** How long, in milliseconds, the jobs may take of a frame between them. */+ /** How long, in milliseconds, all the work spread over frames may take of one frame between it. */budgetMs = 8;+ /** When this frame's budget runs out, on the clock `step` was given. */+ private deadline_ = -Infinity;+ private clock_: () => number = () => performance.now();+ /** Whether work stepped elsewhere ran out of time, this frame and the one before. */+ private starved_ = false;+ private starvedBefore_ = false;private readonly running_ = new Set<Running>();private readonly marks_ = new Map<object, { label: string; progress: number }>();@@ -71,10 +81,25 @@ export class Bakes {return out;}- /** Steps the jobs for the frame's budget, oldest first; a job that finishes or throws settles its promise. */+ /**+ * Whether work stepped elsewhere may go on this frame. Such work does what it must at once (what stands right by the player)+ * whatever this says, and stops when it says no; saying no is remembered, so the jobs leave it more of the next frame.+ */+ hasTime(): boolean {+ if (this.clock_() < this.deadline_) return true;+ this.starved_ = true;+ return false;+ }++ /** Starts the frame's budget and steps the jobs for their part of it, oldest first; a job that finishes or throws settles its promise. */step(now: () => number = () => performance.now()): void {+ this.clock_ = now;+ this.starvedBefore_ = this.starved_;+ this.starved_ = false;+ const start = now();+ this.deadline_ = start + this.budgetMs;if (this.running_.size === 0) return;- const end = now() + this.budgetMs;+ const end = start + (this.starvedBefore_ ? this.budgetMs / 2 : this.budgetMs);for (const r of [...this.running_]) {// Every job advances at least once a frame, so a long one cannot starve those behind it.do {diff --git a/sdk/src/terrain/terrainPlugin.ts b/sdk/src/terrain/terrainPlugin.tsindex b49ec3b86..de43b35ab 100644--- a/sdk/src/terrain/terrainPlugin.ts+++ b/sdk/src/terrain/terrainPlugin.ts@@ -42,8 +42,9 @@ import { levelRange, nodeKey, parentOf, selectNodes, type QuadtreeParams, type Timport { makePage, PageTable, PAGE_SIDE, PAGE_TEXELS, PATCH_CELLS, type PageImage } from './pages';import { noiseProvider, ProviderSource, terrainProvider, TerrainUnavailable } from './provider';import { buildPatchMesh } from './patch';-import { TerrainSurface, TILE_CELLS } from './surface';+import { TerrainSurface, TILE_CELLS, type SurfaceTile } from './surface';import { collisionGeometryOf } from '../runtime/collisionGeometry';+import { chunksOf, ProceduralChunksRes, type ChunkSource } from '../residency/chunks';import { CharacterController3D, RigidBody3D, type RigidBody3DData } from '../physics3d/Physics3DComponents';/** The engine's own provider of ground without end: seeded noise of the world's position. */@@ -176,13 +177,12 @@ export function paintWeights(h: number, ny: number, t: Pick<TerrainData, 'rockSl/** The side of the atlases the pages are kept in, in texels: 900 pages of 67 by 67. */const ATLAS_SIZE = 2048;-/** Collision tiles built a frame beyond the ones under something that moves, which are built at once. */-const TILE_BUDGET = 4;-+/** The chunk layer a terrain's collision is, and the key of one tile's piece of collision geometry. */+const collisionLayerOf = (entity: Entity): string => `terrain-collision:${entity}`;const tileKey = (entity: Entity, tx: number, tz: number): string => `terrain:${entity}:${tx}:${tz}`;-/** How long a frame may spend making pages, in milliseconds; at least one is made a frame while any is wanted. */-const PAGE_BUDGET_MS = 5;+/** Pages asked at once of a provider that answers later. */+const PAGES_IN_FLIGHT = 16;/** What the plugin knows about one terrain it has built. */interface Built {@@ -191,11 +191,6 @@ interface Built {source: TerrainSource | null;/** The triangles of the finest level, which queries and collision read. */surface: TerrainSurface | null;- /** The collision tiles built from this source, by key, and the settings they were built with. */- tiles: Set<string>;- /** Tiles of the ground this one replaced, kept until its own are built over them or nothing is near them. */- stale: Set<string>;- tileSettings: string;/** Bumped on every rebuild so an answer that arrives for an older one is thrown away. */epoch: number;loading: boolean;@@ -260,17 +255,14 @@ export class Terrains {/** Whether the ground under (x, z) is built for collision: what a game waits on before it drops something there. */collisionReadyAt(x: number, z: number): boolean {- const world = this.app_?.world;- if (!world) return false;+ const app = this.app_;+ if (!app?.hasResource(ProceduralChunksRes)) return false;+ const chunks = app.getResource(ProceduralChunksRes);for (const [entity, built] of this.built_) {- const surface = built.surface;- if (!surface || !world.valid(entity)) continue;- const t = world.tryGet(entity, Transform) as TransformData | null;- if (!t) continue;- const lx = x - t.worldPosition.x, lz = z - t.worldPosition.z;- if (!surface.covers(lx, lz)) continue;- const span = TILE_CELLS * surface.cell;- return built.tiles.has(tileKey(entity, Math.floor(lx / span), Math.floor(lz / span)));+ const t = app.world.valid(entity) ? app.world.tryGet(entity, Transform) as TransformData | null : null;+ if (!t || !built.surface?.covers(x - t.worldPosition.x, z - t.worldPosition.z)) continue;+ const state = chunks.stateAt(collisionLayerOf(entity), x, z);+ return state === 'ready' || state === 'stale';}return false;}@@ -310,6 +302,24 @@ function signatureOf(data: TerrainData): string {return JSON.stringify(shape);}+/** Where what collides with the ground is: every moving 3D body and every character. */+function movers(app: App): ChunkSource[] {+ const world = app.world;+ world.ensureTransformsComposed();+ const out: ChunkSource[] = [];+ for (const e of world.getEntitiesWithComponents([RigidBody3D, Transform])) {+ const body = world.get(e, RigidBody3D) as RigidBody3DData;+ if (!body.enabled || body.bodyType === 0) continue;+ const p = (world.get(e, Transform) as TransformData).worldPosition;+ out.push({ x: p.x, z: p.z });+ }+ for (const e of world.getEntitiesWithComponents([CharacterController3D, Transform])) {+ const p = (world.get(e, Transform) as TransformData).worldPosition;+ out.push({ x: p.x, z: p.z });+ }+ return out;+}+export class TerrainPlugin implements Plugin {name = 'terrain';@@ -330,11 +340,9 @@ export class TerrainPlugin implements Plugin {const signature = signatureOf(data);let built = terrains.built_.get(entity);if (!built || built.signature !== signature) {- // The old ground's collision tiles stay until the new ground's replace them, so nothing on it falls while it rebuilds.- const kept = built?.tiles ?? new Set<string>();if (built) this.destroy(app, built);built = {- signature, data: { ...data }, source: null, surface: null, tiles: new Set(), stale: kept, tileSettings: '', epoch: (built?.epoch ?? 0) + 1, loading: true, cancel: null,+ signature, data: { ...data }, source: null, surface: null, epoch: (built?.epoch ?? 0) + 1, loading: true, cancel: null,table: new PageTable(ATLAS_SIZE), heights: 0, paint: 0, mesh: 0, instance: 0,nodes: new Map(), spare: [], wanted: new Map(), asked: new Set(), pending: false, failure: null,};@@ -343,10 +351,8 @@ export class TerrainPlugin implements Plugin {continue;}built.data = { ...data };- if (built.failure) this.dropCollision(app, entity, built);- if (built.loading || !built.source) continue;this.collide(app, entity, built);- if (!rendering) continue;+ if (built.loading || !built.source || !rendering) continue;if (!built.instance) {if (!built.pending) void this.prepare(app, built);continue;@@ -360,7 +366,7 @@ export class TerrainPlugin implements Plugin {if (!app?.hasResource(TerrainsRes)) return;const terrains = app.getResource(TerrainsRes);for (const [entity, built] of terrains.built_) {- this.dropCollision(app, entity, built);+ if (app.hasResource(ProceduralChunksRes)) app.getResource(ProceduralChunksRes).remove(collisionLayerOf(entity));this.destroy(app, built);}terrains.built_.clear();@@ -484,80 +490,43 @@ export class TerrainPlugin implements Plugin {}/**- * Builds the collision tiles within `collisionDistance` of every moving 3D body and character, the ones under them at once and- * the rest a few a frame, nearest first; lets go of tiles nothing has come within a tile of that distance.+ * The terrain's collision as a layer of procedural chunks: a tile within `collisionDistance` of every moving 3D body and character,+ * made when one comes near, let go when none is, and made again (the old tile kept till then) when the ground changes.*/private collide(app: App, entity: Entity, built: Built): void {- const d = built.data, surface = built.surface;- if (!d.collision || !surface) { this.dropCollision(app, entity, built); return; }- const geometry = collisionGeometryOf(app);- // Where things are now, not where they were when transforms were last composed: O(1) when nothing moved.- app.world.ensureTransformsComposed();- const t = app.world.get(entity, Transform) as TransformData;- const at = t.worldPosition;- // A tile is placed where the terrain was when it was built: moving the terrain, or another layer or friction, builds them again.- const settings = `${d.collisionLayer}:${d.friction}:${at.x}:${at.y}:${at.z}`;- if (settings !== built.tileSettings) {- for (const k of built.tiles) built.stale.add(k);- built.tiles.clear();- built.tileSettings = settings;- }- const span = TILE_CELLS * surface.cell, reach = Math.max(d.collisionDistance, 0), keep = reach + span;- const bounds = surface.source.bounds;- const near = new Map<string, { tx: number; tz: number; dist: number }>();- const visit = (x: number, z: number): void => {- const lx = x - at.x, lz = z - at.z;- for (let tz = Math.floor((lz - keep) / span); tz <= Math.floor((lz + keep) / span); tz++) {- for (let tx = Math.floor((lx - keep) / span); tx <= Math.floor((lx + keep) / span); tx++) {- const x0 = tx * span, z0 = tz * span;- if (bounds && (x0 >= bounds[2] || z0 >= bounds[3] || x0 + span <= bounds[0] || z0 + span <= bounds[1])) continue;- const dist = Math.hypot(Math.max(x0 - lx, 0, lx - x0 - span), Math.max(z0 - lz, 0, lz - z0 - span));- if (dist > keep) continue;- const key = tileKey(entity, tx, tz);- const had = near.get(key);- if (!had || dist < had.dist) near.set(key, { tx, tz, dist });- }- }- };- for (const e of app.world.getEntitiesWithComponents([RigidBody3D, Transform])) {- const body = app.world.get(e, RigidBody3D) as RigidBody3DData;- if (!body.enabled || body.bodyType === 0) continue;- const p = (app.world.get(e, Transform) as TransformData).worldPosition;- visit(p.x, p.z);- }- for (const e of app.world.getEntitiesWithComponents([CharacterController3D, Transform])) {- const p = (app.world.get(e, Transform) as TransformData).worldPosition;- visit(p.x, p.z);- }-- const missing = [...near].filter(([key, n]) => n.dist <= reach && !built.tiles.has(key)).sort((a, b) => a[1].dist - b[1].dist);- let budget = TILE_BUDGET;- for (const [key, n] of missing) {- if (n.dist > 0 && budget <= 0) break;- const tile = surface.tile(n.tx, n.tz);- // A provider that answers later has been asked for the samples; the tile is built once they are in.- if (!tile) continue;- if (n.dist > 0) budget--;- geometry.set(key, {- owner: entity, origin: [at.x + tile.x0, at.y, at.z + tile.z0], positions: tile.positions, indices: tile.indices,- friction: d.friction, restitution: 0, layer: d.collisionLayer,- });- built.tiles.add(key);- built.stale.delete(key);+ const id = collisionLayerOf(entity);+ const d = built.data;+ if (!d.collision || built.failure) {+ if (app.hasResource(ProceduralChunksRes)) app.getResource(ProceduralChunksRes).remove(id);+ return;}- for (const key of built.tiles) if (!near.has(key)) { geometry.delete(key); built.tiles.delete(key); }- for (const key of built.stale) if (!near.has(key)) { geometry.delete(key); built.stale.delete(key); }- }-- /** Takes a terrain's collision tiles out of the world, its own and those of the ground it replaced. */- private dropCollision(app: App, entity: Entity, built: Built): void {- if (built.tiles.size === 0 && built.stale.size === 0) return;+ const chunks = chunksOf(app);+ const at = (app.world.get(entity, Transform) as TransformData).worldPosition;+ const cell = Math.max(d.cellSize, 1e-3), span = TILE_CELLS * cell;+ const bounds = built.source?.bounds ?? (d.extent === TerrainExtent.Area ? [-d.sizeX / 2, -d.sizeZ / 2, d.sizeX / 2, d.sizeZ / 2] : null);const geometry = collisionGeometryOf(app);- for (const key of built.tiles) geometry.delete(key);- for (const key of built.stale) geometry.delete(key);- built.tiles.clear();- built.stale.clear();- built.tileSettings = '';+ chunks.set<{ key: string; tile: SurfaceTile }>(id, {+ label: 'Building the ground\'s collision',+ originX: at.x, originZ: at.z, sizeX: span, sizeZ: span,+ extent: bounds && [Math.floor(bounds[0] / span), Math.floor(bounds[1] / span), Math.ceil(bounds[2] / span), Math.ceil(bounds[3] / span)],+ loadRadius: Math.max(d.collisionDistance, 0),+ unloadRadius: Math.max(d.collisionDistance, 0) + span,+ // The ground (rebuilt under a new epoch), where it stands, and the layer and friction its tiles were made with.+ generation: `${built.epoch}:${at.x}:${at.y}:${at.z}:${d.collisionLayer}:${d.friction}`,+ sources: () => movers(app),+ make: (tx, tz) => {+ // The ground is not known yet (still loading, or a provider still answering): asked again next frame.+ const tile = built.surface?.tile(tx, tz);+ return tile ? { key: tileKey(entity, tx, tz), tile } : null;+ },+ publish: (_tx, _tz, { key, tile }) => {+ geometry.set(key, {+ owner: entity, origin: [at.x + tile.x0, at.y, at.z + tile.z0], positions: tile.positions, indices: tile.indices,+ friction: d.friction, restitution: 0, layer: d.collisionLayer,+ });+ },+ release: (_tx, _tz, { key }) => geometry.delete(key),+ });}/** Where the eye is, in the terrain's space: the active camera, or the editor's own eye while it looks at the scene in 3D. */@@ -644,7 +613,6 @@ export class TerrainPlugin implements Plugin {if (built.wanted.size === 0) { bakes.mark(built, 'Building the terrain', 1); return; }const order = [...built.wanted.values()].sort((a, b) => b.level - a.level|| Math.hypot(a.x0 + a.size / 2 - eye[0], a.z0 + a.size / 2 - eye[2]) - Math.hypot(b.x0 + b.size / 2 - eye[0], b.z0 + b.size / 2 - eye[2]));- const until = performance.now() + PAGE_BUDGET_MS;let made = 0;const store = (key: string, image: PageImage): boolean => {const page = built.table.claim(key, image.min, image.max);@@ -658,6 +626,7 @@ export class TerrainPlugin implements Plugin {for (const node of order) {const key = nodeKey(node.level, node.ix, node.iz);if (built.asked.has(key)) continue;+ if (source.region && built.asked.size >= PAGES_IN_FLIGHT) break;const image = makePage(source, node.x0, node.z0, node.size);if (image instanceof Promise) {// A provider answering later: its page is stored when it lands, if the terrain is still the one that asked.@@ -674,7 +643,8 @@ export class TerrainPlugin implements Plugin {if (!store(key, image)) break;built.wanted.delete(key);made++;- if (performance.now() >= until) break;+ // The frame's one budget, shared with the bakes and the chunks of the world; at least one page a frame.+ if (!bakes.hasTime()) break;}bakes.mark(built, 'Building the terrain', made === 0 ? 0 : 1 - built.wanted.size / (built.wanted.size + made));}@@ -748,7 +718,7 @@ export class TerrainPlugin implements Plugin {private sweep(app: App, terrains: Terrains): void {for (const [entity, built] of terrains.built_) {if (app.world.valid(entity) && app.world.has(entity, Terrain)) continue;- this.dropCollision(app, entity, built);+ chunksOf(app).remove(collisionLayerOf(entity));this.destroy(app, built);terrains.built_.delete(entity);terrains.revision_++;diff --git a/sdk/tests/procedural-chunks.test.ts b/sdk/tests/procedural-chunks.test.tsnew file mode 100644index 000000000..cc1885d96--- /dev/null+++ b/sdk/tests/procedural-chunks.test.ts@@ -0,0 +1,175 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file Procedural chunks have one owner: made round the sources within the frame's budget, let go past them, and never published+ * for inputs that are gone.+ */+import { describe, expect, it } from 'vitest';+import { ProceduralChunks, type ChunkLayer, type ChunkSource } from '../src/residency/chunks';+import { Bakes } from '../src/runtime/bakes';++/** A layer that records what it was asked, and what is in the world because of it. */+function recording(over: Partial<ChunkLayer<string>> = {}) {+ const live = new Map<string, string>();+ const log = { made: [] as string[], published: [] as string[], released: [] as string[] };+ const layer: ChunkLayer<string> = {+ label: 'test', originX: 0, originZ: 0, sizeX: 10, sizeZ: 10, extent: null,+ loadRadius: 25, unloadRadius: 40, generation: 1,+ make: (cx, cz) => { log.made.push(`${cx},${cz}`); return `${cx},${cz}@${layer.generation}`; },+ publish: (cx, cz, v) => {+ const key = `${cx},${cz}`;+ // Never two versions of one chunk in the world.+ expect(live.has(key)).toBe(false);+ live.set(key, v);+ log.published.push(v);+ },+ release: (cx, cz, v) => {+ expect(live.get(`${cx},${cz}`)).toBe(v);+ live.delete(`${cx},${cz}`);+ log.released.push(v);+ },+ ...over,+ };+ return { layer, live, log };+}++const always = () => true;++describe('procedural chunks', () => {+ it('hold a bounded number of chunks for a source walking for ever, and make none twice on the way back within the band', () => {+ const chunks = new ProceduralChunks();+ let at: ChunkSource = { x: 0, z: 0 };+ chunks.sources_ = () => [at];+ const { layer, live, log } = recording();+ chunks.set('l', layer);+ let most = 0;+ for (let x = 0; x <= 5000; x += 3) {+ at = { x, z: 0 };+ chunks.step(always);+ most = Math.max(most, live.size);+ }+ // Within the unload radius of one source: (2 * 40 / 10 + 2) squared at most.+ expect(most).toBeLessThanOrEqual(100);+ expect(live.size).toBeGreaterThan(0);+ const before = log.made.length;+ // A step back and forth inside the band makes nothing new.+ for (const x of [4990, 4985, 4995, 5000]) { at = { x, z: 0 }; chunks.step(always); }+ expect(log.made.length).toBe(before);+ });++ it('make the chunk a source stands in at once, and the rest nearest first while there is time', () => {+ const chunks = new ProceduralChunks();+ chunks.sources_ = () => [{ x: 5, z: 5 }];+ const { layer, log } = recording();+ chunks.set('l', layer);+ chunks.step(() => false);+ expect(log.made).toEqual(['0,0']);+ let budget = 3;+ chunks.step(() => budget-- > 0);+ // Neighbours across an edge before those across a corner.+ expect(log.made.slice(1, 5).every((k) => ['1,0', '-1,0', '0,1', '0,-1'].includes(k))).toBe(true);+ expect(chunks.status('l')!.pending).toBeGreaterThan(0);+ });++ it('keep a chunk\'s old version in the world until its new one replaces it', () => {+ const chunks = new ProceduralChunks();+ chunks.sources_ = () => [{ x: 5, z: 5 }];+ const { layer, live } = recording();+ chunks.set('l', layer);+ chunks.step(always);+ const count = live.size;+ layer.generation = 2;+ chunks.step(() => false);+ // Only the chunk under the source was made again; every other one still stands, old.+ expect(live.size).toBe(count);+ expect(live.get('0,0')).toBe('0,0@2');+ expect(chunks.stateAt('l', 15, 5)).toBe('stale');+ chunks.step(always);+ expect([...live.values()].every((v) => v.endsWith('@2'))).toBe(true);+ expect(chunks.status('l')).toMatchObject({ ready: count, stale: 0, pending: 0 });+ });++ it('throw away an answer for inputs that are gone, and stop what a source has left', async () => {+ const chunks = new ProceduralChunks();+ let at: ChunkSource = { x: 5, z: 5 };+ chunks.sources_ = () => [at];+ const answers: { cx: number; resolve: (v: string) => void; signal: AbortSignal; generation: number | string }[] = [];+ const { layer, live } = recording({ loadRadius: 0, unloadRadius: 0 });+ layer.make = (cx, _cz, signal) => new Promise((resolve) => answers.push({ cx, resolve, signal, generation: layer.generation }));+ chunks.set('l', layer);+ chunks.step(always);+ expect(answers).toHaveLength(1);+ // Teleported to another world: the old world's answer must not land in this one.+ layer.generation = 'planet-b';+ at = { x: 1005, z: 5 };+ chunks.step(always);+ expect(answers[0]!.signal.aborted).toBe(true);+ answers[0]!.resolve('old');+ await Promise.resolve();+ expect(live.size).toBe(0);+ expect(answers).toHaveLength(2);+ answers[1]!.resolve('new');+ await Promise.resolve();+ expect([...live.values()]).toEqual(['new']);+ expect(chunks.stateAt('l', 1005, 5)).toBe('ready');+ });++ it('say why a chunk failed, and try it again once the inputs change', () => {+ const chunks = new ProceduralChunks();+ chunks.sources_ = () => [{ x: 5, z: 5 }];+ let broken = true;+ const { layer } = recording({ loadRadius: 0, unloadRadius: 0 });+ const make = layer.make;+ layer.make = (cx, cz, s) => { if (broken) throw new Error('no ground here'); return make(cx, cz, s); };+ chunks.set('l', layer);+ chunks.step(always);+ chunks.step(always);+ expect(chunks.status('l')).toMatchObject({ failed: 1, reason: 'no ground here' });+ broken = false;+ layer.generation = 2;+ chunks.step(always);+ expect(chunks.stateAt('l', 5, 5)).toBe('ready');+ });++ it('release everything a layer published when the layer goes, and keep within its extent', () => {+ const chunks = new ProceduralChunks();+ chunks.sources_ = () => [{ x: 0, z: 0 }];+ const { layer, live } = recording({ extent: [0, 0, 2, 2] });+ chunks.set('l', layer);+ chunks.step(always);+ expect([...live.keys()].sort()).toEqual(['0,0', '0,1', '1,0', '1,1']);+ chunks.remove('l');+ expect(live.size).toBe(0);+ });++ it('follow a layer\'s own sources when it names them, and want nothing where there are none', () => {+ const chunks = new ProceduralChunks();+ chunks.sources_ = () => [{ x: 0, z: 0 }];+ let movers: ChunkSource[] = [];+ const { layer, live } = recording({ loadRadius: 0, unloadRadius: 0, sources: () => movers });+ chunks.set('l', layer);+ chunks.step(always);+ expect(live.size).toBe(0);+ movers = [{ x: 55, z: -5 }];+ chunks.step(always);+ expect([...live.keys()]).toEqual(['5,-1']);+ });+});++describe('the frame\'s one budget', () => {+ it('is shared: work stepped elsewhere that ran short gets half of the next frame from the jobs', () => {+ const bakes = new Bakes();+ bakes.budgetMs = 10;+ let t = 0;+ const clock = () => t;+ let steps = 0;+ bakes.run('long', (function* () { for (;;) { t += 1; steps++; yield 0; } })());+ bakes.step(clock);+ expect(steps).toBe(10);+ expect(bakes.hasTime()).toBe(false);+ steps = 0;+ bakes.step(clock);+ expect(steps).toBe(5);+ expect(bakes.hasTime()).toBe(true);+ });+});diff --git a/tools/check-gizmo-coverage.mjs b/tools/check-gizmo-coverage.mjsindex b0f070974..125bf916d 100644--- a/tools/check-gizmo-coverage.mjs+++ b/tools/check-gizmo-coverage.mjs@@ -119,6 +119,7 @@ const DISPOSITION = {'Foliage.sizeZ': ['owed', 'the area plants grow in is not outlined in the viewport yet'],'Terrain.cellSize': ['no-place', 'the finest cell of the ground\'s mesh near the eye, not a region of the entity'],'Terrain.drawDistance': ['no-place', 'how far from the eye ground without end is drawn, not a region of the entity'],+ 'Terrain.collisionDistance': ['no-place', 'how far round each moving body the ground is built for collision, not a region of the entity'],'Foliage.cellSize': ['no-place', 'the square the area is cut into for drawing, not a region of the entity'],'Foliage.bladeWidth': ['renders', 'the blades drawn at it are the picture'],'Foliage.bladeHeight': ['renders', 'the blades drawn at it are the picture'],diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex 7f969b31f..13930d438 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -2768,4 +2768,6 @@ export const NOTED = {{"note":"Terrain collision, the same ground that is drawn."},"fix(editor): the running game has a resolution picker you can actually reach":{"note":"The running game's resolution can be chosen."},+ "feat(residency): procedural chunks have one owner and the frame one budget; terrain collision and foliage cells are chunk layers":+ {"note":"Procedural chunks, with one owner and one budget."},};