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(export): an authored single-level KTX2 ships with a mip chain
esengine54f43e6a3aa1
diff --git a/pipeline/src/assets/cookAssets.ts b/pipeline/src/assets/cookAssets.tsindex 21ae0c6ba..cde4c04d4 100644--- a/pipeline/src/assets/cookAssets.ts+++ b/pipeline/src/assets/cookAssets.ts@@ -44,6 +44,7 @@ import { isBuiltinAssetRef, resolveRelativePath, resolveDocumentRef } from '../.// realm (sdk/src/asset/assetGroups.ts) so cook and editor never disagree.import { resolveAssetGroup, resolveAtlas, type AssetGroupsConfig } from '../../../sdk/src/asset/assetGroups';import type { BundleMode } from '../../../sdk/src/asset/AddressableManifest';+import { readKtx2Layout, wantsMipChain, halveRgba, spliceMipChain } from './ktx2Mips';import { cookCached, encoderIdentity } from './cookCache';const MANIFEST = 'assets.manifest.json';@@ -222,6 +223,7 @@ interface BasisEncoderModule {ENCODER_WASM: string;}+const KTX2_SCHEME_ZSTD = 2;/** Replace a path's extension (e.g. .png → .ktx2); appends if it had none. */function swapExt(p: string, ext: string): string {@@ -724,6 +726,28 @@ export async function cookAssets(let ext = path.extname(entry.path);let compressedFormats: string[] | undefined;let cook: TextureCookDecision | undefined;+ // An authored single-level UASTC KTX2 gets the chain a compressed texture+ // cannot generate on the device, under its own untouched level 0.+ const layout = textureEnc && entry.type === 'texture' && ext.toLowerCase() === '.ktx2' ? readKtx2Layout(data) : null;+ if (textureEnc && wantsMipChain(layout)) {+ const enc = textureEnc;+ const source = data;+ try {+ data = (await cookCached(root, [source, 'ktx2-mip-chain:1', encoderId], async () => {+ const decoded = await enc.transcodeKtx2ToRgba(source);+ const half = halveRgba(decoded.pixels, decoded.width, decoded.height, layout.srgb);+ const below = await enc.encodeToKtx2(+ { type: enc.ImageType.RGBA, data: half.rgba, width: half.width, height: half.height },+ {+ mode: 'uastc', srgb: layout.srgb, mipmaps: true, yFlip: false, uastcLevel: 0,+ supercompress: layout.scheme === KTX2_SCHEME_ZSTD,+ });+ return spliceMipChain(source, below);+ })).bytes;+ } catch (err) {+ warnings.push(`${entry.path}: ships its single level without mips — ${err instanceof Error ? err.message : String(err)}`);+ }+ }// Every image takes the decision, not only the ones an encoder accepts: a// JPEG whose Compress row reads ON leaves no other trace. Hash + name below// reflect the ENCODED bytes, so this composes with content-addressing.diff --git a/pipeline/src/assets/ktx2Mips.ts b/pipeline/src/assets/ktx2Mips.tsnew file mode 100644index 000000000..eb4dc480a--- /dev/null+++ b/pipeline/src/assets/ktx2Mips.ts@@ -0,0 +1,172 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file ktx2Mips.ts — a mip chain under an authored single-level UASTC KTX2,+ * with its level 0 kept bit for bit.+ *+ * A KTX2 made elsewhere often carries one level, and a compressed level cannot+ * have a chain generated on the device. The cook encodes the levels below it+ * from a half-size image and splices them under the file's own level 0: every+ * level is stored (and supercompressed) on its own, so the base is never+ * decoded and re-encoded.+ */++const IDENTIFIER = [0xab, 0x4b, 0x54, 0x58, 0x20, 0x32, 0x30, 0xbb, 0x0d, 0x0a, 0x1a, 0x0a];+const HEADER_BYTES = 80;+const LEVEL_ENTRY_BYTES = 24;+const KHR_DF_MODEL_UASTC = 166;+const KHR_DF_TRANSFER_SRGB = 2;+const SCHEME_NONE = 0;+/** UASTC is 4x4 blocks of 16 bytes: the plain layout aligns levels to them. */+const UASTC_BLOCK_BYTES = 16;++export interface Ktx2Level { offset: number; length: number; uncompressed: number }++export interface Ktx2Layout {+ width: number;+ height: number;+ scheme: number;+ /** The data format descriptor's colour model; UASTC is 166. */+ colorModel: number;+ srgb: boolean;+ dfd: { offset: number; length: number };+ kvd: { offset: number; length: number };+ sgdLength: number;+ levels: Ktx2Level[];+}++/** The layout of a KTX2, or null when the bytes are not one. */+export function readKtx2Layout(bytes: Uint8Array): Ktx2Layout | null {+ if (bytes.byteLength < HEADER_BYTES || IDENTIFIER.some((b, i) => bytes[i] !== b)) return null;+ const v = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);+ const levelCount = Math.max(1, v.getUint32(40, true));+ if (HEADER_BYTES + levelCount * LEVEL_ENTRY_BYTES > bytes.byteLength) return null;+ const dfd = { offset: v.getUint32(48, true), length: v.getUint32(52, true) };+ const levels: Ktx2Level[] = [];+ for (let i = 0; i < levelCount; i++) {+ const at = HEADER_BYTES + i * LEVEL_ENTRY_BYTES;+ levels.push({+ offset: Number(v.getBigUint64(at, true)),+ length: Number(v.getBigUint64(at + 8, true)),+ uncompressed: Number(v.getBigUint64(at + 16, true)),+ });+ }+ // The basic descriptor block starts after the 4-byte total size: colour model+ // at +8 of the block, transfer function at +10.+ const hasDfd = dfd.length >= 16 && dfd.offset + 16 <= bytes.byteLength;+ return {+ width: v.getUint32(20, true),+ height: v.getUint32(24, true),+ scheme: v.getUint32(44, true),+ colorModel: hasDfd ? bytes[dfd.offset + 12] : -1,+ srgb: hasDfd && bytes[dfd.offset + 14] === KHR_DF_TRANSFER_SRGB,+ dfd,+ kvd: { offset: v.getUint32(56, true), length: v.getUint32(60, true) },+ sgdLength: Number(v.getBigUint64(72, true)),+ levels,+ };+}++/** Whether the cook can give this file a chain: one UASTC level, bigger than 1x1. */+export function wantsMipChain(layout: Ktx2Layout | null): layout is Ktx2Layout {+ return layout !== null && layout.levels.length === 1 && layout.colorModel === KHR_DF_MODEL_UASTC+ && layout.sgdLength === 0 && Math.max(layout.width, layout.height) > 1;+}++const toLinear = new Float32Array(256).map((_, i) => {+ const c = i / 255;+ return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;+});++function toSrgbByte(linear: number): number {+ const c = linear <= 0.0031308 ? linear * 12.92 : 1.055 * linear ** (1 / 2.4) - 0.055;+ return Math.max(0, Math.min(255, Math.round(c * 255)));+}++/**+ * The next level down: each pixel the mean of the (up to) four above it. Colour+ * stored as sRGB is averaged as light, not as its encoding, or every level comes+ * out darker than the one it was made from; alpha is averaged as it is.+ */+export function halveRgba(rgba: Uint8Array, width: number, height: number, srgb: boolean): {+ rgba: Uint8Array; width: number; height: number;+} {+ const w = Math.max(1, width >> 1), h = Math.max(1, height >> 1);+ const out = new Uint8Array(w * h * 4);+ for (let y = 0; y < h; y++) {+ const y0 = Math.min(height - 1, y * 2), y1 = Math.min(height - 1, y * 2 + 1);+ for (let x = 0; x < w; x++) {+ const x0 = Math.min(width - 1, x * 2), x1 = Math.min(width - 1, x * 2 + 1);+ const taps = [(y0 * width + x0) * 4, (y0 * width + x1) * 4, (y1 * width + x0) * 4, (y1 * width + x1) * 4];+ const o = (y * w + x) * 4;+ for (let c = 0; c < 3; c++) {+ out[o + c] = srgb+ ? toSrgbByte(taps.reduce((n, t) => n + toLinear[rgba[t + c]], 0) / 4)+ : Math.round(taps.reduce((n, t) => n + rgba[t + c], 0) / 4);+ }+ out[o + 3] = Math.round(taps.reduce((n, t) => n + rgba[t + 3], 0) / 4);+ }+ }+ return { rgba: out, width: w, height: h };+}++/**+ * `base`'s level 0 over every level of `below` (encoded from the half-size+ * image, so its level 0 is the base's level 1), as one KTX2 with `base`'s+ * header and descriptors. Throws when the two cannot be one file.+ */+export function spliceMipChain(base: Uint8Array, below: Uint8Array): Uint8Array {+ const top = readKtx2Layout(base);+ const rest = readKtx2Layout(below);+ if (!top || !rest) throw new Error('spliceMipChain: not a KTX2');+ if (top.levels.length !== 1) throw new Error(`spliceMipChain: base has ${top.levels.length} levels, not 1`);+ if (top.scheme !== rest.scheme) {+ throw new Error(`spliceMipChain: supercompression differs (${top.scheme} over ${rest.scheme})`);+ }+ if (top.colorModel !== KHR_DF_MODEL_UASTC || rest.colorModel !== KHR_DF_MODEL_UASTC) {+ throw new Error('spliceMipChain: both must be UASTC');+ }+ if (top.sgdLength || rest.sgdLength) throw new Error('spliceMipChain: global data cannot be spliced');+ if (rest.width !== Math.max(1, top.width >> 1) || rest.height !== Math.max(1, top.height >> 1)) {+ throw new Error(`spliceMipChain: ${rest.width}x${rest.height} is not the level under ${top.width}x${top.height}`);+ }++ const sources = [+ { bytes: base, level: top.levels[0] },+ ...rest.levels.map((level) => ({ bytes: below, level })),+ ];+ const count = sources.length;+ const align = top.scheme === SCHEME_NONE ? UASTC_BLOCK_BYTES : 1;+ const round = (n: number) => Math.ceil(n / align) * align;++ let cursor = HEADER_BYTES + count * LEVEL_ENTRY_BYTES;+ const dfdAt = cursor;+ cursor += top.dfd.length;+ const kvdAt = top.kvd.length ? cursor : 0;+ cursor += top.kvd.length;+ // Smallest level first, as the format lays them out.+ const placed = new Array<number>(count);+ for (let i = count - 1; i >= 0; i--) {+ cursor = round(cursor);+ placed[i] = cursor;+ cursor += sources[i].level.length;+ }++ const out = new Uint8Array(cursor);+ const v = new DataView(out.buffer);+ out.set(base.subarray(0, 48), 0);+ v.setUint32(40, count, true);+ v.setUint32(48, dfdAt, true); v.setUint32(52, top.dfd.length, true);+ v.setUint32(56, kvdAt, true); v.setUint32(60, top.kvd.length, true);+ v.setBigUint64(64, 0n, true); v.setBigUint64(72, 0n, true);+ out.set(base.subarray(top.dfd.offset, top.dfd.offset + top.dfd.length), dfdAt);+ if (top.kvd.length) out.set(base.subarray(top.kvd.offset, top.kvd.offset + top.kvd.length), kvdAt);+ sources.forEach(({ bytes, level }, i) => {+ const at = HEADER_BYTES + i * LEVEL_ENTRY_BYTES;+ v.setBigUint64(at, BigInt(placed[i]), true);+ v.setBigUint64(at + 8, BigInt(level.length), true);+ v.setBigUint64(at + 16, BigInt(level.uncompressed), true);+ out.set(bytes.subarray(level.offset, level.offset + level.length), placed[i]);+ });+ return out;+}diff --git a/pipeline/tests/ktx2-mips.test.ts b/pipeline/tests/ktx2-mips.test.tsnew file mode 100644index 000000000..faf892a09--- /dev/null+++ b/pipeline/tests/ktx2-mips.test.ts@@ -0,0 +1,106 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file An authored single-level KTX2 leaves the cook with a mip chain under its+ * own level 0, and a second cook reads the encode back.+ *+ * The encoder is the real one; sdk/tests/basis-mip-chain-wasm.test.ts reads a+ * spliced chain back through the side module the runtime loads.+ */+import { describe, it, expect, beforeAll, afterAll } from 'vitest';+import { mkdtempSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { readKtx2Layout, wantsMipChain, halveRgba, spliceMipChain } from '../src/assets/ktx2Mips';+import { cookCached } from '../src/assets/cookCache';+import { cookAssets } from '../src/assets/cookAssets';++const SIDE = 64;+const work = mkdtempSync(path.join(tmpdir(), 'ktx2-mips-'));+afterAll(() => rmSync(work, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 }));++type Encoder = typeof import('../../build-tools/basis/encoder.mjs');+let enc: Encoder;+let authored: Uint8Array;++beforeAll(async () => {+ enc = await import('../../build-tools/basis/encoder.mjs');+ const rgba = new Uint8Array(SIDE * SIDE * 4).map((_, i) => (i * 37) & 0xff);+ // What a KTX2 made elsewhere usually is: UASTC under zstd, one level.+ authored = await enc.encodeToKtx2({ type: enc.ImageType.RGBA, data: rgba, width: SIDE, height: SIDE },+ { mode: 'uastc', mipmaps: false, supercompress: true });+});++async function chainOf(source: Uint8Array): Promise<Uint8Array> {+ const layout = readKtx2Layout(source)!;+ const decoded = await enc.transcodeKtx2ToRgba(source);+ const half = halveRgba(decoded.pixels, decoded.width, decoded.height, layout.srgb);+ const below = await enc.encodeToKtx2({ type: enc.ImageType.RGBA, data: half.rgba, width: half.width, height: half.height },+ { mode: 'uastc', mipmaps: true, yFlip: false, uastcLevel: 0, supercompress: layout.scheme === 2 });+ return spliceMipChain(source, below);+}++describe('the chain under an authored level', () => {+ it('keeps level 0 byte for byte and adds every level down to 1x1', async () => {+ const src = readKtx2Layout(authored)!;+ expect(wantsMipChain(src)).toBe(true);+ const out = await chainOf(authored);+ const got = readKtx2Layout(out)!;+ expect(got.levels).toHaveLength(7);+ const bytesOf = (b: Uint8Array, l: { offset: number; length: number }) => b.subarray(l.offset, l.offset + l.length);+ expect(Buffer.from(bytesOf(out, got.levels[0])).equals(Buffer.from(bytesOf(authored, src.levels[0])))).toBe(true);+ expect(wantsMipChain(got)).toBe(false);+ });++ it('refuses levels whose supercompression differs from the base', async () => {+ const rgba = new Uint8Array(32 * 32 * 4).fill(128);+ const plain = await enc.encodeToKtx2({ type: enc.ImageType.RGBA, data: rgba, width: 32, height: 32 },+ { mode: 'uastc', mipmaps: true, supercompress: false });+ expect(() => spliceMipChain(authored, plain)).toThrow(/supercompression differs/);+ });+});++describe('halving an sRGB image', () => {+ it('averages light, not its encoding', () => {+ // Black and white side by side: half the light is 188 in sRGB, not 128.+ const px = new Uint8Array([0, 0, 0, 255, 255, 255, 255, 255, 0, 0, 0, 255, 255, 255, 255, 255]);+ expect(halveRgba(px, 2, 2, true).rgba[0]).toBe(188);+ expect(halveRgba(px, 2, 2, false).rgba[0]).toBe(128);+ });+});++describe('the cook cache', () => {+ it('reads an encode back instead of redoing it', async () => {+ const root = mkdtempSync(path.join(work, 'cache-'));+ let made = 0;+ const produce = async () => { made++; return new Uint8Array([1, 2, 3]); };+ const first = await cookCached(root, [new Uint8Array([9]), 'k'], produce);+ const second = await cookCached(root, [new Uint8Array([9]), 'k'], produce);+ expect([first.hit, second.hit, made]).toEqual([false, true, 1]);+ expect([...second.bytes]).toEqual([1, 2, 3]);+ await cookCached(root, [new Uint8Array([9]), 'other'], produce);+ expect(made).toBe(2);+ });+});++describe('cooking an authored single-level KTX2', () => {+ it('ships it with a chain, and keeps the encode for the next cook', async () => {+ const r = mkdtempSync(path.join(work, 'project-'));+ const TEX = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';+ const SC = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb';+ mkdirSync(path.join(r, 't'), { recursive: true });+ mkdirSync(path.join(r, 's'), { recursive: true });+ writeFileSync(path.join(r, 't', 'wall.ktx2'), authored);+ writeFileSync(path.join(r, 't', 'wall.ktx2.meta'), JSON.stringify({ uuid: TEX, version: '2.0', type: 'texture', importer: {} }));+ writeFileSync(path.join(r, 's', 'main.esscene'), JSON.stringify({ version: '1.0', name: 's', entities: [+ { id: 1, name: 'E', parent: null, children: [], components: [{ type: 'Sprite', data: { texture: `@uuid:${TEX}` } }] }] }));+ writeFileSync(path.join(r, 's', 'main.esscene.meta'), JSON.stringify({ uuid: SC, version: '2.0', type: 'scene', importer: {} }));++ const res = await cookAssets(r, { entryScenes: ['s/main.esscene'], outDir: 'out', compressTextures: true });+ expect(res.warnings.filter((w) => w.includes('wall.ktx2'))).toEqual([]);+ const m = JSON.parse(readFileSync(res.manifestPath!, 'utf8')) as { entries: Array<{ uuid: string; path: string }> };+ const shipped = new Uint8Array(readFileSync(path.join(res.outDir, m.entries.find((e) => e.uuid === TEX)!.path)));+ expect(readKtx2Layout(shipped)!.levels).toHaveLength(7);+ expect(readdirSync(path.join(r, '.esengine', 'cache', 'cook'))).toHaveLength(1);+ }, 60_000);+});diff --git a/sdk/src/asset/compressed.ts b/sdk/src/asset/compressed.tsindex 8e491f5b5..6edfcda0d 100644--- a/sdk/src/asset/compressed.ts+++ b/sdk/src/asset/compressed.ts@@ -221,7 +221,7 @@ export interface CompressedUploadOptions {readonly wrap?: 'repeat' | 'clamp' | 'mirror';/** Linear pipeline: store sRGB-encoded so the sampler linearizes in hardware. */readonly srgb?: boolean;- /** The import setting: false keeps level 0 alone, however many the file carries. */+ /** False keeps level 0 alone, however many levels the file carries. */readonly mipmaps?: boolean;}diff --git a/sdk/tests/basis-mip-chain-wasm.test.ts b/sdk/tests/basis-mip-chain-wasm.test.tsindex cb19f6d08..dbfa68692 100644--- a/sdk/tests/basis-mip-chain-wasm.test.ts+++ b/sdk/tests/basis-mip-chain-wasm.test.ts@@ -14,6 +14,7 @@ import { createRequire } from 'node:module';import path from 'node:path';import { transcoderFromModule, type BasisWasmModule } from '../src/asset/basisTranscoder';import { CompressedTextureFormat, type BasisTranscoder } from '../src/asset/compressed';+import { readKtx2Layout, halveRgba, spliceMipChain } from '../../pipeline/src/assets/ktx2Mips';const ROOT = path.resolve(__dirname, '../..');const MODULE = path.join(ROOT, 'build/wasm/web/basis.js');@@ -48,4 +49,18 @@ describe.skipIf(!existsSync(MODULE))('a KTX2 mip chain through the built transcoconst r = transcoder.transcodeToRgba(ktx2)!;expect(r.levels?.map((l) => l.data.byteLength)).toEqual(sides.map((s) => s * s * 4));});++ // What the cook makes of an authored single-level KTX2 (pipeline ktx2Mips).+ it('decodes every level of a chain spliced under an authored level 0', async () => {+ const encoder = await import(path.join(ROOT, 'build-tools/basis/encoder.mjs'));+ const rgba = new Uint8Array(SIDE * SIDE * 4).map((_, i) => (i * 11) & 0xff);+ const authored = await encoder.encodeToKtx2(+ { type: encoder.ImageType.RGBA, data: rgba, width: SIDE, height: SIDE }, { mode: 'uastc', mipmaps: false, supercompress: true });+ const decoded = await encoder.transcodeKtx2ToRgba(authored);+ const half = halveRgba(decoded.pixels, decoded.width, decoded.height, readKtx2Layout(authored)!.srgb);+ const below = await encoder.encodeToKtx2({ type: encoder.ImageType.RGBA, data: half.rgba, width: half.width, height: half.height },+ { mode: 'uastc', mipmaps: true, yFlip: false, uastcLevel: 0, supercompress: true });+ const t = transcoder.transcode(spliceMipChain(authored, below), CompressedTextureFormat.ASTC_4x4)!;+ expect(t.levels?.map((l) => l.width)).toEqual(sides);+ });});