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): heightmaps name their format, and 16-bit grey PNGs are read at full depth
yhh2c4141d34f68
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3bf6e8c86..9e6b9219b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -31,6 +31,7 @@ published separately; it ships inside the editor.- **Rays against the terrain, anywhere.** `Terrains.raycast(origin, direction, maxDistance)` meets the ground's triangles exactly (the ones collision and `heightAt` use) wherever the ray goes, with no physics world and no collision tile there, for a line of sight, a pick or a landing spot.- **Far versions for generated decoration.** A recipe member can name its far version (`far`: crossed cards, or a tent for a conifer, showing a rectangle of its texture), drawn past its layer's `lodDistance`, and decoration that leans with the ground (`attach: 'align'`) now leans in its merged mesh too.- **Terrain modifiers, and zones that level their ground.** `Terrains.setModifier` lays a change over the ground (`flattenModifier` levels a circle or a turned box, blending back over its edge) that what is drawn, the queries, rays and collision all follow, remaking only the pages and collision tiles it reaches; `heightBeneathAt` reads the ground as it was made. A `WorldZone` with `flatten` levels its plot to the ground's height at its centre.+- **Heightmaps say how they hold their heights.** `Terrain.heightmapFormat` is Grey (the grey or red channel at the file's depth, so a 16-bit grey PNG, what terrain tools export, is read at full precision) or Red + green (sixteen bits across two 8-bit channels); the format is no longer guessed from the pixels. A heightmap that cannot be read as data says it must ship as the PNG it is. **Upgrading:** a terrain whose heightmap packs sixteen bits into red and green sets `heightmapFormat` to Red + green.- **Rivers cut their beds.** A river's `WaterBody.bedDepth` cuts its bed into the terrain, a trough under its surface with banks that blend back into the ground, laid as terrain modifiers along it so what is drawn, the queries and collision follow, and editing the spline remakes only the ground along the river.- **Whether a place can be walked to.** `Terrains.findPath(from, to, { maxSlope, step, blocked })` searches the ground for a way a walker held to a slope can take, reading the ground where it goes (modifiers too, nothing baked), and returns it pulled straight with its length, or says whether there is no way, the search ran out, or an end stands on no ground: what a game checks a spawn or a goal against.- **World rules as a file, with an editor.** A WorldGen's `rules` can name a `.esworld` file: the biomes, recipes and layers as data, checked as they are read (a missing recipe or layer fails the world with where it went wrong), followed by the cook like a material so the meshes and materials it names ship with the scene, and watched so a saved edit lays the world out again. The editor opens it in a World Rules editor that lists the biomes, recipes and layers, edits each with a form, and says whether the engine would take the rules as they stand.diff --git a/docs/WORLD_GENERATION_PLAN.md b/docs/WORLD_GENERATION_PLAN.mdindex 2efe27475..14e5f6d43 100644--- a/docs/WORLD_GENERATION_PLAN.md+++ b/docs/WORLD_GENERATION_PLAN.md@@ -80,7 +80,7 @@| 优先级 | 项目 || --- | --- || P1 | 地形分层法线/粗糙度(每层 normal/ORM);当前地形着色器仅四张颜色图与统一粗糙度 |-| P1 | 高度图显式格式字段(取代按 G 通道猜 R8/RG16),数据图无色彩转换/预乘/有损压缩 |+| P1 | 高度图显式格式字段(取代按 G 通道猜 R8/RG16),数据图无色彩转换/预乘/有损压缩。已完成:`Terrain.heightmapFormat`(Grey:按文件位深,16 位 PNG 全精度读取;RedGreen16),PNG 数据读取支持 16 位通道;高度图按原始字节读取(无色彩转换/预乘),被压缩时地形失败并说明原因 || P1 | 河床与岸线生成配合(生成器形成岸线后提供湖泊边界/河流样条) || P2 | 球面与极远坐标(平面 XZ 的局限、原点精度) || P2 | 洞穴/体积挖掘(高度场不支持) |diff --git a/docs/astro/src/content/docs/graphics/terrain.mdx b/docs/astro/src/content/docs/graphics/terrain.mdxindex e6dae9c16..e04734d5e 100644--- a/docs/astro/src/content/docs/graphics/terrain.mdx+++ b/docs/astro/src/content/docs/graphics/terrain.mdx@@ -25,7 +25,8 @@ The ground is one of two kinds, chosen by `extent`:| Field | What it does ||---|---|| `extent` | `Area` or `Infinite`, as above. |-| `heightmap` | Area only. An image: the red channel is the height. If the green channel is not just grey it is taken as the low byte of a 16-bit height, so a 16-bit map exported into an 8-bit-per-channel PNG keeps its precision. Empty makes the ground from noise. |+| `heightmap` | Area only. An image read as data: its bytes as the file holds them, with no colour conversion, so it ships as the PNG it is (a heightmap compressed on the way fails the terrain, saying so). Empty makes the ground from noise. |+| `heightmapFormat` | How the heightmap holds its heights. **Grey**: the grey (or red) channel, at the depth of the file: 16 bits from a 16-bit PNG (what World Machine, Gaea and most tools export), 256 steps from an 8-bit one. **Red + green**: sixteen bits across red (high byte) and green (low byte) of an 8-bit image. || `sizeX`, `sizeZ`, `height` | An area's world size and the world height of its highest ground. For infinite ground `sizeX` is the span that `frequency` hills are spread over, and `sizeZ` is not used. || `cellSize` | The finest cell of the ground's mesh, in world units: what the ground is drawn at near the eye. Further off the cells double, level by level. || `detail` | A multiplier on how far the finest cells reach before the ground coarsens. Above 1 is finer at a distance and costs more triangles. |diff --git a/docs/astro/src/content/docs/zh-cn/graphics/terrain.mdx b/docs/astro/src/content/docs/zh-cn/graphics/terrain.mdxindex 4c358cd0a..98be431ef 100644--- a/docs/astro/src/content/docs/zh-cn/graphics/terrain.mdx+++ b/docs/astro/src/content/docs/zh-cn/graphics/terrain.mdx@@ -17,7 +17,8 @@ description: 一个 Terrain 组件,用高度图或噪声生成地面,可以是| 字段 | 作用 ||---|---|| `extent` | `Area` 或 `Infinite`,见上。 |-| `heightmap` | 仅区域。一张图:红色通道是高度。如果绿色通道不全是灰,它被当作 16 位高度的低字节,所以导出到每通道 8 位 PNG 里的 16 位高度图也能保留精度。为空则用噪声生成地面。 |+| `heightmap` | 仅区域。按数据读取的图:取文件里原样的字节,不做色彩转换,所以它以原本的 PNG 发布(打包时被压缩的高度图会让地形失败并说明原因)。为空则用噪声生成地面。 |+| `heightmapFormat` | 高度图如何存放高度。**灰度**:灰度(或红色)通道,按文件的位深读取:16 位 PNG 读 16 位(World Machine、Gaea 等大多数工具的导出格式),8 位图只有 256 级。**红 + 绿**:8 位图里红色(高字节)和绿色(低字节)拼成的 16 位。 || `sizeX`、`sizeZ`、`height` | 区域的世界尺寸,以及最高处地面的世界高度。对无限地面,`sizeX` 是 `frequency` 座山丘铺开的跨度,`sizeZ` 不使用。 || `cellSize` | 地面网格最细的格子,以世界单位计:视点近处地面按它绘制。再远一些,格子逐级加倍。 || `detail` | 最细格子在地面变粗之前能延伸多远的倍率。大于 1 时远处更细,三角形也更多。 |diff --git a/docs/astro/src/data/components.generated.json b/docs/astro/src/data/components.generated.jsonindex 269e92cff..243b79288 100644--- a/docs/astro/src/data/components.generated.json+++ b/docs/astro/src/data/components.generated.json@@ -5290,7 +5290,17 @@"key": "heightmap","type": "Asset<texture>","default": "none",- "doc": "A heightmap image: red is the height. Empty makes the ground from noise; a heightmap that cannot be read fails the terrain instead."+ "doc": "A heightmap image, read as data (shipped as the PNG it is). Empty makes the ground from noise; a heightmap that cannot be read fails the terrain instead."+ },+ {+ "key": "heightmapFormat",+ "type": "enum",+ "default": "Grey (8 or 16 bit)",+ "doc": "How the heightmap holds its heights: grey (or red) at the depth of the file, 16 bits from a 16-bit PNG; or sixteen bits across red (high byte) and green (low byte) of an 8-bit image.",+ "values": [+ "Grey (8 or 16 bit)",+ "Red + green (16 bit)"+ ]},{"key": "splatmap",@@ -5477,6 +5487,7 @@"extent","generatorVersion","heightmap",+ "heightmapFormat","splatmap","material","sizeX",diff --git a/examples/terrain-water/assets/scenes/main.esscene b/examples/terrain-water/assets/scenes/main.essceneindex c6f6d42e0..9977b5c49 100644--- a/examples/terrain-water/assets/scenes/main.esscene+++ b/examples/terrain-water/assets/scenes/main.esscene@@ -263,7 +263,8 @@"detail": 1,"heightmap": "assets/textures/height.png","splatmap": "assets/textures/splat.png",- "material": "assets/materials/ground.esmaterial"+ "material": "assets/materials/ground.esmaterial",+ "heightmapFormat": 1}}]diff --git a/examples/terrain-water/tools/build.mjs b/examples/terrain-water/tools/build.mjsindex 8cc4d0a4f..cd838d8ab 100644--- a/examples/terrain-water/tools/build.mjs+++ b/examples/terrain-water/tools/build.mjs@@ -495,7 +495,7 @@ function scene() {{ type: 'Transform', data: { position: { x: 0, y: WORLD.base, z: 0 } } },{ type: 'Terrain', data: {sizeX: WORLD.size, sizeZ: WORLD.size, height: WORLD.height, cellSize: 30, detail: 1,- heightmap: 'assets/textures/height.png', splatmap: 'assets/textures/splat.png', material: 'assets/materials/ground.esmaterial' } },+ heightmap: 'assets/textures/height.png', heightmapFormat: 1, splatmap: 'assets/textures/splat.png', material: 'assets/materials/ground.esmaterial' } },]);// The water: one zone over the whole island, which the sea, the lake and the two rivers are baked into and drawn from as one surface.add('Water', [diff --git a/examples/wilds/assets/scenes/main.esscene b/examples/wilds/assets/scenes/main.essceneindex ed046dd85..353d292fe 100644--- a/examples/wilds/assets/scenes/main.esscene+++ b/examples/wilds/assets/scenes/main.esscene@@ -257,7 +257,8 @@"rockSlope": 0.34,"dirtHeight": 0.5,"snowHeight": 0.84,- "material": "assets/materials/terrain.esmaterial"+ "material": "assets/materials/terrain.esmaterial",+ "heightmapFormat": 1}}]diff --git a/examples/wilds/tools/build.mjs b/examples/wilds/tools/build.mjsindex 61af6c6e3..540c1de53 100644--- a/examples/wilds/tools/build.mjs+++ b/examples/wilds/tools/build.mjs@@ -138,7 +138,7 @@ function landHeight(u, v) {return Math.min(1, Math.max(h, h + (rim - h) * wall));}-/** The heightmap: sixteen bits across red (high) and green (low), which the Terrain component reads back as one number. */+/** The heightmap: sixteen bits across red (high) and green (low), which the Terrain reads back as one number (its format RedGreen16). */function heightmap() {const n = WORLD.resolution;const image = png(n, n, (x, y) => {@@ -350,7 +350,7 @@ function scene() {{ type: 'Transform', data: {} },{ type: 'Terrain', data: {sizeX: WORLD.size, sizeZ: WORLD.size, height: WORLD.height, cellSize: 4, detail: 1.4,- heightmap: 'assets/textures/height.png', rockSlope: 0.34, dirtHeight: 0.5, snowHeight: 0.84, material: 'assets/materials/terrain.esmaterial' } },+ heightmap: 'assets/textures/height.png', heightmapFormat: 1, rockSlope: 0.34, dirtHeight: 0.5, snowHeight: 0.84, material: 'assets/materials/terrain.esmaterial' } },]),entity(5, 'Lake', [{ type: 'Transform', data: { position: { x: 0, y: waterY, z: 0 }, scale: { x: WORLD.size / 100, y: 1, z: WORLD.size / 100 } } },diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex ad934a860..b9ad9c5e8 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 · 1833 experimental · 3 deprecated+Symbols: 115 public · 159 beta · 1834 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -4678,6 +4678,11 @@ height: numberwidth: number```+## HeightmapFormat — const @experimental+```+{ readonly Grey: 0; readonly RedGreen16: 1; }+```+## HingeJoint2D — const @experimental```ComponentDef<HingeJoint2DData>@@ -10003,6 +10008,7 @@ friction: numbergeneratorVersion: numberheight: numberheightmap: number+heightmapFormat: numberlayerColor0: ColorlayerColor1: ColorlayerColor2: Color@@ -13980,7 +13986,7 @@ Plugin## heightfieldFromPixels — function @experimental```-(width: number, height: number, pixels: ArrayLike<number>): Heightfield+(width: number, height: number, pixels: ArrayLike<number>, format?: number, wide?: ArrayLike<number>): Heightfield```## imageBitmapOptions — function @experimentaldiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex c017d78a9..f756b7e26 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 · 1852 experimental · 3 deprecated+Symbols: 115 public · 164 beta · 1853 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -4686,6 +4686,11 @@ height: numberwidth: number```+## HeightmapFormat — const @experimental+```+{ readonly Grey: 0; readonly RedGreen16: 1; }+```+## HingeJoint2D — const @experimental```ComponentDef<HingeJoint2DData>@@ -10216,6 +10221,7 @@ friction: numbergeneratorVersion: numberheight: numberheightmap: number+heightmapFormat: numberlayerColor0: ColorlayerColor1: ColorlayerColor2: Color@@ -14233,7 +14239,7 @@ Plugin## heightfieldFromPixels — function @experimental```-(width: number, height: number, pixels: ArrayLike<number>): Heightfield+(width: number, height: number, pixels: ArrayLike<number>, format?: number, wide?: ArrayLike<number>): Heightfield```## imageBitmapOptions — function @experimentaldiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex 18a9cc404..81c170345 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 · 1832 experimental · 3 deprecated+Symbols: 115 public · 161 beta · 1833 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -4673,6 +4673,11 @@ height: numberwidth: number```+## HeightmapFormat — const @experimental+```+{ readonly Grey: 0; readonly RedGreen16: 1; }+```+## HingeJoint2D — const @experimental```ComponentDef<HingeJoint2DData>@@ -9998,6 +10003,7 @@ friction: numbergeneratorVersion: numberheight: numberheightmap: number+heightmapFormat: numberlayerColor0: ColorlayerColor1: ColorlayerColor2: Color@@ -13975,7 +13981,7 @@ Plugin## heightfieldFromPixels — function @experimental```-(width: number, height: number, pixels: ArrayLike<number>): Heightfield+(width: number, height: number, pixels: ArrayLike<number>, format?: number, wide?: ArrayLike<number>): Heightfield```## imageBitmapOptions — function @experimentaldiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex 4b20c3502..998e9b8a6 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 · 1854 experimental · 3 deprecated+Symbols: 115 public · 159 beta · 1855 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -4673,6 +4673,11 @@ height: numberwidth: number```+## HeightmapFormat — const @experimental+```+{ readonly Grey: 0; readonly RedGreen16: 1; }+```+## HingeJoint2D — const @experimental```ComponentDef<HingeJoint2DData>@@ -10291,6 +10296,7 @@ friction: numbergeneratorVersion: numberheight: numberheightmap: number+heightmapFormat: numberlayerColor0: ColorlayerColor1: ColorlayerColor2: Color@@ -14279,7 +14285,7 @@ Plugin## heightfieldFromPixels — function @experimental```-(width: number, height: number, pixels: ArrayLike<number>): Heightfield+(width: number, height: number, pixels: ArrayLike<number>, format?: number, wide?: ArrayLike<number>): Heightfield```## imageBitmapOptions — function @experimentaldiff --git a/sdk/etc/terrain.api.md b/sdk/etc/terrain.api.mdindex d720132dc..3177624ba 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 · 56 experimental · 0 deprecated+Symbols: 0 public · 0 beta · 57 experimental · 0 deprecated## Eroded — interface @experimental```@@ -39,6 +39,11 @@ height: numberwidth: number```+## HeightmapFormat — const @experimental+```+{ readonly Grey: 0; readonly RedGreen16: 1; }+```+## ModifiedSource — class @experimental```base: TerrainSource@@ -218,6 +223,7 @@ friction: numbergeneratorVersion: numberheight: numberheightmap: number+heightmapFormat: numberlayerColor0: ColorlayerColor1: ColorlayerColor2: Color@@ -382,7 +388,7 @@ ResourceDef<Terrains>## heightfieldFromPixels — function @experimental```-(width: number, height: number, pixels: ArrayLike<number>): Heightfield+(width: number, height: number, pixels: ArrayLike<number>, format?: number, wide?: ArrayLike<number>): Heightfield```## levelRange — function @experimentaldiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex bdcc75c46..c093d401c 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 · 1845 experimental · 3 deprecated+Symbols: 115 public · 159 beta · 1846 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -4673,6 +4673,11 @@ height: numberwidth: number```+## HeightmapFormat — const @experimental+```+{ readonly Grey: 0; readonly RedGreen16: 1; }+```+## HingeJoint2D — const @experimental```ComponentDef<HingeJoint2DData>@@ -10005,6 +10010,7 @@ friction: numbergeneratorVersion: numberheight: numberheightmap: number+heightmapFormat: numberlayerColor0: ColorlayerColor1: ColorlayerColor2: Color@@ -14006,7 +14012,7 @@ Plugin## heightfieldFromPixels — function @experimental```-(width: number, height: number, pixels: ArrayLike<number>): Heightfield+(width: number, height: number, pixels: ArrayLike<number>, format?: number, wide?: ArrayLike<number>): Heightfield```## imageBitmapOptions — function @experimentaldiff --git a/sdk/src/asset/pngData.ts b/sdk/src/asset/pngData.tsindex 10b2a366e..eda855caf 100644--- a/sdk/src/asset/pngData.ts+++ b/sdk/src/asset/pngData.ts@@ -13,15 +13,21 @@ import type { DecodedPixels } from './imageDecode';const SIGNATURE = [137, 80, 78, 71, 13, 10, 26, 10];-/** Whether `bytes` is a PNG this reader takes: 8 bits a channel, grey, grey+alpha, RGB or RGBA, not interlaced. */-function header(bytes: Uint8Array): { width: number; height: number; channels: number } | null {+/** A PNG read as data: its RGBA bytes, and for one of 16 bits a channel its first channel at full depth too. */+export interface PngData extends DecodedPixels {+ /** The first channel (grey, or red) of each pixel as the file holds it, 0 to 65535: present only for a PNG of 16 bits a channel. */+ wide?: Uint16Array;+}++/** Whether `bytes` is a PNG this reader takes: 8 or 16 bits a channel, grey, grey+alpha, RGB or RGBA, not interlaced. */+function header(bytes: Uint8Array): { width: number; height: number; channels: number; depth: number } | null {if (bytes.length < 33 || SIGNATURE.some((b, i) => bytes[i] !== b)) return null;const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);const width = view.getUint32(16), height = view.getUint32(20);const depth = bytes[24], type = bytes[25], interlace = bytes[28];const channels = ({ 0: 1, 2: 3, 4: 2, 6: 4 } as Record<number, number>)[type!];- if (depth !== 8 || !channels || interlace !== 0 || !width || !height) return null;- return { width, height, channels };+ if ((depth !== 8 && depth !== 16) || !channels || interlace !== 0 || !width || !height) return null;+ return { width, height, channels, depth };}async function inflate(data: Uint8Array<ArrayBuffer>): Promise<Uint8Array> {@@ -38,10 +44,12 @@ const paeth = (a: number, b: number, c: number): number => {* The RGBA bytes of a PNG, top row first, as stored; null when it is not a PNG this reads or the host has no* DecompressionStream, and the caller decodes it as an image instead.*/-export async function decodePngData(bytes: Uint8Array): Promise<DecodedPixels | null> {+export async function decodePngData(bytes: Uint8Array): Promise<PngData | null> {const head = header(bytes);if (!head || typeof DecompressionStream !== 'function') return null;- const { width, height, channels } = head;+ const { width, height, channels, depth } = head;+ // The row filters work on bytes, a pixel's width apart: two bytes a channel at 16 bits.+ const size = depth / 8, step = channels * size;const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);const parts: Uint8Array[] = [];for (let at = 8; at + 8 <= bytes.length;) {@@ -54,30 +62,35 @@ export async function decodePngData(bytes: Uint8Array): Promise<DecodedPixels |const joined = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));parts.reduce((at, p) => (joined.set(p, at), at + p.length), 0);const raw = await inflate(joined);- const stride = width * channels;+ const stride = width * step;if (raw.length < (stride + 1) * height) return null;const rows = new Uint8Array(stride * height);for (let y = 0; y < height; y++) {const filter = raw[y * (stride + 1)]!;const src = y * (stride + 1) + 1, dst = y * stride, up = dst - stride;for (let x = 0; x < stride; x++) {- const a = x >= channels ? rows[dst + x - channels]! : 0;+ const a = x >= step ? rows[dst + x - step]! : 0;const b = y > 0 ? rows[up + x]! : 0;- const c = x >= channels && y > 0 ? rows[up + x - channels]! : 0;+ const c = x >= step && y > 0 ? rows[up + x - step]! : 0;const v = raw[src + x]!;rows[dst + x] = (filter === 1 ? v + a : filter === 2 ? v + b : filter === 3 ? v + ((a + b) >> 1): filter === 4 ? v + paeth(a, b, c) : v) & 255;}}- if (channels === 4) return { width, height, pixels: rows };+ if (channels === 4 && size === 1) return { width, height, pixels: rows };+ // At 16 bits a channel the bytes are big-endian: the RGBA bytes keep each channel's high byte.+ const at = (i: number, ch: number): number => rows[i * step + ch * size]!;const pixels = new Uint8Array(width * height * 4);for (let i = 0; i < width * height; i++) {- const s = i * channels, d = i * 4;+ const d = i * 4;const grey = channels <= 2;- pixels[d] = rows[s]!;- pixels[d + 1] = grey ? rows[s]! : rows[s + 1]!;- pixels[d + 2] = grey ? rows[s]! : rows[s + 2]!;- pixels[d + 3] = channels === 2 ? rows[s + 1]! : channels === 4 ? rows[s + 3]! : 255;+ pixels[d] = at(i, 0);+ pixels[d + 1] = grey ? at(i, 0) : at(i, 1);+ pixels[d + 2] = grey ? at(i, 0) : at(i, 2);+ pixels[d + 3] = channels === 2 ? at(i, 1) : channels === 4 ? at(i, 3) : 255;}- return { width, height, pixels };+ if (size === 1) return { width, height, pixels };+ const wide = new Uint16Array(width * height);+ for (let i = 0; i < width * height; i++) wide[i] = (rows[i * step]! << 8) | rows[i * step + 1]!;+ return { width, height, pixels, wide };}diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.tsindex 2614c96fa..504b8c0f6 100644--- a/sdk/src/core-content.ts+++ b/sdk/src/core-content.ts@@ -831,7 +831,7 @@ export {type Plant, type Ground, type ScatterParams, type BladeParams, type CardRect,} from './foliage/builder';export {- erodeHeightfield, erosionJob, heightfieldFromPixels, proceduralHeightfield, sampleHeight, terrainNormal,+ erodeHeightfield, erosionJob, heightfieldFromPixels, HeightmapFormat, proceduralHeightfield, sampleHeight, terrainNormal,type Eroded, type ErosionParams, type Heightfield, type ProceduralParams,} from './terrain/heightfield';export { FieldSource, NoiseSource, ModifiedSource, flattenModifier, noised, type NoiseParams, type Splat, type TerrainSource, type TerrainModifier } from './terrain/source';diff --git a/sdk/src/terrain/heightfield.ts b/sdk/src/terrain/heightfield.tsindex 8e314e351..6ba32e63e 100644--- a/sdk/src/terrain/heightfield.ts+++ b/sdk/src/terrain/heightfield.ts@@ -17,19 +17,27 @@ export interface Heightfield {}/**- * A heightfield from an RGBA image: the red channel is the height. 8 bits is 256 steps, which on a tall terrain- * reads as terraces, so a green channel that is not all zero is taken as the low byte of a 16-bit height- * (red is the high one), the way an exported 16-bit map is usually packed into an 8-bit-per-channel PNG.+ * How a heightmap image holds its heights. The file says how deep its channels are; this says what they mean, so an image is never+ * read one way or another by what its pixels happen to hold.+ * @experimental*/-export function heightfieldFromPixels(width: number, height: number, pixels: ArrayLike<number>): Heightfield {+export const HeightmapFormat = {+ /** The grey (or red) channel is the height, at the depth the file has: 16 bits from a 16-bit PNG, 8 (256 steps) from any other. */+ Grey: 0,+ /** Sixteen bits across two 8-bit channels: red is the high byte, green the low one. */+ RedGreen16: 1,+} as const;++/**+ * A heightfield from an RGBA image read as data, 0 at its lowest and 1 at its highest, by `format`. `wide` is the first channel at 16+ * bits, for an image whose file holds 16 bits a channel.+ */+export function heightfieldFromPixels(width: number, height: number, pixels: ArrayLike<number>, format: number = HeightmapFormat.Grey,+ wide?: ArrayLike<number>): Heightfield {const data = new Float32Array(width * height);- let wide = false;- for (let i = 0; i < width * height; i++) {- if (pixels[i * 4 + 1]! !== 0 && pixels[i * 4 + 1]! !== pixels[i * 4]!) { wide = true; break; }- }for (let i = 0; i < width * height; i++) {- const hi = pixels[i * 4]!;- data[i] = wide ? (hi * 256 + pixels[i * 4 + 1]!) / 65535 : hi / 255;+ data[i] = format === HeightmapFormat.RedGreen16 ? (pixels[i * 4]! * 256 + pixels[i * 4 + 1]!) / 65535+ : wide ? wide[i]! / 65535 : pixels[i * 4]! / 255;}return { width, height, data };}diff --git a/sdk/src/terrain/index.ts b/sdk/src/terrain/index.tsindex 5436ddf32..3950447c7 100644--- a/sdk/src/terrain/index.ts+++ b/sdk/src/terrain/index.ts@@ -4,7 +4,7 @@ export {Terrain, TerrainExtent, Terrains, TerrainsRes, TerrainPlugin, terrainPlugin, paintWeights, NOISE_PROVIDER, type TerrainData, type TerrainStatus,} from './terrainPlugin';export {- erodeHeightfield, erosionJob, heightfieldFromPixels, proceduralHeightfield, sampleHeight, terrainNormal,+ erodeHeightfield, erosionJob, heightfieldFromPixels, HeightmapFormat, proceduralHeightfield, sampleHeight, terrainNormal,type Eroded, type ErosionParams, type Heightfield, type ProceduralParams,} from './heightfield';export { FieldSource, NoiseSource, ModifiedSource, flattenModifier, noised, type NoiseParams, type Splat, type TerrainSource, type TerrainModifier } from './source';diff --git a/sdk/src/terrain/terrainPlugin.ts b/sdk/src/terrain/terrainPlugin.tsindex 2779866b1..0e2712b4a 100644--- a/sdk/src/terrain/terrainPlugin.ts+++ b/sdk/src/terrain/terrainPlugin.ts@@ -36,7 +36,7 @@ import { EditorView, editorViewEye } from '../camera/EditorView';import { log } from '../util/logger';import { bakesOf } from '../runtime/bakes';import type { Color, Entity } from '../types';-import { erosionJob, heightfieldFromPixels, type Heightfield } from './heightfield';+import { erosionJob, heightfieldFromPixels, HeightmapFormat, type Heightfield } from './heightfield';import { findGroundPath, type ReachOptions, type ReachResult } from './reach';import { FieldSource, ModifiedSource, type TerrainModifier, type TerrainSource } from './source';import { levelRange, nodeKey, parentOf, selectNodes, type QuadtreeParams, type TerrainNode } from './quadtree';@@ -66,8 +66,10 @@ export interface TerrainData {provider: string;world: string;generatorVersion: number;- /** A heightmap image: red is the height (green, if it is not just grey, its low byte). Empty makes the ground from noise. */+ /** A heightmap image, read as {@link heightmapFormat} says. Empty makes the ground from noise. */heightmap: number;+ /** How the heightmap holds its heights: a {@link HeightmapFormat}. */+ heightmapFormat: number;/** An image whose four channels are the weights of the four layers; empty paints by height and slope. */splatmap: number;/** A material on the Terrain shader. Empty draws the layer colours onto the ground. */@@ -118,7 +120,7 @@ const rgb = (r: number, g: number, b: number): Color => ({ r, g, b, a: 1 });* @experimental*/export const Terrain: ComponentDef<TerrainData> = defineComponent<TerrainData>('Terrain', {- extent: TerrainExtent.Area, provider: NOISE_PROVIDER, world: '', generatorVersion: 1, heightmap: 0, splatmap: 0, material: 0,+ extent: TerrainExtent.Area, provider: NOISE_PROVIDER, world: '', generatorVersion: 1, heightmap: 0, heightmapFormat: HeightmapFormat.Grey, splatmap: 0, material: 0,sizeX: 1000, sizeZ: 1000, height: 150, cellSize: 2, detail: 1, drawDistance: 4000,collision: true, collisionDistance: 64, collisionLayer: 0, friction: 0.6,seed: 1, frequency: 3, octaves: 5, persistence: 0.5, ridged: 0.35, resolution: 257, warp: 0, erosion: 0,@@ -131,7 +133,8 @@ export const Terrain: ComponentDef<TerrainData> = defineComponent<TerrainData>('provider: { category: 'Shape', tooltip: 'The generator the ground is made by, without end or (with no heightmap) in an area: estella:noise, or one the game registers. The same provider, world, seed and version are the same ground on every machine, and two areas side by side join.' },world: { category: 'Shape', tooltip: 'The world (a planet, a level) the ground belongs to, as the game names it; handed to the provider.' },generatorVersion: { min: 1, step: 1, category: 'Shape', tooltip: 'The generator version the world was made with. A version the provider no longer has fails the terrain rather than growing other ground under what was built.' },- heightmap: { tooltip: 'A heightmap image: red is the height. Empty makes the ground from noise; a heightmap that cannot be read fails the terrain instead.', category: 'Shape', shownWhen: { field: 'extent', values: [TerrainExtent.Area] } },+ heightmap: { tooltip: 'A heightmap image, read as data (shipped as the PNG it is). Empty makes the ground from noise; a heightmap that cannot be read fails the terrain instead.', category: 'Shape', shownWhen: { field: 'extent', values: [TerrainExtent.Area] } },+ heightmapFormat: { enum: [{ label: 'Grey (8 or 16 bit)', value: HeightmapFormat.Grey }, { label: 'Red + green (16 bit)', value: HeightmapFormat.RedGreen16 }], category: 'Shape', tooltip: 'How the heightmap holds its heights: grey (or red) at the depth of the file, 16 bits from a 16-bit PNG; or sixteen bits across red (high byte) and green (low byte) of an 8-bit image.', shownWhen: { field: 'extent', values: [TerrainExtent.Area] } },splatmap: { tooltip: 'An image whose red, green, blue and alpha are the weights of grass, dirt, snow and rock.', category: 'Layers', shownWhen: { field: 'extent', values: [TerrainExtent.Area] } },material: { tooltip: 'A material on the Terrain shader. Empty draws the layer colours onto the ground.', category: 'Layers' },sizeX: { min: 1, category: 'Shape', tooltip: 'An area\'s size along x; for ground without end, the span its hills are spread over.' },@@ -559,7 +562,7 @@ export class TerrainPlugin implements Plugin {} else {// A heightmap named and not read is a failure: a world built on that ground must not quietly get other ground.const height = await this.pixelsOf(app, data.heightmap);- if (data.heightmap && !height) throw new TerrainUnavailable(`the heightmap (texture ${data.heightmap}) could not be read`);+ if (data.heightmap && !height) throw new TerrainUnavailable(`the heightmap (texture ${data.heightmap}) could not be read: it is read as data, so it must ship as the PNG it is (not compressed)`);const splat = await this.pixelsOf(app, data.splatmap);if (built.epoch !== epoch || !app.world.valid(entity)) return;// Without a heightmap an area is a window on its provider's ground, read where it stands in the world: two areas side by@@ -567,7 +570,7 @@ export class TerrainPlugin implements Plugin {let range: [number, number] = [0, data.height];let made: Heightfield;if (height) {- made = heightfieldFromPixels(height.width, height.height, height.pixels);+ made = heightfieldFromPixels(height.width, height.height, height.pixels, data.heightmapFormat, height.wide);} else {const provider = providerOf({ ...data, erosion: 0 });const checked = new ProviderSource(provider, data.world, data.seed, data.generatorVersion, 0, 0, 1, paintBy(provider, data));@@ -602,7 +605,7 @@ export class TerrainPlugin implements Plugin {}}- private async pixelsOf(app: App, handle: number): Promise<{ width: number; height: number; pixels: Uint8Array } | null> {+ private async pixelsOf(app: App, handle: number): Promise<{ width: number; height: number; pixels: Uint8Array; wide?: Uint16Array } | null> {if (!handle || !app.hasResource(Assets)) return null;const assets = app.getResource(Assets);const path = assets.pathForHandle('texture', handle);diff --git a/sdk/tests/png-data.test.ts b/sdk/tests/png-data.test.tsindex c974c5612..48e417e4c 100644--- a/sdk/tests/png-data.test.ts+++ b/sdk/tests/png-data.test.ts@@ -54,4 +54,23 @@ describe('a PNG read as data', () => {it('declines what it does not read, so the image path decodes it', async () => {expect(await decodePngData(new Uint8Array([1, 2, 3]))).toBeNull();});++ it('reads a 16-bit grey PNG at its full depth, keeping each high byte in the RGBA bytes', async () => {+ const values = [0, 0x1234, 0xffff, 0x8001];+ const raw: number[] = [];+ for (let y = 0; y < 2; y++) { raw.push(0); for (let x = 0; x < 2; x++) { const v = values[y * 2 + x]!; raw.push(v >> 8, v & 255); } }+ const chunk = (name: string, data: Uint8Array): number[] => {+ const len = [data.length >>> 24, (data.length >>> 16) & 255, (data.length >>> 8) & 255, data.length & 255];+ return [...len, ...Array.from(name, (ch) => ch.charCodeAt(0)), ...data, 0, 0, 0, 0];+ };+ const ihdr = new Uint8Array(13);+ new DataView(ihdr.buffer).setUint32(0, 2);+ new DataView(ihdr.buffer).setUint32(4, 2);+ ihdr[8] = 16; ihdr[9] = 0;+ const bytes = new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10, ...chunk('IHDR', ihdr), ...chunk('IDAT', deflateSync(Buffer.from(raw))), ...chunk('IEND', new Uint8Array())]);+ const out = await decodePngData(bytes);+ expect(Array.from(out!.wide!)).toEqual(values);+ expect(out!.pixels[4]).toBe(0x12);+ expect(out!.pixels[7]).toBe(255);+ });});diff --git a/sdk/tests/terrain-surface.test.ts b/sdk/tests/terrain-surface.test.tsindex ee00887a1..e0114a9b9 100644--- a/sdk/tests/terrain-surface.test.ts+++ b/sdk/tests/terrain-surface.test.ts@@ -276,3 +276,16 @@ describe.skipIf(!HAS_WASM || !hasSideModule('physics3d'))('the ground in the 3Dexpect(p.y).toBeLessThan(under + 1.2);});});++describe('heightfieldFromPixels', () => {+ it('reads heights as its format says, never by what the pixels hold', async () => {+ const { heightfieldFromPixels, HeightmapFormat } = await import('../src/terrain/heightfield');+ // Two texels whose green happens to differ from red: grey reads red alone, red+green reads both.+ const pixels = [0x80, 0x40, 0, 255, 0xff, 0xff, 0, 255];+ const grey = heightfieldFromPixels(2, 1, pixels).data, wide = heightfieldFromPixels(2, 1, pixels, HeightmapFormat.RedGreen16).data;+ expect(grey[0]).toBeCloseTo(0x80 / 255, 6);+ expect(wide[0]).toBeCloseTo(0x8040 / 65535, 6);+ expect([grey[1], wide[1]]).toEqual([1, 1]);+ expect(heightfieldFromPixels(2, 1, pixels, HeightmapFormat.Grey, [0x8001, 0]).data[0]).toBeCloseTo(0x8001 / 65535, 6);+ });+});diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex 4d46231e4..d55720bb7 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -2806,4 +2806,6 @@ export const NOTED = {{"note":"Whether a place can be walked to."},"feat(water): rivers cut their beds into the terrain":{"note":"Rivers cut their beds."},+ "feat(terrain): heightmaps name their format, and 16-bit grey PNGs are read at full depth":+ {"note":"Heightmaps say how they hold their heights."},};