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.

feat(assets): a cutout's mips keep its coverage

esengine10ec9dc7f8f7
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a70d51737..8b76cc267 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -18,6 +18,7 @@ published separately; it ships inside the editor.
- **A cutout's edge is antialiased.** With multisampling on (the default), a material with an alpha cutoff turns its alpha into multisample coverage along the cut instead of testing it, so leaves, grass and fences stop stair-stepping at their edges. A shader opts in with `#pragma coverage <param>`, which the built-in Model shader declares for `u_alphaCutoff`; a material without a cutoff, and a blended one, draw as before. A project in gamma space with no post-processing has no multisampled target, and there the cut stays hard.
- **Project Health names the textures a material reads as data while they are still decoded as colour.** In a linear project, a normal map or packed roughness marked sRGB is bent on the way in; models imported before 0.74 left every one of them that way. The report lists them in one finding and its Fix turns sRGB off on all of them. Which texture params hold numbers is the shader's to say: `#pragma param … texture … texel(data)`, which the built-in Model and Lit shaders now declare. The same report names settings in `project.esproject` that nothing reads.
+- **A cutout's mip levels keep its coverage.** A texture a material cuts at an alpha threshold is encoded with each mip level's alpha rescaled so the share of texels past the cut stays what it is at full size; plain averaging thins it until distant railings and fences are gone. Bistro's wrought-iron texture keeps 14% of its texels past the cut at 32 and 16 px, where averaging leaves 4% and none. Importing a model sets it (Mip Coverage Cutoff, an advanced texture setting) on the base colour of every cutout material, also when a blended material shares the image. It applies to UASTC KTX2 textures, which such a texture now stays even when larger than its image.
### Fixed
diff --git a/desktop b/desktop
index 5ec5719f0..1274ef3ab 160000
--- a/desktop
+++ b/desktop
@@ -1 +1 @@
-Subproject commit 5ec5719f023ee243f62ff1dff9f0cc82fc58644a
+Subproject commit 1274ef3ab1e86093787805e6001b0c0e6806e481
diff --git a/pipeline/bin/estella.mjs b/pipeline/bin/estella.mjs
index 90694a440..3a981025e 100644
--- a/pipeline/bin/estella.mjs
+++ b/pipeline/bin/estella.mjs
@@ -658,14 +658,9 @@ if (opts.command === 'import-model' || opts.command === 'import-gltf') {
// Settings the source asked for, by product name; only ever the FIRST mint.
const settings = new Map();
const externalImages = new Set();
- for (const mesh of meshes) {
- for (const image of [mesh.material?.baseColorTexture, mesh.material?.normalTexture,
- mesh.material?.emissiveTexture, mesh.material?.occlusionTexture,
- mesh.material?.metallicRoughnessTexture]) {
- if (!image) continue;
- if (image.settings) settings.set(image.external ? path.resolve(sourceDir, image.file) : image.file, image.settings);
- if (image.external) externalImages.add(path.resolve(sourceDir, image.file));
- }
+ for (const [file, { external, settings: asked }] of importer.importedImageSettings(meshes)) {
+ settings.set(external ? path.resolve(sourceDir, file) : file, asked);
+ if (external) externalImages.add(path.resolve(sourceDir, file));
}
const adopt = (file) => meta.adoptOrphan(file, settings.get(file) ?? settings.get(path.basename(file)));
diff --git a/pipeline/src/assets/cookAssets.ts b/pipeline/src/assets/cookAssets.ts
index 20568075d..8a6231414 100644
--- a/pipeline/src/assets/cookAssets.ts
+++ b/pipeline/src/assets/cookAssets.ts
@@ -44,7 +44,9 @@ import { isBuiltinAssetRef, resolveRelativePath, resolveDocumentRef } from '../.
// realm (sdk/src/asset/assetGroups.ts) so cook and editor never disagree.
import { resolveAssetGroup, resolveAtlas, type AssetGroupsConfig } from '../../../sdk/src/asset/assetGroups';
import type { BundleMode } from '../../../sdk/src/asset/AddressableManifest';
-import { readKtx2Layout, wantsMipChain, halveRgba, spliceMipChain } from './ktx2Mips';
+import {
+ readKtx2Layout, wantsMipChain, halveRgba, spliceMipChain, joinMipLevels, alphaCoverage, preserveAlphaCoverage,
+} from './ktx2Mips';
import { cookCached, encoderIdentity } from './cookCache';
const MANIFEST = 'assets.manifest.json';
@@ -249,6 +251,27 @@ async function mapInOrder<T, R>(items: T[], limit: number, fn: (item: T) => Prom
const KTX2_SCHEME_ZSTD = 2;
+/**
+ * A cutout's UASTC chain, each level halved here from the one above with its alpha
+ * rescaled to the full image's coverage at @p cutoff — plain averaging thins a
+ * sparse cutout, such as a railing, until nothing of it passes the cut.
+ */
+async function encodeCoverageChain(enc: BasisEncoderModule, img: { rgba: Uint8Array; width: number; height: number },
+ srgb: boolean, cutoff: number): Promise<Uint8Array> {
+ const coverage = alphaCoverage(img.rgba, cutoff);
+ const parts: Uint8Array[] = [];
+ let level = img;
+ for (;;) {
+ parts.push(await enc.encodeToKtx2({ type: enc.ImageType.RGBA, data: level.rgba, width: level.width, height: level.height },
+ { mode: 'uastc', srgb, mipmaps: false }));
+ if (level.width === 1 && level.height === 1) break;
+ const half = halveRgba(level.rgba, level.width, level.height, srgb);
+ preserveAlphaCoverage(half.rgba, cutoff, coverage);
+ level = half;
+ }
+ return joinMipLevels(parts);
+}
+
/** Replace a path's extension (e.g. .png → .ktx2); appends if it had none. */
function swapExt(p: string, ext: string): string {
const cur = path.extname(p);
@@ -817,13 +840,18 @@ export async function cookAssets(
const enc = textureEnc!;
const mode = cook.selected;
const source = data;
+ const coverage = mode === 'uastc' ? tex.mipCoverage : 0;
const encoded = (await cookCached(root,
- [source, JSON.stringify({ mode, srgb: tex.srgb, maxSize: tex.maxSize, scaled: rgba ? [tw, th] : null }), encoderId],
- () => (rgba
- ? enc.encodeToKtx2({ type: enc.ImageType.RGBA, data: rgba, width: tw, height: th }, { mode, srgb: tex.srgb })
- : enc.encodeToKtx2({ type: enc.ImageType.PNG, data: source }, { mode, srgb: tex.srgb })),
+ [source, JSON.stringify({ mode, srgb: tex.srgb, maxSize: tex.maxSize, scaled: rgba ? [tw, th] : null,
+ ...(coverage ? { mipCoverage: coverage } : {}) }), encoderId],
+ () => (coverage
+ ? encodeCoverageChain(enc, rgba ? { rgba, width: tw, height: th } : decodePngImage(entry.path, source),
+ tex.srgb, coverage)
+ : rgba
+ ? enc.encodeToKtx2({ type: enc.ImageType.RGBA, data: rgba, width: tw, height: th }, { mode, srgb: tex.srgb })
+ : enc.encodeToKtx2({ type: enc.ImageType.PNG, data: source }, { mode, srgb: tex.srgb })),
)).bytes;
- cook = keepSmaller(cook, encoded.byteLength, data.byteLength);
+ cook = keepSmaller(cook, encoded.byteLength, data.byteLength, coverage > 0);
if (cook.selected !== 'raw') {
data = encoded;
ext = '.ktx2';
diff --git a/pipeline/src/assets/ktx2Mips.ts b/pipeline/src/assets/ktx2Mips.ts
index eb4dc480a..9a2931c62 100644
--- a/pipeline/src/assets/ktx2Mips.ts
+++ b/pipeline/src/assets/ktx2Mips.ts
@@ -83,6 +83,29 @@ function toSrgbByte(linear: number): number {
return Math.max(0, Math.min(255, Math.round(c * 255)));
}
+/** The share of texels whose alpha reaches @p cutoff (0..1 against 0..255 bytes). */
+export function alphaCoverage(rgba: Uint8Array, cutoff: number, scale = 1): number {
+ const threshold = cutoff * 255;
+ let above = 0;
+ for (let i = 3; i < rgba.length; i += 4) if (Math.min(255, rgba[i]! * scale) >= threshold) above++;
+ return above / (rgba.length / 4);
+}
+
+/**
+ * Scale @p rgba's alpha in place so the share of texels at or above @p cutoff is
+ * @p coverage — what a mip level of a cutout needs, or averaging thins it level by
+ * level until distant foliage has no leaves. The scale is found by bisection.
+ */
+export function preserveAlphaCoverage(rgba: Uint8Array, cutoff: number, coverage: number): void {
+ let lo = 0, hi = 4;
+ for (let i = 0; i < 20; i++) {
+ const mid = (lo + hi) / 2;
+ if (alphaCoverage(rgba, cutoff, mid) < coverage) lo = mid; else hi = mid;
+ }
+ const scale = hi;
+ for (let i = 3; i < rgba.length; i += 4) rgba[i] = Math.min(255, Math.round(rgba[i]! * scale));
+}
+
/**
* The next level down: each pixel the mean of the (up to) four above it. Colour
* stored as sRGB is averaged as light, not as its encoding, or every level comes
@@ -117,24 +140,35 @@ export function halveRgba(rgba: Uint8Array, width: number, height: number, srgb:
*/
export function spliceMipChain(base: Uint8Array, below: Uint8Array): Uint8Array {
const top = readKtx2Layout(base);
- const rest = readKtx2Layout(below);
- if (!top || !rest) throw new Error('spliceMipChain: not a KTX2');
+ if (!top) throw new Error('spliceMipChain: not a KTX2');
if (top.levels.length !== 1) throw new Error(`spliceMipChain: base has ${top.levels.length} levels, not 1`);
- if (top.scheme !== rest.scheme) {
- throw new Error(`spliceMipChain: supercompression differs (${top.scheme} over ${rest.scheme})`);
- }
- if (top.colorModel !== KHR_DF_MODEL_UASTC || rest.colorModel !== KHR_DF_MODEL_UASTC) {
- throw new Error('spliceMipChain: both must be UASTC');
- }
- if (top.sgdLength || rest.sgdLength) throw new Error('spliceMipChain: global data cannot be spliced');
- if (rest.width !== Math.max(1, top.width >> 1) || rest.height !== Math.max(1, top.height >> 1)) {
- throw new Error(`spliceMipChain: ${rest.width}x${rest.height} is not the level under ${top.width}x${top.height}`);
- }
+ return joinMipLevels([base, below]);
+}
- const sources = [
- { bytes: base, level: top.levels[0] },
- ...rest.levels.map((level) => ({ bytes: below, level })),
- ];
+/**
+ * One UASTC KTX2 of every level the parts hold, in order: each part's first level
+ * must be half the size of the previous part's last. The first part's header and
+ * descriptors are the result's.
+ */
+export function joinMipLevels(parts: Uint8Array[]): Uint8Array {
+ const layouts = parts.map((p) => readKtx2Layout(p));
+ if (layouts.some((l) => !l)) throw new Error('joinMipLevels: not a KTX2');
+ const top = layouts[0]!;
+ const base = parts[0]!;
+ const sources: Array<{ bytes: Uint8Array; level: Ktx2Level }> = [];
+ let expect: [number, number] | null = null;
+ layouts.forEach((layout, i) => {
+ const l = layout!;
+ if (l.scheme !== top.scheme) throw new Error(`joinMipLevels: supercompression differs (${top.scheme} and ${l.scheme})`);
+ if (l.colorModel !== KHR_DF_MODEL_UASTC) throw new Error('joinMipLevels: every part must be UASTC');
+ if (l.sgdLength) throw new Error('joinMipLevels: global data cannot be joined');
+ if (expect && (l.width !== expect[0] || l.height !== expect[1])) {
+ throw new Error(`joinMipLevels: ${l.width}x${l.height} is not the level under ${expect[0] * 2}x${expect[1] * 2}`);
+ }
+ l.levels.forEach((level) => sources.push({ bytes: parts[i]!, level }));
+ const w = Math.max(1, l.width >> (l.levels.length - 1)), h = Math.max(1, l.height >> (l.levels.length - 1));
+ expect = [Math.max(1, w >> 1), Math.max(1, h >> 1)];
+ });
const count = sources.length;
const align = top.scheme === SCHEME_NONE ? UASTC_BLOCK_BYTES : 1;
const round = (n: number) => Math.ceil(n / align) * align;
diff --git a/pipeline/src/assets/modelImages.ts b/pipeline/src/assets/modelImages.ts
index dfcc1f176..9f3fc0085 100644
--- a/pipeline/src/assets/modelImages.ts
+++ b/pipeline/src/assets/modelImages.ts
@@ -155,6 +155,11 @@ export function prepareModelImages(result: ModelImportResult,
+ ` ${pixels.width}x${pixels.height} — a material constant would say the same`);
}
}
+ // A cutout's mips keep its coverage at the cutoff it tests, or it thins with distance.
+ const base = material.baseColorTexture;
+ if (base && material.alphaCutoff !== undefined && material.alphaCutoff > 0) {
+ material.baseColorTexture = { ...base, settings: { ...base.settings, mipCoverage: material.alphaCutoff } };
+ }
}
const converted = new Set([...seen.entries()].filter(([k]) => k.startsWith('x:') && isDdsName(k.slice(2)))
diff --git a/pipeline/src/assets/modelImport.ts b/pipeline/src/assets/modelImport.ts
index 63616fd7d..5e984ddc8 100644
--- a/pipeline/src/assets/modelImport.ts
+++ b/pipeline/src/assets/modelImport.ts
@@ -41,7 +41,9 @@ export interface ImportedImageRef {
external: boolean;
/** Import settings the source's sampler asks for, in the engine's own words.
* Absent where the source names no sampler (its defaults are the engine's). */
- settings?: { filterMode?: 'nearest' | 'linear'; wrapMode?: 'repeat' | 'clamp' | 'mirror'; sRGB?: boolean };
+ settings?: {
+ filterMode?: 'nearest' | 'linear'; wrapMode?: 'repeat' | 'clamp' | 'mirror'; sRGB?: boolean; mipCoverage?: number;
+ };
}
/**
@@ -400,6 +402,27 @@ function materialName(stem: string, material: ImportedMaterial): string {
* draw's own — a model told to occlude itself would start blending the moment
* it gained a material.
*/
+/**
+ * Every image the materials reference, with the import settings its references ask
+ * for, merged: two materials sharing a texture (a cutout's leaves and a blended
+ * wing on one atlas) each add their keys, the first to name a key keeping it.
+ * Keyed by the ref's `file` as the reader spelled it.
+ */
+export function importedImageSettings(meshes: ImportedMesh[]):
+ Map<string, { external: boolean; settings: NonNullable<ImportedImageRef['settings']> }> {
+ const out = new Map<string, { external: boolean; settings: NonNullable<ImportedImageRef['settings']> }>();
+ for (const mesh of meshes) {
+ const m = mesh.material;
+ for (const image of [m?.baseColorTexture, m?.normalTexture, m?.emissiveTexture,
+ m?.occlusionTexture, m?.metallicRoughnessTexture]) {
+ if (!image) continue;
+ const seen = out.get(image.file);
+ out.set(image.file, { external: image.external, settings: { ...image.settings, ...seen?.settings } });
+ }
+ }
+ return out;
+}
+
export function materialProducts(meshes: ImportedMesh[], stem: string,
refs: ProductRefs = {}): ImportedMaterialAsset[] {
const out: ImportedMaterialAsset[] = [];
diff --git a/pipeline/src/assets/textureCookDecision.ts b/pipeline/src/assets/textureCookDecision.ts
index 2e9150a4a..63f38bf9d 100644
--- a/pipeline/src/assets/textureCookDecision.ts
+++ b/pipeline/src/assets/textureCookDecision.ts
@@ -110,14 +110,14 @@ export function decideTextureCook(input: TextureCookInputs): TextureCookDecision
/**
* The payload once the encoder has answered: a KTX2 bigger than the image it
- * encoded is not a compression, whatever it was asked for. Basis writes about a
- * byte per pixel and PNG writes almost nothing for flat art — a 512px sky came
- * out 35x its PNG, and obliged the package to carry a megabyte of transcoder.
+ * encoded is not a compression (a 512px sky came out 35x its PNG) — unless it
+ * carries what the image cannot: a cutout's coverage-kept mips, which a chain
+ * built on the device loses, so the leaves thin out with distance.
*/
export function keepSmaller(
- d: TextureCookDecision, encodedBytes: number, rawBytes: number,
+ d: TextureCookDecision, encodedBytes: number, rawBytes: number, carriesMips = false,
): TextureCookDecision {
- if (d.selected === 'raw' || encodedBytes < rawBytes) return d;
+ if (d.selected === 'raw' || carriesMips || encodedBytes < rawBytes) return d;
return { ...d, selected: 'raw', reason: 'bigger-than-raw' };
}
diff --git a/pipeline/src/project/importSettings.ts b/pipeline/src/project/importSettings.ts
index b6df48886..ad2b03156 100644
--- a/pipeline/src/project/importSettings.ts
+++ b/pipeline/src/project/importSettings.ts
@@ -82,6 +82,13 @@ const TEXTURE: ImporterFieldSpec[] = [
tooltip: 'The image stores sRGB-encoded color (albedo/UI). Disable for authored-linear '
+ 'data like normal maps and masks — only meaningful when the project renders in linear color.',
},
+ {
+ key: 'mipCoverage', label: 'Mip Coverage Cutoff', type: 'number', default: 0, min: 0, max: 1, step: 0.01,
+ category: 'Texture', advanced: true,
+ tooltip: 'For a cutout (leaves, grass, fences): the alpha cutoff its material tests. Each mip '
+ + 'level keeps the share of texels above it that the full image has, so the cutout does '
+ + 'not thin out with distance. 0 = off. Applies to UASTC-compressed textures.',
+ },
{ key: 'sliceBorder.left', label: 'Border Left', type: 'number', default: 0, min: 0, category: '9-Slice', advanced: true },
{ key: 'sliceBorder.right', label: 'Border Right', type: 'number', default: 0, min: 0, category: '9-Slice', advanced: true },
{ key: 'sliceBorder.top', label: 'Border Top', type: 'number', default: 0, min: 0, category: '9-Slice', advanced: true },
@@ -274,9 +281,10 @@ export interface TexturePlatformOverride {
* `importer.overrides[platform]` wins per field; an unset field inherits the
* default. Defaults match a fresh `.meta`. */
export function readTextureCookSettings(importer: Record<string, unknown> | undefined, platform?: string): {
- compress: boolean; format: 'uastc' | 'etc1s'; maxSize: number; srgb: boolean;
+ compress: boolean; format: 'uastc' | 'etc1s'; maxSize: number; srgb: boolean; mipCoverage: number;
} {
const compress = importer?.compress;
+ const mipCoverage = importer?.mipCoverage;
const format = importer?.compressFormat;
const maxSize = importer?.maxSize;
const srgb = importer?.sRGB;
@@ -285,6 +293,7 @@ export function readTextureCookSettings(importer: Record<string, unknown> | unde
format: (format === 'etc1s' ? 'etc1s' : 'uastc') as 'uastc' | 'etc1s',
maxSize: typeof maxSize === 'number' && maxSize > 0 ? maxSize : 2048,
srgb: typeof srgb === 'boolean' ? srgb : true,
+ mipCoverage: typeof mipCoverage === 'number' && mipCoverage > 0 && mipCoverage < 1 ? mipCoverage : 0,
};
const overrides = importer?.overrides as Record<string, TexturePlatformOverride> | undefined;
const ov = platform ? overrides?.[platform] : undefined;
diff --git a/pipeline/tests/imported-image-settings.test.ts b/pipeline/tests/imported-image-settings.test.ts
new file mode 100644
index 000000000..853f287b3
--- /dev/null
+++ b/pipeline/tests/imported-image-settings.test.ts
@@ -0,0 +1,29 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file An image several materials share gets every setting its references ask for.
+ */
+import { describe, it, expect } from 'vitest';
+import { importedImageSettings, type ImportedMesh } from '../src/assets/modelImport';
+
+const mesh = (material: ImportedMesh['material']) => ({ material }) as ImportedMesh;
+
+describe('settings of images materials share', () => {
+ it('a cutout and a blended material on one atlas keep the cutout\'s coverage', () => {
+ const got = importedImageSettings([
+ mesh({ baseColorTexture: { file: 'atlas.png', external: true, settings: { mipCoverage: 0.5 } } } as never),
+ mesh({ baseColorTexture: { file: 'atlas.png', external: true, settings: { sRGB: true } },
+ normalTexture: { file: 'n.png', external: true, settings: { sRGB: false } } } as never),
+ ]);
+ expect(got.get('atlas.png')).toEqual({ external: true, settings: { mipCoverage: 0.5, sRGB: true } });
+ expect(got.get('n.png')).toEqual({ external: true, settings: { sRGB: false } });
+ });
+
+ it('the first reference to name a key keeps it', () => {
+ const got = importedImageSettings([
+ mesh({ baseColorTexture: { file: 'a.png', external: false, settings: { sRGB: true } } } as never),
+ mesh({ occlusionTexture: { file: 'a.png', external: false, settings: { sRGB: false } } } as never),
+ ]);
+ expect(got.get('a.png')?.settings).toEqual({ sRGB: true });
+ });
+});
diff --git a/pipeline/tests/ktx2-mips.test.ts b/pipeline/tests/ktx2-mips.test.ts
index faf892a09..80f916648 100644
--- a/pipeline/tests/ktx2-mips.test.ts
+++ b/pipeline/tests/ktx2-mips.test.ts
@@ -11,7 +11,9 @@ import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import { mkdtempSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
-import { readKtx2Layout, wantsMipChain, halveRgba, spliceMipChain } from '../src/assets/ktx2Mips';
+import {
+ readKtx2Layout, wantsMipChain, halveRgba, spliceMipChain, joinMipLevels, alphaCoverage, preserveAlphaCoverage,
+} from '../src/assets/ktx2Mips';
import { cookCached } from '../src/assets/cookCache';
import { cookAssets } from '../src/assets/cookAssets';
@@ -104,3 +106,33 @@ describe('cooking an authored single-level KTX2', () => {
expect(readdirSync(path.join(r, '.esengine', 'cache', 'cook'))).toHaveLength(1);
}, 60_000);
});
+
+describe('a cutout\'s mips keep its coverage', () => {
+ // Leaves: one texel in four solid, the rest clear.
+ const leaves = (side: number) => {
+ const rgba = new Uint8Array(side * side * 4);
+ for (let i = 0; i < side * side; i++) {
+ rgba.set([60, 140, 40, (i % 2 === 0 && Math.floor(i / side) % 2 === 0) ? 255 : 0], i * 4);
+ }
+ return rgba;
+ };
+
+ it('thins under averaging, and comes back to the full image\'s share once rescaled', () => {
+ const full = leaves(16);
+ const target = alphaCoverage(full, 0.5);
+ const half = halveRgba(full, 16, 16, false);
+ expect(target).toBe(0.25);
+ expect(alphaCoverage(half.rgba, 0.5)).toBe(0);
+ preserveAlphaCoverage(half.rgba, 0.5, target);
+ expect(alphaCoverage(half.rgba, 0.5)).toBeGreaterThanOrEqual(0.25);
+ });
+
+ it('joins single levels into one chain, and refuses a level of the wrong size', async () => {
+ const at = async (side: number) => enc.encodeToKtx2({ type: enc.ImageType.RGBA, data: leaves(side), width: side, height: side },
+ { mode: 'uastc', mipmaps: false });
+ const chainParts = [await at(8), await at(4), await at(2)];
+ const chain = readKtx2Layout(joinMipLevels(chainParts))!;
+ expect([chain.width, chain.height, chain.levels.length]).toEqual([8, 8, 3]);
+ expect(() => joinMipLevels([chainParts[0]!, chainParts[2]!])).toThrow(/not the level under/);
+ });
+});
diff --git a/pipeline/tests/model-images.test.ts b/pipeline/tests/model-images.test.ts
index 4e31a3b38..9a3323898 100644
--- a/pipeline/tests/model-images.test.ts
+++ b/pipeline/tests/model-images.test.ts
@@ -76,13 +76,14 @@ describe('preparing a model\'s images', () => {
const result = model({ baseColorTexture: { file: 'leaf.png', external: true } });
prepareModelImages(result, () => png(i => [90, 120, 40, alpha(i)]), { alphaFromBaseColor });
const m = result.meshes[0]!.material!;
- return { cutoff: m.alphaCutoff, opaque: m.opaque };
+ return { cutoff: m.alphaCutoff, opaque: m.opaque, mipCoverage: m.baseColorTexture?.settings?.mipCoverage };
};
- expect(run(i => (i % 4 === 0 ? 0 : 255))).toEqual({ cutoff: 0.5, opaque: true });
- expect(run(() => 128)).toEqual({ cutoff: undefined, opaque: false });
- expect(run(() => 255)).toEqual({ cutoff: undefined, opaque: true });
+ // A cutout's mips are told the cutoff, so distance does not thin it.
+ expect(run(i => (i % 4 === 0 ? 0 : 255))).toEqual({ cutoff: 0.5, opaque: true, mipCoverage: 0.5 });
+ expect(run(() => 128)).toEqual({ cutoff: undefined, opaque: false, mipCoverage: undefined });
+ expect(run(() => 255)).toEqual({ cutoff: undefined, opaque: true, mipCoverage: undefined });
// A glTF says its alpha mode itself; an OPAQUE one ignores the channel.
- expect(run(i => (i % 4 === 0 ? 0 : 255), false)).toEqual({ cutoff: undefined, opaque: true });
+ expect(run(i => (i % 4 === 0 ? 0 : 255), false)).toEqual({ cutoff: undefined, opaque: true, mipCoverage: undefined });
});
it('marks the maps that hold numbers as not sRGB, and leaves colour alone', () => {
diff --git a/pipeline/tests/texture-cook-decision.test.ts b/pipeline/tests/texture-cook-decision.test.ts
index afd7cb1ee..0a837a49a 100644
--- a/pipeline/tests/texture-cook-decision.test.ts
+++ b/pipeline/tests/texture-cook-decision.test.ts
@@ -127,6 +127,10 @@ describe('keepSmaller', () => {
expect(keepSmaller(raw, 1, 999_999)).toEqual(raw);
});
+ it('keeps a bigger encoding that carries a cutout\'s coverage-kept mips', () => {
+ expect(keepSmaller(compressed, 87_792, 2_515, true)).toEqual(compressed);
+ });
+
it('keeps raw on a tie — equal bytes buy nothing and cost a transcoder', () => {
expect(keepSmaller(compressed, 4000, 4000).selected).toBe('raw');
});
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index 8f8f8bfc1..72eb32673 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -1256,6 +1256,10 @@ export const NOTED = {
{ note: 'Project Health names the textures a material reads as data while they are still decoded as colour' },
'feat(render): a cutout\'s edge is antialiased':
{ note: 'A cutout\'s edge is antialiased' },
+ 'feat(assets): a cutout\'s mips keep its coverage':
+ { note: 'A cutout\'s mip levels keep its coverage' },
+ 'feat(import): images several materials share get every setting they ask for':
+ { note: 'A cutout\'s mip levels keep its coverage' },
'fix(render): a shipped game\'s textures are mipmapped':
{ note: 'A shipped game\'s textures are sampled through mip levels' },
'fix(eht): the generator writes LF on every platform':