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.

fix(render): a compressed texture is sampled with the mip chain it carries

esengineea0cee671986
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 00631e53b..a97077931 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -29,6 +29,7 @@ published separately; it ships inside the editor.
### Fixed
+- Compressed (KTX2) textures on web and mini-games are sampled with their mip chain. The cook has always written one into every texture it compresses, and only level 0 reached the GPU: a compressed texture shimmered as it shrank into the distance, and the rest of its bytes shipped for nothing. A texture whose import settings turn mipmaps off keeps level 0 alone, and one decoded to RGBA on a device with no compressed format gets its chain generated.
- The package size report on Windows attributes the SDK's bytes to the directories they come from again: every module read as "project", since the source map's paths were spelled with backslashes.
- A WeChat package registers every engine component and the built-in AI names again. The WeChat entries lost their start-up calls to the bundler, so a scene using a component with no typed definition — a rigged model's MeshSkin among them — loaded without it ("Unknown component type") and its character was never skinned.
- Reading a component whose field is a list of entities — a node's Children, a skin's joints — returns an array from every read path and frees the engine's copy. `world.tryGet` and query iteration handed back the engine's vector: an animated rig leaked one per joint per frame, and on the WeChat EmscriptenGLX engine, whose vectors cannot be iterated, the animator threw every frame.
diff --git a/cmake/Emscripten.cmake b/cmake/Emscripten.cmake
index 9b6f16402..5e5f6ded8 100644
--- a/cmake/Emscripten.cmake
+++ b/cmake/Emscripten.cmake
@@ -445,7 +445,7 @@ set(ES_EMSCRIPTEN_BASIS_MODULE_FLAGS
-sDYNAMIC_EXECUTION=0
-sFILESYSTEM=0
"-sEXPORT_NAME='ESBasisModule'"
- "-sEXPORTED_FUNCTIONS=['_es_basis_init','_es_basis_open','_es_basis_get_width','_es_basis_get_height','_es_basis_transcoded_size','_es_basis_transcode','_es_basis_close','_malloc','_free']"
+ "-sEXPORTED_FUNCTIONS=['_es_basis_init','_es_basis_open','_es_basis_get_width','_es_basis_get_height','_es_basis_transcoded_size','_es_basis_transcode','_es_basis_level_count','_es_basis_level_width','_es_basis_level_height','_es_basis_level_size','_es_basis_transcode_level','_es_basis_close','_malloc','_free']"
"-sEXPORTED_RUNTIME_METHODS=['cwrap','HEAPU8','HEAPU32']"
-O3
-flto
diff --git a/sdk/src/asset/basisTranscoder.ts b/sdk/src/asset/basisTranscoder.ts
index 5aa8557d3..74cacb31f 100644
--- a/sdk/src/asset/basisTranscoder.ts
+++ b/sdk/src/asset/basisTranscoder.ts
@@ -8,7 +8,7 @@
* Marshalling mirrors the physics module: copy the KTX2 bytes into the module's
* heap, transcode into a module-allocated buffer, copy the result back out.
*/
-import type { BasisTranscoder, TranscodeResult, RgbaResult } from './compressed';
+import type { BasisTranscoder, TranscodeResult, RgbaResult, TranscodedLevel } from './compressed';
import { CompressedTextureFormat } from './compressed';
/** Numeric format contract shared with BasisModuleEntry.cpp::mapFormat. */
@@ -27,6 +27,12 @@ export interface BasisWasmModule {
_es_basis_get_height(): number;
_es_basis_transcoded_size(target: number): number;
_es_basis_transcode(target: number, outPtr: number, outLen: number): number;
+ /** Per-level API; a module built before it transcodes level 0 only. */
+ _es_basis_level_count?(): number;
+ _es_basis_level_width?(level: number): number;
+ _es_basis_level_height?(level: number): number;
+ _es_basis_level_size?(target: number, level: number): number;
+ _es_basis_transcode_level?(target: number, level: number, outPtr: number, outLen: number): number;
_es_basis_close(): void;
_malloc(size: number): number;
_free(ptr: number): void;
@@ -55,7 +61,7 @@ export class BasisTranscoderImpl implements BasisTranscoder {
return this.run_(ktx2, RGBA_CODE);
}
- private run_(ktx2: Uint8Array, code: number): { width: number; height: number; data: Uint8Array } | null {
+ private run_(ktx2: Uint8Array, code: number): TranscodeResult | null {
const mod = this.mod;
const inPtr = mod._malloc(ktx2.length);
if (!inPtr) return null;
@@ -63,20 +69,23 @@ export class BasisTranscoderImpl implements BasisTranscoder {
mod.HEAPU8.set(ktx2, inPtr);
if (!mod._es_basis_open(inPtr, ktx2.length)) return null;
try {
- const width = mod._es_basis_get_width();
- const height = mod._es_basis_get_height();
- const size = mod._es_basis_transcoded_size(code);
- if (size <= 0) return null;
- const outPtr = mod._malloc(size);
- if (!outPtr) return null;
- try {
- if (!mod._es_basis_transcode(code, outPtr, size)) return null;
- // .slice() copies out of the wasm heap into a standalone buffer.
- const data = mod.HEAPU8.slice(outPtr, outPtr + size);
- return { width, height, data };
- } finally {
- mod._free(outPtr);
+ const perLevel = typeof mod._es_basis_transcode_level === 'function';
+ const count = perLevel ? Math.max(1, mod._es_basis_level_count!()) : 1;
+ const levels: TranscodedLevel[] = [];
+ for (let level = 0; level < count; level++) {
+ const width = perLevel ? mod._es_basis_level_width!(level) : mod._es_basis_get_width();
+ const height = perLevel ? mod._es_basis_level_height!(level) : mod._es_basis_get_height();
+ const size = perLevel ? mod._es_basis_level_size!(code, level) : mod._es_basis_transcoded_size(code);
+ const data = size > 0 ? this.transcodeLevel_(code, level, size, perLevel) : null;
+ // A chain that stops early is still a chain: keep the levels
+ // that came out, and the base level is the one that must.
+ if (!data) {
+ if (level === 0) return null;
+ break;
+ }
+ levels.push({ width, height, data });
}
+ return { width: levels[0].width, height: levels[0].height, data: levels[0].data, levels };
} finally {
mod._es_basis_close();
}
@@ -84,6 +93,21 @@ export class BasisTranscoderImpl implements BasisTranscoder {
mod._free(inPtr);
}
}
+
+ private transcodeLevel_(code: number, level: number, size: number, perLevel: boolean): Uint8Array | null {
+ const mod = this.mod;
+ const outPtr = mod._malloc(size);
+ if (!outPtr) return null;
+ try {
+ const ok = perLevel
+ ? mod._es_basis_transcode_level!(code, level, outPtr, size)
+ : mod._es_basis_transcode(code, outPtr, size);
+ // .slice() copies out of the wasm heap into a standalone buffer.
+ return ok ? mod.HEAPU8.slice(outPtr, outPtr + size) : null;
+ } finally {
+ mod._free(outPtr);
+ }
+ }
}
/** Convenience: load the module and wrap it as a {@link BasisTranscoder}. */
diff --git a/sdk/src/asset/compressed.ts b/sdk/src/asset/compressed.ts
index 5a8543ca0..8e491f5b5 100644
--- a/sdk/src/asset/compressed.ts
+++ b/sdk/src/asset/compressed.ts
@@ -55,18 +55,28 @@ export function isKtx2Path(path: string): boolean {
// Transcoder seam
// =============================================================================
+export interface TranscodedLevel {
+ readonly width: number;
+ readonly height: number;
+ readonly data: Uint8Array;
+}
+
export interface TranscodeResult {
readonly width: number;
readonly height: number;
- /** GPU-ready compressed block data for the requested format. */
+ /** GPU-ready compressed block data for the requested format, level 0. */
readonly data: Uint8Array;
+ /** Every mip level the file carries, level 0 first; absent means level 0 only. */
+ readonly levels?: readonly TranscodedLevel[];
}
export interface RgbaResult {
readonly width: number;
readonly height: number;
- /** width*height*4 RGBA8 bytes. */
+ /** width*height*4 RGBA8 bytes, level 0. */
readonly data: Uint8Array;
+ /** Every mip level the file carries, level 0 first; absent means level 0 only. */
+ readonly levels?: readonly TranscodedLevel[];
}
/**
@@ -211,6 +221,8 @@ export interface CompressedUploadOptions {
readonly wrap?: 'repeat' | 'clamp' | 'mirror';
/** Linear pipeline: store sRGB-encoded so the sampler linearizes in hardware. */
readonly srgb?: boolean;
+ /** The import setting: false keeps level 0 alone, however many the file carries. */
+ readonly mipmaps?: boolean;
}
export interface UploadedTexture {
@@ -219,11 +231,20 @@ export interface UploadedTexture {
readonly height: number;
}
-function applyParams(gl: WebGL2RenderingContext, opts?: CompressedUploadOptions): void {
- // Single-level textures: never select a mipmap min-filter (would be
- // incomplete) and never generate a chain — which is exactly what the shared
- // sampler state does when told there are no mipmaps.
- applyBoundTextureSampling(gl, { filter: opts?.filter, wrap: opts?.wrap, mipmaps: false });
+/**
+ * A texture's sampling from the levels it was given: a chain the file carried is
+ * sampled as one, and a single compressed level samples without mips — a mip
+ * filter over one level would make it incomplete, and no compressed format can
+ * generate the rest. Only uncompressed pixels may have a chain generated.
+ */
+function applyParams(gl: WebGL2RenderingContext, levels: number, generate: boolean, opts?: CompressedUploadOptions): void {
+ applyBoundTextureSampling(gl, { filter: opts?.filter, wrap: opts?.wrap, mipmaps: generate, levels });
+}
+
+function levelsOf(r: TranscodeResult | RgbaResult, opts?: CompressedUploadOptions): readonly TranscodedLevel[] {
+ const base = { width: r.width, height: r.height, data: r.data };
+ if (opts?.mipmaps === false) return [base];
+ return r.levels && r.levels.length > 0 ? r.levels : [base];
}
/** Upload pre-transcoded compressed blocks via `gl.compressedTexImage2D`. */
@@ -237,10 +258,14 @@ export function uploadCompressedTexture(
// gpuBytes is the ACTUAL VRAM size for the eviction budget — a compressed
// format is 4–8× smaller than the pool's RGBA8 estimate, and billing it at
// the estimate would squat on most of the budget.
+ const levels = levelsOf(t, opts);
const handle = handOverNewTexture(module, gl, (g) => {
- g.compressedTexImage2D(g.TEXTURE_2D, 0, internalFormat, t.width, t.height, 0, t.data);
- applyParams(g, opts);
- }, { width: t.width, height: t.height, content: TextureContent.Asset, gpuBytes: t.data.byteLength });
+ levels.forEach((l, i) => g.compressedTexImage2D(g.TEXTURE_2D, i, internalFormat, l.width, l.height, 0, l.data));
+ applyParams(g, levels.length, false, opts);
+ }, {
+ width: t.width, height: t.height, content: TextureContent.Asset,
+ gpuBytes: levels.reduce((n, l) => n + l.data.byteLength, 0),
+ });
return { handle, width: t.width, height: t.height };
}
@@ -252,8 +277,9 @@ export function uploadRgbaTexture(
// Linear pipeline: the decoded pixels are sRGB-encoded color, same as
// the PNG path — store them in an sRGB format so sampling linearizes.
const internalFormat = opts?.srgb ? g.SRGB8_ALPHA8 : g.RGBA;
- g.texImage2D(g.TEXTURE_2D, 0, internalFormat, r.width, r.height, 0, g.RGBA, g.UNSIGNED_BYTE, r.data);
- applyParams(g, opts);
+ const levels = levelsOf(r, opts);
+ levels.forEach((l, i) => g.texImage2D(g.TEXTURE_2D, i, internalFormat, l.width, l.height, 0, g.RGBA, g.UNSIGNED_BYTE, l.data));
+ applyParams(g, levels.length, levels.length === 1 && opts?.mipmaps !== false, opts);
}, { width: r.width, height: r.height, content: TextureContent.Asset });
return { handle, width: r.width, height: r.height };
}
diff --git a/sdk/src/asset/glTextureUpload.ts b/sdk/src/asset/glTextureUpload.ts
index 88f541beb..393706eba 100644
--- a/sdk/src/asset/glTextureUpload.ts
+++ b/sdk/src/asset/glTextureUpload.ts
@@ -32,6 +32,9 @@ export interface TextureSampling {
readonly filter?: 'linear' | 'nearest';
readonly wrap?: TextureWrap;
readonly mipmaps?: boolean;
+ /** Levels already uploaded: more than one samples them as a mip chain and
+ * generates none — a compressed texture cannot generate one. */
+ readonly levels?: number;
}
/**
@@ -69,7 +72,8 @@ export function uploadBoundTextureImage(
*/
export function applyBoundTextureSampling(gl: WebGL2RenderingContext, sampling?: TextureSampling): void {
const filter = sampling?.filter ?? 'linear';
- const useMipmaps = sampling?.mipmaps ?? true;
+ const uploaded = sampling?.levels ?? 1;
+ const useMipmaps = uploaded > 1 || (sampling?.mipmaps ?? true);
const glMinFilter = filter === 'nearest'
? (useMipmaps ? gl.NEAREST_MIPMAP_NEAREST : gl.NEAREST)
: (useMipmaps ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
@@ -78,7 +82,9 @@ export function applyBoundTextureSampling(gl: WebGL2RenderingContext, sampling?:
const glWrap = glWrapMode(gl, sampling?.wrap);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, glWrap);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, glWrap);
- if (useMipmaps) gl.generateMipmap(gl.TEXTURE_2D);
+ // A chain that stops before 1x1 is complete only when told where it ends.
+ if (uploaded > 1) gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAX_LEVEL, uploaded - 1);
+ else if (useMipmaps) gl.generateMipmap(gl.TEXTURE_2D);
}
// =============================================================================
diff --git a/sdk/src/asset/loaders/TextureLoader.ts b/sdk/src/asset/loaders/TextureLoader.ts
index 25fa4dd1c..922c4a4b5 100644
--- a/sdk/src/asset/loaders/TextureLoader.ts
+++ b/sdk/src/asset/loaders/TextureLoader.ts
@@ -288,9 +288,17 @@ export class TextureLoader implements AssetLoader<TextureResult> {
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,
+ // Level 0 first, packed, as the device unpacks them; a WebGPU copy
+ // refuses a level that is not whole blocks, so the chain stops there.
+ const all = t.levels ?? [t];
+ let count = 1;
+ while (count < all.length && all[count].width % 4 === 0 && all[count].height % 4 === 0) count++;
+ const levels = all.slice(0, count);
+ const size = levels.reduce((n, l) => n + l.data.length, 0);
+ const handle = withMalloc(module, size, (ptr) => {
+ let at = ptr;
+ for (const l of levels) { module.HEAPU8.set(l.data, at); at += l.data.length; }
+ return rm.createCompressedTexture!(t.width, t.height, code, ptr, size, levels.length,
TextureContent.Asset);
});
if (handle) return { handle, width: t.width, height: t.height };
diff --git a/sdk/tests/basis-mip-chain-wasm.test.ts b/sdk/tests/basis-mip-chain-wasm.test.ts
new file mode 100644
index 000000000..cb19f6d08
--- /dev/null
+++ b/sdk/tests/basis-mip-chain-wasm.test.ts
@@ -0,0 +1,51 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file The transcoder returns every level a KTX2 carries.
+ *
+ * The cook's encoder writes a mip chain into every texture. This encodes with
+ * that encoder and transcodes with the built side module, so neither half is a
+ * stand-in. Requires build/wasm/web/basis.wasm.
+ */
+import { describe, it, expect, beforeAll } from 'vitest';
+import { existsSync, readFileSync, writeFileSync, mkdtempSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { createRequire } from 'node:module';
+import path from 'node:path';
+import { transcoderFromModule, type BasisWasmModule } from '../src/asset/basisTranscoder';
+import { CompressedTextureFormat, type BasisTranscoder } from '../src/asset/compressed';
+
+const ROOT = path.resolve(__dirname, '../..');
+const MODULE = path.join(ROOT, 'build/wasm/web/basis.js');
+const SIDE = 64;
+
+describe.skipIf(!existsSync(MODULE))('a KTX2 mip chain through the built transcoder', () => {
+ let transcoder: BasisTranscoder;
+ let ktx2: Uint8Array;
+
+ beforeAll(async () => {
+ // The glue is CommonJS inside a package that reads `.js` as ESM.
+ const cjs = path.join(mkdtempSync(path.join(tmpdir(), 'basis-')), 'basis.cjs');
+ writeFileSync(cjs, readFileSync(MODULE));
+ const factory = createRequire(__filename)(cjs) as (o: object) => Promise<BasisWasmModule>;
+ transcoder = transcoderFromModule(await factory({ locateFile: (f: string) => path.join(path.dirname(MODULE), f) }));
+ const encoder = await import(path.join(ROOT, 'build-tools/basis/encoder.mjs'));
+ const rgba = new Uint8Array(SIDE * SIDE * 4).map((_, i) => (i * 37) & 0xff);
+ ktx2 = await encoder.encodeToKtx2(
+ { type: encoder.ImageType.RGBA, data: rgba, width: SIDE, height: SIDE }, { mode: 'uastc', mipmaps: true });
+ });
+
+ const sides = [64, 32, 16, 8, 4, 2, 1];
+
+ it('comes back with every level, each half the one before', () => {
+ const t = transcoder.transcode(ktx2, CompressedTextureFormat.ASTC_4x4)!;
+ expect(t.levels?.map((l) => l.width)).toEqual(sides);
+ // ASTC 4x4: one 16-byte block per 4x4, and a level smaller than a block still takes one.
+ expect(t.levels?.map((l) => l.data.byteLength)).toEqual(sides.map((s) => Math.ceil(s / 4) ** 2 * 16));
+ });
+
+ it('decodes every level to RGBA as well', () => {
+ const r = transcoder.transcodeToRgba(ktx2)!;
+ expect(r.levels?.map((l) => l.data.byteLength)).toEqual(sides.map((s) => s * s * 4));
+ });
+});
diff --git a/sdk/tests/compressed-texture.test.ts b/sdk/tests/compressed-texture.test.ts
index 124d587c3..ec29e7fd5 100644
--- a/sdk/tests/compressed-texture.test.ts
+++ b/sdk/tests/compressed-texture.test.ts
@@ -36,6 +36,8 @@ function makeGl(support: { astc?: boolean; etc?: boolean; s3tc?: boolean; s3tcSr
TEXTURE_2D: 0x0de1, RGBA: 0x1908, UNSIGNED_BYTE: 0x1401, SRGB8_ALPHA8,
NEAREST: 0x2600, LINEAR: 0x2601, CLAMP_TO_EDGE: 0x812f, MIRRORED_REPEAT: 0x8370, REPEAT: 0x2901,
TEXTURE_MIN_FILTER: 0x2801, TEXTURE_MAG_FILTER: 0x2800, TEXTURE_WRAP_S: 0x2802, TEXTURE_WRAP_T: 0x2803,
+ LINEAR_MIPMAP_LINEAR: 0x2703, NEAREST_MIPMAP_NEAREST: 0x2700, TEXTURE_MAX_LEVEL: 0x813d,
+ generateMipmap: vi.fn(),
getExtension: vi.fn((n: string) => exts[n] ?? null),
createTexture: vi.fn(() => ({}) as WebGLTexture),
bindTexture: vi.fn(),
@@ -187,6 +189,50 @@ describe('loadCompressedTexture', () => {
});
});
+describe('mip levels', () => {
+ const minFilter = (gl: ReturnType<typeof makeGl>) =>
+ gl.texParameteri.mock.calls.find((c) => c[1] === gl.TEXTURE_MIN_FILTER)?.[2];
+ const maxLevel = (gl: ReturnType<typeof makeGl>) =>
+ gl.texParameteri.mock.calls.find((c) => c[1] === gl.TEXTURE_MAX_LEVEL)?.[2];
+ const chain = [8, 4, 2].map((w) => ({ width: w, height: w, data: new Uint8Array(w) }));
+
+ // Every KTX2 the cook writes carries a chain; a level left behind is a texture
+ // that shimmers in the distance and bytes shipped for nothing.
+ it('uploads every level a compressed file carries and samples them as a chain', () => {
+ const gl = makeGl({ astc: true });
+ loadCompressedTexture(gl as never, makeModule() as never,
+ makeTranscoder({ transcode: vi.fn(() => ({ ...chain[0], levels: chain })) }), KTX2_HEADER);
+ expect(gl.compressedTexImage2D.mock.calls.map((c) => [c[1], c[3]])).toEqual([[0, 8], [1, 4], [2, 2]]);
+ expect(minFilter(gl)).toBe(gl.LINEAR_MIPMAP_LINEAR);
+ expect(maxLevel(gl)).toBe(2);
+ expect(gl.generateMipmap).not.toHaveBeenCalled();
+ });
+
+ it('keeps level 0 alone when the import setting turns mipmaps off', () => {
+ const gl = makeGl({ astc: true });
+ loadCompressedTexture(gl as never, makeModule() as never,
+ makeTranscoder({ transcode: vi.fn(() => ({ ...chain[0], levels: chain })) }), KTX2_HEADER, { mipmaps: false });
+ expect(gl.compressedTexImage2D).toHaveBeenCalledTimes(1);
+ expect(minFilter(gl)).toBe(gl.LINEAR);
+ expect(gl.generateMipmap).not.toHaveBeenCalled();
+ });
+
+ it('samples a single compressed level without mips, since none can be generated', () => {
+ const gl = makeGl({ astc: true });
+ loadCompressedTexture(gl as never, makeModule() as never, makeTranscoder(), KTX2_HEADER);
+ expect(minFilter(gl)).toBe(gl.LINEAR);
+ expect(maxLevel(gl)).toBeUndefined();
+ expect(gl.generateMipmap).not.toHaveBeenCalled();
+ });
+
+ it('generates a chain for a single level decoded to RGBA', () => {
+ const gl = makeGl();
+ loadCompressedTexture(gl as never, makeModule() as never, makeTranscoder(), KTX2_HEADER);
+ expect(minFilter(gl)).toBe(gl.LINEAR_MIPMAP_LINEAR);
+ expect(gl.generateMipmap).toHaveBeenCalledTimes(1);
+ });
+});
+
describe('uploadCompressedTexture', () => {
it('throws if the chosen format has no enabling extension', () => {
const gl = makeGl(); // ASTC not enabled
diff --git a/src/esengine/bindings/modules/basis/BasisModuleEntry.cpp b/src/esengine/bindings/modules/basis/BasisModuleEntry.cpp
index de6cfcee7..9275b72bc 100644
--- a/src/esengine/bindings/modules/basis/BasisModuleEntry.cpp
+++ b/src/esengine/bindings/modules/basis/BasisModuleEntry.cpp
@@ -34,7 +34,7 @@ basist::transcoder_texture_format mapFormat(int target) {
bool isUncompressed(int target) { return target == 3; }
-// Blocks (compressed) or pixels (uncompressed) in level 0.
+// Blocks (compressed) or pixels (uncompressed) in one level.
uint32_t levelUnits(const basist::ktx2_image_level_info& info, int target) {
return isUncompressed(target) ? (info.m_orig_width * info.m_orig_height)
: (info.m_num_blocks_x * info.m_num_blocks_y);
@@ -66,23 +66,42 @@ int es_basis_open(const uint8_t* pData, uint32_t dataSize) {
uint32_t es_basis_get_width() { return g_open ? g_transcoder.get_width() : 0u; }
uint32_t es_basis_get_height() { return g_open ? g_transcoder.get_height() : 0u; }
-/** Bytes required to transcode level 0 to `target`, or 0 on error. */
-uint32_t es_basis_transcoded_size(int target) {
+/** Mip levels the open container carries (1 for a texture without a chain). */
+uint32_t es_basis_level_count() { return g_open ? g_transcoder.get_levels() : 0u; }
+
+uint32_t es_basis_level_width(uint32_t level) {
+ basist::ktx2_image_level_info info;
+ return g_open && g_transcoder.get_image_level_info(info, level, 0, 0) ? info.m_orig_width : 0u;
+}
+
+uint32_t es_basis_level_height(uint32_t level) {
+ basist::ktx2_image_level_info info;
+ return g_open && g_transcoder.get_image_level_info(info, level, 0, 0) ? info.m_orig_height : 0u;
+}
+
+/** Bytes required to transcode `level` to `target`, or 0 on error. */
+uint32_t es_basis_level_size(int target, uint32_t level) {
if (!g_open) return 0u;
basist::ktx2_image_level_info info;
- if (!g_transcoder.get_image_level_info(info, 0, 0, 0)) return 0u;
+ if (!g_transcoder.get_image_level_info(info, level, 0, 0)) return 0u;
return levelUnits(info, target) * basist::basis_get_bytes_per_block_or_pixel(mapFormat(target));
}
-/** Transcode level 0 into `pOut` (>= es_basis_transcoded_size). Returns 1 on success. */
-int es_basis_transcode(int target, uint8_t* pOut, uint32_t outSize) {
+/** Transcode `level` into `pOut` (>= es_basis_level_size). Returns 1 on success. */
+int es_basis_transcode_level(int target, uint32_t level, uint8_t* pOut, uint32_t outSize) {
if (!g_open || !pOut) return 0;
basist::ktx2_image_level_info info;
- if (!g_transcoder.get_image_level_info(info, 0, 0, 0)) return 0;
+ if (!g_transcoder.get_image_level_info(info, level, 0, 0)) return 0;
const basist::transcoder_texture_format fmt = mapFormat(target);
const uint32_t units = levelUnits(info, target);
if (outSize < units * basist::basis_get_bytes_per_block_or_pixel(fmt)) return 0;
- return g_transcoder.transcode_image_level(0, 0, 0, pOut, units, fmt) ? 1 : 0;
+ return g_transcoder.transcode_image_level(level, 0, 0, pOut, units, fmt) ? 1 : 0;
+}
+
+uint32_t es_basis_transcoded_size(int target) { return es_basis_level_size(target, 0); }
+
+int es_basis_transcode(int target, uint8_t* pOut, uint32_t outSize) {
+ return es_basis_transcode_level(target, 0, pOut, outSize);
}
/** Release the open container. Safe to call when none is open. */
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index 99477c6b0..ae78965a4 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -1212,4 +1212,6 @@ export const NOTED = {
{ note: 'The package size report on Windows attributes the SDK\'s bytes to the directories they come from again: every module read as "project", since the source map\'s paths were spelled with backslashes.' },
'test(launch): the launchers print every warning and error, and count a logged error':
{ internal: 'Repository launchers; no creator runs them.' },
+ 'fix(render): a compressed texture is sampled with the mip chain it carries':
+ { note: 'Compressed (KTX2) textures on web and mini-games are sampled with their mip chain. The cook has always written one into every texture it compresses, and only level 0 reached the GPU: a compressed texture shimmered as it shrank into the distance, and the rest of its bytes shipped for nothing. A texture whose import settings turn mipmaps off keeps level 0 alone, and one decoded to RGBA on a device with no compressed format gets its chain generated.' },
};