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(terrain): tiled ground is sculpted and painted on the tiles in memory, a changed tile stays until it is saved, and a save writes only what changed
yhh6a9cfb10db4d
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3f7a340ad..28bac31fc 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,7 +16,8 @@ published separately; it ships inside the editor.### Added-- **A terrain can be kept as tiles that are read where they are looked at.** A Terrain's `tiles` names a `.esterrain`: the ground cut into tiles of 513 samples a side and a low-detail overview. Distant ground is drawn from the overview, which is always in memory; full-detail tiles are read near where the view or a moving body is, and the least recently used are let go past 256 MiB. Measured in the editor on a 4096-unit area: an 8193 by 8193 field held as one image is 256 MiB, as tiles it opened holding 36 MiB and 45 MiB close to the ground. **Split into Tiles** in the terrain sculpt panel converts a terrain; tiled ground cannot be sculpted yet. The tile images are referenced only by the `.esterrain`, so they are no longer preloaded and uploaded as textures the way a `heightmap` is. The editor now also waits for ground still being built before it counts itself idle.+- **Tiled terrain can be sculpted and painted, and a save writes only what changed.** A brush on tiled ground runs on the samples copied out of the tiles under it and writes them back to every tile that holds them, so a seam stays one height and the result is the same as on one heightfield, sample for sample. Only tiles in memory are edited: a dab over one not read yet is skipped and the tile is read. A changed tile is kept in memory past the budget until it is saved, the overview follows each stroke so distant ground shows it, and undo covers the tiles and the overview. **Save Ground** writes the changed tiles and the overview only: six dabs on a 4097 by 4097 terrain wrote 2 of its 64 tiles.+- **A terrain can be kept as tiles that are read where they are looked at.** A Terrain's `tiles` names a `.esterrain`: the ground cut into tiles of 513 samples a side and a low-detail overview. Distant ground is drawn from the overview, which is always in memory; full-detail tiles are read near where the view or a moving body is, and the least recently used are let go past 256 MiB. Measured in the editor on a 4096-unit area: an 8193 by 8193 field held as one image is 256 MiB, as tiles it opened holding 36 MiB and 45 MiB close to the ground. **Split into Tiles** in the terrain sculpt panel converts a terrain. The tile images are referenced only by the `.esterrain`, so they are no longer preloaded and uploaded as textures the way a `heightmap` is. The editor now also waits for ground still being built before it counts itself idle.- **A streamed world opens in the editor without its cells.** Only its `WorldPersistent` entities are in the view when a scene with `StreamedWorld` opens, and the textures and meshes of the rest are not loaded. The World panel loads and unloads cells one at a time or all at once, the viewport marks the loaded ones, and the next session opens with the same cells loaded. The document still holds every entity: an unloaded cell is saved as it is, and Play and export see the whole world. The `get_world_cells` and `set_world_cells_loaded` tools do the same for an agent.- **Hands that hold things.** A `GripPose` holds a rig's hands in a named pose: `pistol`, `handle`, `cup`, `fist` and others, or one a game registers. A pose says how far each finger bends and nothing about bones, so it fits any rig with fingers; a change of pose eases over, a trigger moves the index finger alone, and it goes over what a clip does with the fingers by its weight.- **Clouds that keep time with the game.** Where a Sky Atmosphere's clouds are is now what the wind has done so far, so a wind that changes carries them on instead of moving the whole sky; a Weather's wind reaches them, their shapes change as they go, and a paused game has a still sky. They can have a second layer with its own height, grain and wind, and `skyClockState()` keeps their place in a save. Self-shadowing reaches through a deep cloud, edges wear into billows, and the lit edge near the sun is narrower.diff --git a/desktop b/desktopindex 649b1cd6e..15407e866 160000--- a/desktop+++ b/desktop@@ -1 +1 @@-Subproject commit 649b1cd6e5dac86176bc3d9faf2c55b3125f48ae+Subproject commit 15407e866c14e92cf75b77d86d66d596ff86e7d7diff --git a/docs/astro/src/content/docs/graphics/terrain.mdx b/docs/astro/src/content/docs/graphics/terrain.mdxindex bed3ec29d..892402ba0 100644--- a/docs/astro/src/content/docs/graphics/terrain.mdx+++ b/docs/astro/src/content/docs/graphics/terrain.mdx@@ -339,7 +339,9 @@ A heightmap is read whole: an 8193 by 8193 field is about 256 MiB. Point `tiles`- Distant ground is drawn from the overview, which is always in memory.- Full-detail tiles are read only near the view or a moving body, and past 256 MiB the least recently used are let go. Where no tile hasbeen read yet the height is not known, and collision and queries wait for it.-- **Split into Tiles** in the terrain sculpt panel converts a terrain. Tiled ground cannot be sculpted yet.+- **Split into Tiles** in the terrain sculpt panel converts a terrain.+- Tiled ground is sculpted and painted like any other, on the tiles in memory: a dab over a tile not read yet is skipped and the tile+ is read. A changed tile stays in memory until it is saved, and a save writes the changed tiles and the overview only.- The tile images are named only by the `.esterrain`, so they are not preloaded and uploaded as textures the way a `heightmap` is.Measured in the editor on a 4096-unit area: an 8193 by 8193 field opened as tiles holds 36 MiB, and 45 MiB close to the ground.diff --git a/docs/astro/src/content/docs/zh-cn/graphics/terrain.mdx b/docs/astro/src/content/docs/zh-cn/graphics/terrain.mdxindex 4ac7b5344..6653776fa 100644--- a/docs/astro/src/content/docs/zh-cn/graphics/terrain.mdx+++ b/docs/astro/src/content/docs/zh-cn/graphics/terrain.mdx@@ -261,7 +261,8 @@ registerPlanetProvider({- 远处的地面从总览图画,总览图一直在内存里。- 视点或运动物体附近才读精细分块;超过 256 MiB 时先放掉最久没用的块。还没读到的地方高度暂时未知,碰撞和查询会等它读到后再算。-- 在地形雕刻面板里点 **拆分为分块**,就能把现有地形转换过去。转换后暂时还不能雕刻。+- 在地形雕刻面板里点 **拆分为分块**,就能把现有地形转换过去。+- 分块地形照样能雕刻和绘制,但只改已加载的分块:笔刷底下有块还没读到,这一笔就跳过并去读它。改过的块在保存前不会被放掉,保存只写改过的块和总览图。- 分块图只经 `.esterrain` 引用,不会像 `heightmap` 那样在打开场景时作为贴图预载、上传。编辑器里实测(4096 单位见方):8193×8193 的地面按分块打开时占 36 MiB,贴近地面时占 45 MiB。diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.jsonindex af2be8411..9b88191a2 100644--- a/docs/astro/src/data/apiStability.generated.json+++ b/docs/astro/src/data/apiStability.generated.json@@ -3,10 +3,10 @@"counts": {"public": 115,"beta": 178,- "experimental": 2988,+ "experimental": 2991,"deprecated": 3},- "total": 3281,+ "total": 3284,"subsystems": [{"id": "mobile-controls",diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex f8fadeb27..5c625d2e4 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -11478,7 +11478,7 @@ collisionReadyAt: (x: number, z: number) => booleandeleteModifier: (id: string) => voidfindPath: (from: { x: number; z: number; }, to: { x: number; z: number; }, options?: ReachOptions) => ReachResultgroundData: () => GroundData | null-groundEdit: (entity: Entity) => GroundEdit | null+groundEdit: (entity: Entity) => GroundEdit | TiledGroundEdit | nullgroundKnownAt: (x: number, z: number) => booleanheightAt: (x: number, z: number) => number | nullheightBeneathAt: (x: number, z: number) => number | null@@ -11912,6 +11912,16 @@ title: number## TiledSource — class @experimental```+@internal dirtyTiles: () => string[]+@internal ensureTileSplats: (tile: Tile, tx: number, tz: number, second: boolean) => void+@internal hasTile: (tx: number, tz: number) => boolean+@internal markDirty: (tx: number, tz: number) => void+@internal markOverviewDirty: () => void+@internal markSaved: () => void+@internal overviewDirty: boolean+@internal overviewSplats: (make: boolean, second: boolean) => { a: Splat | null; b: Splat | null; }+@internal readTile: (tx: number, tz: number) => Promise<Tile | null>+@internal tileAt: (tx: number, tz: number) => Tile | undefinedbounds: readonly [number, number, number, number]budget: numberdoc: TerrainTilesDocument@@ -11920,6 +11930,7 @@ infinite: falsemaxHeight: numberminHeight: 0normal: (x: number, z: number) => [number, number, number] | null+overview: HeightfieldoverviewBytes: numberoverviewSpacing: numberpaint: (x: number, z: number, h: number, ny: number) => LayerWeightsdiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex a56fa7443..d853623b6 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -11694,7 +11694,7 @@ collisionReadyAt: (x: number, z: number) => booleandeleteModifier: (id: string) => voidfindPath: (from: { x: number; z: number; }, to: { x: number; z: number; }, options?: ReachOptions) => ReachResultgroundData: () => GroundData | null-groundEdit: (entity: Entity) => GroundEdit | null+groundEdit: (entity: Entity) => GroundEdit | TiledGroundEdit | nullgroundKnownAt: (x: number, z: number) => booleanheightAt: (x: number, z: number) => number | nullheightBeneathAt: (x: number, z: number) => number | null@@ -12128,6 +12128,16 @@ title: number## TiledSource — class @experimental```+@internal dirtyTiles: () => string[]+@internal ensureTileSplats: (tile: Tile, tx: number, tz: number, second: boolean) => void+@internal hasTile: (tx: number, tz: number) => boolean+@internal markDirty: (tx: number, tz: number) => void+@internal markOverviewDirty: () => void+@internal markSaved: () => void+@internal overviewDirty: boolean+@internal overviewSplats: (make: boolean, second: boolean) => { a: Splat | null; b: Splat | null; }+@internal readTile: (tx: number, tz: number) => Promise<Tile | null>+@internal tileAt: (tx: number, tz: number) => Tile | undefinedbounds: readonly [number, number, number, number]budget: numberdoc: TerrainTilesDocument@@ -12136,6 +12146,7 @@ infinite: falsemaxHeight: numberminHeight: 0normal: (x: number, z: number) => [number, number, number] | null+overview: HeightfieldoverviewBytes: numberoverviewSpacing: numberpaint: (x: number, z: number, h: number, ny: number) => LayerWeightsdiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex 7f402230e..f5945e54c 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -11473,7 +11473,7 @@ collisionReadyAt: (x: number, z: number) => booleandeleteModifier: (id: string) => voidfindPath: (from: { x: number; z: number; }, to: { x: number; z: number; }, options?: ReachOptions) => ReachResultgroundData: () => GroundData | null-groundEdit: (entity: Entity) => GroundEdit | null+groundEdit: (entity: Entity) => GroundEdit | TiledGroundEdit | nullgroundKnownAt: (x: number, z: number) => booleanheightAt: (x: number, z: number) => number | nullheightBeneathAt: (x: number, z: number) => number | null@@ -11907,6 +11907,16 @@ title: number## TiledSource — class @experimental```+@internal dirtyTiles: () => string[]+@internal ensureTileSplats: (tile: Tile, tx: number, tz: number, second: boolean) => void+@internal hasTile: (tx: number, tz: number) => boolean+@internal markDirty: (tx: number, tz: number) => void+@internal markOverviewDirty: () => void+@internal markSaved: () => void+@internal overviewDirty: boolean+@internal overviewSplats: (make: boolean, second: boolean) => { a: Splat | null; b: Splat | null; }+@internal readTile: (tx: number, tz: number) => Promise<Tile | null>+@internal tileAt: (tx: number, tz: number) => Tile | undefinedbounds: readonly [number, number, number, number]budget: numberdoc: TerrainTilesDocument@@ -11915,6 +11925,7 @@ infinite: falsemaxHeight: numberminHeight: 0normal: (x: number, z: number) => [number, number, number] | null+overview: HeightfieldoverviewBytes: numberoverviewSpacing: numberpaint: (x: number, z: number, h: number, ny: number) => LayerWeightsdiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex b22feda2d..74855b76f 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -11769,7 +11769,7 @@ collisionReadyAt: (x: number, z: number) => booleandeleteModifier: (id: string) => voidfindPath: (from: { x: number; z: number; }, to: { x: number; z: number; }, options?: ReachOptions) => ReachResultgroundData: () => GroundData | null-groundEdit: (entity: Entity) => GroundEdit | null+groundEdit: (entity: Entity) => GroundEdit | TiledGroundEdit | nullgroundKnownAt: (x: number, z: number) => booleanheightAt: (x: number, z: number) => number | nullheightBeneathAt: (x: number, z: number) => number | null@@ -12203,6 +12203,16 @@ title: number## TiledSource — class @experimental```+@internal dirtyTiles: () => string[]+@internal ensureTileSplats: (tile: Tile, tx: number, tz: number, second: boolean) => void+@internal hasTile: (tx: number, tz: number) => boolean+@internal markDirty: (tx: number, tz: number) => void+@internal markOverviewDirty: () => void+@internal markSaved: () => void+@internal overviewDirty: boolean+@internal overviewSplats: (make: boolean, second: boolean) => { a: Splat | null; b: Splat | null; }+@internal readTile: (tx: number, tz: number) => Promise<Tile | null>+@internal tileAt: (tx: number, tz: number) => Tile | undefinedbounds: readonly [number, number, number, number]budget: numberdoc: TerrainTilesDocument@@ -12211,6 +12221,7 @@ infinite: falsemaxHeight: numberminHeight: 0normal: (x: number, z: number) => [number, number, number] | null+overview: HeightfieldoverviewBytes: numberoverviewSpacing: numberpaint: (x: number, z: number, h: number, ny: number) => LayerWeightsdiff --git a/sdk/etc/terrain.api.md b/sdk/etc/terrain.api.mdindex f8ec5388d..434c32c49 100644--- a/sdk/etc/terrain.api.md+++ b/sdk/etc/terrain.api.md@@ -1,7 +1,7 @@# API surface — esengine/terrain<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 0 public · 0 beta · 111 experimental · 0 deprecated+Symbols: 0 public · 0 beta · 114 experimental · 0 deprecated## Brush — interface @experimental```@@ -70,6 +70,8 @@ maxHeight: numberminHeight: numberorigin: { x: number; z: number; }paint: (layer: number, x: number, z: number, radius: number, falloff: number, strength: number, erase?: boolean) => void+samplesX: number+samplesZ: numbersculpt: (mode: number, x: number, z: number, radius: number, falloff: number, amount: number, target?: number) => voidsplatmapPixels: () => { a: Splat | null; b: Splat | null; }static new (host: GroundHost, source: FieldSource, modified: ModifiedSource, sizeX: number, sizeZ: number): GroundEdit@@ -532,6 +534,7 @@ tint: [number, number, number]cpuBytes: numberloading: numbertiles: number+unsaved: number```## TerrainModifier — interface @experimental@@ -631,7 +634,7 @@ collisionReadyAt: (x: number, z: number) => booleandeleteModifier: (id: string) => voidfindPath: (from: { x: number; z: number; }, to: { x: number; z: number; }, options?: ReachOptions) => ReachResultgroundData: () => GroundData | null-groundEdit: (entity: Entity) => GroundEdit | null+groundEdit: (entity: Entity) => GroundEdit | TiledGroundEdit | nullgroundKnownAt: (x: number, z: number) => booleanheightAt: (x: number, z: number) => number | nullheightBeneathAt: (x: number, z: number) => number | null@@ -655,6 +658,43 @@ static prototype: TerrainsResourceDef<Terrains>```+## TiledGroundEdit — class @experimental+```+apply: (patch: TiledGroundPatch, side: "before" | "after") => void+area: { sizeX: number; sizeZ: number; }+begin: () => void+end: () => TiledGroundPatch | null+heightAt: (x: number, z: number) => number | null+maxHeight: number+minHeight: number+origin: { x: number; z: number; }+paint: (layer: number, x: number, z: number, radius: number, falloff: number, strength: number, erase?: boolean) => void+samplesX: number+samplesZ: number+saveImages: () => { images: TiledGroundImage[]; document: TerrainTilesDocument | null; }+saved: () => void+sculpt: (mode: number, x: number, z: number, radius: number, falloff: number, amount: number, target?: number) => void+tiled: true+unsaved: string[]+static new (host: GroundHost, source: TiledSource, modified: ModifiedSource, sizeX: number, sizeZ: number): TiledGroundEdit+static prototype: TiledGroundEdit+```++## TiledGroundImage — interface @experimental+```+height: number+path: string+pixels: Uint8Array<ArrayBufferLike>+width: number+```++## TiledGroundPatch — interface @experimental+```+bounds: [number, number, number, number]+overview: Arrays+tiles: Map<string, Arrays>+```+## boxDistance — function @experimental```(x0: number, z0: number, size: number, y0: number, y1: number, ex: number, ey: number, ez: number): numberdiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex e4ca341a2..fcbee0d7f 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -11480,7 +11480,7 @@ collisionReadyAt: (x: number, z: number) => booleandeleteModifier: (id: string) => voidfindPath: (from: { x: number; z: number; }, to: { x: number; z: number; }, options?: ReachOptions) => ReachResultgroundData: () => GroundData | null-groundEdit: (entity: Entity) => GroundEdit | null+groundEdit: (entity: Entity) => GroundEdit | TiledGroundEdit | nullgroundKnownAt: (x: number, z: number) => booleanheightAt: (x: number, z: number) => number | nullheightBeneathAt: (x: number, z: number) => number | null@@ -11914,6 +11914,16 @@ title: number## TiledSource — class @experimental```+@internal dirtyTiles: () => string[]+@internal ensureTileSplats: (tile: Tile, tx: number, tz: number, second: boolean) => void+@internal hasTile: (tx: number, tz: number) => boolean+@internal markDirty: (tx: number, tz: number) => void+@internal markOverviewDirty: () => void+@internal markSaved: () => void+@internal overviewDirty: boolean+@internal overviewSplats: (make: boolean, second: boolean) => { a: Splat | null; b: Splat | null; }+@internal readTile: (tx: number, tz: number) => Promise<Tile | null>+@internal tileAt: (tx: number, tz: number) => Tile | undefinedbounds: readonly [number, number, number, number]budget: numberdoc: TerrainTilesDocument@@ -11922,6 +11932,7 @@ infinite: falsemaxHeight: numberminHeight: 0normal: (x: number, z: number) => [number, number, number] | null+overview: HeightfieldoverviewBytes: numberoverviewSpacing: numberpaint: (x: number, z: number, h: number, ny: number) => LayerWeightsdiff --git a/sdk/src/terrain/groundEdit.ts b/sdk/src/terrain/groundEdit.tsindex 55281ca74..9e648db69 100644--- a/sdk/src/terrain/groundEdit.ts+++ b/sdk/src/terrain/groundEdit.ts@@ -19,7 +19,8 @@ type Texels = Float32Array | Uint8Array;interface Tile<T> { rect: Dirty; before: T; after: T }-interface Piece<T> { rect: Dirty; width: number; tiles: Tile<T>[] }+/** @internal What one stroke changed in one array: the 32-by-32 tiles it touched, as they were and as they are. */+export interface Piece<T> { rect: Dirty; width: number; tiles: Tile<T>[] }const TILE = 32;@@ -30,7 +31,8 @@ export interface GroundPatch {splat2: Piece<Uint8Array> | null;}-class BeforeTiles<T extends Texels> {+/** @internal */+export class BeforeTiles<T extends Texels> {readonly kept = new Map<number, { rect: Dirty; before: T }>();constructor(private readonly width: number, private readonly height: number, private readonly stride: number) {}@@ -74,6 +76,8 @@ export class GroundEdit {private readonly sizeX: number, private readonly sizeZ: number) {}get field(): Heightfield { return this.source.field; }+ get samplesX(): number { return this.source.field.width; }+ get samplesZ(): number { return this.source.field.height; }/** The world height the field's 0 sits at and its 1 reaches. */get minHeight(): number { return this.source.minHeight; }get maxHeight(): number { return this.source.maxHeight; }@@ -186,7 +190,8 @@ function copied<T extends Texels>(from: T, width: number, rect: Dirty, stride: nreturn out;}-function put<T extends Texels>(into: T, p: Piece<T>, side: 'before' | 'after', stride: number): void {+/** @internal */+export function put<T extends Texels>(into: T, p: Piece<T>, side: 'before' | 'after', stride: number): void {for (const tile of p.tiles) {const from = tile[side], r = tile.rect, w = (r.i1 - r.i0 + 1) * stride;for (let j = r.j0; j <= r.j1; j++) {diff --git a/sdk/src/terrain/index.ts b/sdk/src/terrain/index.tsindex 532f76c81..b4571bd6c 100644--- a/sdk/src/terrain/index.ts+++ b/sdk/src/terrain/index.ts@@ -32,4 +32,5 @@ export {type SphereNode, type SphereTreeParams,} from './sphere';export { GroundEdit, type GroundPatch } from './groundEdit';+export { TiledGroundEdit, type TiledGroundPatch, type TiledGroundImage } from './tiledGroundEdit';export { SculptMode, brushWeight, encodeHeightmap, paintSplat, sculptField, unionDirty, type Brush, type Dirty, type PaintDab, type SculptDab } from './sculpt';diff --git a/sdk/src/terrain/terrainPlugin.ts b/sdk/src/terrain/terrainPlugin.tsindex ff93df0c4..a48b050aa 100644--- a/sdk/src/terrain/terrainPlugin.ts+++ b/sdk/src/terrain/terrainPlugin.ts@@ -55,6 +55,7 @@ import { movers } from './movers';import { createLayerArrays, imagePixelsAt, readAndPackLayers, releaseLayerArrays } from './layerArrays';import { createPageAtlases } from './atlases';import { parseTerrainTiles, TiledSource } from './tiles';+import { TiledGroundEdit } from './tiledGroundEdit';/** The engine's own provider of ground without end: seeded noise of the world's position. */export const NOISE_PROVIDER = 'estella:noise';@@ -238,7 +239,7 @@ interface Built {/** Where a terrain's ground stands: still being made, ready, or failed (with why). */export interface TerrainStatus { state: 'loading' | 'ready' | 'failed'; reason?: string }-export interface TerrainLoad { loading: number; cpuBytes: number; tiles: number }+export interface TerrainLoad { loading: number; cpuBytes: number; tiles: number; unsaved: number }/** Run-time access to the ground: how high it is anywhere, for putting things on it. */export class Terrains {@@ -436,7 +437,7 @@ export class Terrains {}load(): TerrainLoad {- let loading = 0, cpuBytes = 0, tiles = 0;+ let loading = 0, cpuBytes = 0, tiles = 0, unsaved = 0;for (const built of this.built_.values()) {if (built.loading) loading++;const source = built.source instanceof ModifiedSource ? built.source.base : built.source;@@ -445,13 +446,14 @@ export class Terrains {loading += s.reading;cpuBytes += s.bytes + source.overviewBytes;tiles += s.resident;+ unsaved += source.dirtyTiles().length;continue;}if (!(source instanceof FieldSource)) continue;const { a, b } = source.splats();cpuBytes += source.field.data.byteLength + (a?.pixels.byteLength ?? 0) + (b?.pixels.byteLength ?? 0);}- return { loading, cpuBytes, tiles };+ return { loading, cpuBytes, tiles, unsaved };}/** @internal The modifiers laid over every terrain's ground, by id, in the order they were set. */@@ -480,8 +482,11 @@ export class Terrains {* A handle to change the ground of the area terrain on `entity` with brushes (sculpt.ts), or null while it is being made, when it* is not an area of its own heights (infinite ground, a provider's) or when it is not a terrain.*/- groundEdit(entity: Entity): GroundEdit | null {+ groundEdit(entity: Entity): GroundEdit | TiledGroundEdit | null {const built = this.built_.get(entity), source = built?.source;+ if (built && source instanceof ModifiedSource && source.base instanceof TiledSource) {+ return new TiledGroundEdit({ remake: (b) => this.remake_(b) }, source.base, source, built.data.sizeX, built.data.sizeZ);+ }if (!built || !(source instanceof ModifiedSource) || !(source.base instanceof FieldSource)) return null;return new GroundEdit({ remake: (b) => this.remake_(b) }, source.base, source, built.data.sizeX, built.data.sizeZ);}diff --git a/sdk/src/terrain/tiledGroundEdit.ts b/sdk/src/terrain/tiledGroundEdit.tsnew file mode 100644index 000000000..de629e0ae--- /dev/null+++ b/sdk/src/terrain/tiledGroundEdit.ts@@ -0,0 +1,319 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file tiledGroundEdit.ts+ * @brief Brushes on ground kept as tiles: a dab changes the tiles in memory under it and the overview with them, and a changed tile stays+ * in memory until it is saved.+ *+ * @details A dab is run on a window of the area's samples copied out of the tiles it covers (one sample wider, for smoothing), with the+ * same brushes as an area of one heightfield (sculpt.ts), and written back to every tile that holds each changed sample, so a+ * seam two tiles share stays one height. Where a tile under the brush is not in memory yet, it is read and that dab is skipped,+ * as only loaded ground can be edited.+ */+import { encodeHeightmap, paintSplat, reach, sculptField, unionDirty, type Brush, type Dirty } from './sculpt';+import { BeforeTiles, put, type Piece } from './groundEdit';+import type { ModifiedSource, Splat } from './source';+import type { Heightfield } from './heightfield';+import type { Tile, TiledSource, TerrainTilesDocument } from './tiles';+import type { GroundHost } from './groundEdit';++/** What one stroke changed in one array of a tiled ground. */+interface Arrays { heights: Piece<Float32Array> | null; splat: Piece<Uint8Array> | null; splat2: Piece<Uint8Array> | null }++/** What one stroke on a tiled ground changed: in each tile it reached, and in the overview. @experimental */+export interface TiledGroundPatch { tiles: Map<string, Arrays>; overview: Arrays; bounds: [number, number, number, number] }++interface Kept {+ heights: BeforeTiles<Float32Array> | null;+ splat: BeforeTiles<Uint8Array> | null;+ splat2: BeforeTiles<Uint8Array> | null;+ h: Dirty | null;+ s: Dirty | null;+ s2: Dirty | null;+}++/** An image a save writes, with where it goes. @experimental */+export interface TiledGroundImage { path: string; width: number; height: number; pixels: Uint8Array }++const kept = (): Kept => ({ heights: null, splat: null, splat2: null, h: null, s: null, s2: null });++/** One tiled ground, open to brushes. @experimental */+export class TiledGroundEdit {+ readonly tiled = true;+ private open_: { tiles: Map<string, Kept>; overview: Kept; bounds: [number, number, number, number] | null } | null = null;++ /** @internal */+ constructor(private readonly host: GroundHost, private readonly source: TiledSource, private readonly modified: ModifiedSource,+ private readonly sizeX: number, private readonly sizeZ: number) {}++ get minHeight(): number { return this.source.minHeight; }+ get maxHeight(): number { return this.source.maxHeight; }+ get area(): { sizeX: number; sizeZ: number } { return { sizeX: this.sizeX, sizeZ: this.sizeZ }; }+ get origin(): { x: number; z: number } { return { x: this.modified.origin.x, z: this.modified.origin.z }; }+ get samplesX(): number { return this.source.samplesX; }+ get samplesZ(): number { return this.source.samplesZ; }+ /** Tiles changed and not saved yet. */+ get unsaved(): string[] { return this.source.dirtyTiles(); }++ heightAt(x: number, z: number): number | null {+ return this.source.height(x - this.modified.origin.x, z - this.modified.origin.z);+ }++ begin(): void {+ if (!this.open_) this.open_ = { tiles: new Map(), overview: kept(), bounds: null };+ }++ sculpt(mode: number, x: number, z: number, radius: number, falloff: number, amount: number, target?: number): void {+ const span = this.span;+ this.dab({ x, z, radius, falloff }, (win, sx, sz, brush) => {+ const field: Heightfield = { width: win.w, height: win.h, data: this.readWindow(win, (t) => t.field.data, 1) };+ const hit = sculptField(field, sx, sz, { mode, brush, amount: mode <= 1 ? amount / span : amount,+ target: target === undefined ? undefined : (target - this.minHeight) / span });+ if (hit) this.writeWindow(win, hit, field.data, 1, 'heights');+ return hit;+ });+ }++ paint(layer: number, x: number, z: number, radius: number, falloff: number, strength: number, erase = false): void {+ this.dab({ x, z, radius, falloff }, (win, sx, sz, brush) => {+ const second = layer > 3 || win.tiles.some(({ tile }) => tile.splat2);+ for (const { tile, tx, tz } of win.tiles) this.source.ensureTileSplats(tile, tx, tz, second);+ const a: Splat = { width: win.w, height: win.h, pixels: this.readWindow(win, (t) => t.splat!.pixels, 4) };+ const b: Splat | null = second ? { width: win.w, height: win.h, pixels: this.readWindow(win, (t) => t.splat2!.pixels, 4) } : null;+ const hit = paintSplat(a, b, sx, sz, { layer, brush, strength, erase });+ if (!hit) return null;+ this.writeWindow(win, hit, a.pixels, 4, 'splat');+ if (b) this.writeWindow(win, hit, b.pixels, 4, 'splat2');+ return hit;+ });+ }++ end(): TiledGroundPatch | null {+ const o = this.open_;+ this.open_ = null;+ if (!o || !o.bounds) return null;+ const tiles = new Map<string, Arrays>();+ for (const [key, k] of o.tiles) {+ const [tx, tz] = key.split(':').map(Number) as [number, number];+ const tile = this.source.tileAt(tx, tz);+ if (tile) tiles.set(key, finish(k, tile.field.data, tile.splat?.pixels, tile.splat2?.pixels));+ }+ const { a, b } = this.source.overviewSplats(false, false);+ return { tiles, overview: finish(o.overview, this.source.overview.data, a?.pixels, b?.pixels), bounds: o.bounds };+ }++ /** Lays a patch's `before` or `after` back; a tile that has left memory since is read again first. */+ apply(patch: TiledGroundPatch, side: 'before' | 'after'): void {+ const lay = (tile: Tile, arrays: Arrays): void => {+ if (arrays.heights) put(tile.field.data, arrays.heights, side, 1);+ if (arrays.splat && tile.splat) put(tile.splat.pixels, arrays.splat, side, 4);+ if (arrays.splat2 && tile.splat2) put(tile.splat2.pixels, arrays.splat2, side, 4);+ };+ const later: Promise<void>[] = [];+ for (const [key, arrays] of patch.tiles) {+ const [tx, tz] = key.split(':').map(Number) as [number, number];+ this.source.markDirty(tx, tz);+ const tile = this.source.tileAt(tx, tz);+ if (tile) { lay(tile, arrays); continue; }+ later.push(this.source.readTile(tx, tz).then((t) => { if (t) lay(t, arrays); }));+ }+ const { a, b } = this.source.overviewSplats(!!patch.overview.splat, !!patch.overview.splat2);+ if (patch.overview.heights) put(this.source.overview.data, patch.overview.heights, side, 1);+ if (patch.overview.splat && a) put(a.pixels, patch.overview.splat, side, 4);+ if (patch.overview.splat2 && b) put(b.pixels, patch.overview.splat2, side, 4);+ this.source.markOverviewDirty();+ this.host.remake(this.world(patch.bounds));+ if (later.length) void Promise.all(later).then(() => this.host.remake(this.world(patch.bounds)));+ }++ /**+ * What a save writes: every changed tile's images, and the overview's, at the paths the document names. A splatmap the document did not+ * name before is given a path beside its tile's heights, and `document` is then the document to write as well (null when unchanged).+ */+ saveImages(): { images: TiledGroundImage[]; document: TerrainTilesDocument | null } {+ const doc = this.source.doc, images: TiledGroundImage[] = [];+ let named = false;+ const beside = (path: string, suffix: string): string => path.replace(/(\.[^./]+)?$/, `${suffix}.png`);+ for (const key of this.source.dirtyTiles()) {+ const [tx, tz] = key.split(':').map(Number) as [number, number];+ const tile = this.source.tileAt(tx, tz), entry = doc.tiles.find((t) => t.x === tx && t.z === tz);+ if (!tile || !entry) continue;+ images.push({ path: entry.height, width: tile.field.width, height: tile.field.height, pixels: encodeHeightmap(tile.field) });+ if (tile.splat) {+ if (!entry.splat) { entry.splat = beside(entry.height, '_splat'); named = true; }+ images.push({ path: entry.splat, ...tile.splat });+ }+ if (tile.splat2) {+ if (!entry.splat2) { entry.splat2 = beside(entry.height, '_splat2'); named = true; }+ images.push({ path: entry.splat2, ...tile.splat2 });+ }+ }+ if (this.source.overviewDirty) {+ images.push({ path: doc.overview, width: this.source.overview.width, height: this.source.overview.height, pixels: encodeHeightmap(this.source.overview) });+ const { a, b } = this.source.overviewSplats(false, false);+ if (a) {+ if (!doc.overviewSplat) { doc.overviewSplat = beside(doc.overview, '_splat'); named = true; }+ images.push({ path: doc.overviewSplat, ...a });+ }+ if (b) {+ if (!doc.overviewSplat2) { doc.overviewSplat2 = beside(doc.overview, '_splat2'); named = true; }+ images.push({ path: doc.overviewSplat2, ...b });+ }+ }+ return { images, document: named ? doc : null };+ }++ /** After the images of {@link saveImages} are written: the tiles may leave memory again. */+ saved(): void {+ this.source.markSaved();+ }++ private get span(): number {+ return Math.max(this.maxHeight - this.minHeight, 1e-6);+ }++ /** The window of samples a brush reaches, one wider, and the tiles in memory over it; null where one is not, after asking for it. */+ private dab(world: Brush, run: (win: Window, sx: number, sz: number, brush: Brush) => Dirty | null): void {+ const o = this.modified.origin, s = this.source;+ const brush = { ...world, x: world.x - o.x, z: world.z - o.z };+ const span = reach(s.samplesX, s.samplesZ, this.sizeX, this.sizeZ, brush);+ if (!span) return;+ const win = this.window(span);+ if (!win) return;+ const ex = this.sizeX / (s.samplesX - 1), ez = this.sizeZ / (s.samplesZ - 1);+ const cx = ((win.i0 + win.i1) / 2 / (s.samplesX - 1) - 0.5) * this.sizeX, cz = ((win.j0 + win.j1) / 2 / (s.samplesZ - 1) - 0.5) * this.sizeZ;+ const hit = run(win, (win.w - 1) * ex, (win.h - 1) * ez, { ...brush, x: brush.x - cx, z: brush.z - cz });+ if (!hit) return;+ const global = { i0: hit.i0 + win.i0, j0: hit.j0 + win.j0, i1: hit.i1 + win.i0, j1: hit.j1 + win.j0 };+ this.updateOverview(global);+ const bounds: [number, number, number, number] = [+ (global.i0 / (s.samplesX - 1) - 0.5) * this.sizeX - ex, (global.j0 / (s.samplesZ - 1) - 0.5) * this.sizeZ - ez,+ (global.i1 / (s.samplesX - 1) - 0.5) * this.sizeX + ex, (global.j1 / (s.samplesZ - 1) - 0.5) * this.sizeZ + ez,+ ];+ if (this.open_) {+ const b = this.open_.bounds;+ this.open_.bounds = b ? [Math.min(b[0], bounds[0]), Math.min(b[1], bounds[1]), Math.max(b[2], bounds[2]), Math.max(b[3], bounds[3])] : bounds;+ }+ this.host.remake(this.world(bounds));+ }++ private window(span: Dirty): Window | null {+ const s = this.source, n = s.doc.tileSamples - 1;+ const i0 = Math.max(span.i0 - 1, 0), j0 = Math.max(span.j0 - 1, 0);+ const i1 = Math.min(span.i1 + 1, s.samplesX - 1), j1 = Math.min(span.j1 + 1, s.samplesZ - 1);+ const tiles: Window['tiles'] = [];+ let missing = false;+ for (let tz = Math.min(Math.floor(j0 / n), s.doc.tilesZ - 1); tz <= Math.min(Math.floor(j1 / n), s.doc.tilesZ - 1); tz++) {+ for (let tx = Math.min(Math.floor(i0 / n), s.doc.tilesX - 1); tx <= Math.min(Math.floor(i1 / n), s.doc.tilesX - 1); tx++) {+ if (!s.hasTile(tx, tz)) continue;+ const tile = s.tileAt(tx, tz);+ if (tile) tiles.push({ tile, tx, tz });+ else { missing = true; void s.readTile(tx, tz); }+ }+ }+ return missing ? null : { i0, j0, i1, j1, w: i1 - i0 + 1, h: j1 - j0 + 1, tiles };+ }++ /** The window's values of one array, read from whichever tile holds each sample. */+ private readWindow<T extends Float32Array | Uint8Array>(win: Window, of: (t: Tile) => T, stride: number): T {+ const n = this.source.doc.tileSamples - 1, t = n + 1;+ let out: T | null = null;+ for (const { tile, tx, tz } of win.tiles) {+ const src = of(tile);+ out ??= new (src.constructor as { new (k: number): T })(win.w * win.h * stride);+ const gi0 = Math.max(win.i0, tx * n), gi1 = Math.min(win.i1, tx * n + n), gj0 = Math.max(win.j0, tz * n), gj1 = Math.min(win.j1, tz * n + n);+ for (let gj = gj0; gj <= gj1; gj++) {+ const from = ((gj - tz * n) * t + (gi0 - tx * n)) * stride;+ out.set(src.subarray(from, from + (gi1 - gi0 + 1) * stride) as never, ((gj - win.j0) * win.w + (gi0 - win.i0)) * stride);+ }+ }+ return out!;+ }++ /** Writes the window's `hit` back into every tile that holds a sample of it, keeping each tile's values first for undo. */+ private writeWindow(win: Window, hit: Dirty, values: Float32Array | Uint8Array, stride: number, which: 'heights' | 'splat' | 'splat2'): void {+ const n = this.source.doc.tileSamples - 1, t = n + 1;+ const gi0 = hit.i0 + win.i0, gi1 = hit.i1 + win.i0, gj0 = hit.j0 + win.j0, gj1 = hit.j1 + win.j0;+ for (const { tile, tx, tz } of win.tiles) {+ const a0 = Math.max(gi0, tx * n), a1 = Math.min(gi1, tx * n + n), b0 = Math.max(gj0, tz * n), b1 = Math.min(gj1, tz * n + n);+ if (a0 > a1 || b0 > b1) continue;+ const into = which === 'heights' ? tile.field.data : which === 'splat' ? tile.splat!.pixels : tile.splat2!.pixels;+ const local = { i0: a0 - tx * n, j0: b0 - tz * n, i1: a1 - tx * n, j1: b1 - tz * n };+ if (this.open_) {+ const key = `${tx}:${tz}`;+ let k = this.open_.tiles.get(key);+ if (!k) this.open_.tiles.set(key, k = kept());+ if (which === 'heights') { (k.heights ??= new BeforeTiles(t, t, 1)).keep(into as Float32Array, local); k.h = unionDirty(k.h, local); }+ else if (which === 'splat') { (k.splat ??= new BeforeTiles(t, t, 4)).keep(into as Uint8Array, local); k.s = unionDirty(k.s, local); }+ else { (k.splat2 ??= new BeforeTiles(t, t, 4)).keep(into as Uint8Array, local); k.s2 = unionDirty(k.s2, local); }+ }+ for (let gj = b0; gj <= b1; gj++) {+ const from = ((gj - win.j0) * win.w + (a0 - win.i0)) * stride;+ into.set(values.subarray(from, from + (a1 - a0 + 1) * stride) as never, ((gj - tz * n) * t + (a0 - tx * n)) * stride);+ }+ this.source.markDirty(tx, tz);+ }+ }++ /** Brings the overview's samples over the changed samples up to date, from the tiles. */+ private updateOverview(g: Dirty): void {+ const s = this.source, ov = s.overview, ow = ov.width, oh = ov.height;+ const fx = (ow - 1) / (s.samplesX - 1), fz = (oh - 1) / (s.samplesZ - 1);+ const span = { i0: Math.max(Math.floor((g.i0 - 1) * fx), 0), j0: Math.max(Math.floor((g.j0 - 1) * fz), 0),+ i1: Math.min(Math.ceil((g.i1 + 1) * fx), ow - 1), j1: Math.min(Math.ceil((g.j1 + 1) * fz), oh - 1) };+ const anySplat = [...this.tilesOver(span, fx, fz)].some(({ tile }) => tile.splat);+ const { a, b } = s.overviewSplats(anySplat, [...this.tilesOver(span, fx, fz)].some(({ tile }) => tile.splat2));+ const k = this.open_?.overview;+ if (k) {+ (k.heights ??= new BeforeTiles(ow, oh, 1)).keep(ov.data, span); k.h = unionDirty(k.h, span);+ if (a) { (k.splat ??= new BeforeTiles(ow, oh, 4)).keep(a.pixels, span); k.s = unionDirty(k.s, span); }+ if (b) { (k.splat2 ??= new BeforeTiles(ow, oh, 4)).keep(b.pixels, span); k.s2 = unionDirty(k.s2, span); }+ }+ const n = s.doc.tileSamples - 1;+ for (let oj = span.j0; oj <= span.j1; oj++) for (let oi = span.i0; oi <= span.i1; oi++) {+ const gx = oi / fx, gz = oj / fz;+ const tx = Math.min(Math.floor(gx / n), s.doc.tilesX - 1), tz = Math.min(Math.floor(gz / n), s.doc.tilesZ - 1);+ const tile = s.tileAt(tx, tz);+ if (!tile) continue;+ const lx = gx - tx * n, lz = gz - tz * n;+ ov.data[oj * ow + oi] = bilinear(tile.field.data, n + 1, lx, lz);+ const li = Math.round(lx), lj = Math.round(lz), at = (lj * (n + 1) + li) * 4, to = (oj * ow + oi) * 4;+ if (a && tile.splat) a.pixels.set(tile.splat.pixels.subarray(at, at + 4), to);+ if (b && tile.splat2) b.pixels.set(tile.splat2.pixels.subarray(at, at + 4), to);+ }+ s.markOverviewDirty();+ }++ private *tilesOver(span: Dirty, fx: number, fz: number): Generator<{ tile: Tile }> {+ const s = this.source, n = s.doc.tileSamples - 1;+ for (let tz = Math.floor(span.j0 / fz / n); tz <= Math.min(Math.floor(span.j1 / fz / n), s.doc.tilesZ - 1); tz++) {+ for (let tx = Math.floor(span.i0 / fx / n); tx <= Math.min(Math.floor(span.i1 / fx / n), s.doc.tilesX - 1); tx++) {+ const tile = s.tileAt(tx, tz);+ if (tile) yield { tile };+ }+ }+ }++ private world(b: readonly [number, number, number, number]): [number, number, number, number] {+ const o = this.modified.origin;+ return [b[0] + o.x, b[1] + o.z, b[2] + o.x, b[3] + o.z];+ }+}++interface Window { i0: number; j0: number; i1: number; j1: number; w: number; h: number; tiles: Array<{ tile: Tile; tx: number; tz: number }> }++function finish(k: Kept, heights: Float32Array, splat: Uint8Array | undefined, splat2: Uint8Array | undefined): Arrays {+ return {+ heights: k.heights && k.h ? k.heights.piece(heights, k.h) : null,+ splat: k.splat && k.s && splat ? k.splat.piece(splat, k.s) : null,+ splat2: k.splat2 && k.s2 && splat2 ? k.splat2.piece(splat2, k.s2) : null,+ };+}++function bilinear(data: Float32Array, width: number, fx: number, fz: number): number {+ const height = data.length / width;+ const i = Math.min(Math.max(Math.floor(fx), 0), width - 2), j = Math.min(Math.max(Math.floor(fz), 0), height - 2);+ const u = fx - i, v = fz - j;+ const a = data[j * width + i]!, b = data[j * width + i + 1]!, c = data[(j + 1) * width + i]!, d = data[(j + 1) * width + i + 1]!;+ return a + (b - a) * u + (c - a) * v + (a - b - c + d) * u * v;+}diff --git a/sdk/src/terrain/tiles.ts b/sdk/src/terrain/tiles.tsindex 5b52301d0..35fe3e8ed 100644--- a/sdk/src/terrain/tiles.ts+++ b/sdk/src/terrain/tiles.ts@@ -60,7 +60,8 @@ export function parseTerrainTiles(json: unknown, file = 'terrain tiles'): Terraioverview: o.overview, overviewSplat: o.overviewSplat, overviewSplat2: o.overviewSplat2, tiles: o.tiles };}-interface Tile { field: Heightfield; splat: Splat | null; splat2: Splat | null; bytes: number; used: number }+/** @internal One tile in memory. */+export interface Tile { field: Heightfield; splat: Splat | null; splat2: Splat | null; bytes: number; used: number }type Params = Pick<TerrainData, 'sizeX' | 'sizeZ' | 'height' | 'rockSlope' | 'dirtHeight' | 'snowHeight'>;@@ -79,6 +80,8 @@ export class TiledSource implements TerrainSource {private readonly entries_ = new Map<string, TerrainTileEntry>();private readonly tiles_ = new Map<string, Tile>();private readonly reading_ = new Map<string, Promise<Tile | null>>();+ private readonly dirty_ = new Set<string>();+ private overviewDirty_ = false;private clock_ = 0;private bytes_ = 0;private reads_ = 0;@@ -87,9 +90,9 @@ export class TiledSource implements TerrainSource {constructor(readonly doc: TerrainTilesDocument,private readonly params: Params,- private readonly overview: Heightfield,- private readonly overviewSplat: Splat | null,- private readonly overviewSplat2: Splat | null,+ readonly overview: Heightfield,+ private overviewSplat: Splat | null,+ private overviewSplat2: Splat | null,private readonly read: (path: string) => Promise<TerrainImage | null>,readonly budget = TERRAIN_TILE_BUDGET,) {@@ -155,7 +158,7 @@ export class TiledSource implements TerrainSource {/** Lets go of tiles, least recently used first, until what is held is within the budget; those in `keep` stay. */trim(keep: ReadonlySet<string> = new Set()): void {if (this.bytes_ <= this.budget) return;- const order = [...this.tiles_].filter(([k]) => !keep.has(k)).sort((a, b) => a[1].used - b[1].used);+ const order = [...this.tiles_].filter(([k]) => !keep.has(k) && !this.dirty_.has(k)).sort((a, b) => a[1].used - b[1].used);for (const [key, tile] of order) {if (this.bytes_ <= this.budget) break;this.tiles_.delete(key);@@ -164,6 +167,82 @@ export class TiledSource implements TerrainSource {}}+ /** @internal The tile at (tx, tz) if it is in memory. */+ tileAt(tx: number, tz: number): Tile | undefined {+ return this.tile(`${tx}:${tz}`);+ }++ /** @internal Reads the tile at (tx, tz) if it is not in memory; null where the document has none. */+ readTile(tx: number, tz: number): Promise<Tile | null> {+ return this.ensure(`${tx}:${tz}`);+ }++ /** @internal Whether the document has a tile at (tx, tz). */+ hasTile(tx: number, tz: number): boolean {+ return this.entries_.has(`${tx}:${tz}`);+ }++ /** @internal Keeps a changed tile in memory until {@link markSaved}: a tile let go with changes in it would lose them. */+ markDirty(tx: number, tz: number): void {+ this.dirty_.add(`${tx}:${tz}`);+ }++ /** @internal The tiles changed since they were read or last saved. */+ dirtyTiles(): string[] {+ return [...this.dirty_].sort();+ }++ /** @internal Whether the overview has changed since it was read or last saved. */+ get overviewDirty(): boolean {+ return this.overviewDirty_;+ }++ /** @internal */+ markOverviewDirty(): void {+ this.overviewDirty_ = true;+ }++ /** @internal Lets saved tiles go again. */+ markSaved(): void {+ this.dirty_.clear();+ this.overviewDirty_ = false;+ this.trim();+ }++ /** @internal Gives a tile in memory its splatmaps where it has none, painted as the ground is painted now. */+ ensureTileSplats(tile: Tile, tx: number, tz: number, second: boolean): void {+ const t = this.doc.tileSamples, n = t - 1;+ const make = (layers: number): Splat => {+ const pixels = new Uint8Array(t * t * 4);+ for (let j = 0; j < t; j++) for (let i = 0; i < t; i++) {+ const x = ((tx * n + i) / (this.samplesX - 1) - 0.5) * this.params.sizeX, z = ((tz * n + j) / (this.samplesZ - 1) - 0.5) * this.params.sizeZ;+ const h = this.params.height * tile.field.data[j * t + i]!;+ const w = this.paint(x, z, h, this.normal(x, z)?.[1] ?? 1);+ for (let c = 0; c < 4; c++) pixels[(j * t + i) * 4 + c] = Math.round(Math.min(Math.max(w[c + layers] ?? 0, 0), 1) * 255);+ }+ return { width: t, height: t, pixels };+ };+ if (!tile.splat) { tile.splat = make(0); tile.bytes += tile.splat.pixels.byteLength; this.bytes_ += tile.splat.pixels.byteLength; }+ if (second && !tile.splat2) { tile.splat2 = make(4); tile.bytes += tile.splat2.pixels.byteLength; this.bytes_ += tile.splat2.pixels.byteLength; }+ }++ /** @internal The overview's splatmaps, made at the overview's size where it has none. */+ overviewSplats(make: boolean, second: boolean): { a: Splat | null; b: Splat | null } {+ const w = this.overview.width, h = this.overview.height;+ if (make && !this.overviewSplat) {+ const pixels = new Uint8Array(w * h * 4), d = this.overview.data, ex = this.params.sizeX / (w - 1), ez = this.params.sizeZ / (h - 1);+ for (let j = 0; j < h; j++) for (let i = 0; i < w; i++) {+ const at = (ii: number, jj: number) => d[Math.min(Math.max(jj, 0), h - 1) * w + Math.min(Math.max(ii, 0), w - 1)]! * this.params.height;+ const sx = (at(i + 1, j) - at(i - 1, j)) / (2 * ex), sz = (at(i, j + 1) - at(i, j - 1)) / (2 * ez);+ const weights = paintWeights(d[j * w + i]!, 1 / Math.hypot(sx, 1, sz), this.params);+ for (let c = 0; c < 4; c++) pixels[(j * w + i) * 4 + c] = Math.round(weights[c]! * 255);+ }+ this.overviewSplat = { width: w, height: h, pixels };+ }+ if (make && second && !this.overviewSplat2) this.overviewSplat2 = { width: w, height: h, pixels: new Uint8Array(w * h * 4) };+ return { a: this.overviewSplat, b: this.overviewSplat2 };+ }+private tile(key: string): Tile | undefined {const t = this.tiles_.get(key);if (t) t.used = ++this.clock_;diff --git a/sdk/tests/terrain-sculpt.test.ts b/sdk/tests/terrain-sculpt.test.tsindex 8241383a5..a70ae3203 100644--- a/sdk/tests/terrain-sculpt.test.ts+++ b/sdk/tests/terrain-sculpt.test.ts@@ -117,7 +117,7 @@ describe('Terrains.load', () => {const wrapped = new ModifiedSource(source, () => [], { x: 0, y: 0, z: 0 }, 1);terrains.built_.set(1 as never, { loading: false, source: wrapped } as never);terrains.built_.set(2 as never, { loading: true, source: null } as never);- expect(terrains.load()).toEqual({ loading: 1, cpuBytes: field.data.byteLength + 256, tiles: 0 });+ expect(terrains.load()).toEqual({ loading: 1, cpuBytes: field.data.byteLength + 256, tiles: 0, unsaved: 0 });});});diff --git a/sdk/tests/terrain-tiled-sculpt.test.ts b/sdk/tests/terrain-tiled-sculpt.test.tsnew file mode 100644index 000000000..f24b1d0c3--- /dev/null+++ b/sdk/tests/terrain-tiled-sculpt.test.ts@@ -0,0 +1,144 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { describe, expect, it } from 'vitest';+import { HeightmapFormat, type Heightfield } from '../src/terrain/heightfield';+import { GroundEdit } from '../src/terrain/groundEdit';+import { TiledGroundEdit } from '../src/terrain/tiledGroundEdit';+import { FieldSource, ModifiedSource } from '../src/terrain/source';+import { SculptMode } from '../src/terrain/sculpt';+import { TiledSource, type TerrainImage, type TerrainTilesDocument } from '../src/terrain/tiles';++const T = 17, TILES = 3, N = TILES * (T - 1) + 1, SIZE = 480, HEIGHT = 100;+const params = { sizeX: SIZE, sizeZ: SIZE, height: HEIGHT, rockSlope: 0.35, dirtHeight: 0.62, snowHeight: 0.88 };+const q = (v: number): number => Math.round(v * 65535) / 65535;+const ground = (i: number, j: number): number => q(0.5 + 0.3 * Math.sin(i / 5) * Math.cos(j / 7));++function image(width: number, at: (i: number, j: number) => number): TerrainImage {+ const pixels = new Uint8Array(width * width * 4);+ for (let j = 0; j < width; j++) for (let i = 0; i < width; i++) {+ const v = Math.round(at(i, j) * 65535);+ pixels.set([v >> 8, v & 255, 0, 255], (j * width + i) * 4);+ }+ return { width, height: width, pixels };+}++function tiled(budget?: number) {+ const files = new Map<string, TerrainImage>();+ const doc: TerrainTilesDocument = { version: 1, tileSamples: T, tilesX: TILES, tilesZ: TILES, format: HeightmapFormat.RedGreen16, overview: 'o.png', tiles: [] };+ for (let tz = 0; tz < TILES; tz++) for (let tx = 0; tx < TILES; tx++) {+ files.set(`t${tx}_${tz}.png`, image(T, (i, j) => ground(tx * (T - 1) + i, tz * (T - 1) + j)));+ doc.tiles.push({ x: tx, z: tz, height: `t${tx}_${tz}.png` });+ }+ const overview: Heightfield = { width: 9, height: 9, data: Float32Array.from({ length: 81 }, (_, k) => ground((k % 9) * 6, Math.floor(k / 9) * 6)) };+ const reads: string[] = [];+ const source = new TiledSource(doc, params, overview, null, null, async (p) => { reads.push(p); return files.get(p) ?? null; }, budget);+ const modified = new ModifiedSource(source, () => [], { x: 0, y: 0, z: 0 }, 1);+ const remade: number[][] = [];+ const edit = new TiledGroundEdit({ remake: (b) => remade.push([...b]) }, source, modified, SIZE, SIZE);+ return { source, edit, reads, remade };+}++function whole() {+ const field: Heightfield = { width: N, height: N, data: Float32Array.from({ length: N * N }, (_, k) => ground(k % N, Math.floor(k / N))) };+ const source = new FieldSource(field, params, null, null);+ return { field, edit: new GroundEdit({ remake: () => {} }, source, new ModifiedSource(source, () => [], { x: 0, y: 0, z: 0 }, 1), SIZE, SIZE) };+}++async function loadAll(source: TiledSource): Promise<void> {+ for (let tz = 0; tz < TILES; tz++) for (let tx = 0; tx < TILES; tx++) await source.readTile(tx, tz);+}++function stitched(source: TiledSource): Float32Array {+ const out = new Float32Array(N * N), n = T - 1;+ for (let tz = 0; tz < TILES; tz++) for (let tx = 0; tx < TILES; tx++) {+ const tile = source.tileAt(tx, tz)!;+ for (let j = 0; j < T; j++) for (let i = 0; i < T; i++) {+ const g = (tz * n + j) * N + tx * n + i, v = tile.field.data[j * T + i]!;+ out[g] = v;+ }+ }+ return out;+}++const seam = -SIZE / 2 + (T - 1) * SIZE / (N - 1);++describe('brushes on ground kept as tiles', () => {+ for (const [name, mode, amount] of [['raise', SculptMode.Raise, 12], ['smooth', SculptMode.Smooth, 0.8], ['flatten', SculptMode.Flatten, 0.6]] as const) {+ it(`${name} across a seam leaves the same ground as on one heightfield, and the seam one height`, async () => {+ const t = tiled(), w = whole();+ await loadAll(t.source);+ for (const [x, z] of [[seam, seam], [seam + 7, seam - 11], [-200, 150]]) {+ t.edit.sculpt(mode, x!, z!, 40, 0.5, amount, 60);+ w.edit.sculpt(mode, x!, z!, 40, 0.5, amount, 60);+ }+ const got = stitched(t.source);+ let worst = 0;+ for (let k = 0; k < N * N; k++) worst = Math.max(worst, Math.abs(got[k]! - w.field.data[k]!));+ expect(worst).toBeLessThan(1e-6);+ const n = T - 1, a = t.source.tileAt(0, 0)!, b = t.source.tileAt(1, 0)!;+ for (let j = 0; j < T; j++) expect(a.field.data[j * T + n]).toBe(b.field.data[j * T]);+ });+ }++ it('skips a dab over a tile not in memory, and reads it for the next', async () => {+ const t = tiled();+ await t.source.readTile(0, 0);+ t.reads.length = 0;+ t.edit.sculpt(SculptMode.Raise, seam, -200, 30, 0.5, 10);+ expect(t.remade).toEqual([]);+ expect(t.reads).toEqual(['t1_0.png']);+ await t.source.readTile(1, 0);+ t.edit.sculpt(SculptMode.Raise, seam, -200, 30, 0.5, 10);+ expect(t.remade).toHaveLength(1);+ });++ it('keeps a changed tile in memory past the budget until it is saved', async () => {+ const one = T * T * 4;+ const t = tiled(one);+ await t.source.readTile(0, 0);+ t.edit.sculpt(SculptMode.Raise, -220, -220, 10, 0.5, 10);+ await t.source.readTile(2, 2);+ expect(t.source.tileAt(0, 0)).toBeDefined();+ expect(t.edit.unsaved).toEqual(['0:0']);+ t.edit.saved();+ await t.source.readTile(2, 1);+ expect(t.source.tileAt(0, 0)).toBeUndefined();+ });++ it('takes a stroke back and puts it again, in the tiles and the overview', async () => {+ const t = tiled();+ await loadAll(t.source);+ const before = stitched(t.source), overview = Float32Array.from(t.source.overview.data);+ t.edit.begin();+ t.edit.sculpt(SculptMode.Raise, seam, seam, 50, 0.5, 30);+ t.edit.sculpt(SculptMode.Raise, seam + 20, seam, 50, 0.5, 30);+ const patch = t.edit.end()!;+ const after = stitched(t.source), overviewAfter = Float32Array.from(t.source.overview.data);+ expect(overviewAfter).not.toEqual(overview);+ t.edit.apply(patch, 'before');+ expect(stitched(t.source)).toEqual(before);+ expect(t.source.overview.data).toEqual(overview);+ t.edit.apply(patch, 'after');+ expect(stitched(t.source)).toEqual(after);+ expect(t.source.overview.data).toEqual(overviewAfter);+ });++ it('draws distant ground from the overview as the stroke left it', async () => {+ const t = tiled();+ await loadAll(t.source);+ const at = () => t.source.region(0, 0, 60, 1);+ const was = (at() as { heights: Float32Array }).heights[0]!;+ t.edit.sculpt(SculptMode.Raise, 0, 0, 80, 0.5, 30);+ expect((at() as { heights: Float32Array }).heights[0]!).toBeGreaterThan(was + 10);+ });++ it('saves the changed tiles and the overview, and names the splatmaps it made', async () => {+ const t = tiled();+ await loadAll(t.source);+ t.edit.paint(2, -220, -220, 20, 0.5, 1);+ const out = t.edit.saveImages();+ expect(out.images.map((i) => i.path).sort()).toEqual(['o.png', 'o_splat.png', 't0_0.png', 't0_0_splat.png']);+ expect(out.document?.tiles.find((e) => e.x === 0 && e.z === 0)?.splat).toBe('t0_0_splat.png');+ expect(out.document?.overviewSplat).toBe('o_splat.png');+ });+});diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex bbd55435a..c1247035c 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -4248,6 +4248,10 @@ export const NOTED = {{"note": "A 2D character can be rigged in the editor, with no other program."},"fix(text): a glyph's outline costs what its size does, and text too large for a bitmap glyph draws from a distance field":{"note": "Zooming in on outlined text no longer freezes the editor."},+ "feat(terrain): tiled ground is sculpted and painted on the tiles in memory, a changed tile stays until it is saved, and a save writes only what changed":+ {"note": "Tiled terrain can be sculpted and painted, and a save writes only what changed."},+ "feat(terrain): the sculpt panel saves tiled ground, and a tiled terrain is sculpted, saved and reopened in the editor":+ {"note": "Tiled terrain can be sculpted and painted, and a save writes only what changed."},"feat(terrain): an area's ground can be kept as tiles, read where it is looked at under a memory budget, with an overview for the distance":{"note": "A terrain can be kept as tiles that are read where they are looked at."},"feat(terrain): a terrain splits into tiles from the sculpt panel, the editor waits for ground still being built, and opening a tiled terrain is measured near and far":