Skip to content

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

refactor(assets): one texture cook for a build and the editor

esenginecfbd00f62501
diff --git a/pipeline/src/assets/cookAssets.ts b/pipeline/src/assets/cookAssets.ts
index 8a6231414..dd5de0712 100644
--- a/pipeline/src/assets/cookAssets.ts
+++ b/pipeline/src/assets/cookAssets.ts
@@ -23,7 +23,7 @@ import { statSync } from 'node:fs';
import { isInsideRoot } from '../fs/pathSandbox';
import path from 'node:path';
import { scanAssetDatabase, type AssetEntry } from './assetDb';
-import { packAtlas, decodePngImage, encodePagePng, encodeRgbaPng, downscaleRgba, type AtlasInputImage } from './atlasPacker';
+import { packAtlas, decodePngImage, encodePagePng, type AtlasInputImage } from './atlasPacker';
// Per-asset texture cook settings (compress opt-out / format / size cap), read
// from the `.meta` `importer` block — the same registry the inspector edits, so a
// texture's ship-time compression is authored per asset, not one global switch.
@@ -32,7 +32,7 @@ import { readTextureCookSettings } from '../project/importSettings';
// The branch below IS this function — a cook that re-derived the choice would
// be a second answer to the question an inspector asks before a build runs.
import {
- decideTextureCook, cookIntentDefeated, explainTextureCook, keepSmaller,
+ decideTextureCook, cookIntentDefeated, explainTextureCook,
type TextureCookDecision,
} from './textureCookDecision';
// Single-source content hash (sdk/src/asset/contentHash.ts). Imported as source —
@@ -45,9 +45,10 @@ import { isBuiltinAssetRef, resolveRelativePath, resolveDocumentRef } from '../.
import { resolveAssetGroup, resolveAtlas, type AssetGroupsConfig } from '../../../sdk/src/asset/assetGroups';
import type { BundleMode } from '../../../sdk/src/asset/AddressableManifest';
import {
- readKtx2Layout, wantsMipChain, halveRgba, spliceMipChain, joinMipLevels, alphaCoverage, preserveAlphaCoverage,
+ readKtx2Layout, wantsMipChain, halveRgba, spliceMipChain,
} from './ktx2Mips';
-import { cookCached, encoderIdentity } from './cookCache';
+import { cookCached } from './cookCache';
+import { cookTexture, loadTextureEncoder, COMPRESSED_TARGETS, type BasisEncoderModule } from './textureCook';
const MANIFEST = 'assets.manifest.json';
@@ -190,41 +191,6 @@ function underGroupRoot(rel: string, name: string, delivery: GroupDelivery): str
return `${root}/${rel}`;
}
-/** Targets the KTX2 the cook emits can transcode to at runtime (UASTC + ETC1S). */
-const COMPRESSED_TARGETS = ['astc-4x4', 'etc2-rgba8', 's3tc-dxt5'];
-
-/** PNG width/height from the IHDR (big-endian u32 at byte offsets 16 / 20) —
- * a header peek, so the `maxSize` cap can skip decoding textures already in range. */
-function safePngDimensions(png: Uint8Array): { width: number; height: number } | null {
- try {
- return pngDimensions(png);
- } catch {
- return null;
- }
-}
-
-function pngDimensions(png: Uint8Array): { width: number; height: number } {
- const dv = new DataView(png.buffer, png.byteOffset, png.byteLength);
- return { width: dv.getUint32(16), height: dv.getUint32(20) };
-}
-
-/** The slice of the vendored Basis encoder (build-tools/basis/encoder.mjs, a JS
- * module) the cook uses. Typed locally so the per-texture format/srgb path stays
- * type-checked without a hand-written `.d.ts`. */
-interface BasisEncoderModule {
- encodePngToKtx2(png: Uint8Array, opts?: { mode?: string; srgb?: boolean }): Promise<Uint8Array>;
- encodeToKtx2(
- source: { type: string; data: Uint8Array; width?: number; height?: number },
- opts?: {
- mode?: string; srgb?: boolean; mipmaps?: boolean; yFlip?: boolean;
- supercompress?: boolean; uastcLevel?: number;
- },
- ): Promise<Uint8Array>;
- transcodeKtx2ToRgba(ktx2: Uint8Array): Promise<{ width: number; height: number; pixels: Uint8Array }>;
- ImageType: { PNG: string; JPG: string; RGBA: string };
- ENCODER_WASM: string;
- ENCODER_PARALLELISM: number;
-}
/** What cooking one asset reports, held apart so concurrent cooks merge in order. */
interface CookSink {
@@ -251,27 +217,6 @@ async function mapInOrder<T, R>(items: T[], limit: number, fn: (item: T) => Prom
const KTX2_SCHEME_ZSTD = 2;
-/**
- * A cutout's UASTC chain, each level halved here from the one above with its alpha
- * rescaled to the full image's coverage at @p cutoff — plain averaging thins a
- * sparse cutout, such as a railing, until nothing of it passes the cut.
- */
-async function encodeCoverageChain(enc: BasisEncoderModule, img: { rgba: Uint8Array; width: number; height: number },
- srgb: boolean, cutoff: number): Promise<Uint8Array> {
- const coverage = alphaCoverage(img.rgba, cutoff);
- const parts: Uint8Array[] = [];
- let level = img;
- for (;;) {
- parts.push(await enc.encodeToKtx2({ type: enc.ImageType.RGBA, data: level.rgba, width: level.width, height: level.height },
- { mode: 'uastc', srgb, mipmaps: false }));
- if (level.width === 1 && level.height === 1) break;
- const half = halveRgba(level.rgba, level.width, level.height, srgb);
- preserveAlphaCoverage(half.rgba, cutoff, coverage);
- level = half;
- }
- return joinMipLevels(parts);
-}
-
/** Replace a path's extension (e.g. .png → .ktx2); appends if it had none. */
function swapExt(p: string, ext: string): string {
const cur = path.extname(p);
@@ -621,9 +566,8 @@ export async function cookAssets(
let textureEnc: BasisEncoderModule | null = null;
let encoderId = '';
if (compressTextures) {
- textureEnc = await import('../../../build-tools/basis/encoder.mjs') as unknown as BasisEncoderModule;
+ ({ module: textureEnc, id: encoderId } = await loadTextureEncoder());
encodePng = (png) => textureEnc!.encodePngToKtx2(png, { mode: 'uastc' });
- encoderId = encoderIdentity(textureEnc.ENCODER_WASM);
}
// WAV → MP3 (LAME wasm) rides the same lazy pattern; per-asset importer
// settings can opt a clip out (seamless loops) or pick a bitrate.
@@ -803,61 +747,15 @@ export async function cookAssets(
// JPEG whose Compress row reads ON leaves no other trace. Hash + name below
// reflect the ENCODED bytes, so this composes with content-addressing.
if (entry.type !== 'scene' && getAssetTypeEntry(entry.path)?.contentType === 'image') {
- const tex = readTextureCookSettings(entry.importer, platform);
- const raster = ext.toLowerCase() === '.png';
- // maxSize downscale first — it applies even when a texture opts OUT of
- // compression (a huge UI sprite can ship as a smaller raw PNG), and the
- // ENCODED size is what block alignment is judged on.
- let rgba: Uint8Array | null = null;
- let tw = 0, th = 0;
- if (textureEnc && raster) {
- try {
- const dims = pngDimensions(data);
- if (tex.maxSize < Math.max(dims.width, dims.height)) {
- const scaled = downscaleRgba(decodePngImage(entry.path, data), tex.maxSize);
- rgba = scaled.rgba; tw = scaled.width; th = scaled.height;
- if (!tex.compress) data = encodeRgbaPng(tw, th, rgba); // ship the shrunk PNG
- }
- } catch (err) {
- warnings.push(`${entry.path}: texture resize skipped — ${err instanceof Error ? err.message : String(err)}`);
- }
- }
- const size = raster ? (rgba ? { width: tw, height: th } : safePngDimensions(data)) : null;
- cook = decideTextureCook({
- compressTextures, atlasTextures, inAtlas: false, raster,
- compress: tex.compress, format: tex.format, size,
+ const t = await cookTexture({
+ root, path: entry.path, data, ext, importer: entry.importer, platform,
+ encoder: textureEnc ? { module: textureEnc, id: encoderId } : null,
+ compressTextures, atlasTextures,
});
- if (cookIntentDefeated(cook)) {
- // A source format the encoder does not take is a property of the whole
- // project's art, not of one asset — it is summarized once, below.
- if (cook.reason === 'not-raster') defeatedByFormat.push(entry.path);
- else warnings.push(`${entry.path}: ${explainTextureCook(cook, size)}`);
- }
- if (cook.selected !== 'raw') {
- // Only a build that encodes can select an encoding, and that is exactly
- // when the encoder was loaded — an absent one here is a broken invariant
- // and should say so rather than silently ship raw.
- const enc = textureEnc!;
- const mode = cook.selected;
- const source = data;
- const coverage = mode === 'uastc' ? tex.mipCoverage : 0;
- const encoded = (await cookCached(root,
- [source, JSON.stringify({ mode, srgb: tex.srgb, maxSize: tex.maxSize, scaled: rgba ? [tw, th] : null,
- ...(coverage ? { mipCoverage: coverage } : {}) }), encoderId],
- () => (coverage
- ? encodeCoverageChain(enc, rgba ? { rgba, width: tw, height: th } : decodePngImage(entry.path, source),
- tex.srgb, coverage)
- : rgba
- ? enc.encodeToKtx2({ type: enc.ImageType.RGBA, data: rgba, width: tw, height: th }, { mode, srgb: tex.srgb })
- : enc.encodeToKtx2({ type: enc.ImageType.PNG, data: source }, { mode, srgb: tex.srgb })),
- )).bytes;
- cook = keepSmaller(cook, encoded.byteLength, data.byteLength, coverage > 0);
- if (cook.selected !== 'raw') {
- data = encoded;
- ext = '.ktx2';
- compressedFormats = COMPRESSED_TARGETS;
- } else grewUnderEncoding.push({ path: entry.path, saved: encoded.byteLength - data.byteLength });
- }
+ data = t.data; ext = t.ext; cook = t.cook; compressedFormats = t.compressedFormats;
+ warnings.push(...t.warnings);
+ if (t.defeatedByFormat) defeatedByFormat.push(entry.path);
+ if (t.grew !== undefined) grewUnderEncoding.push({ path: entry.path, saved: t.grew });
}
// WAV sources re-encode to MP3 (universal decode); other audio formats are
// already compressed and pass through. Hash + name reflect the ENCODED bytes.
diff --git a/pipeline/src/assets/cookCache.ts b/pipeline/src/assets/cookCache.ts
index 4ab1f1adb..9bc395fef 100644
--- a/pipeline/src/assets/cookCache.ts
+++ b/pipeline/src/assets/cookCache.ts
@@ -32,15 +32,25 @@ export function encoderIdentity(encoderFile: string): string {
/** Concurrent cooks in one process can produce the same key; each writes its own temp file. */
let tmpSerial = 0;
-export async function cookCached(
- root: string, inputs: ReadonlyArray<Uint8Array | string>, produce: () => Promise<Uint8Array>,
-): Promise<{ bytes: Uint8Array; hit: boolean }> {
+function cacheFile(root: string, inputs: ReadonlyArray<Uint8Array | string>): string {
const h = createHash('sha256');
for (const part of inputs) {
h.update(typeof part === 'string' ? `s${part.length}:${part}` : `b${part.byteLength}:`);
if (typeof part !== 'string') h.update(part);
}
- const file = path.join(root, CACHE_DIR, `${h.digest('hex')}.bin`);
+ return path.join(root, CACHE_DIR, `${h.digest('hex')}.bin`);
+}
+
+/** What an earlier cook made for these inputs, or null — never produces. */
+export async function cookCacheHit(root: string, inputs: ReadonlyArray<Uint8Array | string>): Promise<Uint8Array | null> {
+ const file = cacheFile(root, inputs);
+ return existsSync(file) ? new Uint8Array(await readFile(file)) : null;
+}
+
+export async function cookCached(
+ root: string, inputs: ReadonlyArray<Uint8Array | string>, produce: () => Promise<Uint8Array>,
+): Promise<{ bytes: Uint8Array; hit: boolean }> {
+ const file = cacheFile(root, inputs);
if (existsSync(file)) return { bytes: new Uint8Array(await readFile(file)), hit: true };
const bytes = await produce();
try {
diff --git a/pipeline/src/assets/textureCook.ts b/pipeline/src/assets/textureCook.ts
new file mode 100644
index 000000000..9c396127a
--- /dev/null
+++ b/pipeline/src/assets/textureCook.ts
@@ -0,0 +1,205 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file textureCook.ts
+ * @brief What one texture becomes when it is compressed — for a build and the editor alike.
+ *
+ * @details The build and the editor ask for the same bytes: the editor shows a
+ * texture as the game will draw it, and both read and write the same
+ * cook cache, so whichever compresses a texture first pays for it once.
+ */
+import { readTextureCookSettings } from '../project/importSettings';
+import { decodePngImage, encodeRgbaPng, downscaleRgba } from './atlasPacker';
+import {
+ decideTextureCook, cookIntentDefeated, explainTextureCook, keepSmaller,
+ type TextureCookDecision,
+} from './textureCookDecision';
+import { halveRgba, joinMipLevels, alphaCoverage, preserveAlphaCoverage } from './ktx2Mips';
+import { cookCached, cookCacheHit, encoderIdentity } from './cookCache';
+
+/** Targets the KTX2 the cook emits can transcode to at runtime (UASTC + ETC1S). */
+export const COMPRESSED_TARGETS = ['astc-4x4', 'etc2-rgba8', 's3tc-dxt5'];
+
+/** The slice of the vendored Basis encoder (build-tools/basis/encoder.mjs, a JS
+ * module) the cook uses. Typed locally so the per-texture format/srgb path stays
+ * type-checked without a hand-written `.d.ts`. */
+export interface BasisEncoderModule {
+ encodePngToKtx2(png: Uint8Array, opts?: { mode?: string; srgb?: boolean }): Promise<Uint8Array>;
+ encodeToKtx2(
+ source: { type: string; data: Uint8Array; width?: number; height?: number },
+ opts?: {
+ mode?: string; srgb?: boolean; mipmaps?: boolean; yFlip?: boolean;
+ supercompress?: boolean; uastcLevel?: number;
+ },
+ ): Promise<Uint8Array>;
+ transcodeKtx2ToRgba(ktx2: Uint8Array): Promise<{ width: number; height: number; pixels: Uint8Array }>;
+ ImageType: { PNG: string; JPG: string; RGBA: string };
+ ENCODER_WASM: string;
+ ENCODER_PARALLELISM: number;
+}
+
+/**
+ * A cutout's UASTC chain, each level halved here from the one above with its alpha
+ * rescaled to the full image's coverage at @p cutoff — plain averaging thins a
+ * sparse cutout, such as a railing, until nothing of it passes the cut.
+ */
+async function encodeCoverageChain(enc: BasisEncoderModule, img: { rgba: Uint8Array; width: number; height: number },
+ srgb: boolean, cutoff: number): Promise<Uint8Array> {
+ const coverage = alphaCoverage(img.rgba, cutoff);
+ const parts: Uint8Array[] = [];
+ let level = img;
+ for (;;) {
+ parts.push(await enc.encodeToKtx2({ type: enc.ImageType.RGBA, data: level.rgba, width: level.width, height: level.height },
+ { mode: 'uastc', srgb, mipmaps: false }));
+ if (level.width === 1 && level.height === 1) break;
+ const half = halveRgba(level.rgba, level.width, level.height, srgb);
+ preserveAlphaCoverage(half.rgba, cutoff, coverage);
+ level = half;
+ }
+ return joinMipLevels(parts);
+}
+
+/** A loaded encoder and the identity its outputs are cached under. */
+export interface TextureEncoder {
+ module: BasisEncoderModule;
+ id: string;
+}
+
+let encoder: Promise<TextureEncoder> | null = null;
+
+/** The vendored Basis encoder, loaded once. By dynamic import, so the Electron-main
+ * bundle keeps it external rather than inlining a module that resolves its wasm
+ * via import.meta.url. */
+export function loadTextureEncoder(): Promise<TextureEncoder> {
+ encoder ??= (import('../../../build-tools/basis/encoder.mjs') as Promise<unknown>).then((m) => {
+ const module = m as BasisEncoderModule;
+ return { module, id: encoderIdentity(module.ENCODER_WASM) };
+ });
+ return encoder;
+}
+
+/** PNG width/height from the IHDR (big-endian u32 at byte offsets 16 / 20) —
+ * a header peek, so the `maxSize` cap can skip decoding textures already in range. */
+export function pngDimensions(png: Uint8Array): { width: number; height: number } {
+ const dv = new DataView(png.buffer, png.byteOffset, png.byteLength);
+ return { width: dv.getUint32(16), height: dv.getUint32(20) };
+}
+
+function safePngDimensions(png: Uint8Array): { width: number; height: number } | null {
+ try {
+ return pngDimensions(png);
+ } catch {
+ return null;
+ }
+}
+
+export interface TextureCookInput {
+ root: string;
+ /** Project-relative path, for messages. */
+ path: string;
+ /** The source file's bytes. */
+ data: Uint8Array;
+ /** The source's extension, with its dot. */
+ ext: string;
+ importer?: Record<string, unknown>;
+ platform?: string;
+ /** Null when this cook compresses nothing — the decision is still taken. */
+ encoder: TextureEncoder | null;
+ compressTextures: boolean;
+ atlasTextures: 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;
+ /** Keep the KTX2 even where the source file is smaller. A package weighs its
+ * download; a viewport holding a project's art weighs its video memory, where
+ * a block-compressed texture is a quarter of the decoded one whatever the file
+ * size. The encode, and the cache entry, are the same either way. */
+ keepCompressed?: boolean;
+}
+
+export interface TextureCookOutput {
+ data: Uint8Array;
+ ext: string;
+ cook: TextureCookDecision;
+ /** GPU formats the output transcodes to, when it is compressed. */
+ compressedFormats?: string[];
+ warnings: string[];
+ /** Asked to compress, and its source format is one the encoder does not take. */
+ defeatedByFormat: boolean;
+ /** Encoded and thrown away as larger than the source: by how many bytes. */
+ grew?: number;
+ /** `cachedOnly`, and the encode this texture asks for has not been run. */
+ pending?: boolean;
+}
+
+/**
+ * One texture as a build ships it: capped at its `maxSize`, then compressed to
+ * KTX2 where its settings and the build ask for it and the result is smaller.
+ * Encodes go through the cook cache under the source bytes, the settings that
+ * shape the output and the encoder's identity.
+ */
+export async function cookTexture(input: TextureCookInput): Promise<TextureCookOutput> {
+ const { root, path, platform } = input;
+ let { data, ext } = input;
+ const warnings: string[] = [];
+ const tex = readTextureCookSettings(input.importer, platform);
+ const raster = ext.toLowerCase() === '.png';
+ const textureEnc = input.encoder?.module ?? null;
+ // maxSize downscale first — it applies even when a texture opts OUT of
+ // compression (a huge UI sprite can ship as a smaller raw PNG), and the
+ // ENCODED size is what block alignment is judged on.
+ let rgba: Uint8Array | null = null;
+ let tw = 0, th = 0;
+ if (textureEnc && raster) {
+ try {
+ const dims = pngDimensions(data);
+ if (tex.maxSize < Math.max(dims.width, dims.height)) {
+ const scaled = downscaleRgba(decodePngImage(path, data), tex.maxSize);
+ rgba = scaled.rgba; tw = scaled.width; th = scaled.height;
+ if (!tex.compress) data = encodeRgbaPng(tw, th, rgba); // ship the shrunk PNG
+ }
+ } catch (err) {
+ warnings.push(`${path}: texture resize skipped — ${err instanceof Error ? err.message : String(err)}`);
+ }
+ }
+ const size = raster ? (rgba ? { width: tw, height: th } : safePngDimensions(data)) : null;
+ let cook = decideTextureCook({
+ compressTextures: input.compressTextures, atlasTextures: input.atlasTextures, inAtlas: false, raster,
+ compress: tex.compress, format: tex.format, size,
+ });
+ let defeatedByFormat = false;
+ if (cookIntentDefeated(cook)) {
+ // A source format the encoder does not take is a property of the whole
+ // project's art, not of one asset — the caller summarizes it once.
+ if (cook.reason === 'not-raster') defeatedByFormat = true;
+ else warnings.push(`${path}: ${explainTextureCook(cook, size)}`);
+ }
+ let compressedFormats: string[] | undefined;
+ let grew: number | undefined;
+ if (cook.selected !== 'raw') {
+ // Only a build that encodes can select an encoding, and that is exactly
+ // when the encoder was loaded — an absent one here is a broken invariant
+ // and should say so rather than silently ship raw.
+ const enc = textureEnc!;
+ const mode = cook.selected;
+ const source = data;
+ const coverage = mode === 'uastc' ? tex.mipCoverage : 0;
+ const key = [source, JSON.stringify({ mode, srgb: tex.srgb, maxSize: tex.maxSize, scaled: rgba ? [tw, th] : null,
+ ...(coverage ? { mipCoverage: coverage } : {}) }), input.encoder!.id];
+ const produce = (): Promise<Uint8Array> => (coverage
+ ? encodeCoverageChain(enc, rgba ? { rgba, width: tw, height: th } : decodePngImage(path, source),
+ tex.srgb, coverage)
+ : rgba
+ ? enc.encodeToKtx2({ type: enc.ImageType.RGBA, data: rgba, width: tw, height: th }, { mode, srgb: tex.srgb })
+ : enc.encodeToKtx2({ type: enc.ImageType.PNG, data: source }, { mode, srgb: tex.srgb }));
+ const encoded = input.cachedOnly ? await cookCacheHit(root, key) : (await cookCached(root, key, produce)).bytes;
+ if (!encoded) return { data, ext, cook, warnings, defeatedByFormat, pending: true };
+ if (!input.keepCompressed) cook = keepSmaller(cook, encoded.byteLength, data.byteLength, coverage > 0);
+ if (cook.selected !== 'raw') {
+ data = encoded;
+ ext = '.ktx2';
+ compressedFormats = COMPRESSED_TARGETS;
+ } else grew = encoded.byteLength - data.byteLength;
+ }
+ return { data, ext, cook, compressedFormats, warnings, defeatedByFormat, grew };
+}
diff --git a/pipeline/tests/texture-cook.test.ts b/pipeline/tests/texture-cook.test.ts
new file mode 100644
index 000000000..1ceca8848
--- /dev/null
+++ b/pipeline/tests/texture-cook.test.ts
@@ -0,0 +1,97 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * The editor and a build ask one function for a texture's compressed form, through
+ * one cache: what the editor compressed is what a later export ships, byte for
+ * byte, without encoding it again.
+ */
+import { describe, it, expect } from 'vitest';
+import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync, readdirSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { cookTexture, loadTextureEncoder } from '../src/assets/textureCook';
+import { cookAssets } from '../src/assets/cookAssets';
+import { noisePng, solidPng } from './fixtures/solidPng.mjs';
+
+describe('a texture compressed for the editor', () => {
+ it('is pending until compressed, then answered from the cache a build reads', async () => {
+ const r = mkdtempSync(path.join(tmpdir(), 'estella-texcook-'));
+ try {
+ const TEX = '71717171-7171-4717-8717-717171717171';
+ const SC = '81818181-8181-4818-8818-818181818181';
+ const png = noisePng(64, 64);
+ const abs = path.join(r, 't/noise.png');
+ mkdirSync(path.dirname(abs), { recursive: true });
+ writeFileSync(abs, png);
+ writeFileSync(`${abs}.meta`, JSON.stringify({ uuid: TEX, version: '2.0', type: 'texture', importer: {} }));
+ const encoder = await loadTextureEncoder();
+ const ask = (cachedOnly: boolean) => cookTexture({
+ root: r, path: 't/noise.png', data: new Uint8Array(png), ext: '.png', importer: {},
+ encoder, compressTextures: true, atlasTextures: false, cachedOnly,
+ });
+
+ const cold = await ask(true);
+ expect(cold.pending).toBe(true);
+ expect(cold.ext).toBe('.png');
+ const cacheDir = path.join(r, '.esengine/cache/cook');
+ expect(() => readdirSync(cacheDir)).toThrow(); // asking did not encode
+
+ const made = await ask(false);
+ expect(made.ext).toBe('.ktx2');
+ const warm = await ask(true);
+ expect(warm.pending).toBeUndefined();
+ expect(Buffer.from(warm.data).equals(Buffer.from(made.data))).toBe(true);
+
+ const sc = path.join(r, 's/main.esscene');
+ mkdirSync(path.dirname(sc), { recursive: true });
+ writeFileSync(sc, JSON.stringify({ version: '1.0', name: 's', entities: [
+ { id: 1, name: 'E', parent: null, children: [], components: [{ type: 'Sprite', data: { texture: `@uuid:${TEX}` } }] },
+ ] }));
+ writeFileSync(`${sc}.meta`, JSON.stringify({ uuid: SC, version: '2.0', type: 'scene', importer: {} }));
+ const entries = readdirSync(cacheDir).length;
+ const res = await cookAssets(r, { entryScenes: ['s/main.esscene'], outDir: 'out', compressTextures: true });
+ const m = JSON.parse(readFileSync(res.manifestPath!, 'utf8')) as { entries: Array<{ uuid: string; path: string }> };
+ const shipped = readFileSync(path.join(res.outDir, m.entries.find((e) => e.uuid === TEX)!.path));
+ expect(shipped.equals(Buffer.from(made.data))).toBe(true);
+ expect(readdirSync(cacheDir).length).toBe(entries); // the build encoded nothing new
+ } finally {
+ rmSync(r, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 });
+ }
+ }, 60_000);
+
+ it('keeps the KTX2 for the editor where a build would ship the smaller PNG', async () => {
+ const r = mkdtempSync(path.join(tmpdir(), 'estella-texcook-flat-'));
+ try {
+ // A solid colour: PNG writes almost nothing, the KTX2 a byte a pixel.
+ const flat = new Uint8Array(solidPng(64, 64, [40, 90, 200, 255]));
+ const encoder = await loadTextureEncoder();
+ const ask = (keepCompressed: boolean) => cookTexture({
+ root: r, path: 'sky.png', data: flat, ext: '.png', importer: {},
+ encoder, compressTextures: true, atlasTextures: false, keepCompressed,
+ });
+ const build = await ask(false);
+ expect(build.ext).toBe('.png');
+ expect(build.cook.reason).toBe('bigger-than-raw');
+ const editor = await ask(true);
+ expect(editor.ext).toBe('.ktx2');
+ expect(readdirSync(path.join(r, '.esengine/cache/cook')).length).toBe(1); // one encode for both
+ } finally {
+ rmSync(r, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 });
+ }
+ }, 60_000);
+
+ it('stays as it is where its settings keep it raw, and is never pending', async () => {
+ const r = mkdtempSync(path.join(tmpdir(), 'estella-texcook-raw-'));
+ try {
+ const out = await cookTexture({
+ root: r, path: 'lightmap.png', data: new Uint8Array(noisePng(64, 64)), ext: '.png',
+ importer: { compress: false }, encoder: await loadTextureEncoder(),
+ compressTextures: true, atlasTextures: false, cachedOnly: true,
+ });
+ expect(out.ext).toBe('.png');
+ expect(out.pending).toBeUndefined();
+ } finally {
+ rmSync(r, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 });
+ }
+ }, 60_000);
+});