Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(terrain): brushes change an area's ground in place, with the pages made again only where a stroke reached

yhh724e6241f45e
diff --git a/sdk/src/terrain/groundEdit.ts b/sdk/src/terrain/groundEdit.ts
new file mode 100644
index 000000000..431029be9
--- /dev/null
+++ b/sdk/src/terrain/groundEdit.ts
@@ -0,0 +1,166 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file groundEdit.ts
+ * @brief A handle on one area terrain's ground that a tool can change: strokes in, the drawn ground, its queries and its collision follow.
+ *
+ * @details The ground an area draws is a field of heights and up to two splatmaps (source.ts). A handle changes those arrays in place with
+ * the brushes of sculpt.ts and has the terrain make again only the pages the stroke reached. A stroke is bracketed by
+ * {@link GroundEdit.begin} and {@link GroundEdit.end}, and `end` returns what changed as a {@link GroundPatch} that
+ * {@link GroundEdit.apply} lays down either way, which is what an editor's undo is made of. Nothing here writes a file: the
+ * arrays are what {@link GroundEdit.heightmapPixels} and {@link GroundEdit.splatmapPixels} hand over to be saved.
+ */
+import type { Heightfield } from './heightfield';
+import type { FieldSource, Splat } from './source';
+import type { ModifiedSource } from './source';
+import { encodeHeightmap, paintSplat, sculptField, unionDirty, type Dirty } from './sculpt';
+
+/** The texels of one array a stroke changed, as they were and as they are. */
+interface Piece<T> { rect: Dirty; width: number; before: T; after: T }
+
+/** What one stroke changed. @experimental */
+export interface GroundPatch {
+ heights: Piece<Float32Array> | null;
+ splat: Piece<Uint8Array> | null;
+ splat2: Piece<Uint8Array> | null;
+}
+
+/** The stroke being made: the arrays as they were, copied when it began. */
+interface Open {
+ heights: Float32Array;
+ splat: Uint8Array | null;
+ splat2: Uint8Array | null;
+ h: Dirty | null;
+ s: Dirty | null;
+ s2: Dirty | null;
+}
+
+/** What a handle needs of its terrain. @internal */
+export interface GroundHost {
+ /** Makes again the pages and the collision of the world square [minX, minZ, maxX, maxZ]. */
+ remake(b: readonly [number, number, number, number]): void;
+}
+
+/** One area terrain's ground, open to brushes. @experimental */
+export class GroundEdit {
+ private open_: Open | null = null;
+
+ /** @internal */
+ constructor(private readonly host: GroundHost, private readonly source: FieldSource, private readonly modified: ModifiedSource,
+ private readonly sizeX: number, private readonly sizeZ: number) {}
+
+ get field(): Heightfield { return this.source.field; }
+ /** 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; }
+ get area(): { sizeX: number; sizeZ: number } { return { sizeX: this.sizeX, sizeZ: this.sizeZ }; }
+ /** The terrain's world position on the ground plane: the brush's world (x, z) is this far from the terrain's own. */
+ get origin(): { x: number; z: number } { return { x: this.modified.origin.x, z: this.modified.origin.z }; }
+
+ private get span(): number { return Math.max(this.maxHeight - this.minHeight, 1e-6); }
+
+ /** The height of the ground (the brushes' own, without modifiers laid over it) at world (x, z), or null off the area. */
+ heightAt(x: number, z: number): number | null {
+ return this.source.height(x - this.modified.origin.x, z - this.modified.origin.z);
+ }
+
+ /** Starts a stroke: the arrays are copied so that {@link end} can say what changed. */
+ begin(): void {
+ if (this.open_) return;
+ const { a, b } = this.source.splats();
+ this.open_ = {
+ heights: this.field.data.slice(), splat: a ? a.pixels.slice() : null, splat2: b ? b.pixels.slice() : null,
+ h: null, s: null, s2: null,
+ };
+ }
+
+ /**
+ * One dab of height. `amount` is in world units for raise and lower (how far the brush's core moves the ground) and 0 to 1 for smooth
+ * and flatten (how much of the way they go); `target` is flatten's world height. At the world position (x, z).
+ */
+ sculpt(mode: number, x: number, z: number, radius: number, falloff: number, amount: number, target?: number): void {
+ const o = this.modified.origin;
+ const dab = { mode, brush: { x: x - o.x, z: z - o.z, radius, falloff }, amount: mode <= 1 ? amount / this.span : amount,
+ target: target === undefined ? undefined : (target - this.minHeight) / this.span };
+ const hit = sculptField(this.field, this.sizeX, this.sizeZ, dab);
+ if (!hit) return;
+ if (this.open_) this.open_.h = unionDirty(this.open_.h, hit);
+ this.remake(x, z, radius, this.field);
+ }
+
+ /** One dab of paint at the world position (x, z). Layers 5 to 8 make the second splatmap if there is none. */
+ paint(layer: number, x: number, z: number, radius: number, falloff: number, strength: number, erase = false): void {
+ const o = this.modified.origin;
+ const { a, b } = this.source.ensureSplats(layer > 3);
+ const hit = paintSplat(a, b, this.sizeX, this.sizeZ, { layer, brush: { x: x - o.x, z: z - o.z, radius, falloff }, strength, erase });
+ if (!hit) return;
+ if (this.open_) { this.open_.s = unionDirty(this.open_.s, hit); if (b) this.open_.s2 = unionDirty(this.open_.s2, hit); }
+ this.remake(x, z, radius, a);
+ }
+
+ /** Ends the stroke and says what it changed, or null when it changed nothing. */
+ end(): GroundPatch | null {
+ const o = this.open_;
+ this.open_ = null;
+ if (!o) return null;
+ const { a, b } = this.source.splats();
+ const patch: GroundPatch = {
+ heights: o.h ? piece(this.field.width, o.h, o.heights, this.field.data) : null,
+ splat: o.s && a ? piece(a.width, o.s, o.splat ?? zeros(a), a.pixels, 4) : null,
+ splat2: o.s2 && b ? piece(b.width, o.s2, o.splat2 ?? zeros(b), b.pixels, 4) : null,
+ };
+ return patch.heights || patch.splat || patch.splat2 ? patch : null;
+ }
+
+ /** Lays a patch's `before` or its `after` back over the ground. */
+ apply(patch: GroundPatch, side: 'before' | 'after'): void {
+ let rect: Dirty | null = null;
+ if (patch.heights) { put(this.field.data, patch.heights, side, 1); rect = patch.heights.rect; }
+ const { a, b } = this.source.splats();
+ if (patch.splat && a) put(a.pixels, patch.splat, side, 4);
+ if (patch.splat2 && b) put(b.pixels, patch.splat2, side, 4);
+ const r = rect ?? patch.splat?.rect ?? patch.splat2?.rect;
+ if (!r) return;
+ const w = patch.heights ? this.field.width : (a ?? b)!.width, h = patch.heights ? this.field.height : (a ?? b)!.height;
+ const x0 = (r.i0 / (w - 1) - 0.5) * this.sizeX + this.modified.origin.x, x1 = (r.i1 / (w - 1) - 0.5) * this.sizeX + this.modified.origin.x;
+ const z0 = (r.j0 / (h - 1) - 0.5) * this.sizeZ + this.modified.origin.z, z1 = (r.j1 / (h - 1) - 0.5) * this.sizeZ + this.modified.origin.z;
+ this.host.remake([x0 - this.sizeX / w, z0 - this.sizeZ / h, x1 + this.sizeX / w, z1 + this.sizeZ / h]);
+ }
+
+ /** The heights as the image a heightmap is saved as: red and green 16 bits, `RGBA`, `field.width` by `field.height`. */
+ heightmapPixels(): { width: number; height: number; pixels: Uint8Array } {
+ return { width: this.field.width, height: this.field.height, pixels: encodeHeightmap(this.field) };
+ }
+
+ /** The splatmaps as `RGBA` images to save, null where the ground has none. */
+ splatmapPixels(): { a: Splat | null; b: Splat | null } {
+ return this.source.splats();
+ }
+
+ private remake(x: number, z: number, radius: number, grid: { width: number }): void {
+ const pad = Math.max(this.sizeX / Math.max(grid.width - 1, 1), 0);
+ this.host.remake([x - radius - pad, z - radius - pad, x + radius + pad, z + radius + pad]);
+ }
+}
+
+function zeros(s: Splat): Uint8Array { return new Uint8Array(s.pixels.length); }
+
+/** The texels of `rect` of a `width`-wide array, from `before` (the whole array as it was) and `now`. `stride` is values a texel. */
+function piece<T extends Float32Array | Uint8Array>(width: number, rect: Dirty, before: T, now: T, stride = 1): Piece<T> {
+ const w = rect.i1 - rect.i0 + 1, h = rect.j1 - rect.j0 + 1;
+ const make = (from: T): T => {
+ const out = new (from.constructor as { new (n: number): T })(w * h * stride);
+ for (let j = 0; j < h; j++) for (let i = 0; i < w; i++) for (let c = 0; c < stride; c++) {
+ out[(j * w + i) * stride + c] = from[((rect.j0 + j) * width + rect.i0 + i) * stride + c]!;
+ }
+ return out;
+ };
+ return { rect, width, before: make(before), after: make(now) };
+}
+
+function put<T extends Float32Array | Uint8Array>(into: T, p: Piece<T>, side: 'before' | 'after', stride: number): void {
+ const from = p[side], r = p.rect, w = r.i1 - r.i0 + 1;
+ for (let j = r.j0; j <= r.j1; j++) for (let i = r.i0; i <= r.i1; i++) for (let c = 0; c < stride; c++) {
+ into[(j * p.width + i) * stride + c] = from[((j - r.j0) * w + (i - r.i0)) * stride + c]!;
+ }
+}
diff --git a/sdk/src/terrain/index.ts b/sdk/src/terrain/index.ts
index 9fa0aa757..1606a2a07 100644
--- a/sdk/src/terrain/index.ts
+++ b/sdk/src/terrain/index.ts
@@ -31,3 +31,5 @@ export {
FACES, direction, faceOf, levelsFor, nodeAt, nodeBound, nodeDistance, nodePoint, nodeRect, nodeSpan, selectSphereNodes, sphereNodeKey, sphereRange,
type SphereNode, type SphereTreeParams,
} from './sphere';
+export { GroundEdit, type GroundPatch } from './groundEdit';
+export { SculptMode, brushWeight, encodeHeightmap, paintSplat, sculptField, unionDirty, type Brush, type Dirty, type PaintDab, type SculptDab } from './sculpt';
diff --git a/sdk/src/terrain/sculpt.ts b/sdk/src/terrain/sculpt.ts
new file mode 100644
index 000000000..f2dbc3951
--- /dev/null
+++ b/sdk/src/terrain/sculpt.ts
@@ -0,0 +1,173 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file sculpt.ts
+ * @brief Brush strokes on an area's ground: raise, lower, smooth and flatten its heights, and paint its layers.
+ *
+ * @details Pure arithmetic over the arrays the ground is made of (a heightfield, and up to two splatmaps), so an editor tool and a
+ * test drive the same code. Positions are in the terrain's own space (its entity at the origin); a brush reaches `radius`
+ * from its centre, at full strength over the inner `1 - falloff` of that and easing to nothing at the edge.
+ * Heights are the field's 0 to 1, so an amount in world units is divided by the span the field is read over.
+ */
+import type { Heightfield } from './heightfield';
+import type { Splat } from './source';
+
+/** What a brush does to heights. @experimental */
+export const SculptMode = { Raise: 0, Lower: 1, Smooth: 2, Flatten: 3 } as const;
+
+/** A brush at (x, z) in the terrain's space. */
+export interface Brush {
+ x: number;
+ z: number;
+ radius: number;
+ /** 0 to 1: how much of the brush's edge eases away. 0 is a hard disc, 1 a cone. */
+ falloff: number;
+}
+
+/** The texels a stroke changed, both corners included. */
+export interface Dirty { i0: number; j0: number; i1: number; j1: number }
+
+/** The brush's weight at `d` from its centre, 1 over its core, easing (smoothstep) to 0 at its edge. */
+export function brushWeight(d: number, radius: number, falloff: number): number {
+ if (d >= radius) return 0;
+ const core = radius * (1 - Math.min(Math.max(falloff, 0), 1));
+ if (d <= core) return 1;
+ const t = 1 - (d - core) / Math.max(radius - core, 1e-9);
+ return t * t * (3 - 2 * t);
+}
+
+/** The texel span of a brush over a grid `width` by `height` laid across `sizeX` by `sizeZ`, or null when it reaches none. */
+function reach(width: number, height: number, sizeX: number, sizeZ: number, b: Brush): Dirty | null {
+ const u0 = (b.x - b.radius) / sizeX + 0.5, u1 = (b.x + b.radius) / sizeX + 0.5;
+ const v0 = (b.z - b.radius) / sizeZ + 0.5, v1 = (b.z + b.radius) / sizeZ + 0.5;
+ const i0 = Math.max(Math.ceil(u0 * (width - 1)), 0), i1 = Math.min(Math.floor(u1 * (width - 1)), width - 1);
+ const j0 = Math.max(Math.ceil(v0 * (height - 1)), 0), j1 = Math.min(Math.floor(v1 * (height - 1)), height - 1);
+ return i0 > i1 || j0 > j1 ? null : { i0, j0, i1, j1 };
+}
+
+/** The union of two dirty spans, either of which may be absent. */
+export function unionDirty(a: Dirty | null, b: Dirty | null): Dirty | null {
+ if (!a) return b;
+ if (!b) return a;
+ return { i0: Math.min(a.i0, b.i0), j0: Math.min(a.j0, b.j0), i1: Math.max(a.i1, b.i1), j1: Math.max(a.j1, b.j1) };
+}
+
+/** What one dab does. */
+export interface SculptDab {
+ mode: number;
+ brush: Brush;
+ /**
+ * Raise and lower: how far the brush's core moves the ground, in the field's 0 to 1. Smooth and flatten: how much of the way to
+ * the average or to `target` it goes, 0 to 1.
+ */
+ amount: number;
+ /** Flatten's height, in the field's 0 to 1. */
+ target?: number;
+}
+
+/**
+ * Applies one dab to `field` and says which texels it touched (null when the brush is off the area). Heights stay between 0 and 1.
+ */
+export function sculptField(field: Heightfield, sizeX: number, sizeZ: number, dab: SculptDab): Dirty | null {
+ const span = reach(field.width, field.height, sizeX, sizeZ, dab.brush);
+ if (!span) return null;
+ const { width, data } = field, b = dab.brush;
+ // Smoothing reads the ground as it was before the dab, or the first texels it softens would feed the ones after.
+ const before = dab.mode === SculptMode.Smooth ? sliceOf(field, span) : null;
+ const w = span.i1 - span.i0 + 1;
+ for (let j = span.j0; j <= span.j1; j++) {
+ for (let i = span.i0; i <= span.i1; i++) {
+ const x = (i / (field.width - 1) - 0.5) * sizeX, z = (j / (field.height - 1) - 0.5) * sizeZ;
+ const k = brushWeight(Math.hypot(x - b.x, z - b.z), b.radius, b.falloff);
+ if (k <= 0) continue;
+ const at = j * width + i;
+ const h = data[at]!;
+ let next = h;
+ if (dab.mode === SculptMode.Raise) next = h + dab.amount * k;
+ else if (dab.mode === SculptMode.Lower) next = h - dab.amount * k;
+ else if (dab.mode === SculptMode.Flatten) next = h + ((dab.target ?? h) - h) * Math.min(dab.amount * k, 1);
+ else if (before) {
+ let sum = 0, n = 0;
+ for (let dj = -1; dj <= 1; dj++) for (let di = -1; di <= 1; di++) {
+ const ii = Math.min(Math.max(i + di, 0), field.width - 1), jj = Math.min(Math.max(j + dj, 0), field.height - 1);
+ // Outside the span the ground is untouched by this dab, so the field itself is the "before".
+ const inside = ii >= span.i0 && ii <= span.i1 && jj >= span.j0 && jj <= span.j1;
+ sum += inside ? before[(jj - span.j0) * w + (ii - span.i0)]! : data[jj * width + ii]!;
+ n++;
+ }
+ next = h + (sum / n - h) * Math.min(dab.amount * k, 1);
+ }
+ data[at] = Math.min(Math.max(next, 0), 1);
+ }
+ }
+ return span;
+}
+
+function sliceOf(field: Heightfield, s: Dirty): Float32Array {
+ const w = s.i1 - s.i0 + 1, out = new Float32Array(w * (s.j1 - s.j0 + 1));
+ for (let j = s.j0; j <= s.j1; j++) for (let i = s.i0; i <= s.i1; i++) out[(j - s.j0) * w + (i - s.i0)] = field.data[j * field.width + i]!;
+ return out;
+}
+
+/** What one paint dab does. */
+export interface PaintDab {
+ /** The layer, 0 to 7: layers 1 to 4 live in the first splatmap, 5 to 8 in the second. */
+ layer: number;
+ brush: Brush;
+ /** 0 to 1: how far toward the layer being all there is a texel at the brush's core goes. */
+ strength: number;
+ /** Takes the layer away instead of laying it. */
+ erase?: boolean;
+}
+
+/** One texel's eight weights, from the splatmaps. */
+function readWeights(a: Splat, b: Splat | null, at: number, out: Float32Array): void {
+ for (let c = 0; c < 4; c++) {
+ out[c] = a.pixels[at * 4 + c]! / 255;
+ out[4 + c] = b ? b.pixels[at * 4 + c]! / 255 : 0;
+ }
+}
+
+/**
+ * Paints one dab into the splatmaps (`b` null paints layers 1 to 4 only) and says which texels it touched. The two maps must be the
+ * same size. The weights of a texel always add to one: laying a layer takes from the others in proportion to what they had, and
+ * erasing one gives its share back to them (to layer 1 where there is nothing else).
+ */
+export function paintSplat(a: Splat, b: Splat | null, sizeX: number, sizeZ: number, dab: PaintDab): Dirty | null {
+ if (dab.layer < 0 || dab.layer > 7 || (dab.layer > 3 && !b)) return null;
+ const span = reach(a.width, a.height, sizeX, sizeZ, dab.brush);
+ if (!span) return null;
+ const bb = dab.brush, w = new Float32Array(8);
+ for (let j = span.j0; j <= span.j1; j++) {
+ for (let i = span.i0; i <= span.i1; i++) {
+ const x = (i / (a.width - 1) - 0.5) * sizeX, z = (j / (a.height - 1) - 0.5) * sizeZ;
+ const k = brushWeight(Math.hypot(x - bb.x, z - bb.z), bb.radius, bb.falloff) * dab.strength;
+ if (k <= 0) continue;
+ const at = j * a.width + i;
+ readWeights(a, b, at, w);
+ let others = 0;
+ for (let c = 0; c < 8; c++) if (c !== dab.layer) others += w[c]!;
+ const was = w[dab.layer]!;
+ const now = Math.min(Math.max(dab.erase ? was * (1 - Math.min(k, 1)) : was + (1 - was) * Math.min(k, 1), 0), 1);
+ const rest = 1 - now;
+ if (others > 1e-6) for (let c = 0; c < 8; c++) { if (c !== dab.layer) w[c] = w[c]! * rest / others; }
+ else if (dab.erase) w[dab.layer === 0 ? 1 : 0] = rest;
+ w[dab.layer] = now;
+ for (let c = 0; c < 4; c++) {
+ a.pixels[at * 4 + c] = Math.round(w[c]! * 255);
+ if (b) b.pixels[at * 4 + c] = Math.round(w[4 + c]! * 255);
+ }
+ }
+ }
+ return span;
+}
+
+/** A height field as the red-and-green 16-bit image a heightmap is saved as (red the high byte): `RGBA` pixels, opaque. */
+export function encodeHeightmap(field: Heightfield): Uint8Array {
+ const out = new Uint8Array(field.width * field.height * 4);
+ for (let i = 0; i < field.width * field.height; i++) {
+ const v = Math.round(Math.min(Math.max(field.data[i]!, 0), 1) * 65535);
+ out[i * 4] = v >> 8; out[i * 4 + 1] = v & 255; out[i * 4 + 2] = 0; out[i * 4 + 3] = 255;
+ }
+ return out;
+}
diff --git a/sdk/src/terrain/source.ts b/sdk/src/terrain/source.ts
index 22a976768..d4f7eebc2 100644
--- a/sdk/src/terrain/source.ts
+++ b/sdk/src/terrain/source.ts
@@ -71,15 +71,41 @@ export class FieldSource implements TerrainSource {
constructor(
readonly field: Heightfield,
private readonly data: Pick<TerrainData, 'sizeX' | 'sizeZ' | 'height' | 'rockSlope' | 'dirtHeight' | 'snowHeight'>,
- private readonly splat: Splat | null,
+ private splat: Splat | null,
private readonly flow: Float32Array | null,
range: readonly [number, number] = [0, data.height],
- private readonly splat2: Splat | null = null,
+ private splat2: Splat | null = null,
) {
this.bounds = [-data.sizeX / 2, -data.sizeZ / 2, data.sizeX / 2, data.sizeZ / 2];
[this.minHeight, this.maxHeight] = range;
}
+ /**
+ * The splatmaps a brush paints into, made where the ground had none: the first from the paint the ground has now (by height and
+ * slope), the second (layers 5 to 8) empty, and only when `second` says it is wanted. They are as fine as the field, to 1024 a side.
+ */
+ ensureSplats(second: boolean): { a: Splat; b: Splat | null } {
+ const f = this.field, width = Math.min(f.width, 1024), height = Math.min(f.height, 1024);
+ if (!this.splat) {
+ const pixels = new Uint8Array(width * height * 4);
+ const sx = this.data.sizeX, sz = this.data.sizeZ;
+ for (let j = 0; j < height; j++) for (let i = 0; i < width; i++) {
+ const x = (i / (width - 1) - 0.5) * sx, z = (j / (height - 1) - 0.5) * sz;
+ const h = this.height(x, z) ?? this.minHeight, n = this.normal(x, z);
+ const w = paintWeights((h - this.minHeight) / this.span, n ? n[1] : 1, this.data);
+ for (let c = 0; c < 4; c++) pixels[(j * width + i) * 4 + c] = Math.round(w[c]! * 255);
+ }
+ this.splat = { width, height, pixels };
+ }
+ if (second && !this.splat2) this.splat2 = { width: this.splat.width, height: this.splat.height, pixels: new Uint8Array(this.splat.width * this.splat.height * 4) };
+ return { a: this.splat, b: this.splat2 };
+ }
+
+ /** The splatmaps now, null where the ground has none. */
+ splats(): { a: Splat | null; b: Splat | null } {
+ return { a: this.splat, b: this.splat2 };
+ }
+
private get span(): number {
return Math.max(this.maxHeight - this.minHeight, 1e-6);
}
diff --git a/sdk/src/terrain/terrainPlugin.ts b/sdk/src/terrain/terrainPlugin.ts
index ec1e31544..b8650f439 100644
--- a/sdk/src/terrain/terrainPlugin.ts
+++ b/sdk/src/terrain/terrainPlugin.ts
@@ -41,6 +41,7 @@ import { findGroundPath, type ReachOptions, type ReachResult } from './reach';
import { paintWeights } from './paint';
export { paintWeights };
+import { GroundEdit } from './groundEdit';
import { FieldSource, ModifiedSource, NoiseSource, type TerrainModifier, type TerrainSource } from './source';
import { levelRange, nodeKey, parentOf, selectNodes, type QuadtreeParams, type TerrainNode } from './quadtree';
import { makePage, PageTable, PAGE_SIDE, PAGE_TEXELS, PATCH_CELLS, type PageImage, type Repaint } from './pages';
@@ -448,6 +449,16 @@ export class Terrains {
this.remake_(had.bounds);
}
+ /**
+ * 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 {
+ const built = this.built_.get(entity), source = built?.source;
+ 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);
+ }
+
/** @internal Makes again what the world square `b` reaches: its pages and its collision, and what stands on the ground. */
remake_(b: readonly [number, number, number, number]): void {
const app = this.app_;
diff --git a/sdk/tests/terrain-sculpt.test.ts b/sdk/tests/terrain-sculpt.test.ts
new file mode 100644
index 000000000..807beedc9
--- /dev/null
+++ b/sdk/tests/terrain-sculpt.test.ts
@@ -0,0 +1,169 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Brushes on an area's ground: what each one does to a field and to the splatmaps, and that a stroke can be taken back.
+ */
+import { describe, expect, it } from 'vitest';
+import { GroundEdit } from '../src/terrain/groundEdit';
+import { FieldSource, ModifiedSource, type Splat } from '../src/terrain/source';
+import type { Heightfield } from '../src/terrain/heightfield';
+import { SculptMode, brushWeight, encodeHeightmap, paintSplat, sculptField } from '../src/terrain/sculpt';
+
+const flat = (n: number, v = 0.5): Heightfield => ({ width: n, height: n, data: new Float32Array(n * n).fill(v) });
+const at = (f: Heightfield, i: number, j: number): number => f.data[j * f.width + i]!;
+const data = { sizeX: 100, sizeZ: 100, height: 50, rockSlope: 0.35, dirtHeight: 0.62, snowHeight: 0.88 };
+
+describe('brushWeight', () => {
+ it('is one over the core and nothing at the edge, easing between', () => {
+ expect(brushWeight(0, 10, 0.5)).toBe(1);
+ expect(brushWeight(5, 10, 0.5)).toBe(1);
+ expect(brushWeight(10, 10, 0.5)).toBe(0);
+ const mid = brushWeight(7.5, 10, 0.5);
+ expect(mid).toBeGreaterThan(0.4);
+ expect(mid).toBeLessThan(0.6);
+ expect(brushWeight(9.99, 10, 0)).toBe(1);
+ });
+});
+
+describe('sculptField', () => {
+ it('raises the ground under the brush and only there', () => {
+ const f = flat(101);
+ const hit = sculptField(f, 100, 100, { mode: SculptMode.Raise, brush: { x: 0, z: 0, radius: 10, falloff: 0.5 }, amount: 0.1 });
+ expect(hit).not.toBeNull();
+ expect(at(f, 50, 50)).toBeCloseTo(0.6, 5);
+ expect(at(f, 60, 50)).toBe(0.5);
+ expect(at(f, 0, 0)).toBe(0.5);
+ expect(hit!.i0).toBeGreaterThanOrEqual(40);
+ expect(hit!.i1).toBeLessThanOrEqual(60);
+ });
+
+ it('lowers it, and never past the range of the field', () => {
+ const f = flat(101, 0.05);
+ sculptField(f, 100, 100, { mode: SculptMode.Lower, brush: { x: 0, z: 0, radius: 10, falloff: 0 }, amount: 0.5 });
+ expect(at(f, 50, 50)).toBe(0);
+ const g = flat(101, 0.95);
+ sculptField(g, 100, 100, { mode: SculptMode.Raise, brush: { x: 0, z: 0, radius: 10, falloff: 0 }, amount: 0.5 });
+ expect(at(g, 50, 50)).toBe(1);
+ });
+
+ it('flattens toward a height', () => {
+ const f = flat(101, 0.2);
+ f.data[50 * 101 + 50] = 0.9;
+ sculptField(f, 100, 100, { mode: SculptMode.Flatten, brush: { x: 0, z: 0, radius: 10, falloff: 0 }, amount: 1, target: 0.4 });
+ expect(at(f, 50, 50)).toBeCloseTo(0.4, 5);
+ expect(at(f, 52, 50)).toBeCloseTo(0.4, 5);
+ });
+
+ it('smooths a spike toward its neighbours without reading what it has just changed', () => {
+ const f = flat(101, 0.2);
+ f.data[50 * 101 + 50] = 0.9;
+ sculptField(f, 100, 100, { mode: SculptMode.Smooth, brush: { x: 0, z: 0, radius: 10, falloff: 0 }, amount: 1 });
+ expect(at(f, 50, 50)).toBeCloseTo((0.9 + 8 * 0.2) / 9, 5);
+ // A neighbour saw the spike as it was, not as it had just become.
+ expect(at(f, 51, 50)).toBeCloseTo((0.9 + 8 * 0.2) / 9, 5);
+ });
+
+ it('does nothing for a brush off the area', () => {
+ const f = flat(33);
+ expect(sculptField(f, 100, 100, { mode: SculptMode.Raise, brush: { x: 500, z: 0, radius: 10, falloff: 0 }, amount: 1 })).toBeNull();
+ expect(Array.from(f.data).every((v) => v === 0.5)).toBe(true);
+ });
+});
+
+describe('paintSplat', () => {
+ const splat = (n: number, r: number, g = 0): Splat => {
+ const pixels = new Uint8Array(n * n * 4);
+ for (let i = 0; i < n * n; i++) { pixels[i * 4] = r; pixels[i * 4 + 1] = g; }
+ return { width: n, height: n, pixels };
+ };
+ const weights = (a: Splat, b: Splat | null, i: number, j: number): number[] => {
+ const o = (j * a.width + i) * 4;
+ return [0, 1, 2, 3].map((c) => a.pixels[o + c]! / 255).concat([0, 1, 2, 3].map((c) => b ? b.pixels[o + c]! / 255 : 0));
+ };
+
+ it('lays a layer and takes the others down in proportion, so the weights still add to one', () => {
+ const a = splat(33, 128, 127);
+ paintSplat(a, null, 100, 100, { layer: 2, brush: { x: 0, z: 0, radius: 20, falloff: 0 }, strength: 0.5 });
+ const w = weights(a, null, 16, 16);
+ expect(w[2]).toBeGreaterThan(0.45);
+ expect(w.reduce((s, v) => s + v, 0)).toBeCloseTo(1, 1);
+ expect(w[0]! / w[1]!).toBeCloseTo(128 / 127, 1);
+ });
+
+ it('reaches layers five to eight through the second map and refuses them without one', () => {
+ const a = splat(33, 255), b = splat(33, 0);
+ expect(paintSplat(a, null, 100, 100, { layer: 5, brush: { x: 0, z: 0, radius: 20, falloff: 0 }, strength: 1 })).toBeNull();
+ paintSplat(a, b, 100, 100, { layer: 5, brush: { x: 0, z: 0, radius: 20, falloff: 0 }, strength: 1 });
+ const w = weights(a, b, 16, 16);
+ expect(w[5]).toBe(1);
+ expect(w[0]).toBe(0);
+ });
+
+ it('erases a layer back to the others, or to the first one when it was alone', () => {
+ const a = splat(33, 0, 255);
+ paintSplat(a, null, 100, 100, { layer: 1, brush: { x: 0, z: 0, radius: 20, falloff: 0 }, strength: 1, erase: true });
+ const w = weights(a, null, 16, 16);
+ expect(w[1]).toBe(0);
+ expect(w[0]).toBe(1);
+ });
+});
+
+describe('GroundEdit', () => {
+ const make = (): { edit: GroundEdit; field: Heightfield; remade: number[][] } => {
+ const field = flat(65);
+ const source = new FieldSource(field, data, null, null);
+ const modified = new ModifiedSource(source, () => [], { x: 0, y: 0, z: 0 }, 1);
+ const remade: number[][] = [];
+ return { edit: new GroundEdit({ remake: (b) => remade.push([...b]) }, source, modified, 100, 100), field, remade };
+ };
+
+ it('changes the ground a source answers and has the terrain make again only what the stroke reached', () => {
+ const { edit, remade } = make();
+ edit.sculpt(SculptMode.Raise, 0, 0, 10, 0.5, 5);
+ expect(edit.heightAt(0, 0)).toBeCloseTo(25 + 5, 3);
+ expect(edit.heightAt(40, 40)).toBeCloseTo(25, 3);
+ expect(remade).toHaveLength(1);
+ const [x0, z0, x1, z1] = remade[0]!;
+ expect(x0).toBeLessThanOrEqual(-10);
+ expect(x1).toBeLessThan(20);
+ expect(z0).toBeLessThanOrEqual(-10);
+ expect(z1).toBeLessThan(20);
+ });
+
+ it('takes a stroke back and puts it again', () => {
+ const { edit, field } = make();
+ edit.begin();
+ edit.sculpt(SculptMode.Raise, 0, 0, 10, 0.5, 5);
+ edit.sculpt(SculptMode.Raise, 12, 0, 10, 0.5, 5);
+ const patch = edit.end();
+ expect(patch).not.toBeNull();
+ const peak = Float32Array.from(field.data);
+ edit.apply(patch!, 'before');
+ expect(Array.from(field.data).every((v) => v === 0.5)).toBe(true);
+ edit.apply(patch!, 'after');
+ expect(Array.from(field.data)).toEqual(Array.from(peak));
+ });
+
+ it('makes a splatmap on the first paint and gives it up on undo', () => {
+ const { edit } = make();
+ expect(edit.splatmapPixels().a).toBeNull();
+ edit.begin();
+ edit.paint(3, 0, 0, 10, 0.5, 1);
+ const patch = edit.end();
+ const a = edit.splatmapPixels().a!;
+ expect(a).not.toBeNull();
+ const mid = ((a.height >> 1) * a.width + (a.width >> 1)) * 4;
+ expect(a.pixels[mid + 3]).toBe(255);
+ edit.apply(patch!, 'before');
+ expect(a.pixels[mid + 3]).toBe(0);
+ });
+
+ it('encodes heights as sixteen bits across red and green', () => {
+ const f = flat(2, 0);
+ f.data[1] = 1; f.data[2] = 0.5;
+ const px = encodeHeightmap(f);
+ expect(Array.from(px.slice(4, 8))).toEqual([255, 255, 0, 255]);
+ const v = (px[8]! << 8) | px[9]!;
+ expect(v).toBe(Math.round(0.5 * 65535));
+ });
+});