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(assets): a texture's Use says whether it is a picture or numbers - Data keeps its depth and its size in a build, a 16-bit PNG is imported as Data, a Terrain's heightmap is marked Data when it is set, and Project Health lists the ones that are not
yhh6558d50aea14
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 0f0c9762a..16fe0962f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,12 +16,13 @@ published separately; it ships inside the editor.### Added+- **A texture says whether it is a picture or numbers.** Import settings have a **Use**: Colour, or Data for an image read a number a texel (a heightmap, a mask of measured values, a lookup table). A build treats Data as what it is: never compressed, never decoded as sRGB or filled, kept at its depth, and at its own size unless Max Size (which now offers Source size) says otherwise, in which case it is resampled at 16 bits and not through 8. Nobody has to know to set it: a PNG of 16 bits a sample is imported as Data from the editor and the CLI alike, a texture put in a `Terrain`'s heightmap is marked Data there and then, and Project Health lists textures a component reads as numbers that are still set up as pictures, with the fix on the row.- **An ocean reaches the horizon.** The sea's surface is rings of mesh round the camera, and it ended where they did: from a hill, or with a small `cells` and `rings`, a straight edge with nothing past it. A flat apron now carries it on to 80 km, at the cost of one row of quads.- **One setting says what a unit is, for materials too.** A shader param declares `unit(length)` or `unit(perLength)` and its default and range follow the project's Units per Metre, as a component's lengths and a post-process effect's already did; the inspector shows the project's numbers. The water was the reason: its shader, `WaterBody`, `WaterZone` and the sky's World Units per km held their defaults in metres while the engine's reference is centimetres, so stock water in a default project was a hundredth of its size and a scene in metres copied from one in centimetres drew clear water. They are now written once, at the reference, and are the same water in either. **A scene that relied on the old defaults in a centimetre project** (a `WaterBody` or `WaterZone` field left unset, a Water material with unset lengths, clouds with World Units per km unset) draws them a hundred times larger than before, which is what they were meant to be; state the values, or set Units per Metre to 1 if the scene is in metres.### Fixed-- **A 16-bit heightmap keeps its depth and size in a build.** A texture is capped at its Max Size (2048 unless set) when a build cooks it, and the cap decodes a PNG to 8 bits a channel on the way. A `Terrain` heightmap of 4096 samples and 16 bits therefore shipped as 2048 samples of 256 steps: the exported ground was terraced and coarser than the same ground in the editor, which reads the file itself, and nothing said so. A PNG that holds 16 bits a channel now ships byte for byte. A texture a `Terrain` names as its heightmap is never capped either, at any depth.+- **A 16-bit heightmap keeps its depth and size in a build.** A texture is capped at its Max Size (2048 unless set) when a build cooks it, and the cap decodes a PNG to 8 bits a channel on the way. A `Terrain` heightmap of 4096 samples and 16 bits therefore shipped as 2048 samples of 256 steps: the exported ground was terraced and coarser than the same ground in the editor, which reads the file itself, and nothing said so. See Use, above; a PNG of 16 bits that is still marked Colour ships byte for byte and the build says so.## [0.103.0] - 2026-11-12diff --git a/desktop b/desktopindex 0fa4d369f..d09d5335a 160000--- a/desktop+++ b/desktop@@ -1 +1 @@-Subproject commit 0fa4d369f65ea31c0f1d8db8ab376cfcdfc7b99f+Subproject commit d09d5335ae772b95dcc7efe07c6fe99a3b73a4d9diff --git a/docs/astro/src/content/docs/assets/textures.mdx b/docs/astro/src/content/docs/assets/textures.mdxindex e5451267b..2053d19d3 100644--- a/docs/astro/src/content/docs/assets/textures.mdx+++ b/docs/astro/src/content/docs/assets/textures.mdx@@ -117,7 +117,8 @@ Browser — every sprite that uses the texture inherits them.| Setting | Default | What it does ||---|---|---|-| **Max Size** | `2048` | Downscale cap applied at cook (256 to 8192, a power of two). A source larger than this on its longest side is box-filtered down; a smaller source is untouched. |+| **Use** | `Colour` | What the image holds. **Colour** is a picture: a build may shrink it to Max Size, compress it and fill the colour under its clear texels. **Data** is numbers a texel, read as they are (a heightmap, a mask of measured values, a lookup table): a build keeps its depth (a 16-bit PNG stays 16 bits), never compresses it or decodes it as sRGB, and shrinks it only when Max Size says so, at that depth. A PNG of 16 bits a sample is imported as Data, a texture given to a `Terrain` as its heightmap is marked Data when it is, and Project Health lists any that are read as numbers and still set up as pictures, with a one-click fix. |+| **Max Size** | `2048` | Downscale cap applied at cook (256 to 8192, a power of two). A source larger than this on its longest side is box-filtered down; a smaller source is untouched. **Source size** never shrinks it, and is what a Data texture starts at. || **Compression** | `Auto` | **GPU compressed** ships a KTX2 (Basis Universal) that stays compressed in video memory — about a quarter of the decoded image — and transcodes per device. **Original image** ships the file as it is: exact, and for flat art far smaller to download, but decoded in full on the GPU. **Auto** is GPU compressed for a texture a mesh draws (directly or through its material) and the original image for sprites and UI. A build does what this row says; it never swaps one for the other because a file came out smaller. || **Compress Format** | `uastc` | `uastc` — high quality, larger. `etc1s` — much smaller, lower quality (good for photographic art). Only used when the texture is GPU compressed. || **Mip Maps** | on | Keep a chain of half-size copies so a texture drawn small samples a filtered image instead of shimmering; costs a third more memory. Turn it off for pixel art and UI that is always drawn at its own size. |diff --git a/docs/astro/src/content/docs/graphics/terrain.mdx b/docs/astro/src/content/docs/graphics/terrain.mdxindex b19f2cb82..4631ec337 100644--- a/docs/astro/src/content/docs/graphics/terrain.mdx+++ b/docs/astro/src/content/docs/graphics/terrain.mdx@@ -25,7 +25,7 @@ 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 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. |+| `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). Its texture is marked **Data** in its import settings when it is put here (see [Textures](/assets/textures/)): no size cap unless you set one, and a cap keeps the file's 16 bits. 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. |diff --git a/pipeline/src/assets/assetMeta.ts b/pipeline/src/assets/assetMeta.tsindex db136ed59..8dc1a006d 100644--- a/pipeline/src/assets/assetMeta.ts+++ b/pipeline/src/assets/assetMeta.ts@@ -16,7 +16,7 @@ import { randomUUID } from 'node:crypto';import { META_EXT } from './contentPolicy';import { importerDefaults } from '../project/importSettings';import {- EXT_TO_TYPE, metaTypeForExt, metaTypeForContent, needsContentType, CONTENT_SNIFF_BYTES,+ EXT_TO_TYPE, metaTypeForExt, metaTypeForContent, needsContentType, CONTENT_SNIFF_BYTES, dataImporterForHead,} from '../../../tools/assetMetaTable.js';export const META_VERSION = '2.0';@@ -83,7 +83,22 @@ export async function lutStripImporter(absFile: string): Promise<Record<string,if (bytesRead < 24 || head.readUInt32BE(0) !== 0x89504e47) return null;const width = head.readUInt32BE(16), height = head.readUInt32BE(20);if (![16, 32, 64].includes(height) || width !== height * height) return null;- return { compress: 'off', mipmaps: false, sRGB: false, filterMode: 'linear', wrapMode: 'clamp', maxSize: width };+ return { use: 'data', compress: 'off', mipmaps: false, sRGB: false, filterMode: 'linear', wrapMode: 'clamp', maxSize: width };+ } catch {+ return null;+ } finally {+ await handle?.close();+ }+}++/** What a texture file that is plainly numbers needs (assetMetaTable's `dataImporterForHead`), or null for a picture. */+export async function wideImageImporter(absFile: string): Promise<Record<string, unknown> | null> {+ let handle: Awaited<ReturnType<typeof open>> | undefined;+ try {+ handle = await open(absFile, 'r');+ const head = Buffer.alloc(32);+ const { bytesRead } = await handle.read(head, 0, 32, 0);+ return dataImporterForHead(absFile, head.subarray(0, bytesRead));} catch {return null;} finally {@@ -102,7 +117,7 @@ export async function adoptOrphan(absFile: string,const type = await metaTypeForFile(absFile);if (!type) return 'unknown-type';// What the file's own shape says comes first, and what an importing source asked for over it.- if (type === 'texture') importer = { ...(await lutStripImporter(absFile) ?? {}), ...importer };+ if (type === 'texture') importer = { ...(await lutStripImporter(absFile) ?? await wideImageImporter(absFile) ?? {}), ...importer };// Exclusive: the file's creator may have written its sidecar since the check, and// the uuid it handed out is the one refs point at.try {diff --git a/pipeline/src/assets/cookAssets.ts b/pipeline/src/assets/cookAssets.tsindex e33bca929..c8943678d 100644--- a/pipeline/src/assets/cookAssets.ts+++ b/pipeline/src/assets/cookAssets.ts@@ -51,7 +51,7 @@ import {} from './ktx2Mips';import { cookCached } from './cookCache';import { cookTexture, loadTextureEncoder, pngDimensions, fillClearTexels, fillsClearTexels, COMPRESSED_TARGETS, type BasisEncoderModule } from './textureCook';-import { meshTextureRoles, texturesReadAsNumbers } from './textureUsage';+import { meshTextureRoles } from './textureUsage';import { makeStreamTail, type StreamTail } from './streamTail';import { matchScriptAssetRefs, scanScriptAssetRefs } from './scriptAssetRefs';import { readManifest } from '../project/readProject';@@ -681,7 +681,6 @@ export async function cookAssets(// What Auto compression resolves by: whether a mesh anywhere in the project draws it.const roles = await meshTextureRoles(root, shippable);const drawnIn3D = new Set(roles.keys());- const readAsNumbers = await texturesReadAsNumbers(root, shippable);const pageCompressedBy = (frame: AssetEntry): boolean =>textureAsksCompression(readTextureCookSettings(frame.importer, platform).compress, drawnIn3D.has(frame.uuid));@@ -852,7 +851,7 @@ export async function cookAssets(root, path: entry.path, data, ext, importer: entry.importer, platform,encoder: textureEnc ? { module: textureEnc, id: encoderId } : null,compressTextures, atlasTextures, drawnIn3D: drawnIn3D.has(entry.uuid),- resizeTextures: opts.resizeTextures, readAsNumbers: readAsNumbers.has(entry.uuid),+ resizeTextures: opts.resizeTextures,});data = t.data; ext = t.ext; cook = t.cook; compressedFormats = t.compressedFormats;warnings.push(...t.warnings);diff --git a/pipeline/src/assets/dataTextureAudit.ts b/pipeline/src/assets/dataTextureAudit.tsindex 1c3b7852a..51e547ee9 100644--- a/pipeline/src/assets/dataTextureAudit.ts+++ b/pipeline/src/assets/dataTextureAudit.ts@@ -12,6 +12,8 @@import { reflectEsshader } from '../../../sdk/src/render/shaderReflect';import { builtinShaderTemplate } from '../../../sdk/src/render/builtinShaders';import { builtinRefId, resolveDocumentRef } from '../../../sdk/src/asset/documentRef';+import { DATA_TEXTURE_FIELDS } from '../../../sdk/src/asset/textureUse';+import { textureUse } from '../project/importSettings';export interface DataTextureAuditSource {/** Project paths of every `.esmaterial`. */@@ -87,3 +89,45 @@ export async function dataTexturesMarkedColour(src: DataTextureAuditSource): Pro}return [...found.values()].sort((a, b) => a.texture.localeCompare(b.texture));}++export interface NumberTextureAuditSource {+ /** Project paths of every scene and prefab. */+ documents: Iterable<string>;+ readText(path: string): Promise<string | null>;+ resolveRef(ref: string): string | null;+ importer(path: string): Record<string, unknown> | undefined;+}++export interface NumberTextureFinding {+ texture: string;+ /** Every component field that reads it as numbers. */+ readBy: Array<{ document: string; component: string; field: string }>;+}++/**+ * Every texture a component reads as numbers (DATA_TEXTURE_FIELDS: a Terrain's heightmap) whose Use is still Colour, in path+ * order. A build caps such a texture at its Max Size and takes a picture's liberties with it; marked Data it keeps its samples.+ */+export async function numberTexturesMarkedColour(src: NumberTextureAuditSource): Promise<NumberTextureFinding[]> {+ const found = new Map<string, NumberTextureFinding['readBy']>();+ for (const document of src.documents) {+ const text = await src.readText(document);+ if (text === null) continue;+ let parsed: { entities?: Array<{ components?: Array<{ type?: string; data?: Record<string, unknown> }> }> };+ try { parsed = JSON.parse(text); } catch { continue; }+ for (const entity of parsed.entities ?? []) {+ for (const component of entity.components ?? []) {+ for (const field of DATA_TEXTURE_FIELDS[component.type ?? ''] ?? []) {+ const ref = component.data?.[field];+ if (typeof ref !== 'string' || ref === '' || builtinRefId(ref) !== null) continue;+ const texture = refFrom({ ...src, materials: [] }, document, ref);+ if (texture === null || textureUse(src.importer(texture)?.use) === 'data') continue;+ const readBy = found.get(texture) ?? [];+ readBy.push({ document, component: component.type!, field });+ found.set(texture, readBy);+ }+ }+ }+ }+ return [...found].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)).map(([texture, readBy]) => ({ texture, readBy }));+}diff --git a/pipeline/src/assets/png16.ts b/pipeline/src/assets/png16.tsnew file mode 100644index 000000000..0de6b0222--- /dev/null+++ b/pipeline/src/assets/png16.ts@@ -0,0 +1,100 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file png16.ts — a grey PNG of 16 bits a sample, read, shrunk and written at that depth.+ *+ * A heightmap is one. The cook's own image path decodes to 8 bits a channel, which is 256 steps of ground where the file+ * holds 65536; a size cap on a heightmap goes through here instead.+ */+import { deflateSync, inflateSync, crc32 } from 'node:zlib';++export interface Grey16 { width: number; height: number; data: Uint16Array }++const SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);++/** The image, or null when the file is not a non-interlaced grey PNG of 16 bits (anything else keeps to the 8-bit path, or ships as it is). */+export function decodeGrey16(png: Uint8Array): Grey16 | null {+ const buf = Buffer.from(png.buffer, png.byteOffset, png.byteLength);+ if (buf.length < 33 || !buf.subarray(0, 8).equals(SIGNATURE)) return null;+ const width = buf.readUInt32BE(16), height = buf.readUInt32BE(20);+ if (buf[24] !== 16 || buf[25] !== 0 || buf[28] !== 0) return null;+ const parts: Buffer[] = [];+ for (let at = 8; at + 12 <= buf.length;) {+ const length = buf.readUInt32BE(at), type = buf.toString('latin1', at + 4, at + 8);+ if (type === 'IDAT') parts.push(buf.subarray(at + 8, at + 8 + length));+ if (type === 'IEND') break;+ at += 12 + length;+ }+ const raw = inflateSync(Buffer.concat(parts));+ const stride = width * 2;+ if (raw.length < height * (stride + 1)) return null;+ const data = new Uint16Array(width * height);+ const line = Buffer.alloc(stride), above = Buffer.alloc(stride);+ for (let y = 0; y < height; y++) {+ const filter = raw[y * (stride + 1)]!;+ raw.copy(line, 0, y * (stride + 1) + 1, (y + 1) * (stride + 1));+ for (let i = 0; i < stride; i++) {+ const left = i >= 2 ? line[i - 2]! : 0, up = above[i]!, corner = i >= 2 ? above[i - 2]! : 0;+ let predicted = 0;+ if (filter === 1) predicted = left;+ else if (filter === 2) predicted = up;+ else if (filter === 3) predicted = (left + up) >> 1;+ else if (filter === 4) {+ const p = left + up - corner, a = Math.abs(p - left), b = Math.abs(p - up), c = Math.abs(p - corner);+ predicted = a <= b && a <= c ? left : b <= c ? up : corner;+ }+ line[i] = (line[i]! + predicted) & 255;+ }+ for (let x = 0; x < width; x++) data[y * width + x] = (line[x * 2]! << 8) | line[x * 2 + 1]!;+ line.copy(above);+ }+ return { width, height, data };+}++/** The image with its longer side at most @p maxDim, each sample the mean of the samples it covers. The same image when it already is. */+export function downscaleGrey16(image: Grey16, maxDim: number): Grey16 {+ const longest = Math.max(image.width, image.height);+ if (!(maxDim > 0) || longest <= maxDim) return image;+ const width = Math.max(1, Math.round((image.width * maxDim) / longest)), height = Math.max(1, Math.round((image.height * maxDim) / longest));+ const data = new Uint16Array(width * height);+ for (let y = 0; y < height; y++) {+ const y0 = Math.floor((y * image.height) / height), y1 = Math.max(y0 + 1, Math.floor(((y + 1) * image.height) / height));+ for (let x = 0; x < width; x++) {+ const x0 = Math.floor((x * image.width) / width), x1 = Math.max(x0 + 1, Math.floor(((x + 1) * image.width) / width));+ let sum = 0;+ for (let v = y0; v < y1; v++) for (let u = x0; u < x1; u++) sum += image.data[v * image.width + u]!;+ data[y * width + x] = Math.round(sum / ((y1 - y0) * (x1 - x0)));+ }+ }+ return { width, height, data };+}++function chunk(type: string, body: Buffer): Buffer {+ const head = Buffer.alloc(8);+ head.writeUInt32BE(body.length, 0);+ head.write(type, 4, 'latin1');+ const tail = Buffer.alloc(4);+ tail.writeUInt32BE(crc32(Buffer.concat([head.subarray(4), body])) >>> 0, 0);+ return Buffer.concat([head, body, tail]);+}++/** A grey PNG of 16 bits a sample. */+export function encodeGrey16(image: Grey16): Uint8Array {+ const { width, height, data } = image;+ const ihdr = Buffer.alloc(13);+ ihdr.writeUInt32BE(width, 0);+ ihdr.writeUInt32BE(height, 4);+ ihdr[8] = 16;+ const rows = Buffer.alloc(height * (1 + width * 2));+ for (let y = 0; y < height; y++) {+ const at = y * (1 + width * 2);+ // Sub: a height field is smooth along a row, and the difference from the sample before deflates far better than the sample.+ rows[at] = 1;+ for (let x = 0; x < width; x++) {+ const v = data[y * width + x]!, before = x > 0 ? data[y * width + x - 1]! : 0;+ rows[at + 1 + x * 2] = ((v >> 8) - (before >> 8)) & 255;+ rows[at + 2 + x * 2] = ((v & 255) - (before & 255)) & 255;+ }+ }+ return new Uint8Array(Buffer.concat([SIGNATURE, chunk('IHDR', ihdr), chunk('IDAT', deflateSync(rows)), chunk('IEND', Buffer.alloc(0))]));+}diff --git a/pipeline/src/assets/textureCook.ts b/pipeline/src/assets/textureCook.tsindex 6035984e3..e859c1e16 100644--- a/pipeline/src/assets/textureCook.ts+++ b/pipeline/src/assets/textureCook.ts@@ -10,6 +10,7 @@*/import { readTextureCookSettings } from '../project/importSettings';import { decodePngImage, encodeRgbaPng, downscaleRgba } from './atlasPacker';+import { decodeGrey16, downscaleGrey16, encodeGrey16 } from './png16';import {decideTextureCook, cookIntentDefeated, explainTextureCook, downscaledSize,type TextureCookDecision,@@ -99,7 +100,8 @@ export function fillClearTexels(image: { rgba: Uint8Array; width: number; height/** Whether an importer lets its clear texels be filled: a colour image that has not said no. */export function fillsClearTexels(importer: Record<string, unknown> | undefined, platform?: string): boolean {- return readTextureCookSettings(importer, platform).srgb && importer?.alphaIsTransparency !== false;+ const tex = readTextureCookSettings(importer, platform);+ return tex.use !== 'data' && tex.srgb && importer?.alphaIsTransparency !== false;}/**@@ -179,8 +181,6 @@ export interface TextureCookInput {atlasTextures: boolean;/** A mesh draws this texture (texturesDrawnIn3D) — what Auto compression resolves by. */drawnIn3D: boolean;- /** A component reads this texture as numbers (a Terrain's heightmap): it is neither resized nor encoded. */- readAsNumbers?: boolean;/** Answer only from the cook cache: an encode it would have to run is left* undone, and the output says `pending` instead. */cachedOnly?: boolean;@@ -214,13 +214,26 @@ export async function cookTexture(input: TextureCookInput): Promise<TextureCookOconst tex = readTextureCookSettings(input.importer, platform);const raster = ext.toLowerCase() === '.png';const textureEnc = input.encoder?.module ?? null;- // A texture a component reads as numbers (a heightmap), and any PNG of 16 bits a channel, is not a picture: the size cap would ship- // different ground, and shrinking, filling and encoding all decode to 8 bits first. It ships as the file it is.- if (input.readAsNumbers || (raster && pngBitDepth(data) === 16)) {+ // Numbers, not a picture: a texture whose Use is Data, and any PNG of 16 bits a sample whatever it is marked (the paths below all+ // decode to 8 bits first). It is never encoded or filled; it is shrunk only where a Data texture's Max Size says so, at its own depth.+ const wide = raster && pngBitDepth(data) === 16;+ if (tex.use === 'data' || wide) {const cook = decideTextureCook({compressTextures: input.compressTextures, atlasTextures: input.atlasTextures, inAtlas: false, raster,- compress: 'off', drawnIn3D: input.drawnIn3D, format: tex.format, size: safePngDimensions(data),+ compress: 'off', drawnIn3D: input.drawnIn3D, format: tex.format, size: raster ? safePngDimensions(data) : null,});+ const size = raster ? safePngDimensions(data) : null;+ const capped = tex.use === 'data' && (textureEnc || input.resizeTextures) && size && tex.maxSize > 0 && tex.maxSize < Math.max(size.width, size.height);+ if (tex.use !== 'data') {+ warnings.push(`${path}: holds 16 bits a sample but its Use is Colour - shipped as the file it is, uncapped. Set Use to Data to say so, and to cap it.`);+ } else if (capped) {+ const grey = wide ? decodeGrey16(data) : null;+ if (grey) data = encodeGrey16(downscaleGrey16(grey, tex.maxSize));+ else if (!wide) {+ const small = downscaleRgba(decodePngImage(path, data), tex.maxSize);+ data = encodeRgbaPng(small.width, small.height, small.rgba);+ } else warnings.push(`${path}: Max Size ${tex.maxSize} was not applied - a 16-bit PNG that is not plain grey is shipped at its own size.`);+ }return { data, ext, cook, warnings, defeatedByFormat: false };}// maxSize downscale first — it applies even when a texture opts OUT ofdiff --git a/pipeline/src/assets/textureUsage.ts b/pipeline/src/assets/textureUsage.tsindex 5b3c254c4..54c7d399e 100644--- a/pipeline/src/assets/textureUsage.ts+++ b/pipeline/src/assets/textureUsage.ts@@ -33,14 +33,6 @@ const MESH_MATERIAL_FIELDS: Readonly<Record<string, readonly string[]>> = {MeshRenderer: ['material'],};-/**- * Component fields whose texture is read as numbers, a sample a texel, never drawn: a size cap or a codec is not a smaller- * picture there but different ground.- */-const NUMBER_TEXTURE_FIELDS: Readonly<Record<string, readonly string[]>> = {- Terrain: ['heightmap'],-};-interface Documented {entities?: Array<{ components?: Array<{ type?: string; data?: Record<string, unknown> }> }>;}@@ -127,37 +119,3 @@ export async function meshTextureRoles(}));return drawn;}--/**- * The uuids of the textures a component in @p entries' scenes and prefabs reads as numbers (a Terrain's heightmap). A build ships- * these as the files they are.- */-export async function texturesReadAsNumbers(- root: string,- entries: readonly AssetEntry[],- read: (file: string) => Promise<string> = (file) => readFile(path.join(root, file), 'utf8'),-): Promise<Set<string>> {- const byUuid = new Map(entries.map((e) => [e.uuid, e]));- const byPath = new Map(entries.map((e) => [e.path, e]));- const found = new Set<string>();- await Promise.all(entries.filter((e) => e.type === 'scene' || e.type === 'prefab').map(async (doc) => {- let parsed: Documented;- try {- parsed = JSON.parse(await read(doc.path)) as Documented;- } catch {- return;- }- for (const entity of parsed.entities ?? []) {- for (const component of entity.components ?? []) {- for (const field of NUMBER_TEXTURE_FIELDS[component.type ?? ''] ?? []) {- const ref = component.data?.[field];- if (typeof ref !== 'string' || ref === '' || isBuiltinAssetRef(ref) || ref.includes('://')) continue;- const target = ref.startsWith(UUID_PREFIX) ? byUuid.get(ref.slice(UUID_PREFIX.length))- : byPath.get(resolveDocumentRef(doc.path, ref).replace(/^\/+/, ''));- if (target?.type === 'texture') found.add(target.uuid);- }- }- }- }));- return found;-}diff --git a/pipeline/src/project/importSettings.ts b/pipeline/src/project/importSettings.tsindex 83cecd8d3..76ef3d65a 100644--- a/pipeline/src/project/importSettings.ts+++ b/pipeline/src/project/importSettings.ts@@ -53,11 +53,21 @@ export interface ImporterFieldSpec {const powerOfTwo = [256, 512, 1024, 2048, 4096, 8192];const TEXTURE: ImporterFieldSpec[] = [+ {+ key: 'use', label: 'Use', type: 'enum', default: 'colour', category: 'Texture',+ options: [{ label: 'Colour', value: 'colour' }, { label: 'Data', value: 'data' }],+ read: textureUse,+ tooltip: 'What the image holds. Colour is a picture: a build may shrink it to Max Size, compress it and fill the colour under '+ + 'its clear texels. Data is numbers a texel, read as they are - a heightmap, a mask of measured values, a lookup table: a '+ + 'build keeps its depth (16 bits a sample stay 16), never compresses it or decodes it as sRGB, and shrinks it only when '+ + 'Max Size says so.',+ },{key: 'maxSize', label: 'Max Size', type: 'enum', default: 2048, category: 'Texture',- options: powerOfTwo.map((n) => ({ label: String(n), value: n })),+ options: [{ label: 'Source size', value: 0 }, ...powerOfTwo.map((n) => ({ label: String(n), value: n }))],tooltip: 'Downscale cap applied at cook (power of two). A source larger than this on '- + 'its longest side is box-filtered down; smaller sources are untouched.',+ + 'its longest side is box-filtered down; smaller sources are untouched. Source size never shrinks it, which is what a '+ + 'Data texture starts at: half the samples of a heightmap is other ground.',},{key: 'compress', label: 'Compression', type: 'enum', default: 'auto', category: 'Texture',@@ -374,26 +384,41 @@ export function textureCompression(stored: unknown): TextureCompression {return stored === false ? 'off' : 'auto';}+/** What a texture holds: a picture, or numbers a texel (the `use` import setting). */+export type TextureUse = 'colour' | 'data';++/** A stored Use as it reads today: anything that is not `data` is a picture. */+export function textureUse(stored: unknown): TextureUse {+ return stored === 'data' ? 'data' : 'colour';+}++export { DATA_TEXTURE_IMPORTER } from '../../../tools/assetMetaTable.js';+export function readTextureCookSettings(importer: Record<string, unknown> | undefined, platform?: string): {- compress: TextureCompression; format: 'uastc' | 'etc1s'; maxSize: number; srgb: boolean; mipCoverage: number; mipmaps: boolean;+ use: TextureUse; compress: TextureCompression; format: 'uastc' | 'etc1s'; maxSize: number; srgb: boolean; mipCoverage: number; mipmaps: boolean;} {+ const use = textureUse(importer?.use);const compress = importer?.compress;const mipCoverage = importer?.mipCoverage;const format = importer?.compressFormat;const maxSize = importer?.maxSize;const srgb = importer?.sRGB;+ const data = use === 'data';const resolved = {- compress: textureCompression(compress),+ use,+ // Numbers are never encoded, decoded as colour or averaged into a coverage: whatever the other rows say, Data says these.+ compress: data ? 'off' as TextureCompression : textureCompression(compress),format: (format === 'etc1s' ? 'etc1s' : 'uastc') as 'uastc' | 'etc1s',- maxSize: typeof maxSize === 'number' && maxSize > 0 ? maxSize : 2048,- srgb: typeof srgb === 'boolean' ? srgb : true,- mipCoverage: typeof mipCoverage === 'number' && mipCoverage > 0 && mipCoverage < 1 ? mipCoverage : 0,+ // 0 is the source's own size, stated. Unstated, a picture is capped at 2048 and numbers are not capped.+ maxSize: typeof maxSize === 'number' && maxSize >= 0 ? maxSize : data ? 0 : 2048,+ srgb: data ? false : typeof srgb === 'boolean' ? srgb : true,+ mipCoverage: !data && typeof mipCoverage === 'number' && mipCoverage > 0 && mipCoverage < 1 ? mipCoverage : 0,mipmaps: importer?.mipmaps !== false,};const overrides = importer?.overrides as Record<string, TexturePlatformOverride> | undefined;const ov = platform ? overrides?.[platform] : undefined;if (ov?.enabled) {- if (ov.compress !== undefined) resolved.compress = textureCompression(ov.compress);+ if (ov.compress !== undefined && !data) resolved.compress = textureCompression(ov.compress);if (ov.compressFormat === 'etc1s' || ov.compressFormat === 'uastc') resolved.format = ov.compressFormat;if (typeof ov.maxSize === 'number' && ov.maxSize > 0) resolved.maxSize = ov.maxSize;}diff --git a/pipeline/tests/texture-cook.test.ts b/pipeline/tests/texture-cook.test.tsindex f20eaf0a6..6731a2cb6 100644--- a/pipeline/tests/texture-cook.test.ts+++ b/pipeline/tests/texture-cook.test.ts@@ -160,29 +160,68 @@ describe('a PNG of 16 bits a channel', () => {});describe('a texture a component reads as numbers', () => {- it('is found from the Terrain that names it as its heightmap, by path or by uuid', async () => {- const { texturesReadAsNumbers } = await import('../src/assets/textureUsage');- const entries = [- { uuid: 'h1', path: 'assets/height.png', type: 'texture' }, { uuid: 'h2', path: 'assets/other.png', type: 'texture' },- { uuid: 'c1', path: 'assets/colour.png', type: 'texture' }, { uuid: 's1', path: 'assets/scenes/a.esscene', type: 'scene' },- ] as never[];+ it('is found, while its Use is still Colour, from the Terrain that names it as its heightmap', async () => {+ const { numberTexturesMarkedColour } = await import('../src/assets/dataTextureAudit');const scene = JSON.stringify({ entities: [{ components: [{ type: 'Terrain', data: { heightmap: 'assets/height.png', splatmap: 'assets/colour.png' } }] },{ components: [{ type: 'Terrain', data: { heightmap: '@uuid:h2' } }, { type: 'MeshRenderer', data: { texture: 'assets/colour.png' } }] },+ { components: [{ type: 'Terrain', data: { heightmap: 'assets/marked.png' } }] },] });- expect([...await texturesReadAsNumbers('/', entries, async () => scene)].sort()).toEqual(['h1', 'h2']);+ const importers: Record<string, Record<string, unknown>> = { 'assets/marked.png': { use: 'data' }, 'assets/height.png': { maxSize: 2048 } };+ const findings = await numberTexturesMarkedColour({+ documents: ['assets/scenes/a.esscene'], readText: async () => scene,+ resolveRef: (ref) => (ref === '@uuid:h2' ? 'assets/other.png' : ref.startsWith('@uuid:') ? null : ref),+ importer: (p) => importers[p],+ });+ expect(findings.map((f) => f.texture)).toEqual(['assets/height.png', 'assets/other.png']);+ expect(findings[0]!.readBy[0]).toEqual({ document: 'assets/scenes/a.esscene', component: 'Terrain', field: 'heightmap' });});- it('ships as the file it is though it is over its size cap', async () => {+ it('marked Data ships uncapped by default, and at its own depth when its Max Size caps it', async () => {const root = mkdtempSync(path.join(tmpdir(), 'estella-numbers-'));try {- const png = noisePng(96, 96);- const input = { root, path: 'assets/height.png', data: png, ext: '.png', platform: 'web', importer: { maxSize: 32 },- compressTextures: false, atlasTextures: false, resizeTextures: true, drawnIn3D: false, encoder: null } as Parameters<typeof cookTexture>[0];- const capped = await cookTexture(input);- expect(decodePngImage('h', capped.data).width).toBe(32);- const kept = await cookTexture({ ...input, readAsNumbers: true });+ const { encodeGrey16, decodeGrey16 } = await import('../src/assets/png16');+ const { DATA_TEXTURE_IMPORTER } = await import('../src/project/importSettings');+ // A ramp of 16-bit heights no 8-bit image can hold: 64 x 64, every sample its own value.+ const ramp = new Uint16Array(64 * 64).map((_, i) => 1000 + i * 13);+ const png = encodeGrey16({ width: 64, height: 64, data: ramp });+ expect(decodeGrey16(png)!.data).toEqual(ramp);+ const base = { root, path: 'assets/height.png', data: png, ext: '.png', platform: 'web', compressTextures: true, atlasTextures: false,+ resizeTextures: true, drawnIn3D: true, encoder: null } as Parameters<typeof cookTexture>[0];+ // Data: no cap unless one is stated, never encoded.+ const kept = await cookTexture({ ...base, importer: { ...DATA_TEXTURE_IMPORTER } });expect(Buffer.from(kept.data).equals(Buffer.from(png))).toBe(true);+ expect(kept.cook.selected).toBe('raw');+ // Data with a cap: half the samples a side, still 16 bits, each the mean of the four it covers.+ const capped = await cookTexture({ ...base, importer: { ...DATA_TEXTURE_IMPORTER, maxSize: 32 } });+ const small = decodeGrey16(capped.data)!;+ expect([small.width, small.height]).toEqual([32, 32]);+ expect(small.data[0]).toBe(Math.round((ramp[0]! + ramp[1]! + ramp[64]! + ramp[65]!) / 4));+ // Not marked: shipped as it is, and the build says so.+ const unmarked = await cookTexture({ ...base, importer: { maxSize: 32 } });+ expect(Buffer.from(unmarked.data).equals(Buffer.from(png))).toBe(true);+ expect(unmarked.warnings.join(' ')).toMatch(/Use is Colour/);+ // An 8-bit image marked Data is capped as numbers too: shrunk, never filled or encoded.+ const eight = await cookTexture({ ...base, data: noisePng(96, 96), importer: { ...DATA_TEXTURE_IMPORTER, maxSize: 32 } });+ expect(decodePngImage('h', eight.data).width).toBe(32);+ } finally {+ rmSync(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 });+ }+ });++ it('is adopted as Data when its file is a PNG of 16 bits a sample', async () => {+ const root = mkdtempSync(path.join(tmpdir(), 'estella-adopt16-'));+ try {+ const { encodeGrey16 } = await import('../src/assets/png16');+ const { adoptOrphan } = await import('../src/assets/assetMeta');+ const file = path.join(root, 'height.png'), flat = path.join(root, 'flat.png');+ writeFileSync(file, encodeGrey16({ width: 8, height: 8, data: new Uint16Array(64).fill(40000) }));+ writeFileSync(flat, solidPng(8, 8, [10, 20, 30, 255]));+ await adoptOrphan(file);+ await adoptOrphan(flat);+ const importer = (f: string) => JSON.parse(readFileSync(f + '.meta', 'utf8')).importer;+ expect(importer(file)).toMatchObject({ use: 'data', maxSize: 0, compress: 'off', sRGB: false });+ expect(importer(flat).use).toBe('colour');} finally {rmSync(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 });}diff --git a/sdk/src/asset/textureUse.ts b/sdk/src/asset/textureUse.tsnew file mode 100644index 000000000..39e7b5721--- /dev/null+++ b/sdk/src/asset/textureUse.ts@@ -0,0 +1,20 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file textureUse.ts — which component fields read a texture as numbers.+ *+ * A texture is a picture unless something says otherwise, and a build treats a picture as one: capped at a size, compressed,+ * decoded as colour. The fields here read each texel as a number instead (a Terrain's heights), where every one of those is+ * different data. The texture's own import setting (`use: 'data'`) is what a build obeys; this is what the editor sets it by+ * when a texture is put in such a field, and what Project Health holds the two together with.+ */++/** Component type to the texture fields of it that are read as numbers. */+export const DATA_TEXTURE_FIELDS: Readonly<Record<string, readonly string[]>> = {+ Terrain: ['heightmap'],+};++/** Whether `component.field` reads its texture as numbers. */+export function readsTextureAsNumbers(component: string, field: string): boolean {+ return DATA_TEXTURE_FIELDS[component]?.includes(field) ?? false;+}diff --git a/sdk/tests/texture-use.test.ts b/sdk/tests/texture-use.test.tsnew file mode 100644index 000000000..3db1b09a2--- /dev/null+++ b/sdk/tests/texture-use.test.ts@@ -0,0 +1,21 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { describe, expect, it } from 'vitest';+import { DATA_TEXTURE_FIELDS, readsTextureAsNumbers } from '../src/asset/textureUse';+import { Terrain } from '../src/terrain/terrainPlugin';++describe('the fields that read a texture as numbers', () => {+ it('are texture fields their components declare', () => {+ const declared: Record<string, { assetFields?: Array<{ field: string; type: string }> }> = { Terrain: Terrain as never };+ for (const [component, fields] of Object.entries(DATA_TEXTURE_FIELDS)) {+ const assets = (declared[component] as unknown as { assetFields?: Array<{ field: string; type: string }> }).assetFields ?? [];+ for (const field of fields) expect(assets.some((a) => a.field === field && a.type === 'texture'), `${component}.${field}`).toBe(true);+ }+ });++ it('answer for one field', () => {+ expect(readsTextureAsNumbers('Terrain', 'heightmap')).toBe(true);+ expect(readsTextureAsNumbers('Terrain', 'splatmap')).toBe(false);+ expect(readsTextureAsNumbers('Sprite', 'texture')).toBe(false);+ });+});diff --git a/tools/asset-meta.js b/tools/asset-meta.jsindex 41ef07d45..30d30d0a2 100644--- a/tools/asset-meta.js+++ b/tools/asset-meta.js@@ -28,7 +28,7 @@ import { join, relative, resolve } from 'node:path';import { randomUUID } from 'node:crypto';import { parseArgs } from 'node:util';import {- EXT_TO_TYPE, metaTypeForExt, metaTypeForContent, needsContentType, CONTENT_SNIFF_BYTES,+ EXT_TO_TYPE, metaTypeForExt, metaTypeForContent, needsContentType, CONTENT_SNIFF_BYTES, dataImporterForHead,} from './assetMetaTable.js';const META_VERSION = '2.0';@@ -111,13 +111,29 @@ async function getAssetType(filePath) {return metaTypeForContent(filePath, await readHead(filePath, CONTENT_SNIFF_BYTES));}-/** Builds the meta object (JSON-shape) for a given type. */-function buildMeta(type) {+/** The first `bytes` of a file, or null if it can't be read. */+async function readHeadBytes(filePath, bytes) {+ let handle;+ try {+ handle = await open(filePath, 'r');+ const buf = Buffer.alloc(bytes);+ const { bytesRead } = await handle.read(buf, 0, bytes, 0);+ return buf.subarray(0, bytesRead);+ } catch {+ return null;+ } finally {+ await handle?.close();+ }+}++/** Builds the meta object (JSON-shape) for a given type; a texture file that is plainly numbers is adopted as Data. */+async function buildMeta(type, filePath) {+ const data = type === 'texture' && filePath ? dataImporterForHead(filePath, await readHeadBytes(filePath, 32)) : null;return {uuid: randomUUID(),version: META_VERSION,type,- importer: getImporterDefaults(type),+ importer: data ?? getImporterDefaults(type),};}@@ -189,7 +205,7 @@ export async function generateMetaForDir(dir, options = {}) {continue;}- const meta = buildMeta(type);+ const meta = await buildMeta(type, filePath);created.push({ path: filePath, metaPath, meta });if (!dryRun && !check) {diff --git a/tools/assetMetaTable.d.ts b/tools/assetMetaTable.d.tsindex 02d72dcb0..2eac6219d 100644--- a/tools/assetMetaTable.d.ts+++ b/tools/assetMetaTable.d.ts@@ -8,3 +8,5 @@ export function metaTypeForExt(fileOrExt: string): string | null;export function needsContentType(fileOrExt: string): boolean;export function metaTypeForContent(fileOrExt: string, head: string): string | null;export function isProjectPlumbing(fileOrPath: string): boolean;+export const DATA_TEXTURE_IMPORTER: Readonly<Record<string, unknown>>;+export function dataImporterForHead(fileOrPath: string, head: Uint8Array | null | undefined): Record<string, unknown> | null;diff --git a/tools/assetMetaTable.js b/tools/assetMetaTable.jsindex 966b506df..338c056af 100644--- a/tools/assetMetaTable.js+++ b/tools/assetMetaTable.js@@ -219,3 +219,22 @@ export function metaTypeForContent(fileOrExt, head) {if (!needsContentType(fileOrExt)) return null;return SPINE_SKELETON_JSON.test(head) ? 'spine' : 'json';}++/**+ * The import settings of a texture read as numbers (its `use` is `data`): no size cap (0 is the source's own size), no codec,+ * no colour decode, no mips or fill. What marking a texture Data writes, and what {@link dataImporterForHead} adopts one with.+ */+export const DATA_TEXTURE_IMPORTER = Object.freeze({+ use: 'data', maxSize: 0, compress: 'off', mipmaps: false, sRGB: false, alphaIsTransparency: false,+});++/**+ * What a texture file's first bytes say it needs, or null for a picture: a PNG of 16 bits a sample is numbers (a heightmap, in+ * nearly every case), and a picture's settings would shrink it and take its depth. Both mint doors ask this, so the same file+ * is adopted the same way from the CLI and from the editor.+ */+export function dataImporterForHead(fileOrPath, head) {+ if (!String(fileOrPath).toLowerCase().endsWith('.png') || !head || head.length < 25) return null;+ const png = head[0] === 0x89 && head[1] === 0x50 && head[2] === 0x4e && head[3] === 0x47;+ return png && head[24] === 16 ? { ...DATA_TEXTURE_IMPORTER, filterMode: 'linear', wrapMode: 'clamp' } : null;+}diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex 4d3ae486c..3ac2ce06d 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -4516,4 +4516,6 @@ export const NOTED = {{"note": "An ocean reaches the horizon."},"feat(units): a shader param says it is a length with unit(length) and follows the project's units per metre, as components and effects do - the water's defaults were metres in an engine of centimetres":{"note": "One setting says what a unit is, for materials too."},+ "feat(assets): a texture's Use says whether it is a picture or numbers - Data keeps its depth and its size in a build, a 16-bit PNG is imported as Data, a Terrain's heightmap is marked Data when it is set, and Project Health lists the ones that are not":+ {"note": "A texture says whether it is a picture or numbers."},};