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(texture): compression is two decisions, and each records its own
esenginea4a3d6d6931c
diff --git a/desktop b/desktopindex c18a973dc..a432c995f 160000--- a/desktop+++ b/desktop@@ -1 +1 @@-Subproject commit c18a973dcae3b99c3d044e4202332bc0ecbce87a+Subproject commit a432c995f4d28f733f9ca200a430953a877874f3diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.jsonindex b02d437c8..ff6cb257d 100644--- a/docs/astro/src/data/apiStability.generated.json+++ b/docs/astro/src/data/apiStability.generated.json@@ -3,10 +3,10 @@"counts": {"public": 113,"beta": 91,- "experimental": 1802,+ "experimental": 1811,"deprecated": 3},- "total": 2006,+ "total": 2015,"subsystems": [{"id": "ecs",diff --git a/native/host/bindings/RenderBindings.cpp b/native/host/bindings/RenderBindings.cppindex 067998359..9dd01d596 100644--- a/native/host/bindings/RenderBindings.cpp+++ b/native/host/bindings/RenderBindings.cpp@@ -39,10 +39,13 @@ using namespace esengine;namespace eshost {namespace {-// es_createTextureKTX2(ArrayBuffer|TypedArray, srgb?) -> { id, width, height } | null.+// es_createTextureKTX2(ArrayBuffer|TypedArray, srgb?)+// -> { id, width, height, format, blockRefused } | null.// Transcodes a KTX2/Basis container to the best device-supported compressed format// (or RGBA32) and uploads it. Native-only: the web transcodes in a wasm module and// uploads through WebGL2, so there is no engine entry point shared with it.+// `format`/`blockRefused` carry the CHOICE out: an RGBA upload is otherwise a+// correct picture at four times the memory, with nothing saying it happened.JSValue js_createTextureKTX2(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {if (argc < 1) return JS_NULL;std::vector<u8> bytes;@@ -56,6 +59,8 @@ JSValue js_createTextureKTX2(JSContext* ctx, JSValueConst, int argc, JSValueConsJS_SetPropertyStr(ctx, o, "id", JS_NewInt32(ctx, r.handle));JS_SetPropertyStr(ctx, o, "width", JS_NewInt32(ctx, r.width));JS_SetPropertyStr(ctx, o, "height", JS_NewInt32(ctx, r.height));+ JS_SetPropertyStr(ctx, o, "format", JS_NewInt32(ctx, r.format));+ JS_SetPropertyStr(ctx, o, "blockRefused", JS_NewBool(ctx, r.blockRefused));return o;}diff --git a/native/host/media/ktx2_decode.cpp b/native/host/media/ktx2_decode.cppindex 3db32b668..78e05772f 100644--- a/native/host/media/ktx2_decode.cpp+++ b/native/host/media/ktx2_decode.cpp@@ -48,7 +48,7 @@ namespace eshost {KTX2Result transcodeKTX2(const uint8_t* bytes, size_t n, bool srgb,resource::ResourceManager& rm, GfxDevice& device) {- const KTX2Result fail{-1, 0, 0};+ const KTX2Result fail{-1, 0, 0, -1, false};ensureBasis();basist::ktx2_transcoder t;@@ -60,13 +60,20 @@ KTX2Result transcodeKTX2(const uint8_t* bytes, size_t n, bool srgb,basist::transcoder_texture_format basisFmt = basist::transcoder_texture_format::cTFRGBA32;GfxCompressedFormat gfxFmt = GfxCompressedFormat::ETC2_RGBA8;bool compressed = false;+ // The two ways this loop comes up empty are different findings: a device that+ // samples none of these, or an image the device WOULD have taken at a+ // different size. Only the second is the asset's to fix.+ bool blockRefused = false;// WebGPU refuses a compressed copy whose size is not whole blocks — a 70x70// sprite fails CreateTexture and the game draws nothing. Device support is not// the only question, and the block is the FORMAT's, not always 4x4.for (const FormatChoice& c : kChoices) {const GfxCompressedFormat want = srgb ? c.srgb : c.linear;if (!device.supportsCompressedFormat(want)) continue;- if (gfxWholeBlockLevels(want, w, h, 1) == 0) continue;+ if (gfxWholeBlockLevels(want, w, h, 1) == 0) {+ blockRefused = true;+ continue;+ }basisFmt = c.basisFmt;gfxFmt = want;compressed = true;@@ -110,7 +117,9 @@ KTX2Result transcodeKTX2(const uint8_t* bytes, size_t n, bool srgb,? rm.createCompressedTexture(w, h, gfxFmt, span, uploaded): rm.createTexture(w, h, span, srgb ? TextureFormat::SRGB8A8 : TextureFormat::RGBA8, false);if (!handle.isValid()) return fail;- return KTX2Result{static_cast<int>(handle.id()), static_cast<int>(w), static_cast<int>(h)};+ return KTX2Result{static_cast<int>(handle.id()), static_cast<int>(w), static_cast<int>(h),+ compressed ? static_cast<int>(gfxFmt) : -1,+ !compressed && blockRefused};}} // namespace eshostdiff --git a/native/host/media/ktx2_decode.hpp b/native/host/media/ktx2_decode.hppindex f5b996ca9..cbcbec62a 100644--- a/native/host/media/ktx2_decode.hpp+++ b/native/host/media/ktx2_decode.hpp@@ -26,12 +26,20 @@ struct KTX2Result {int handle; ///< ResourceManager texture id, or < 0 on failure.int width;int height;+ /// GfxCompressedFormat ordinal uploaded, or < 0 when it decoded to RGBA32.+ /// The fallback is otherwise indistinguishable from success: the texture+ /// draws correctly at four times the memory somebody paid cook time to avoid.+ int format;+ /// A device format WAS available and this image is not whole blocks of it.+ /// Kept apart from "the device offered none" because only this one is fixed+ /// by the asset — the other is fixed by the build target, or not at all.+ bool blockRefused;};/** Transcode + upload a KTX2 clip (mip level 0). @p srgb selects the sRGB GPU* format variant (the block data is identical). Picks the best format the* @p device supports, falling back to RGBA32 so it always succeeds if the file- * is valid. */+ * is valid — and says in the result which of those happened. */KTX2Result transcodeKTX2(const uint8_t* bytes, size_t n, bool srgb,esengine::resource::ResourceManager& rm, esengine::GfxDevice& device);diff --git a/pipeline/src/assets/atlasPacker.ts b/pipeline/src/assets/atlasPacker.tsindex 03138a062..b061a4281 100644--- a/pipeline/src/assets/atlasPacker.ts+++ b/pipeline/src/assets/atlasPacker.ts@@ -173,12 +173,29 @@ export function encodePagePng(page: AtlasPage): Uint8Array {* into the shrunk result. Pure + deterministic — composes with content-addressed* staging exactly like the packer.*/+/**+ * The size a Max Size cap gives an image, without decoding it.+ *+ * Block alignment is judged on the ENCODED size, so predicting what a build does+ * to a texture needs this number rather than the source's — from the same+ * arithmetic the resize uses, or the prediction is right until a rounding case.+ */+export function downscaledSize(+ width: number, height: number, maxDim: number,+): { width: number; height: number } {+ const longest = Math.max(width, height);+ if (!(maxDim > 0) || longest <= maxDim) return { width, height };+ const scale = maxDim / longest;+ return {+ width: Math.max(1, Math.round(width * scale)),+ height: Math.max(1, Math.round(height * scale)),+ };+}+export function downscaleRgba(img: AtlasInputImage, maxDim: number): AtlasInputImage {const longest = Math.max(img.width, img.height);if (!(maxDim > 0) || longest <= maxDim) return img;- const scale = maxDim / longest;- const nw = Math.max(1, Math.round(img.width * scale));- const nh = Math.max(1, Math.round(img.height * scale));+ const { width: nw, height: nh } = downscaledSize(img.width, img.height, maxDim);const out = new Uint8Array(nw * nh * 4);for (let y = 0; y < nh; y++) {const sy0 = Math.floor((y * img.height) / nh);diff --git a/pipeline/src/assets/cookAssets.ts b/pipeline/src/assets/cookAssets.tsindex 712ee99c7..a5e86b257 100644--- a/pipeline/src/assets/cookAssets.ts+++ b/pipeline/src/assets/cookAssets.ts@@ -26,6 +26,13 @@ import { packAtlas, decodePngImage, encodePagePng, encodeRgbaPng, downscaleRgba,// 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.import { readTextureCookSettings } from '../project/importSettings';+// The compression a build gives one texture, and the one reason it is that.+// 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,+ type TextureCookDecision,+} from './textureCookDecision';// Single-source content hash (sdk/src/asset/contentHash.ts). Imported as source —// no hand-mirrored copy — so the cook and the runtime agree by construction.import { contentHashHex } from '../../../sdk/src/asset/contentHash';@@ -65,6 +72,14 @@ export interface CookManifestEntry extends AssetEntry {sourcePath: string;/** GPU formats the staged KTX2 can transcode to, when the asset was compressed. */compressedFormats?: string[];+ /**+ * What this build did to the texture's compression request, for images only.+ *+ * `compressedFormats` says a payload can transcode; it cannot say why one is+ * absent, and a request defeated by the image's own dimensions and one+ * defeated by the Build dialog are fixed in different places.+ */+ cook?: TextureCookDecision;/*** Addressable group this asset belongs to. `'main'` ships in the main package* (loaded eagerly); any other name is a lazy subpackage (folder convention:@@ -473,6 +488,10 @@ export async function cookAssets(const manifestEntries: CookManifestEntry[] = [];const staged = new Set<string>(); // staged output paths, for content-addressed dedup+ // Images that asked to be compressed and are not PNG. Named together: this is+ // one fact about the project's source art, and one line per JPEG would bury+ // the per-asset findings that each need their own fix.+ const defeatedByFormat: string[] = [];// ---- Auto-atlas (`<name>.atlas/` folder convention) -----------------------// Pack the reachable PNGs of each atlas directory into pages BEFORE the@@ -550,6 +569,16 @@ export async function cookAssets(const framePlan = atlasPlan.get(entry.path);if (framePlan) {const fg = resolveAssetGroup(entry.path, groupsConfig);+ // A frame's own Compress rows never reach an encoder: the page is what+ // ships. Saying so is the point — the row still reads as if it applied.+ const frameTex = readTextureCookSettings(entry.importer, platform);+ const frameCook = decideTextureCook({+ compressTextures, atlasTextures, inAtlas: true, raster: true,+ compress: frameTex.compress, format: frameTex.format, size: null,+ });+ if (cookIntentDefeated(frameCook)) {+ warnings.push(`${entry.path}: ${explainTextureCook(frameCook)}`);+ }manifestEntries.push({uuid: entry.uuid,path: framePlan.pageOutRel,@@ -561,6 +590,7 @@ export async function cookAssets(group: fg.name,groupMode: fg.delivery,...(framePlan.compressedFormats ? { compressedFormats: framePlan.compressedFormats } : {}),+ cook: frameCook,atlas: {page: framePlan.page,frame: framePlan.frame,@@ -581,41 +611,49 @@ export async function cookAssets(: await readFile(path.join(root, entry.path));let ext = path.extname(entry.path);let compressedFormats: string[] | undefined;- // Encode raster textures (PNG) to GPU-compressed KTX2 — they stay compressed- // in VRAM, the runtime transcodes per device. Hash + name reflect the ENCODED- // bytes, so this composes with content-addressing below.- if (textureEnc && entry.type !== 'scene' && ext.toLowerCase() === '.png') {+ let cook: TextureCookDecision | undefined;+ // 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.+ 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).+ // 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;- 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+ 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)}`);}- } catch (err) {- warnings.push(`${entry.path}: texture resize skipped — ${err instanceof Error ? err.message : String(err)}`);}- // Per-asset compression: KTX2 (Basis) in the texture's chosen format, or- // ship the raw/shrunk PNG when the asset opted out. Hash + name below- // reflect the ENCODED bytes, so this composes with content-addressing.- // WebGPU refuses a compressed texture whose size is not a multiple of its- // 4x4 block, so a 70x70 sprite fails CreateTexture on the native runtime- // and the game draws nothing. Ship those raw instead.- const size = rgba ? { width: tw, height: th } : safePngDimensions(data);- const blockAligned = size !== null && size.width % 4 === 0 && size.height % 4 === 0;- if (tex.compress && !blockAligned) {- warnings.push(`${entry.path}: shipped raw — ${size ? `${size.width}x${size.height}` : 'its size'} `- + 'is not a multiple of 4, which a block-compressed texture must be');+ 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,+ });+ 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 (tex.compress && blockAligned) {+ 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!;data = rgba- ? await textureEnc.encodeToKtx2({ type: textureEnc.ImageType.RGBA, data: rgba, width: tw, height: th }, { mode: tex.format, srgb: tex.srgb })- : await textureEnc.encodeToKtx2({ type: textureEnc.ImageType.PNG, data }, { mode: tex.format, srgb: tex.srgb });+ ? await enc.encodeToKtx2({ type: enc.ImageType.RGBA, data: rgba, width: tw, height: th }, { mode: cook.selected, srgb: tex.srgb })+ : await enc.encodeToKtx2({ type: enc.ImageType.PNG, data }, { mode: cook.selected, srgb: tex.srgb });ext = '.ktx2';compressedFormats = COMPRESSED_TARGETS;}@@ -733,6 +771,7 @@ export async function cookAssets(group,groupMode: delivery,...(compressedFormats ? { compressedFormats } : {}),+ ...(cook ? { cook } : {}),});// The video's audio track ships as its own manifest entry addressed as// `<source path>.m4a` / uuid `<video uuid>-audio` — the runtime resolves@@ -792,6 +831,11 @@ export async function cookAssets(const unused = index.entries.filter((e) => !reachable.has(e.uuid)).map((e) => e.uuid);const includedPaths = [...reachable].map((uuid) => byUuid.get(uuid)?.path).filter((p): p is string => p !== undefined);+ if (defeatedByFormat.length) {+ const shown = defeatedByFormat.slice(0, 3).join(', ');+ warnings.push(`${defeatedByFormat.length} image(s) ask to be compressed but are not PNG, so they `+ + `ship as they are — ${shown}${defeatedByFormat.length > 3 ? ', …' : ''}`);+ }return {ok: failed.length === 0,outDir: absOut, manifestPath, included: [...reachable], includedPaths, unused, warnings, failed,diff --git a/pipeline/src/assets/textureCookDecision.ts b/pipeline/src/assets/textureCookDecision.tsnew file mode 100644index 000000000..777a449ee--- /dev/null+++ b/pipeline/src/assets/textureCookDecision.ts@@ -0,0 +1,124 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file textureCookDecision.ts+ * @brief What a build does to one texture's compression request, and why.+ *+ * A texture's compression is decided TWICE, in two lifetimes, and the two+ * answers are not interchangeable. This is the first: at cook, a build+ * picks the payload that ships. The second happens per device, at upload,+ * when that payload becomes a GPU format or is decoded back to RGBA+ * (sdk/src/asset/compressed.ts). Folding them into one "compression was+ * lost" tells an author their memory doubled without telling them whether+ * to change the build target or accept the device.+ *+ * The cook calls this rather than re-deriving it, so what a build did and+ * what an inspector predicts are one function with one branch order.+ */++/** The Basis encoding modes a cooked KTX2 can be written in. */+export type TextureCookFormat = 'uastc' | 'etc1s';++/** What actually ships for a texture: a KTX2 in one of the modes, or the image. */+export type CookedTexturePayload = TextureCookFormat | 'raw';++/**+ * Why the selected payload is what it is.+ *+ * `compressed` is the only outcome that keeps a request; the rest each name a+ * DIFFERENT thing to change — the Build dialog, this asset's Inspector row, its+ * folder, its dimensions, its file format — not one "not compressed".+ */+export type TextureCookReason =+ | 'compressed'+ | 'build-skips-assets'+ | 'asset-opt-out'+ | 'atlas-page'+ | 'not-block-aligned'+ | 'not-raster';++export interface TextureCookDecision {+ /** The mode this asset asked for, or `none` when it opted out. */+ readonly requested: TextureCookFormat | 'none';+ readonly selected: CookedTexturePayload;+ readonly reason: TextureCookReason;+}++export interface TextureCookInputs {+ /** The build encodes textures at all (packaging.assetCompression). */+ readonly compressTextures: boolean;+ /** The build packs `<name>.atlas/` folders. */+ readonly atlasTextures: boolean;+ /** This image is a frame of one of those atlases. */+ readonly inAtlas: boolean;+ /** A source the KTX2 encoder takes — PNG. JPEG/WebP/SVG pass through as-is. */+ readonly raster: boolean;+ /** The asset's own Compress row. */+ readonly compress: boolean;+ readonly format: TextureCookFormat;+ /**+ * The dimensions that would be ENCODED — after any Max Size downscale, not the+ * source's. Null when they could not be read, which is refused exactly as a+ * misaligned size is: an encoder cannot be handed an image of unknown shape.+ */+ readonly size: { readonly width: number; readonly height: number } | null;+}++/** Block-compressed formats copy whole 4x4 blocks; WebGPU refuses a texture that+ * is not a whole number of them, so a 70x70 sprite fails CreateTexture and the+ * game draws nothing. Shipping it raw is the correct outcome, not a workaround. */+function wholeBlocks(size: TextureCookInputs['size']): boolean {+ return size !== null && size.width % 4 === 0 && size.height % 4 === 0;+}++/** The payload a build ships for one texture, and the one reason it is that. */+export function decideTextureCook(input: TextureCookInputs): TextureCookDecision {+ const requested = input.compress ? input.format : 'none';+ // An atlas frame has no payload of its own: the PAGE ships, and a page+ // aggregates images whose settings disagree, so it is always UASTC. Recorded+ // rather than assumed — a frame that asked for ETC1S got the page's answer.+ if (input.atlasTextures && input.inAtlas) {+ return { requested, selected: input.compressTextures ? 'uastc' : 'raw', reason: 'atlas-page' };+ }+ if (!input.compressTextures) return { requested, selected: 'raw', reason: 'build-skips-assets' };+ if (!input.raster) return { requested, selected: 'raw', reason: 'not-raster' };+ if (!input.compress) return { requested, selected: 'raw', reason: 'asset-opt-out' };+ if (!wholeBlocks(input.size)) return { requested, selected: 'raw', reason: 'not-block-aligned' };+ return { requested, selected: input.format, reason: 'compressed' };+}++/**+ * True when the asset asked for an encoding and the build did not give it.+ *+ * Opting out is not a defeat, nor is a build that skips assets on purpose — both+ * are choices. This catches the silent kind: a request that survived every+ * dialog and lost to the image itself, or to the folder it was dropped in.+ */+export function cookIntentDefeated(d: TextureCookDecision): boolean {+ if (d.requested === 'none') return false;+ if (d.reason === 'build-skips-assets') return false;+ return d.selected !== d.requested;+}++/** One line saying what happened to a request, for a build log. */+export function explainTextureCook(+ d: TextureCookDecision, size?: { width: number; height: number } | null,+): string {+ switch (d.reason) {+ case 'compressed':+ return `compressed to KTX2 (${d.selected})`;+ case 'build-skips-assets':+ return 'shipped raw — this build skips asset optimization';+ case 'asset-opt-out':+ return 'shipped raw — Compress is off on this asset';+ case 'atlas-page':+ return d.selected === 'raw'+ ? 'packed into an atlas page, which this build ships raw'+ : `packed into an atlas page, which is encoded ${d.selected} whatever a frame asks for`;+ case 'not-block-aligned':+ return `shipped raw — ${size ? `${size.width}x${size.height}` : 'its size'} `+ + 'is not a multiple of 4, which a block-compressed texture must be';+ case 'not-raster':+ return 'shipped raw — only PNG sources are encoded';+ }+}diff --git a/pipeline/tests/cook-assets.test.ts b/pipeline/tests/cook-assets.test.tsindex 3d04e66c0..c23b2ec17 100644--- a/pipeline/tests/cook-assets.test.ts+++ b/pipeline/tests/cook-assets.test.ts@@ -10,12 +10,13 @@ import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync, existsSyncimport { tmpdir } from 'node:os';import path from 'node:path';import { cookAssets } from '../src/assets/cookAssets';+import type { TextureCookDecision } from '../src/assets/textureCookDecision';import { decodePngImage } from '../src/assets/atlasPacker';import { contentHashHex } from '../../sdk/src/asset/contentHash';interface AssetManifest {version: string;- entries: Array<{ uuid: string; path: string; type: string; contentHash?: string; size?: number; compressedFormats?: string[] }>;+ entries: Array<{ uuid: string; path: string; type: string; contentHash?: string; size?: number; compressedFormats?: string[]; cook?: TextureCookDecision }>;}let root: string;@@ -311,6 +312,10 @@ describe('cookAssets (A4)', () => {expect(tex.path).toMatch(/\.png$/);expect(tex.compressedFormats).toBeUndefined();expect(res.warnings.some((w) => w.includes('70x70') && w.includes('multiple of 4'))).toBe(true);+ // The manifest carries the decision, not just its consequence: an absent+ // `compressedFormats` cannot say whether the build, the asset or the image+ // is why, and those are three different things to go and change.+ expect(tex.cook).toEqual({ requested: 'uastc', selected: 'raw', reason: 'not-block-aligned' });} finally {rmSync(r, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 });}diff --git a/pipeline/tests/texture-cook-decision.test.ts b/pipeline/tests/texture-cook-decision.test.tsnew file mode 100644index 000000000..180d37129--- /dev/null+++ b/pipeline/tests/texture-cook-decision.test.ts@@ -0,0 +1,103 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file The build half of a texture's compression story.+ *+ * Every outcome that is not `compressed` names a DIFFERENT thing to change, and+ * the record's whole value is keeping them apart — "compression was lost" sends+ * an author to the wrong dialog four times out of five.+ */+import { describe, it, expect } from 'vitest';+import {+ decideTextureCook, cookIntentDefeated, explainTextureCook,+ type TextureCookInputs,+} from '../src/assets/textureCookDecision';++const base: TextureCookInputs = {+ compressTextures: true,+ atlasTextures: true,+ inAtlas: false,+ raster: true,+ compress: true,+ format: 'uastc',+ size: { width: 64, height: 64 },+};++describe('decideTextureCook', () => {+ it('encodes a PNG that asked for it and fits whole blocks', () => {+ expect(decideTextureCook(base)).toEqual({+ requested: 'uastc', selected: 'uastc', reason: 'compressed',+ });+ expect(decideTextureCook({ ...base, format: 'etc1s' })).toEqual({+ requested: 'etc1s', selected: 'etc1s', reason: 'compressed',+ });+ });++ it('refuses an image that is not whole 4x4 blocks, and calls that the reason', () => {+ const d = decideTextureCook({ ...base, size: { width: 70, height: 70 } });+ expect(d).toEqual({ requested: 'uastc', selected: 'raw', reason: 'not-block-aligned' });+ // The asset asked and did not get it — this one IS a finding.+ expect(cookIntentDefeated(d)).toBe(true);+ expect(explainTextureCook(d, { width: 70, height: 70 })).toContain('70x70');+ });++ it('treats unreadable dimensions as the same refusal — an encoder cannot be handed an unknown shape', () => {+ expect(decideTextureCook({ ...base, size: null }).reason).toBe('not-block-aligned');+ });++ it('opting out is not a defeat: nothing was requested', () => {+ const d = decideTextureCook({ ...base, compress: false });+ expect(d).toEqual({ requested: 'none', selected: 'raw', reason: 'asset-opt-out' });+ expect(cookIntentDefeated(d)).toBe(false);+ });++ it('a build that skips assets is not a defeat either — it is what somebody chose', () => {+ const d = decideTextureCook({ ...base, compressTextures: false, atlasTextures: false });+ expect(d).toEqual({ requested: 'uastc', selected: 'raw', reason: 'build-skips-assets' });+ expect(cookIntentDefeated(d)).toBe(false);+ });++ it('a non-PNG source asked and was silently passed through', () => {+ const d = decideTextureCook({ ...base, raster: false });+ expect(d).toEqual({ requested: 'uastc', selected: 'raw', reason: 'not-raster' });+ expect(cookIntentDefeated(d)).toBe(true);+ });++ describe('atlas frames', () => {+ it('take the page\'s encoding, not their own', () => {+ const d = decideTextureCook({ ...base, inAtlas: true, format: 'etc1s' });+ expect(d).toEqual({ requested: 'etc1s', selected: 'uastc', reason: 'atlas-page' });+ // The row still reads ETC1S and never applied — the case this record exists for.+ expect(cookIntentDefeated(d)).toBe(true);+ });++ it('agree with a frame that asked for what the page does anyway', () => {+ const d = decideTextureCook({ ...base, inAtlas: true });+ expect(d).toEqual({ requested: 'uastc', selected: 'uastc', reason: 'atlas-page' });+ expect(cookIntentDefeated(d)).toBe(false);+ });++ it('ship raw when the build does not encode, and say the page is why', () => {+ const d = decideTextureCook({ ...base, inAtlas: true, compressTextures: false });+ expect(d).toEqual({ requested: 'uastc', selected: 'raw', reason: 'atlas-page' });+ });++ it('are only atlas frames when the build packs atlases', () => {+ expect(decideTextureCook({ ...base, inAtlas: true, atlasTextures: false }).reason)+ .toBe('compressed');+ });+ });++ it('every reason has its own sentence — a shared one is the collapse this prevents', () => {+ const said = new Set<string>();+ for (const d of [+ decideTextureCook(base),+ decideTextureCook({ ...base, compressTextures: false, atlasTextures: false }),+ decideTextureCook({ ...base, compress: false }),+ decideTextureCook({ ...base, inAtlas: true }),+ decideTextureCook({ ...base, size: { width: 70, height: 70 } }),+ decideTextureCook({ ...base, raster: false }),+ ]) said.add(explainTextureCook(d));+ expect(said.size).toBe(6);+ });+});diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex 43a0e6cab..35759bedc 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: 113 public · 84 beta · 1638 experimental · 3 deprecated+Symbols: 113 public · 84 beta · 1647 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -931,6 +931,7 @@ setManifest: (manifest: AddressableManifest | ManifestModel | null) => voidsetRefCounter: (counter: AssetRefCounter) => voidsetRemoteRoot: (url: string | undefined) => voidsetTextureImportSettingsResolver: (resolver: TextureImportSettingsResolver | null) => void+textureFormatReport: () => TextureFormatReporttexturesAwaitingReupload: () => { handle: number; path: string; }[]static create: (options: AssetsOptions) => AssetsClassstatic new (options: AssetsOptions): AssetsClass@@ -2338,6 +2339,13 @@ transient: boolean | undefined}```+## CompressedTextureFormat — enum @experimental+```+ASTC_4x4 = "astc-4x4"+ETC2_RGBA8 = "etc2-rgba8"+S3TC_DXT5 = "s3tc-dxt5"+```+## CompressorEffectDef — interface @experimental```attack: number | undefined@@ -6683,6 +6691,11 @@ static prototype: QueryInstance<any>]```+## RAW_PAYLOAD_UPLOAD — const @experimental+```+TextureUploadDecision+```+## RENAMED_COMPONENT_TYPES — const @experimental```ReadonlyMap<string, string>@@ -8691,6 +8704,24 @@ width: number(typeof TextureFilter)[keyof typeof TextureFilter]```+## TextureFormatRecord — interface @experimental+```+effective: UploadedGpuFormat+path: string+payload: "ktx2" | "raw"+reason: TextureUploadReason+target: CompressedTextureFormat | null+```++## TextureFormatReport — interface @experimental+```+compressed: number+decoded: number+deviceFormats: readonly CompressedTextureFormat[]+deviceProbed: boolean+textures: readonly TextureFormatRecord[]+```+## TextureHandle — type @experimental```number@@ -8709,6 +8740,23 @@ slot: number | undefinedtextureId: number```+## TextureUploadDecision — interface @experimental+```+effective: UploadedGpuFormat+payload: "ktx2" | "raw"+reason: TextureUploadReason+target: CompressedTextureFormat | null+```++## TextureUploadReason — type @experimental+```+| 'compressed'+ | 'no-device-format'+ | 'transcode-failed'+ | 'not-block-aligned'+ | 'uncompressed-payload'+```+## TextureWrap — type @experimental```(typeof TextureWrap)[keyof typeof TextureWrap]@@ -9766,6 +9814,11 @@ T extends MutWrapper<infer C> ? C :T```+## UploadedGpuFormat — type @experimental+```+CompressedTextureFormat | 'rgba8'+```+## ValidatePrefabOptions — interface @experimental```instanceOverrides: readonly PrefabOverride[] | undefined@@ -10843,6 +10896,11 @@ BtPlugin(graph: MaterialGraph): string```+## compressedUploadDecision — function @experimental+```+(target: CompressedTextureFormat | null, transcoded: boolean): TextureUploadDecision+```+## computeEffectiveOrthoSize — function @experimental```(baseOrthoSize: number, designAspect: number, actualAspect: number, scaleMode: number, matchWidthOrHeight: number): number@@ -13233,6 +13291,11 @@ TextInputPluginTextPlugin```+## textureFormatOf — function @experimental+```+(report: TextureFormatReport | null, path: string): TextureFormatRecord | null+```+## textureImportSettingsFrom — function @experimental```(importer: Record<string, unknown> | undefined | null): ParsedTextureImportSettings | undefineddiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex 730077dc7..f7dd585cd 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: 113 public · 89 beta · 1657 experimental · 3 deprecated+Symbols: 113 public · 89 beta · 1666 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -931,6 +931,7 @@ setManifest: (manifest: AddressableManifest | ManifestModel | null) => voidsetRefCounter: (counter: AssetRefCounter) => voidsetRemoteRoot: (url: string | undefined) => voidsetTextureImportSettingsResolver: (resolver: TextureImportSettingsResolver | null) => void+textureFormatReport: () => TextureFormatReporttexturesAwaitingReupload: () => { handle: number; path: string; }[]static create: (options: AssetsOptions) => AssetsClassstatic new (options: AssetsOptions): AssetsClass@@ -2346,6 +2347,13 @@ transient: boolean | undefined}```+## CompressedTextureFormat — enum @experimental+```+ASTC_4x4 = "astc-4x4"+ETC2_RGBA8 = "etc2-rgba8"+S3TC_DXT5 = "s3tc-dxt5"+```+## CompressorEffectDef — interface @experimental```attack: number | undefined@@ -6866,6 +6874,11 @@ static prototype: QueryInstance<any>]```+## RAW_PAYLOAD_UPLOAD — const @experimental+```+TextureUploadDecision+```+## REGISTRY_BINDINGS — const @experimental```{ readonly createEntity: "es_createEntity"; readonly destroyEntity: "es_destroyEntity"; readonly setParent: "es_setParent"; readonly hasParent: "es_hasParent"; readonly getParent: "es_getParent"; readonly removeParent: "es_removeParent"; readonly hasChildren: "es_hasChildren"; readonly getChildren: "es_getChildren"; readonly getMeshSkinJoints: "es_getMeshSkinJoints"; readonly setMeshSkinJoints: "es_setMeshSkinJoints"; readonly layoutEpoch: "es_registryLayoutEpoch"; readonly transformEpoch: "es_transformEpochBuffer"; readonly ensureComposed: "es_transformEnsureComposed"; }@@ -8884,6 +8897,24 @@ width: number(typeof TextureFilter)[keyof typeof TextureFilter]```+## TextureFormatRecord — interface @experimental+```+effective: UploadedGpuFormat+path: string+payload: "ktx2" | "raw"+reason: TextureUploadReason+target: CompressedTextureFormat | null+```++## TextureFormatReport — interface @experimental+```+compressed: number+decoded: number+deviceFormats: readonly CompressedTextureFormat[]+deviceProbed: boolean+textures: readonly TextureFormatRecord[]+```+## TextureHandle — type @experimental```number@@ -8902,6 +8933,23 @@ slot: number | undefinedtextureId: number```+## TextureUploadDecision — interface @experimental+```+effective: UploadedGpuFormat+payload: "ktx2" | "raw"+reason: TextureUploadReason+target: CompressedTextureFormat | null+```++## TextureUploadReason — type @experimental+```+| 'compressed'+ | 'no-device-format'+ | 'transcode-failed'+ | 'not-block-aligned'+ | 'uncompressed-payload'+```+## TextureWrap — type @experimental```(typeof TextureWrap)[keyof typeof TextureWrap]@@ -9959,6 +10007,11 @@ T extends MutWrapper<infer C> ? C :T```+## UploadedGpuFormat — type @experimental+```+CompressedTextureFormat | 'rgba8'+```+## ValidatePrefabOptions — interface @experimental```instanceOverrides: readonly PrefabOverride[] | undefined@@ -11051,6 +11104,11 @@ BtPlugin(graph: MaterialGraph): string```+## compressedUploadDecision — function @experimental+```+(target: CompressedTextureFormat | null, transcoded: boolean): TextureUploadDecision+```+## computeEffectiveOrthoSize — function @experimental```(baseOrthoSize: number, designAspect: number, actualAspect: number, scaleMode: number, matchWidthOrHeight: number): number@@ -13476,6 +13534,11 @@ TextInputPluginTextPlugin```+## textureFormatOf — function @experimental+```+(report: TextureFormatReport | null, path: string): TextureFormatRecord | null+```+## textureImportSettingsFrom — function @experimental```(importer: Record<string, unknown> | undefined | null): ParsedTextureImportSettings | undefineddiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex a83f846f0..72dd5a0a9 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: 113 public · 86 beta · 1637 experimental · 3 deprecated+Symbols: 113 public · 86 beta · 1646 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -926,6 +926,7 @@ setManifest: (manifest: AddressableManifest | ManifestModel | null) => voidsetRefCounter: (counter: AssetRefCounter) => voidsetRemoteRoot: (url: string | undefined) => voidsetTextureImportSettingsResolver: (resolver: TextureImportSettingsResolver | null) => void+textureFormatReport: () => TextureFormatReporttexturesAwaitingReupload: () => { handle: number; path: string; }[]static create: (options: AssetsOptions) => AssetsClassstatic new (options: AssetsOptions): AssetsClass@@ -2333,6 +2334,13 @@ transient: boolean | undefined}```+## CompressedTextureFormat — enum @experimental+```+ASTC_4x4 = "astc-4x4"+ETC2_RGBA8 = "etc2-rgba8"+S3TC_DXT5 = "s3tc-dxt5"+```+## CompressorEffectDef — interface @experimental```attack: number | undefined@@ -6678,6 +6686,11 @@ static prototype: QueryInstance<any>]```+## RAW_PAYLOAD_UPLOAD — const @experimental+```+TextureUploadDecision+```+## RENAMED_COMPONENT_TYPES — const @experimental```ReadonlyMap<string, string>@@ -8686,6 +8699,24 @@ width: number(typeof TextureFilter)[keyof typeof TextureFilter]```+## TextureFormatRecord — interface @experimental+```+effective: UploadedGpuFormat+path: string+payload: "ktx2" | "raw"+reason: TextureUploadReason+target: CompressedTextureFormat | null+```++## TextureFormatReport — interface @experimental+```+compressed: number+decoded: number+deviceFormats: readonly CompressedTextureFormat[]+deviceProbed: boolean+textures: readonly TextureFormatRecord[]+```+## TextureHandle — type @experimental```number@@ -8704,6 +8735,23 @@ slot: number | undefinedtextureId: number```+## TextureUploadDecision — interface @experimental+```+effective: UploadedGpuFormat+payload: "ktx2" | "raw"+reason: TextureUploadReason+target: CompressedTextureFormat | null+```++## TextureUploadReason — type @experimental+```+| 'compressed'+ | 'no-device-format'+ | 'transcode-failed'+ | 'not-block-aligned'+ | 'uncompressed-payload'+```+## TextureWrap — type @experimental```(typeof TextureWrap)[keyof typeof TextureWrap]@@ -9761,6 +9809,11 @@ T extends MutWrapper<infer C> ? C :T```+## UploadedGpuFormat — type @experimental+```+CompressedTextureFormat | 'rgba8'+```+## ValidatePrefabOptions — interface @experimental```instanceOverrides: readonly PrefabOverride[] | undefined@@ -10838,6 +10891,11 @@ BtPlugin(graph: MaterialGraph): string```+## compressedUploadDecision — function @experimental+```+(target: CompressedTextureFormat | null, transcoded: boolean): TextureUploadDecision+```+## computeEffectiveOrthoSize — function @experimental```(baseOrthoSize: number, designAspect: number, actualAspect: number, scaleMode: number, matchWidthOrHeight: number): number@@ -13238,6 +13296,11 @@ TextInputPluginTextPlugin```+## textureFormatOf — function @experimental+```+(report: TextureFormatReport | null, path: string): TextureFormatRecord | null+```+## textureImportSettingsFrom — function @experimental```(importer: Record<string, unknown> | undefined | null): ParsedTextureImportSettings | undefineddiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex 843d17740..3e4948b94 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: 113 public · 84 beta · 1659 experimental · 3 deprecated+Symbols: 113 public · 84 beta · 1668 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -926,6 +926,7 @@ setManifest: (manifest: AddressableManifest | ManifestModel | null) => voidsetRefCounter: (counter: AssetRefCounter) => voidsetRemoteRoot: (url: string | undefined) => voidsetTextureImportSettingsResolver: (resolver: TextureImportSettingsResolver | null) => void+textureFormatReport: () => TextureFormatReporttexturesAwaitingReupload: () => { handle: number; path: string; }[]static create: (options: AssetsOptions) => AssetsClassstatic new (options: AssetsOptions): AssetsClass@@ -2333,6 +2334,13 @@ transient: boolean | undefined}```+## CompressedTextureFormat — enum @experimental+```+ASTC_4x4 = "astc-4x4"+ETC2_RGBA8 = "etc2-rgba8"+S3TC_DXT5 = "s3tc-dxt5"+```+## CompressorEffectDef — interface @experimental```attack: number | undefined@@ -6924,6 +6932,11 @@ static prototype: QueryInstance<any>]```+## RAW_PAYLOAD_UPLOAD — const @experimental+```+TextureUploadDecision+```+## RENAMED_COMPONENT_TYPES — const @experimental```ReadonlyMap<string, string>@@ -8932,6 +8945,24 @@ width: number(typeof TextureFilter)[keyof typeof TextureFilter]```+## TextureFormatRecord — interface @experimental+```+effective: UploadedGpuFormat+path: string+payload: "ktx2" | "raw"+reason: TextureUploadReason+target: CompressedTextureFormat | null+```++## TextureFormatReport — interface @experimental+```+compressed: number+decoded: number+deviceFormats: readonly CompressedTextureFormat[]+deviceProbed: boolean+textures: readonly TextureFormatRecord[]+```+## TextureHandle — type @experimental```number@@ -8950,6 +8981,23 @@ slot: number | undefinedtextureId: number```+## TextureUploadDecision — interface @experimental+```+effective: UploadedGpuFormat+payload: "ktx2" | "raw"+reason: TextureUploadReason+target: CompressedTextureFormat | null+```++## TextureUploadReason — type @experimental+```+| 'compressed'+ | 'no-device-format'+ | 'transcode-failed'+ | 'not-block-aligned'+ | 'uncompressed-payload'+```+## TextureWrap — type @experimental```(typeof TextureWrap)[keyof typeof TextureWrap]@@ -10007,6 +10055,11 @@ T extends MutWrapper<infer C> ? C :T```+## UploadedGpuFormat — type @experimental+```+CompressedTextureFormat | 'rgba8'+```+## ValidatePrefabOptions — interface @experimental```instanceOverrides: readonly PrefabOverride[] | undefined@@ -11090,6 +11143,11 @@ BtPlugin(graph: MaterialGraph): string```+## compressedUploadDecision — function @experimental+```+(target: CompressedTextureFormat | null, transcoded: boolean): TextureUploadDecision+```+## computeEffectiveOrthoSize — function @experimental```(baseOrthoSize: number, designAspect: number, actualAspect: number, scaleMode: number, matchWidthOrHeight: number): number@@ -13495,6 +13553,11 @@ TextInputPluginTextPlugin```+## textureFormatOf — function @experimental+```+(report: TextureFormatReport | null, path: string): TextureFormatRecord | null+```+## textureImportSettingsFrom — function @experimental```(importer: Record<string, unknown> | undefined | null): ParsedTextureImportSettings | undefineddiff --git a/sdk/etc/wasm.api.md b/sdk/etc/wasm.api.mdindex ce6bd098b..b6487413a 100644--- a/sdk/etc/wasm.api.md+++ b/sdk/etc/wasm.api.md@@ -192,7 +192,7 @@ createShader: (vertSrc: string, fragSrc: string) => numbercreateTexture: (width: number, height: number, pixels: number, pixelsLen: number, format: number, flipY: boolean) => numbercreateTextureEx: (width: number, height: number, pixels: number, pixelsLen: number, format: number, flipY: boolean, filterMode: number, wrapMode: number) => numbercreateTextureFromBytes: ((width: number, height: number, pixels: Uint8Array, format: number, flipY: boolean, filterMode?: number, wrapMode?: number) => number) | undefined-createTextureFromKTX2: ((bytes: Uint8Array, srgb: boolean) => { handle: number; width: number; height: number; } | null) | undefined+createTextureFromKTX2: ((bytes: Uint8Array, srgb: boolean) => { handle: number; width: number; height: number; format?: number; blockRefused?: boolean; } | null) | undefinedgetBitmapFontRefCount: (handle: number) => numbergetResourceStats: () => { shaderCount: number; textureCount: number; vertexBufferCount: number; indexBufferCount: number; cacheHits: number; cacheMisses: number; textureBytes: number; textureBudget: number; textureEvictableCount: number; }getShaderRefCount: (handle: number) => numberdiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex d89237a81..7dbb05bd1 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: 113 public · 84 beta · 1649 experimental · 3 deprecated+Symbols: 113 public · 84 beta · 1658 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -926,6 +926,7 @@ setManifest: (manifest: AddressableManifest | ManifestModel | null) => voidsetRefCounter: (counter: AssetRefCounter) => voidsetRemoteRoot: (url: string | undefined) => voidsetTextureImportSettingsResolver: (resolver: TextureImportSettingsResolver | null) => void+textureFormatReport: () => TextureFormatReporttexturesAwaitingReupload: () => { handle: number; path: string; }[]static create: (options: AssetsOptions) => AssetsClassstatic new (options: AssetsOptions): AssetsClass@@ -2333,6 +2334,13 @@ transient: boolean | undefined}```+## CompressedTextureFormat — enum @experimental+```+ASTC_4x4 = "astc-4x4"+ETC2_RGBA8 = "etc2-rgba8"+S3TC_DXT5 = "s3tc-dxt5"+```+## CompressorEffectDef — interface @experimental```attack: number | undefined@@ -6685,6 +6693,11 @@ static prototype: QueryInstance<any>]```+## RAW_PAYLOAD_UPLOAD — const @experimental+```+TextureUploadDecision+```+## RENAMED_COMPONENT_TYPES — const @experimental```ReadonlyMap<string, string>@@ -8693,6 +8706,24 @@ width: number(typeof TextureFilter)[keyof typeof TextureFilter]```+## TextureFormatRecord — interface @experimental+```+effective: UploadedGpuFormat+path: string+payload: "ktx2" | "raw"+reason: TextureUploadReason+target: CompressedTextureFormat | null+```++## TextureFormatReport — interface @experimental+```+compressed: number+decoded: number+deviceFormats: readonly CompressedTextureFormat[]+deviceProbed: boolean+textures: readonly TextureFormatRecord[]+```+## TextureHandle — type @experimental```number@@ -8711,6 +8742,23 @@ slot: number | undefinedtextureId: number```+## TextureUploadDecision — interface @experimental+```+effective: UploadedGpuFormat+payload: "ktx2" | "raw"+reason: TextureUploadReason+target: CompressedTextureFormat | null+```++## TextureUploadReason — type @experimental+```+| 'compressed'+ | 'no-device-format'+ | 'transcode-failed'+ | 'not-block-aligned'+ | 'uncompressed-payload'+```+## TextureWrap — type @experimental```(typeof TextureWrap)[keyof typeof TextureWrap]@@ -9768,6 +9816,11 @@ T extends MutWrapper<infer C> ? C :T```+## UploadedGpuFormat — type @experimental+```+CompressedTextureFormat | 'rgba8'+```+## ValidatePrefabOptions — interface @experimental```instanceOverrides: readonly PrefabOverride[] | undefined@@ -10866,6 +10919,11 @@ BtPlugin(graph: MaterialGraph): string```+## compressedUploadDecision — function @experimental+```+(target: CompressedTextureFormat | null, transcoded: boolean): TextureUploadDecision+```+## computeEffectiveOrthoSize — function @experimental```(baseOrthoSize: number, designAspect: number, actualAspect: number, scaleMode: number, matchWidthOrHeight: number): number@@ -13261,6 +13319,11 @@ TextInputPluginTextPlugin```+## textureFormatOf — function @experimental+```+(report: TextureFormatReport | null, path: string): TextureFormatRecord | null+```+## textureImportSettingsFrom — function @experimental```(importer: Record<string, unknown> | undefined | null): ParsedTextureImportSettings | undefineddiff --git a/sdk/src/asset/Assets.ts b/sdk/src/asset/Assets.tsindex 57527d2ee..e566a3864 100644--- a/sdk/src/asset/Assets.ts+++ b/sdk/src/asset/Assets.ts@@ -17,6 +17,7 @@ import type { ESEngineModule } from '../wasm';import type { CppResourceManager } from '../wasm';import { requireResourceManager, getResourceManager, evictTextureDimensions } from '../wasm/resourceManager';import type { TextureImportSettings, TextureImportSettingsResolver } from './loaders/TextureLoader';+import type { TextureFormatReport } from './textureFormatReport';import { TextureLoader, textureResidencyKey } from './loaders/TextureLoader';import { AssetRefLedger, type AssetRefLease } from './AssetRefLedger';import { AssetScope, type AssetLease } from './AssetLease';@@ -2071,6 +2072,18 @@ export class Assets {return this.textureLoader_;}+ /**+ * What the textures this realm loaded became on the GPU, and which compressed+ * formats the device samples at all. @experimental+ *+ * The upload half; what the BUILD shipped is the cook's own record. A realm+ * that plays source images still answers `deviceFormats` — the capability a+ * cooked payload would meet here.+ */+ textureFormatReport(): TextureFormatReport {+ return this.textureLoader_.formatReport();+ }+setAssetRefResolver(resolver: AssetRefResolver): void {this.assetRefResolver_ = resolver;}diff --git a/sdk/src/asset/compressed.ts b/sdk/src/asset/compressed.tsindex 2992fbfd4..746521547 100644--- a/sdk/src/asset/compressed.ts+++ b/sdk/src/asset/compressed.ts@@ -141,35 +141,49 @@ export function engineFormatCode(format: CompressedTextureFormat, srgb: boolean)return ENGINE_FORMAT_CODE[format][srgb ? 1 : 0];}-/** Best target the ENGINE says it can sample, in quality/size order. */+/**+ * Quality/size order: ASTC (best), ETC2 (the WebGL2 baseline), S3TC (desktop).+ *+ * ONE list. The GL path and the engine-upload path ask different oracles about+ * the same device; a second ordering would let a texture land in a different+ * format depending on which backend loaded it.+ */+export const TARGET_PREFERENCE: readonly CompressedTextureFormat[] = [+ CompressedTextureFormat.ASTC_4x4,+ CompressedTextureFormat.ETC2_RGBA8,+ CompressedTextureFormat.S3TC_DXT5,+];++/** Best target the ENGINE says it can sample, in {@link TARGET_PREFERENCE} order. */export function chooseEngineTargetFormat(supports: (code: number) => boolean, srgb = false,): CompressedTextureFormat | null {- const order = [- CompressedTextureFormat.ASTC_4x4,- CompressedTextureFormat.ETC2_RGBA8,- CompressedTextureFormat.S3TC_DXT5,- ];- for (const f of order) if (supports(engineFormatCode(f, srgb))) return f;+ for (const f of TARGET_PREFERENCE) if (supports(engineFormatCode(f, srgb))) return f;return null;}/**- * Best available target in quality/size order: ASTC > ETC2 > S3TC. null = none.+ * Best available target in {@link TARGET_PREFERENCE} order. null = none.* With `srgb` (linear pipeline) a format only qualifies when its sRGB variant is* uploadable — S3TC needs the separate s3tc_srgb extension; ASTC/ETC2 sRGB ride* the same extension as their UNORM twins. The transcoded block data is- * identical either way; only the sampling interpretation differs.+ * identical either way; only the sampling interpretation differs, which is why+ * "can this be uploaded" IS whether an internalformat exists for it.*/export function chooseTargetFormat(support: CompressedTextureSupport, srgb = false,): CompressedTextureFormat | null {- if (support.astc) return CompressedTextureFormat.ASTC_4x4;- if (support.etc) return CompressedTextureFormat.ETC2_RGBA8;- if (srgb ? support.s3tcSrgb : support.s3tc) return CompressedTextureFormat.S3TC_DXT5;+ for (const f of TARGET_PREFERENCE) if (glInternalFormat(support, f, srgb) !== null) return f;return null;}+/** Every target this device samples, best first — the capability, not a choice. */+export function supportedTargetFormats(+ supports: (f: CompressedTextureFormat) => boolean,+): CompressedTextureFormat[] {+ return TARGET_PREFERENCE.filter(supports);+}+/** WebGL `internalformat` enum for a chosen format, from its enabling extension. */export function glInternalFormat(support: CompressedTextureSupport, fmt: CompressedTextureFormat, srgb = false,@@ -286,6 +300,91 @@ export function uploadRgbaTexture(// Orchestration (the compressed-vs-fallback decision — the testable core)// =============================================================================+/** What a texture ended up as on the GPU. */+export type UploadedGpuFormat = CompressedTextureFormat | 'rgba8';++/**+ * Why an upload landed on the format it did.+ *+ * `uncompressed-payload` is not a fallback — an ordinary image asked for+ * nothing. The other three each name a different thing to change: the DEVICE+ * samples none, the FILE would not transcode, or its size is not whole blocks.+ */+export type TextureUploadReason =+ | 'compressed'+ | 'no-device-format'+ | 'transcode-failed'+ | 'not-block-aligned'+ | 'uncompressed-payload';++/**+ * What one texture upload did with a cooked payload, on THIS device.+ *+ * The second half; the first is what the build shipped+ * (pipeline/src/assets/textureCookDecision.ts). Kept apart because a cook that+ * shipped raw is a build setting and a device that decoded it is a device.+ */+export interface TextureUploadDecision {+ /** What arrived: a transcodable container, or a plain image. */+ readonly payload: 'ktx2' | 'raw';+ /** The best format this device offered for it; null when it offered none. */+ readonly target: CompressedTextureFormat | null;+ readonly effective: UploadedGpuFormat;+ readonly reason: TextureUploadReason;+}++/** The decision a compressed payload came to, given the device's answer and+ * whether the transcode to it worked. Pure — the three cases hold without a+ * GL context, a device or the basis module. */+export function compressedUploadDecision(+ target: CompressedTextureFormat | null, transcoded: boolean,+): TextureUploadDecision {+ if (target === null) {+ return { payload: 'ktx2', target: null, effective: 'rgba8', reason: 'no-device-format' };+ }+ if (!transcoded) {+ return { payload: 'ktx2', target, effective: 'rgba8', reason: 'transcode-failed' };+ }+ return { payload: 'ktx2', target, effective: target, reason: 'compressed' };+}++/** The target an engine ordinal names, or null when it names none of the three+ * (an RGBA upload, or a format no loader targets). */+export function formatFromEngineCode(code: number): CompressedTextureFormat | null {+ for (const f of TARGET_PREFERENCE) {+ const [unorm, srgb] = ENGINE_FORMAT_CODE[f];+ if (code === unorm || code === srgb) return f;+ }+ return null;+}++/**+ * What a native host's own KTX2 upload came to.+ *+ * `format` is the engine ordinal it uploaded, negative when it decoded to RGBA.+ * `blockRefused` separates the two ways that happens — an image that was not+ * whole blocks, or a device that offered nothing. Only the first is the asset's.+ */+export function hostUploadDecision(format: number, blockRefused: boolean): TextureUploadDecision {+ const target = formatFromEngineCode(format);+ if (target) return { payload: 'ktx2', target, effective: target, reason: 'compressed' };+ return {+ payload: 'ktx2', target: null, effective: 'rgba8',+ reason: blockRefused ? 'not-block-aligned' : 'no-device-format',+ };+}++/** A texture that was never a compressed payload — an ordinary image upload. */+export const RAW_PAYLOAD_UPLOAD: TextureUploadDecision = {+ payload: 'raw', target: null, effective: 'rgba8', reason: 'uncompressed-payload',+};++export interface LoadedCompressedTexture extends UploadedTexture {+ /** What this upload came to, and why — the fallback is otherwise an+ * else-branch that counts nothing. */+ readonly decision: TextureUploadDecision;+}+/*** Load a KTX2 buffer into a GPU texture: prefer a device-supported compressed* format, fall back to RGBA8 when none is available or the compressed transcode@@ -294,15 +393,15 @@ export function uploadRgbaTexture(export function loadCompressedTexture(gl: WebGL2RenderingContext, module: ESEngineModule,transcoder: BasisTranscoder, bytes: Uint8Array, opts?: CompressedUploadOptions,-): UploadedTexture {+): LoadedCompressedTexture {const support = detectCompressedTextureSupport(gl);const target = chooseTargetFormat(support, opts?.srgb ?? false);- if (target !== null) {- const t = transcoder.transcode(bytes, target);- if (t) return uploadCompressedTexture(gl, module, support, target, t, opts);- // transcode to the chosen format failed → fall through to RGBA.+ const t = target !== null ? transcoder.transcode(bytes, target) : null;+ const decision = compressedUploadDecision(target, t !== null);+ if (target !== null && t) {+ return { ...uploadCompressedTexture(gl, module, support, target, t, opts), decision };}const rgba = transcoder.transcodeToRgba(bytes);if (!rgba) throw new Error('BasisTranscoder failed to decode KTX2 (compressed and RGBA paths both failed)');- return uploadRgbaTexture(gl, module, rgba, opts);+ return { ...uploadRgbaTexture(gl, module, rgba, opts), decision };}diff --git a/sdk/src/asset/index.ts b/sdk/src/asset/index.tsindex 393d4b0e6..5654192f8 100644--- a/sdk/src/asset/index.ts+++ b/sdk/src/asset/index.ts@@ -56,3 +56,17 @@ export {export { type AssetLoader, type LoadContext, type TextureResult, type TextureResult as TextureInfo, type SpineResult, type SpineLoadResult, type MaterialResult, type FontResult, type AudioResult, type LocaleResult, type JsonResult } from './AssetLoader';export { TextureLoader, type TextureImportSettings, type TextureImportSettingsResolver } from './loaders/TextureLoader';export { SceneHandle } from './SceneHandle';++// A texture's compression is decided twice — the build picks a payload, the+// device decides what it becomes. This is the second half; the first is the+// cook's own record, in the manifest entry it wrote.+export {+ CompressedTextureFormat,+ compressedUploadDecision,+ RAW_PAYLOAD_UPLOAD,+ type TextureUploadDecision,+ type TextureUploadReason,+ type UploadedGpuFormat,+} from './compressed';+export { textureFormatOf } from './textureFormatReport';+export type { TextureFormatReport, TextureFormatRecord } from './textureFormatReport';diff --git a/sdk/src/asset/loaders/TextureLoader.ts b/sdk/src/asset/loaders/TextureLoader.tsindex a856a3c91..a7a13fd94 100644--- a/sdk/src/asset/loaders/TextureLoader.ts+++ b/sdk/src/asset/loaders/TextureLoader.ts@@ -10,8 +10,12 @@ import type { ESEngineModule } from '../../wasm';import { withMalloc } from '../../wasm/wasmScratch';import {isKtx2, isKtx2Path, loadCompressedTexture, chooseEngineTargetFormat, engineFormatCode,- type BasisTranscoder,+ compressedUploadDecision, detectCompressedTextureSupport, glInternalFormat,+ supportedTargetFormats, hostUploadDecision, RAW_PAYLOAD_UPLOAD,+ CompressedTextureFormat,+ type BasisTranscoder, type TextureUploadDecision,} from '../compressed';+import { TextureFormatLog, type TextureFormatReport } from '../textureFormatReport';import { uploadBoundTextureImage, applyBoundTextureSampling } from '../glTextureUpload';import { createTextureFromPixels, type TextureParams } from '../../runtime/runtimeAssets';@@ -94,6 +98,17 @@ export class TextureLoader implements AssetLoader<TextureResult> {this.transcoder_ = await this.transcoderPending_;return this.transcoder_;}+ /**+ * What every texture this loader uploaded became, and the device capability+ * that constrained it. Owned by the loader, so it is scoped to the realm that+ * took the decisions and cannot outlive the textures it describes.+ */+ private readonly formats_ = new TextureFormatLog();+ /** The decision the in-flight upload came to. Set by the one entry point that+ * chooses a path (decodeAndUpload_) and read by the one that records. */+ private lastDecision_: TextureUploadDecision = RAW_PAYLOAD_UPLOAD;+ private deviceFormats_: CompressedTextureFormat[] | null = null;+private canvas_: PlatformCanvas | null = null;private ctx_: PlatformCanvas2DContext | null = null;/**@@ -183,6 +198,10 @@ export class TextureLoader implements AssetLoader<TextureResult> {path: string, ctx: LoadContext, flip: boolean, settings?: TextureImportSettings,): Promise<TextureResult> {const result = await this.decodeAndUpload_(path, ctx, flip, settings);+ // Recorded HERE, once, for every path into the loader — the compressed+ // paths, the pixel decoder and the <img> upload alike. A record kept only+ // where a fallback happens cannot say that everything else was fine.+ this.formats_.record(textureResidencyKey(path, flip), this.lastDecision_);// Path identity in the C++ pool: after the last release the texture can// survive as an evictable cache entry (budget permitting) and the next// load revives it by this key instead of re-fetching + re-decoding.@@ -195,6 +214,7 @@ export class TextureLoader implements AssetLoader<TextureResult> {private async decodeAndUpload_(path: string, ctx: LoadContext, flip: boolean, settings?: TextureImportSettings,): Promise<TextureResult> {+ this.lastDecision_ = RAW_PAYLOAD_UPLOAD;if (isKtx2Path(path)) {return this.loadCompressed(path, ctx, settings);}@@ -232,6 +252,10 @@ export class TextureLoader implements AssetLoader<TextureResult> {if (rm.createTextureFromKTX2) {const r = rm.createTextureFromKTX2(bytes, linearColorSpace());if (!r) throw new Error(`TextureLoader: KTX2 transcode failed for ${path}`);+ // A host that reports no format says nothing rather than claiming+ // success: -1 with no block refusal reads as "this device offered+ // none", the honest reading of an absent answer.+ this.lastDecision_ = hostUploadDecision(r.format ?? -1, r.blockRefused ?? false);return { handle: r.handle, width: r.width, height: r.height };}const transcoder = await this.ensureTranscoder_();@@ -251,6 +275,7 @@ export class TextureLoader implements AssetLoader<TextureResult> {// above on the missing gl); the KTX2 path is web-only.const r = loadCompressedTexture(gl, this.module_!, transcoder, bytes,{ ...settings, srgb: linearColorSpace() });+ this.lastDecision_ = r.decision;return { handle: r.handle, width: r.width, height: r.height };}@@ -268,17 +293,22 @@ export class TextureLoader implements AssetLoader<TextureResult> {if (module && rm.supportsCompressedFormat && rm.createCompressedTexture) {const supports = rm.supportsCompressedFormat.bind(rm);const target = chooseEngineTargetFormat((code) => supports(code), srgb);- if (target) {- const t = transcoder.transcode(bytes, target);- if (t) {- const code = engineFormatCode(target, srgb);- const handle = withMalloc(module, t.data.length, (ptr) => {- module.HEAPU8.set(t.data, ptr);- return rm.createCompressedTexture!(t.width, t.height, code, ptr, t.data.length, 1);- });- if (handle) return { handle, width: t.width, height: t.height };- }+ const t = target ? transcoder.transcode(bytes, target) : null;+ this.lastDecision_ = compressedUploadDecision(target, t !== null);+ if (target && t) {+ const code = engineFormatCode(target, srgb);+ const handle = withMalloc(module, t.data.length, (ptr) => {+ module.HEAPU8.set(t.data, ptr);+ return rm.createCompressedTexture!(t.width, t.height, code, ptr, t.data.length, 1);+ });+ if (handle) return { handle, width: t.width, height: t.height };+ // The upload itself failed after a good transcode — the payload+ // still becomes RGBA, and saying "compressed" here would be a+ // record of what was intended rather than what happened.+ this.lastDecision_ = compressedUploadDecision(target, false);}+ } else {+ this.lastDecision_ = compressedUploadDecision(null, false);}const rgba = transcoder.transcodeToRgba(bytes);if (!rgba) throw new Error(`TextureLoader: KTX2 decode failed for ${path}`);@@ -335,6 +365,37 @@ export class TextureLoader implements AssetLoader<TextureResult> {return findWebGL2Context(this.module_?.GL);}+ /**+ * Which compressed formats this device samples, best first.+ *+ * The INPUT to every upload decision, and the half a realm answers without+ * loading one. Null when nothing could be asked — an empty list would read as+ * a capability. Cached, since `getExtension` also ENABLES.+ */+ deviceFormats(): CompressedTextureFormat[] | null {+ if (this.deviceFormats_) return this.deviceFormats_;+ const srgb = linearColorSpace();+ const gl = this.getWebGL2Context();+ if (gl) {+ const support = detectCompressedTextureSupport(gl);+ return (this.deviceFormats_ =+ supportedTargetFormats((f) => glInternalFormat(support, f, srgb) !== null));+ }+ const rm = requireResourceManager();+ if (rm.supportsCompressedFormat) {+ const supports = rm.supportsCompressedFormat.bind(rm);+ return (this.deviceFormats_ =+ supportedTargetFormats((f) => supports(engineFormatCode(f, srgb))));+ }+ return null;+ }++ /** What the textures this loader uploaded became, and on what device. */+ formatReport(): TextureFormatReport {+ const formats = this.deviceFormats();+ return this.formats_.report(formats ?? [], formats !== null);+ }+private createTextureWebGL2(gl: WebGL2RenderingContext,img: PlatformImage | ImageBitmap,diff --git a/sdk/src/asset/textureFormatReport.ts b/sdk/src/asset/textureFormatReport.tsnew file mode 100644index 000000000..6af535487--- /dev/null+++ b/sdk/src/asset/textureFormatReport.ts@@ -0,0 +1,77 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file textureFormatReport.ts+ * @brief What the textures this realm loaded actually became on the GPU.+ *+ * A cooked KTX2 that the device cannot sample is decoded to RGBA and+ * uploaded — correctly, four times larger, and until now with nothing+ * anywhere saying so. This is the ledger of those decisions, kept where+ * they are taken (the loader) and therefore scoped to the realm that took+ * them, so a report never outlives the textures it describes.+ *+ * `deviceFormats` is the INPUT, not an outcome: the formats this machine+ * samples at all. Empty with `deviceProbed` false means nobody could be+ * asked yet — a different answer from "this device supports none", and+ * collapsing them is how "0" reads as a fact instead of a silence.+ */+import type { CompressedTextureFormat, TextureUploadDecision } from './compressed';++export interface TextureFormatRecord extends TextureUploadDecision {+ /** The residency key the texture was loaded under. */+ readonly path: string;+}++export interface TextureFormatReport {+ /** Compressed formats this device samples, best first. */+ readonly deviceFormats: readonly CompressedTextureFormat[];+ /** Whether anything was in a position to answer the question. */+ readonly deviceProbed: boolean;+ readonly textures: readonly TextureFormatRecord[];+ /** Compressed payloads that stayed compressed. */+ readonly compressed: number;+ /** Compressed payloads decoded to RGBA — the ones that cost 4x their VRAM. */+ readonly decoded: number;+}++/**+ * The per-realm ledger. One record per residency key: a texture revived from the+ * pool under the same key made the same decision, and a second row would count+ * one texture's memory twice.+ */+export class TextureFormatLog {+ private readonly rows_ = new Map<string, TextureFormatRecord>();++ record(path: string, decision: TextureUploadDecision): void {+ this.rows_.set(path, { path, ...decision });+ }++ report(deviceFormats: readonly CompressedTextureFormat[], deviceProbed: boolean): TextureFormatReport {+ const textures = [...this.rows_.values()];+ let compressed = 0;+ let decoded = 0;+ for (const r of textures) {+ if (r.payload !== 'ktx2') continue;+ if (r.reason === 'compressed') compressed++;+ else decoded++;+ }+ return { deviceFormats, deviceProbed, textures, compressed, decoded };+ }++ clear(): void {+ this.rows_.clear();+ }+}++/**+ * The record for one asset path, whichever flip orientation it loaded under.+ *+ * Rows are keyed by residency key (path + flip), so a caller holding a plain+ * asset path cannot look one up — and a caller that reconstructed the key would+ * own a copy of a shape that is not its to know.+ */+export function textureFormatOf(+ report: TextureFormatReport | null, path: string,+): TextureFormatRecord | null {+ return report?.textures.find((t) => t.path.startsWith(`${path}:`)) ?? null;+}diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.tsindex 10c483bdc..6dee9e2e8 100644--- a/sdk/src/core-content.ts+++ b/sdk/src/core-content.ts@@ -97,6 +97,15 @@ export {type SpineCullingRect,type SpineCullingContract,type SpineManifestContract,+ CompressedTextureFormat,+ compressedUploadDecision,+ RAW_PAYLOAD_UPLOAD,+ type TextureUploadDecision,+ type TextureUploadReason,+ type UploadedGpuFormat,+ textureFormatOf,+ type TextureFormatReport,+ type TextureFormatRecord,} from './asset';/** When the live bindings that READ the asset graph have caught up with it —diff --git a/sdk/src/ecs/bridge/nativeResourceManager.ts b/sdk/src/ecs/bridge/nativeResourceManager.tsindex 05e5a807e..4da1366e2 100644--- a/sdk/src/ecs/bridge/nativeResourceManager.ts+++ b/sdk/src/ecs/bridge/nativeResourceManager.ts@@ -76,12 +76,17 @@ export function createNativeResourceManager([width, height, pixels, pixels.length, format, flipY,filterMode ?? FILTER_LINEAR, wrapMode ?? WRAP_CLAMP_TO_EDGE]) as number,- // The host transcodes KTX2 (basis) and uploads the compressed blocks; it- // returns { id, width, height } — expose it as { handle, ... }.+ // The host transcodes KTX2 (basis) and uploads the blocks:+ // { id, width, height, format, blockRefused } → { handle, ... }. A host+ // without the last two leaves them undefined, never a compressed answer.createTextureFromKTX2: (bytes, srgb) => {const r = hostCall(scope, RESOURCE_BINDINGS.createTextureKTX2, [bytes, srgb]) as- { id: number; width: number; height: number } | null;- return r ? { handle: r.id, width: r.width, height: r.height } : null;+ { id: number; width: number; height: number;+ format?: number; blockRefused?: boolean } | null;+ return r+ ? { handle: r.id, width: r.width, height: r.height,+ format: r.format, blockRefused: r.blockRefused }+ : null;},updateTextureSubregionFromBytes: (handle, x, y, width, height, pixels): void => {diff --git a/sdk/src/wasm.ts b/sdk/src/wasm.tsindex ae11c9c57..7bc564c19 100644--- a/sdk/src/wasm.ts+++ b/sdk/src/wasm.ts@@ -56,7 +56,14 @@ export interface CppResourceManager {/** Transcode + upload a KTX2/Basis container to a device-supported compressed* format (or RGBA32). Native only (the basis transcoder lives in the host);* the web KTX2 path is WebGL2 + the wasm transcoder instead. */- createTextureFromKTX2?(bytes: Uint8Array, srgb: boolean): { handle: number; width: number; height: number } | null;+ /** Transcode + upload a KTX2 natively. `format` is the GfxCompressedFormat+ * ordinal uploaded, negative when it decoded to RGBA; `blockRefused` says a+ * supported format existed and the image was not whole blocks of it. Both+ * optional — an absent answer must not read as a compressed one. */+ createTextureFromKTX2?(bytes: Uint8Array, srgb: boolean): {+ handle: number; width: number; height: number;+ format?: number; blockRefused?: boolean;+ } | null;/** Whether the ACTIVE backend samples this compressed format (the C++* `GfxCompressedFormat` ordinal). Absent on an older wasm build. */supportsCompressedFormat?(format: number): boolean;diff --git a/sdk/tests/compressed-texture.test.ts b/sdk/tests/compressed-texture.test.tsindex bd57e0d2e..21d998aac 100644--- a/sdk/tests/compressed-texture.test.ts+++ b/sdk/tests/compressed-texture.test.ts@@ -124,7 +124,13 @@ describe('loadCompressedTexture', () => {expect(gl.compressedTexImage2D.mock.calls[0][2]).toBe(ASTC);expect(gl.texImage2D).not.toHaveBeenCalled();expect(registerExternalTexture).toHaveBeenCalledWith(7, 4, 4);- expect(r).toEqual({ handle: 42, width: 4, height: 4 });+ expect(r).toEqual({+ handle: 42, width: 4, height: 4,+ decision: {+ payload: 'ktx2', target: CompressedTextureFormat.ASTC_4x4,+ effective: CompressedTextureFormat.ASTC_4x4, reason: 'compressed',+ },+ });});it('falls back to RGBA8 when no compressed format is supported', () => {@@ -137,16 +143,27 @@ describe('loadCompressedTexture', () => {expect(gl.compressedTexImage2D).not.toHaveBeenCalled();expect(gl.texImage2D).toHaveBeenCalledTimes(1);expect(r.handle).toBe(42);+ // The DEVICE turned it down — nothing about the file is wrong, and the+ // fix is a build target rather than the asset.+ expect(r.decision).toEqual({+ payload: 'ktx2', target: null, effective: 'rgba8', reason: 'no-device-format',+ });});it('falls back to RGBA8 when the compressed transcode fails', () => {const gl = makeGl({ etc: true });const transcoder = makeTranscoder({ transcode: vi.fn(() => null) });- loadCompressedTexture(gl as never, makeModule() as never, transcoder, KTX2_HEADER);+ const r = loadCompressedTexture(gl as never, makeModule() as never, transcoder, KTX2_HEADER);expect(transcoder.transcode).toHaveBeenCalledOnce();expect(transcoder.transcodeToRgba).toHaveBeenCalledOnce();expect(gl.texImage2D).toHaveBeenCalledTimes(1);+ // The device DID offer a format; the payload would not become it. Reported+ // apart from "no-device-format" because only this one names the file.+ expect(r.decision).toEqual({+ payload: 'ktx2', target: CompressedTextureFormat.ETC2_RGBA8,+ effective: 'rgba8', reason: 'transcode-failed',+ });});it('throws when both compressed and RGBA decode fail', () => {diff --git a/sdk/tests/texture-format-report.test.ts b/sdk/tests/texture-format-report.test.tsnew file mode 100644index 000000000..9dace3509--- /dev/null+++ b/sdk/tests/texture-format-report.test.ts@@ -0,0 +1,129 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file The upload half of a texture's compression: what a cooked payload became+ * on THIS device, and why it is not what shipped.+ *+ * Pure over the two inputs that decide it — what the device offered and whether+ * the transcode worked — so it holds with no GL context and no basis module.+ */+import { describe, it, expect } from 'vitest';+import {+ CompressedTextureFormat, TARGET_PREFERENCE,+ compressedUploadDecision, hostUploadDecision, supportedTargetFormats,+ formatFromEngineCode, engineFormatCode, RAW_PAYLOAD_UPLOAD,+} from '../src/asset/compressed';+import { TextureFormatLog, textureFormatOf } from '../src/asset/textureFormatReport';++const ASTC = CompressedTextureFormat.ASTC_4x4;+const ETC2 = CompressedTextureFormat.ETC2_RGBA8;+const S3TC = CompressedTextureFormat.S3TC_DXT5;++describe('compressedUploadDecision', () => {+ it('keeps the format when the device offered one and it transcoded', () => {+ expect(compressedUploadDecision(ASTC, true)).toEqual({+ payload: 'ktx2', target: ASTC, effective: ASTC, reason: 'compressed',+ });+ });++ it('separates a device that offers nothing from a payload that would not transcode', () => {+ // Both end at RGBA8 and both cost the same memory; only one is fixed by+ // re-cooking the asset, which is why one reason would be useless.+ const noDevice = compressedUploadDecision(null, false);+ const badPayload = compressedUploadDecision(ETC2, false);+ expect(noDevice.reason).toBe('no-device-format');+ expect(badPayload.reason).toBe('transcode-failed');+ expect(noDevice.target).toBeNull();+ expect(badPayload.target).toBe(ETC2);+ expect(noDevice.effective).toBe('rgba8');+ expect(badPayload.effective).toBe('rgba8');+ });++ it('an ordinary image is not a fallback', () => {+ // The gamma-project lesson: `effective === rgba8` covers "asked and was+ // refused" AND "never asked", and only the payload tells them apart. A+ // project that never turned compression on must see no warning at all.+ expect(RAW_PAYLOAD_UPLOAD.payload).toBe('raw');+ expect(RAW_PAYLOAD_UPLOAD.reason).toBe('uncompressed-payload');+ expect(compressedUploadDecision(null, false).payload).toBe('ktx2');+ });+});++describe('hostUploadDecision (native)', () => {+ it('reads back the engine ordinal it uploaded', () => {+ for (const f of TARGET_PREFERENCE) {+ for (const srgb of [false, true]) {+ const d = hostUploadDecision(engineFormatCode(f, srgb), false);+ expect(d.effective).toBe(f);+ expect(d.reason).toBe('compressed');+ }+ }+ });++ it('names the image, not the device, when the blocks were the refusal', () => {+ expect(hostUploadDecision(-1, true).reason).toBe('not-block-aligned');+ expect(hostUploadDecision(-1, false).reason).toBe('no-device-format');+ });++ it('a host that answers nothing is read as "this device offered none", never as success', () => {+ expect(hostUploadDecision(-1, false).effective).toBe('rgba8');+ });++ it('formatFromEngineCode maps both the unorm and sRGB spellings of one target', () => {+ expect(formatFromEngineCode(engineFormatCode(ASTC, false))).toBe(ASTC);+ expect(formatFromEngineCode(engineFormatCode(ASTC, true))).toBe(ASTC);+ expect(formatFromEngineCode(0)).toBeNull(); // ETC2_RGB8 — no loader targets it+ expect(formatFromEngineCode(-1)).toBeNull();+ });+});++describe('supportedTargetFormats', () => {+ it('answers in the one preference order, best first', () => {+ expect(supportedTargetFormats(() => true)).toEqual([ASTC, ETC2, S3TC]);+ expect(supportedTargetFormats((f) => f !== ASTC)).toEqual([ETC2, S3TC]);+ expect(supportedTargetFormats(() => false)).toEqual([]);+ });+});++describe('TextureFormatLog', () => {+ it('counts the payloads that lost their compression apart from the ones that kept it', () => {+ const log = new TextureFormatLog();+ log.record('a.ktx2:n', compressedUploadDecision(ASTC, true));+ log.record('b.ktx2:n', compressedUploadDecision(null, false));+ log.record('c.ktx2:n', compressedUploadDecision(ETC2, false));+ log.record('d.png:n', RAW_PAYLOAD_UPLOAD);++ const r = log.report([ASTC], true);+ expect(r.compressed).toBe(1);+ expect(r.decoded).toBe(2);+ // A source image is neither: it never had compression to lose, and+ // counting it as decoded would make every uncompressed project look sick.+ expect(r.textures).toHaveLength(4);+ expect(r.deviceFormats).toEqual([ASTC]);+ expect(r.deviceProbed).toBe(true);+ });++ it('a texture revived under the same key is one row, not two', () => {+ const log = new TextureFormatLog();+ log.record('a.ktx2:n', compressedUploadDecision(ASTC, true));+ log.record('a.ktx2:n', compressedUploadDecision(ASTC, true));+ expect(log.report([], false).textures).toHaveLength(1);+ });++ it('nobody asked yet is not the same fact as "this device supports none"', () => {+ const unprobed = new TextureFormatLog().report([], false);+ expect(unprobed.deviceFormats).toEqual([]);+ expect(unprobed.deviceProbed).toBe(false);+ });++ it('answers per ASSET PATH, which is the question an inspector asks', () => {+ // The rows are keyed by residency key (path + flip); a caller holding a+ // plain path must not have to know that shape to look one up.+ const log = new TextureFormatLog();+ log.record('t/a.ktx2:n', compressedUploadDecision(null, false));+ const r = log.report([], false);+ expect(textureFormatOf(r, 't/a.ktx2')?.reason).toBe('no-device-format');+ expect(textureFormatOf(r, 't/a')).toBeNull();+ expect(textureFormatOf(null, 't/a.ktx2')).toBeNull();+ });+});diff --git a/tools/check-texture-format.mjs b/tools/check-texture-format.mjsnew file mode 100644index 000000000..119874db0--- /dev/null+++ b/tools/check-texture-format.mjs@@ -0,0 +1,187 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file check-texture-format.mjs — a texture's compression is decided twice, and+ * both decisions are recorded where they are taken.+ *+ * The unit tests hold the decisions themselves (texture-cook-decision,+ * texture-format-report). This holds the WIRING, which is where this defect lived+ * for as long as it did: the cook's branch and the loader's else-branch each knew+ * the answer and neither wrote it down, so a project that spent cook time on+ * compression paid four times the VRAM with nothing anywhere saying so.+ *+ * The two must stay apart. "Compression was lost" sends an author to the Build+ * dialog when the fix was the image's dimensions, and to the image when the fix+ * was the device they were testing on.+ */+import { readFileSync, existsSync } from 'node:fs';+import path from 'node:path';+import { fileURLToPath } from 'node:url';++const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');+const DECIDE = 'pipeline/src/assets/textureCookDecision.ts';+const COOK = 'pipeline/src/assets/cookAssets.ts';+const COMPRESSED = 'sdk/src/asset/compressed.ts';+const LOADER = 'sdk/src/asset/loaders/TextureLoader.ts';+const NATIVE = 'native/host/media/ktx2_decode.cpp';+const DETAILS = 'desktop/src/panels/Details.tsx';+const SHIP = 'desktop/src/project/textureShipFormat.ts';+const SETTINGS = 'desktop/src/settings/projectSettings.ts';+const SURFACE = 'desktop/src/engine/EditorControlSurface.ts';+const CATALOG = 'desktop/shared/toolCatalog.mjs';++const read = (rel) => readFileSync(path.join(ROOT, rel), 'utf8');+const problems = [];++// ---------------------------------------------------------------- cook (build)+const decide = read(DECIDE);+const cook = read(COOK);++// The reasons are the product. Collapsing two into one is the failure this whole+// record exists to prevent, so the vocabulary is read from the source and every+// consumer below is held to ALL of it rather than to a list written here.+const COOK_REASONS = [...decide.matchAll(/^\s+\| '([a-z-]+)';?$/gm)].map((m) => m[1]);+if (COOK_REASONS.length < 6) {+ problems.push(`${DECIDE}: could not read the TextureCookReason union (found `+ + `${COOK_REASONS.length}) — this gate holds every consumer to it, and a short list judges nothing`);+}++if (!/decideTextureCook\(\{/.test(cook)) {+ problems.push(`${COOK} no longer calls decideTextureCook — a cook that works the choice out again`+ + ' is a second answer to the question the Inspector asks before a build runs');+}+if (/%\s*4\s*===\s*0/.test(cook)) {+ problems.push(`${COOK} tests block alignment itself — that rule belongs to the decision, and a`+ + ' second copy of it is what makes a prediction agree with the build until it does not');+}+if (!/cook\.selected !== 'raw'/.test(cook)) {+ problems.push(`${COOK} does not gate the encode on the recorded decision — an encode condition`+ + ' beside the record is how the two come to disagree about what shipped');+}+if (!/cook: frameCook/.test(cook) || !/\.\.\.\(cook \? \{ cook \} : \{\}\)/.test(cook)) {+ problems.push(`${COOK} no longer writes the decision into the manifest entry — compressedFormats`+ + ' says a payload can transcode and can never say why one is absent');+}+if (!/cookIntentDefeated/.test(cook)) {+ problems.push(`${COOK} warns about nothing: a request that survived every dialog and lost to the`+ + ' image or to the folder it sits in is exactly the silent case');+}++// -------------------------------------------------------------- upload (device)+const compressed = read(COMPRESSED);+const loader = read(LOADER);++const chooser = /export function chooseTargetFormat\(([\s\S]*?)\n\}/.exec(compressed);+if (!chooser) {+ problems.push(`${COMPRESSED}: chooseTargetFormat has moved — this gate reads its body`);+} else if (/ASTC_4x4|ETC2_RGBA8|S3TC_DXT5/.test(chooser[1])) {+ problems.push(`${COMPRESSED}: chooseTargetFormat spells the preference order again instead of`+ + ' walking TARGET_PREFERENCE — two orderings let one texture land in a different format'+ + ' depending on which backend loaded it, which is a difference nobody chose');+}+if (!/export const TARGET_PREFERENCE/.test(compressed)) {+ problems.push(`${COMPRESSED} no longer declares one preference order for both upload paths`);+}+for (const [what, re] of [+ ['a device that offers none', /reason: 'no-device-format'/],+ ['a payload that would not transcode', /reason: 'transcode-failed'/],+ ['an image that is not whole blocks', /'not-block-aligned'/],+ ['a source image, which never asked', /reason: 'uncompressed-payload'/],+]) {+ if (!re.test(compressed)) {+ problems.push(`${COMPRESSED} no longer names ${what} — every one of these ends at RGBA8 and`+ + ' costs the same memory, and only the reason says which of them to go and fix');+ }+}++// One recorder, at the one entry point that chose a path. A record kept only+// where a fallback happens cannot say that everything else was fine.+const records = [...loader.matchAll(/this\.formats_\.record\(/g)].length;+if (records !== 1) {+ problems.push(`${LOADER} records the upload decision in ${records} place(s) — it must be exactly`+ + ' one, at the entry every path returns through, or the paths that were fine go uncounted');+}+for (const [what, re] of [+ ['the native host upload', /hostUploadDecision\(/],+ ['the WebGL2 upload', /this\.lastDecision_ = r\.decision/],+ ['the engine upload', /this\.lastDecision_ = compressedUploadDecision\(/],+ ['an ordinary image', /this\.lastDecision_ = RAW_PAYLOAD_UPLOAD/],+]) {+ if (!re.test(loader)) {+ problems.push(`${LOADER} no longer records ${what} — a path that says nothing is read as the`+ + ' one before it, which is worse than an absent record');+ }+}+if (!/deviceFormats\(\)/.test(loader)) {+ problems.push(`${LOADER} no longer probes the device's compressed formats — that is the half of`+ + ' the question a realm playing source images can still answer');+}++// The native host takes the same decision with an extra way to refuse, and used+// to return only a handle: an RGBA upload was indistinguishable from success.+const native = read(NATIVE);+if (!/blockRefused/.test(native) || !/compressed \? static_cast<int>\(gfxFmt\) : -1/.test(native)) {+ problems.push(`${NATIVE} no longer carries the chosen format out — a correct picture at four`+ + ' times the memory is exactly what nothing was reporting');+}++// ------------------------------------------------------------------ the editor+if (!existsSync(path.join(ROOT, 'desktop', 'src'))) {+ if (problems.length === 0) {+ console.log('check-texture-format: no editor checkout — both decisions are recorded, the readers'+ + ' were not judged.');+ process.exit(0);+ }+} else {+ const details = read(DETAILS);+ const ship = read(SHIP);+ const settings = read(SETTINGS);++ if (!/EditorControlSurface\.textureFormatReport\(\)/.test(details)) {+ problems.push(`${DETAILS} does not read the realm's upload ledger through the surface — the`+ + ' panel and the tool must be one reader, or a behavioural check drives only one of them');+ }+ if (!/textureShipFormat\(\{/.test(details)) {+ problems.push(`${DETAILS} no longer composes through textureShipFormat — a panel that works the`+ + ' cook decision out itself agrees with the build until the day it matters');+ }+ // Reading the settings is fine (the platform-override rows show the defaults);+ // TAKING the decision is not. Only the second makes a second answer.+ if (/decideTextureCook|% 4 ===/.test(details)) {+ problems.push(`${DETAILS} takes the cook decision itself — the composer exists so the panel and`+ + ' the automation surface cannot answer differently');+ }+ for (const reason of COOK_REASONS) {+ if (!details.includes(`'${reason}'`)) {+ problems.push(`${DETAILS} has no sentence for the cook reason '${reason}' — folding it into`+ + ' another sends the reader to a dialog that was never the problem');+ }+ }+ if (!/deviceProbed/.test(ship)) {+ problems.push(`${SHIP} no longer separates "nobody was asked" from "this device supports none"`+ + ' — an unprobed realm would report an empty capability as a fact');+ }+ if (!/method: 'textureFormat'/.test(read(CATALOG))) {+ problems.push(`${CATALOG}: no tool answers for a texture's format — resource_census counts`+ + ' bytes and can never say why they are that many');+ }++ // MSAA: the same one-reader rule, retrofitted. The row worked out the status+ // from the resource directly, so the tool below it would have been a second path.+ if (!/msaaSamples\(\)/.test(read(SURFACE)) || !/method: 'msaaSamples'/.test(read(CATALOG))) {+ problems.push(`${SURFACE}/${CATALOG}: the effective sample count is on no tool — an agent tuning`+ + ' quality reads its own request back and cannot tell whether the device granted it');+ }+ if (/post\.msaaCapability\(\)/.test(settings)) {+ problems.push(`${SETTINGS} asks the PostProcess resource directly while the tool asks the`+ + ' surface — two readers, and only the tool\'s is exercised');+ }+}++if (problems.length) {+ console.error(`check-texture-format: ${problems.length} problem(s)`);+ for (const p of problems) console.error(` - ${p}`);+ process.exit(1);+}+console.log('check-texture-format: the build records what it shipped, the upload records what the'+ + ' device made of it, and one reader answers for both.');diff --git a/tools/gates.mjs b/tools/gates.mjsindex f903ed85d..88c701daa 100644--- a/tools/gates.mjs+++ b/tools/gates.mjs@@ -192,6 +192,7 @@ export const GATES = [{ id: 'shadow-plan', run: 'node tools/check-shadow-plan.mjs' },{ id: 'light-cap', run: 'node tools/check-light-cap.mjs' },{ id: 'hdr-format', run: 'node tools/check-hdr-format.mjs' },+ { id: 'texture-format', run: 'node tools/check-texture-format.mjs' },{ id: 'decision-inventory', run: 'node tools/check-decision-inventory.mjs', needs: 'editor' },{ id: 'mutator-parity', run: 'node tools/check-mutator-parity.mjs', needs: 'editor' },{ id: 'version-authority', run: 'node tools/check-version-authority.mjs', needs: 'editor' },diff --git a/tools/lib/runtimeDecisions.mjs b/tools/lib/runtimeDecisions.mjsindex 550a3df6a..ce3c18f4f 100644--- a/tools/lib/runtimeDecisions.mjs+++ b/tools/lib/runtimeDecisions.mjs@@ -51,12 +51,8 @@ export const DECISIONS = [kind: 'request-vs-capability',owner: { path: 'src/esengine/renderer/frame/PostProcessPipeline.cpp', probe: /scene_samples_ = std::clamp/ },runtime: { has: true, cite: { path: 'src/esengine/bindings/PostProcessBindings.cpp', probe: /postprocess_maxMsaaSamples/ } },- editor: { has: true, cite: { path: 'desktop/src/settings/projectSettings.ts', probe: /msaaCapability\(\)/ } },- agent: {- has: false,- owed: 'the effective count is on no tool; an agent tuning quality reads the request back and '- + 'cannot tell whether the device granted it',- },+ editor: { has: true, cite: { path: 'desktop/src/settings/projectSettings.ts', probe: /EditorControlSurface\.msaaSamples\(\)/ } },+ agent: { has: true, cite: { path: 'desktop/shared/toolCatalog.mjs', probe: /'get_msaa_samples'/ } },},{id: 'residency.cellDemand',@@ -103,18 +99,26 @@ export const DECISIONS = [editor: { has: true, cite: { path: 'desktop/src/settings/projectSettings.ts', probe: /EditorControlSurface\.hdrFormat\(\)/ } },agent: { has: true, cite: { path: 'desktop/shared/toolCatalog.mjs', probe: /'get_hdr_format'/ } },},+ // A texture's compression is TWO decisions in two lifetimes. Folding them keeps+ // the only thing worth knowing out of the answer: which layer lost it. A build+ // that shipped raw is a dialog; a device that decoded it is a device.{- id: 'texture.compressedFormat',- what: 'Whether a cooked compressed texture was uploaded compressed, or decoded to full RGBA.',+ id: 'texture.cookFormat',+ what: 'Which payload a build ships for a texture — a KTX2 in the asked-for mode, or the image.',kind: 'request-vs-capability',- owner: { path: 'sdk/src/asset/loaders/TextureLoader.ts', probe: /chooseEngineTargetFormat/ },- runtime: {- has: false,- owed: 'the RGBA path is the else-branch of a capability test and counts nothing; a project that '- + 'spent cook time on compression pays 4x the VRAM with no sign of it',- },- editor: { has: false, owed: 'the Import Settings row says what was asked for, never what was uploaded' },- agent: { has: false, owed: 'resource_census counts bytes, not why they are that many' },+ owner: { path: 'pipeline/src/assets/textureCookDecision.ts', probe: /export function decideTextureCook/ },+ runtime: { has: true, cite: { path: 'pipeline/src/assets/cookAssets.ts', probe: /\.\.\.\(cook \? \{ cook \} : \{\}\)/ } },+ editor: { has: true, cite: { path: 'desktop/src/panels/Details.tsx', probe: /textureShipFormat\(\{/ } },+ agent: { has: true, cite: { path: 'desktop/shared/toolCatalog.mjs', probe: /'get_texture_format'/ } },+ },+ {+ id: 'texture.uploadFormat',+ what: 'What a cooked payload becomes on THIS device: a GPU format, or decoded back to full RGBA.',+ kind: 'request-vs-capability',+ owner: { path: 'sdk/src/asset/compressed.ts', probe: /export function compressedUploadDecision/ },+ runtime: { has: true, cite: { path: 'sdk/src/asset/loaders/TextureLoader.ts', probe: /this\.formats_\.record\(/ } },+ editor: { has: true, cite: { path: 'desktop/src/panels/Details.tsx', probe: /EditorControlSurface\.textureFormatReport\(\)/ } },+ agent: { has: true, cite: { path: 'desktop/shared/toolCatalog.mjs', probe: /'get_texture_format'/ } },},{id: 'project.spineVersion',