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
fix(render): a cut-out is glTF's MASK at every distance, its mips keeping their coverage both ways
yhhf09dffdd5dc4
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ed2029372..8a1813a8a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -55,12 +55,12 @@ published separately; it ships inside the editor.### Fixed- **Normal maps along a triangle's edge on WebGPU.** On WebGPU with multisampling, every pixel a triangle only partly covers lost its normal map: on Metal the screen-space derivatives that build the frame were moved behind the branch that picks it, where those pixels have no neighbours to difference against. A normal-mapped quad drew a dotted line down its diagonal and round its rim, and the Skin shader's detail layer left those pixels without their highlight.-- **Cut-out chains of coverage.** A cut-out's mip chain holds, as alpha, the share of texels its cut keeps, and its colour is the colour of what the cut keeps. The minified alpha is what a cut-out is drawn with, and a plain average of a soft mask (a painted band of eyelashes fading out) averaged to more than the cut keeps: the probe's lash card drew a pink veil over the iris where Blender draws a few lashes. The chain no longer rescales alpha to keep a cutoff's coverage, and an imported cut-out's clear texels take the colour of the solid ones nearest them, so even a mip the GPU makes does not average in what the painter left under alpha 0.-- **Cut-out shadows.** A cut-out's shadow keeps the share of light it lets through, and is the same shape on both backends. The shadow pass read a card's alpha at level 0 on WebGPU (mips on WebGL2), and cut at the cutoff on both; where the card is smaller than a texel from the light it now cuts against a per-texel threshold through the mip chain, so a fringe of hair throws a shadow as deep as it is dense.+- **Cut-out colour in its clear texels.** An imported cut-out's clear texels take the colour of the solid ones nearest them, so a mip, whether the cook makes it or the GPU does, no longer averages in what the painter left under alpha 0.+- **Cut-out shadows.** A cut-out's shadow is the same shape on both backends: the shadow pass read a card's alpha at level 0 on WebGPU and through its mips on WebGL2. Both now read the mips and cut at the cutoff, as the cut-out itself is cut.- **Imported eyes.** An imported eye shades as the Principled shader it was authored against: the Eye shader's tinted white, its warm wrap of light past the terminator (which reddened a painted iris) and its lid darkening are written as off, and both its glossy layers take the source's roughness instead of a near-mirror cornea.- **Energy in lit materials, and soft sun shadows as wide as the sun.** Lit materials keep the light a rough surface reflects and pass on what it does not. The environment's specular came from Karis' analytic fit, 21% low for a metal at roughness 0.5 and up to 80% off at a grazing view; it is now a fit to the integral itself (tools/gen-dfg-fit.py, worst 3%). The light a rough metal loses to bounces between its microfacets is returned (Fdez-Aguera's multiple-scattering term, and the same ratio on a lamp's highlight), where a metal at roughness 0.9 under a white sky came out at half of Blender's brightness. The diffuse under a dielectric's specular is reduced by what the specular reflects, as in the Principled shader. And a lamp's highlight takes Smith's height-correlated masking at alpha = roughness squared in place of the Schlick k = (r + 1)^2 / 8 remap, which left a rough metal's rim a quarter dark. In the render lab six spheres under a white sky now match Blender within 0.5% at every roughness, and flat cards of five albedos within 0.002, on both backends. A sun with a size casts a penumbra as wide as Blender's. The disc a penumbra was averaged over stopped at 8 texels of the map, which held a sun's soft edge to sixteen texels: with a fine cascade that is less than the sun throws, and the render lab measured an edge 60% as wide as Blender's. The disc now reaches 24 texels, its spiral of taps is turned point by point so the wider disc grains rather than bands, and each blocker tap forgives only as far as it stands from the point, so a box standing on a floor stays shadowed to its foot.- **Mip chains on WebGPU.** On the WebGPU backend, a mesh without a material, a sprite and a particle are sampled through their texture's mip chain, as they always were on WebGL2: their WGSL read level 0 alone, so anything drawn smaller than its texture shimmered into stripes and moire there and not on the other backend. A compressed (KTX2) texture also keeps every level of its chain on WebGPU: the upload stopped at the first level whose side is not a multiple of four, which left a 1240x1268 hair atlas with level 0 alone. In the render lab a card of fine strands seen small now reads the same on both backends.-- **Cut-outs at a distance.** A cut-out seen from far enough away that its texture is smaller than a texel a pixel lets through as much as its texture covers. Its alpha was sharpened to a texel around the cutoff at every distance, and once the mips had averaged fine strands and the gaps between them to one value above the cutoff, the whole card turned solid: a hair card at arm's length drew as a plate. Where the texture is minified the mip-averaged alpha is now the coverage under multisampling, and the cutoff moves to a per-pixel threshold without it. In the render lab a card of fine cut-out strands lets through within 3% of what Blender does, where it let through nothing; the shader helper is cutoutCoverage, and u_time.w carries the scene's multisampling.+- **Cut-outs are glTF's MASK at every distance.** A material with an alpha cutoff keeps a texel where its alpha reaches the cutoff and drops it where it does not, near or far, as glTF defines MASK; under multisampling alpha-to-coverage feathers that edge. Seen small, a cut-out keeps the area it covers because its mips do: the cook rescales each level's alpha so the share of texels past the cutoff is the full image's, now in both directions, so fine strands no longer close into a solid card when averaging lifts them over the cutoff, and sparse ones (a railing) still do not thin away. A soft painted band below the cutoff (eyelashes fading out) stays out at every distance. Khronos's AlphaBlendModeTest cuts each box at its own mark again. The shader helper is `cutoutCoverage(alpha, cutoff, edge)`.- **Faces speckled with dirt in shadow.** The high quality profile's shadow cascades are now 1024 texels on a 4096 atlas (they were 512 on 2048). At 512 a cascade's texel is several millimetres across a close character, so a brow, a hairline or a lash card sitting a fraction of a millimetre above the skin fell inside one texel of it and the shadow speckled the face with dirt; at 1024 the face is clean. Medium and low are unchanged.- **Ambient occlusion at metre scale.** The ambient-occlusion effects, ssao and gtao, accept a radius down to a centimetre (they stopped at one world unit), so a 3D scene measured in metres can use them on hair and faces. A radius of 0.05 separates the cards of a hair mesh without the black speckle a larger one leaves on their edges.- **Global illumination at metre scale.** The global-illumination effects accept lengths down to a centimetre: the voxel size of voxelGI, and the radius and thickness of ssgi, used to stop at four, ten and one world units, so a 3D scene measured in metres could not set them small enough to do anything. Against Blender's render of the same frame, a character lit by one sun gets its soft bounce light in the shadows once they are set to metre-scale values.diff --git a/docs/astro/src/content/docs/graphics/materials.mdx b/docs/astro/src/content/docs/graphics/materials.mdxindex 84adc2ae5..68ff1ab4e 100644--- a/docs/astro/src/content/docs/graphics/materials.mdx+++ b/docs/astro/src/content/docs/graphics/materials.mdx@@ -166,7 +166,7 @@ One file holds every stage plus its metadata, separated by pragmas:| `#pragma param …` | A reflected material parameter (table below). || `#pragma switch NAME [default(on)]` | Material-facing static permutation toggle (a `#define`). || `#pragma feature NAME` | Engine-chosen compile-time variant keyword. |-| `#pragma coverage PARAM` | While the float param `PARAM` is above zero, the shader's output alpha is coverage — a cutout's alpha sharpened to about a texel around the cutoff. An opaque draw into a multisampled target then turns it into multisample coverage, so the cutout's edge is antialiased instead of stair-stepped. Where the texture is seen smaller than a texel a pixel, its edges are finer than the pixel and its own mip-averaged alpha is used as the coverage (or, without multisampling, against a per-pixel threshold), so a card of fine strands far away lets through as much as it covers instead of closing into a solid sheet. A shader does this with `cutoutCoverage(alpha, cutoff, edge, texelsPerPixel, pixel, u_time.w)`; `u_time.w` is the scene's multisampling. The built-in Model shader declares `u_alphaCutoff`. |+| `#pragma coverage PARAM` | While the float param `PARAM` is above zero, the shader's output alpha is coverage — a cutout's alpha sharpened to about a pixel around the cutoff (`cutoutCoverage(alpha, cutoff, fwidth(alpha))`). An opaque draw into a multisampled target then turns it into multisample coverage, so the cutout's edge is antialiased instead of stair-stepped; without multisampling it is the hard cut. The cut is at the cutoff at every distance, as glTF's MASK is: a cutout seen small keeps its area because the cook rescales its mips' alpha to the coverage the full image has at the cutoff. The built-in Model shader declares `u_alphaCutoff`. || `#pragma hairshadow PARAM` | While the float param `PARAM` is above zero, meshes drawn with the material are hair for shadows: the sun's cascades gain one fitted to them alone, and a shader that sets `g_hairShadow` before it lights reads the shadow as a density along the light instead of a hard compare. The value is the density. The built-in Hair shader declares `u_hairShadow`. || `#pragma gbuffer` | A `PostProcess` shader reads the scene's surface record (see [the G-buffer](/docs/graphics/post-processing/#the-g-buffer)) at `u_gbuffer`. Declaring it is what makes the frame draw one; a chain whose shaders do not never pays for it. || `#pragma vertex` / `#pragma fragment` … `#pragma end` | Stage bodies. **The vertex block is optional for 2D domains** — the engine injects the canonical stage. |diff --git a/docs/astro/src/content/docs/zh-cn/graphics/materials.mdx b/docs/astro/src/content/docs/zh-cn/graphics/materials.mdxindex 1875181f6..1ed518f5d 100644--- a/docs/astro/src/content/docs/zh-cn/graphics/materials.mdx+++ b/docs/astro/src/content/docs/zh-cn/graphics/materials.mdx@@ -135,7 +135,7 @@ std140 uniform 块,于是 CPU 能按名字设置、并安全地送到 GPU。一| `#pragma domain <D>` | `Unlit`(默认)、`Lit`、`PostProcess`、`UI`。`Lit` 注入光照 uniform + helper。旧拼写 `Unlit2D` / `Lit2D` 仍按这两个域加载。 || `#pragma param …` | 反射的材质参数(见下表)。 || `#pragma switch NAME [default(on)]` | 材质可控的静态排列开关(一个 `#define`)。 |-| `#pragma coverage PARAM` | 浮点参数 `PARAM` 大于零时,着色器输出的 alpha 就是覆盖率——镂空的 alpha 在阈值附近锐化到约一个纹素宽。不透明物体画进多重采样目标时,它会转成多重采样覆盖率,镂空边缘就有抗锯齿而不是台阶。贴图被缩小到一个像素覆盖多个纹素时,边缘比像素还细,这时直接用经过 mip 平均的 alpha 作为覆盖率(没有多重采样时则与逐像素阈值比较),所以远处一张细发丝卡片透出的比例与它实际覆盖的一致,不会合成一整块实心板。着色器用 `cutoutCoverage(alpha, cutoff, edge, texelsPerPixel, pixel, u_time.w)` 实现,`u_time.w` 是场景的多重采样数。内置 Model 着色器声明了 `u_alphaCutoff`。 |+| `#pragma coverage PARAM` | 浮点参数 `PARAM` 大于零时,着色器输出的 alpha 就是覆盖率——镂空的 alpha 在阈值附近锐化到约一个像素宽(`cutoutCoverage(alpha, cutoff, fwidth(alpha))`)。不透明物体画进多重采样目标时,它会转成多重采样覆盖率,镂空边缘就有抗锯齿而不是台阶;没有多重采样时就是硬切。任何距离都在阈值处切,与 glTF 的 MASK 定义一致:镂空缩小显示时之所以还保持原来的面积,是因为烘焙时把每级 mip 的 alpha 缩放到与原图在阈值处相同的覆盖率。内置 Model 着色器声明了 `u_alphaCutoff`。 || `#pragma feature NAME` | 引擎选择的编译期变体关键字。 || `#pragma hairshadow PARAM` | 浮点参数 `PARAM` 大于零时,用这个材质画的网格就是阴影意义上的头发:太阳的级联多出一个只拟合它们的级联,并且着色器在打光前设置 `g_hairShadow` 的话,阴影就按沿光线的密度读,而不是硬比较。参数值就是密度。内置 Hair 着色器声明了 `u_hairShadow`。 || `#pragma gbuffer` | `PostProcess` 着色器要读取场景的表面记录(见[G-buffer](/docs/zh-cn/graphics/post-processing/#g-buffer)),在 `u_gbuffer` 处。声明它才会让这一帧画出一份;着色器里没有它的链路永远不付这笔钱。 |diff --git a/examples/physics-3d/assets/materials/decal-target.esshader b/examples/physics-3d/assets/materials/decal-target.esshaderindex a87446ed6..d3c8bad28 100644--- a/examples/physics-3d/assets/materials/decal-target.esshader+++ b/examples/physics-3d/assets/materials/decal-target.esshader@@ -27,7 +27,7 @@ void main() {// GENERATED by tools/gen-shader-twins.mjs (glslang + naga) - do not edit.// Regenerate after changing the GLSL stages above.// source-hash: 144f76db1f5f521a-// assembled-hash: 57cdee59a1f0a44c+// assembled-hash: 9d8de349288f7aa6struct MaterialConstants {u_tint: vec4<f32>,}diff --git a/fixtures/scenes/mat-builtin-lit/lit.esshader b/fixtures/scenes/mat-builtin-lit/lit.esshaderindex 42c2151bf..ee59766a8 100644--- a/fixtures/scenes/mat-builtin-lit/lit.esshader+++ b/fixtures/scenes/mat-builtin-lit/lit.esshader@@ -27,7 +27,7 @@ void main() {// GENERATED by tools/gen-shader-twins.mjs (glslang + naga) - do not edit.// Regenerate after changing the GLSL stages above.// source-hash: 5330079245724fa2-// assembled-hash: 033de02da456baf2+// assembled-hash: c06e80b59c8b0295struct SurfaceExt {coat: vec4<f32>,coatN: vec4<f32>,diff --git a/fixtures/scenes/mat-generated-mesh/split.esshader b/fixtures/scenes/mat-generated-mesh/split.esshaderindex a5d37aaab..61ab1c7bc 100644--- a/fixtures/scenes/mat-generated-mesh/split.esshader+++ b/fixtures/scenes/mat-generated-mesh/split.esshader@@ -22,7 +22,7 @@ void main() {// GENERATED by tools/gen-shader-twins.mjs (glslang + naga) - do not edit.// Regenerate after changing the GLSL stages above.// source-hash: 7af6948ea05e1a30-// assembled-hash: dc2175eaba6fcc5a+// assembled-hash: 49b1dd7fa0112adestruct MaterialConstants {u_tint: vec4<f32>,}diff --git a/fixtures/scenes/mat-lit-flatnormal/lit-fn.esshader b/fixtures/scenes/mat-lit-flatnormal/lit-fn.esshaderindex f9d1f8981..d77e92fc7 100644--- a/fixtures/scenes/mat-lit-flatnormal/lit-fn.esshader+++ b/fixtures/scenes/mat-lit-flatnormal/lit-fn.esshader@@ -47,7 +47,7 @@ void main() {// GENERATED by tools/gen-shader-twins.mjs (glslang + naga) - do not edit.// Regenerate after changing the GLSL stages above.// source-hash: a8853729e0f76d55-// assembled-hash: c2659746558cb08d+// assembled-hash: e50f8dec8e61ef88struct gl_PerVertex {@builtin(position) gl_Position: vec4<f32>,gl_PointSize: f32,@@ -123,7 +123,7 @@ fn vs_main(@location(0) a_position: vec3<f32>, @location(1) a_color: vec4<f32>,// GENERATED by tools/gen-shader-twins.mjs (glslang + naga) - do not edit.// Regenerate after changing the GLSL stages above.// source-hash: a8853729e0f76d55-// assembled-hash: c2659746558cb08d+// assembled-hash: e50f8dec8e61ef88struct SurfaceExt {coat: vec4<f32>,coatN: vec4<f32>,diff --git a/fixtures/scenes/mat-lit-normal/lit-normal.esshader b/fixtures/scenes/mat-lit-normal/lit-normal.esshaderindex f3548b30d..fda24a0cd 100644--- a/fixtures/scenes/mat-lit-normal/lit-normal.esshader+++ b/fixtures/scenes/mat-lit-normal/lit-normal.esshader@@ -47,7 +47,7 @@ void main() {// GENERATED by tools/gen-shader-twins.mjs (glslang + naga) - do not edit.// Regenerate after changing the GLSL stages above.// source-hash: 577c1ff7b66006ff-// assembled-hash: b67a3d6ca9ce9b2b+// assembled-hash: 471b46b5b29efcddstruct gl_PerVertex {@builtin(position) gl_Position: vec4<f32>,gl_PointSize: f32,@@ -123,7 +123,7 @@ fn vs_main(@location(0) a_position: vec3<f32>, @location(1) a_color: vec4<f32>,// GENERATED by tools/gen-shader-twins.mjs (glslang + naga) - do not edit.// Regenerate after changing the GLSL stages above.// source-hash: 577c1ff7b66006ff-// assembled-hash: b67a3d6ca9ce9b2b+// assembled-hash: 471b46b5b29efcddstruct SurfaceExt {coat: vec4<f32>,coatN: vec4<f32>,diff --git a/fixtures/scenes/mat-lit/lit.esshader b/fixtures/scenes/mat-lit/lit.esshaderindex fe749dd7d..22301d60b 100644--- a/fixtures/scenes/mat-lit/lit.esshader+++ b/fixtures/scenes/mat-lit/lit.esshader@@ -53,7 +53,7 @@ void main() {// GENERATED by tools/gen-shader-twins.mjs (glslang + naga) - do not edit.// Regenerate after changing the GLSL stages above.// source-hash: 8c118f2b442c055e-// assembled-hash: e50772a36dc99b83+// assembled-hash: 65b8129fa91f5217struct gl_PerVertex {@builtin(position) gl_Position: vec4<f32>,gl_PointSize: f32,@@ -125,7 +125,7 @@ fn vs_main(@location(0) a_position: vec3<f32>, @location(1) a_color: vec4<f32>,// GENERATED by tools/gen-shader-twins.mjs (glslang + naga) - do not edit.// Regenerate after changing the GLSL stages above.// source-hash: 8c118f2b442c055e-// assembled-hash: e50772a36dc99b83+// assembled-hash: 65b8129fa91f5217struct SurfaceExt {coat: vec4<f32>,coatN: vec4<f32>,diff --git a/pipeline/src/assets/ktx2Mips.ts b/pipeline/src/assets/ktx2Mips.tsindex 272f9e810..5772014c1 100644--- a/pipeline/src/assets/ktx2Mips.ts+++ b/pipeline/src/assets/ktx2Mips.ts@@ -93,13 +93,14 @@ export function alphaCoverage(rgba: Uint8Array, cutoff: number, scale = 1): numb/*** 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. Only ever scales up: a level that already reaches the share is- * left alone, because for a fully opaque image the smallest scale that still reaches 100% is the cutoff itself, which would bring every texel's alpha down onto it.+ * @p coverage. Averaging moves the share either way — a sparse cutout (a railing) thins away, a dense fine one (hair) closes into a+ * sheet — so the scale goes either way too: the smallest that reaches the share, by bisection. A level already at the share is left+ * alone; for a fully opaque image the smallest scale reaching 100% is the cutoff itself, which would pull every alpha down onto it.*/export function preserveAlphaCoverage(rgba: Uint8Array, cutoff: number, coverage: number): void {- if (alphaCoverage(rgba, cutoff) >= coverage) return;- let lo = 1, hi = 4;+ const now = alphaCoverage(rgba, cutoff);+ if (now === coverage) return;+ let lo = now < coverage ? 1 : 0, hi = now < coverage ? 4 : 1;for (let i = 0; i < 20; i++) {const mid = (lo + hi) / 2;if (alphaCoverage(rgba, cutoff, mid) < coverage) lo = mid; else hi = mid;@@ -135,42 +136,6 @@ export function halveRgba(rgba: Uint8Array, width: number, height: number, srgb:return { rgba: out, width: w, height: h };}-/**- * The next level down of a cut-out's chain, whose alpha is COVERAGE: the share of the texels under each new texel that the cut keeps.- * Read at the first step from the image itself (`cutoff` given: a texel counts when its alpha reaches it), and from there on by averaging- * shares, which is exact. Colour is weighted the same way, so a level is the colour of what the cut keeps and not of what it throws away.- *- * A plain average of alpha is the share only for a mask that is 0 or 1; a soft one (a painted band of lashes fading out, a strand's- * antialiased edge) averages to more than the cut keeps, and a shader taking the minified alpha as coverage drew the faint parts the- * source never shows. Coverage-preserving rescaling (preserveAlphaCoverage) is the answer for a shader that cuts every level at the- * cutoff; the engine's cut-out shaders read a minified level as the share it is (cutoutCoverage), so this chain gives them the share.- */-export function halveCoverage(rgba: Uint8Array, width: number, height: number, srgb: boolean, cutoff: number | null): {- rgba: Uint8Array; width: number; height: number;-} {- const w = Math.max(1, width >> 1), h = Math.max(1, height >> 1);- const out = new Uint8Array(w * h * 4);- const threshold = cutoff === null ? 0 : cutoff * 255;- for (let y = 0; y < h; y++) {- const y0 = Math.min(height - 1, y * 2), y1 = Math.min(height - 1, y * 2 + 1);- for (let x = 0; x < w; x++) {- const x0 = Math.min(width - 1, x * 2), x1 = Math.min(width - 1, x * 2 + 1);- const taps = [(y0 * width + x0) * 4, (y0 * width + x1) * 4, (y1 * width + x0) * 4, (y1 * width + x1) * 4];- const weights = taps.map(t => (cutoff === null ? rgba[t + 3]! / 255 : (rgba[t + 3]! >= threshold ? 1 : 0)));- const total = weights.reduce((n, v) => n + v, 0);- const o = (y * w + x) * 4;- for (let c = 0; c < 3; c++) {- const mean = (f: (t: number) => number) => (total > 0- ? taps.reduce((n, t, i) => n + f(t) * weights[i]!, 0) / total- : taps.reduce((n, t) => n + f(t), 0) / 4);- out[o + c] = srgb ? toSrgbByte(mean(t => toLinear[rgba[t + c]!]!)) : Math.round(mean(t => rgba[t + c]!));- }- out[o + 3] = Math.round(total / 4 * 255);- }- }- return { rgba: out, width: w, height: h };-}-/*** `base`'s level 0 over every level of `below` (encoded from the half-size* image, so its level 0 is the base's level 1), as one KTX2 with `base`'sdiff --git a/pipeline/src/assets/modelImages.ts b/pipeline/src/assets/modelImages.tsindex 2cf2e1f55..b4ef76aea 100644--- a/pipeline/src/assets/modelImages.ts+++ b/pipeline/src/assets/modelImages.ts@@ -270,8 +270,8 @@ export function prepareModelImages(result: ModelImportResult,+ ` ${pixels.width}x${pixels.height} — a material constant would say the same`);}}- // A cutout's mips hold the share of texels its cut keeps (mipCoverage: see halveCoverage), which is what its shaders read as the- // coverage of a minified pixel.+ // A cutout's mips keep the share of texels its cut keeps (mipCoverage: see preserveAlphaCoverage), so cut at the same cutoff on+ // every level it neither thins away nor closes into a sheet when it is seen small.const base = material.baseColorTexture;if (base && material.alphaCutoff !== undefined && material.alphaCutoff > 0) {material.baseColorTexture = { ...base, settings: { ...base.settings, mipCoverage: material.alphaCutoff } };diff --git a/pipeline/src/assets/textureCook.ts b/pipeline/src/assets/textureCook.tsindex f65dcdedc..2e5dcc1de 100644--- a/pipeline/src/assets/textureCook.ts+++ b/pipeline/src/assets/textureCook.ts@@ -14,7 +14,7 @@ import {decideTextureCook, cookIntentDefeated, explainTextureCook, downscaledSize,type TextureCookDecision,} from './textureCookDecision';-import { joinMipLevels, halveCoverage } from './ktx2Mips';+import { halveRgba, joinMipLevels, alphaCoverage, preserveAlphaCoverage } from './ktx2Mips';import { cookCachedAt, cookCacheFile, cookCacheHitAt, encoderIdentity } from './cookCache';/** Targets the KTX2 the cook emits can transcode to at runtime (UASTC + ETC1S). */@@ -39,20 +39,22 @@ export interface BasisEncoderModule {}/**- * A cutout's UASTC chain: level 0 as authored, and each level below it holding as alpha the share of the image's texels the cut at- * @p cutoff keeps (halveCoverage), the coverage a minified cut-out is drawn with.+ * 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:+ * the shaders cut every level at the cutoff (glTF's MASK), and 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;- let first = true;for (;;) {parts.push(await enc.encodeToKtx2({ type: enc.ImageType.RGBA, data: level.rgba, width: level.width, height: level.height },{ mode: 'uastc', srgb, mipmaps: false, supercompress: true }));if (level.width === 1 && level.height === 1) break;- level = halveCoverage(level.rgba, level.width, level.height, srgb, first ? cutoff : null);- first = false;+ const half = halveRgba(level.rgba, level.width, level.height, srgb);+ preserveAlphaCoverage(half.rgba, cutoff, coverage);+ level = half;}return joinMipLevels(parts);}@@ -180,8 +182,8 @@ export async function cookTexture(input: TextureCookInput): Promise<TextureCookO// before this existed is re-encoded rather than reused.const supercompress = mode === 'uastc';const key = [source, JSON.stringify({ mode, srgb: tex.srgb, maxSize: tex.maxSize, scaled: scaled ? [size!.width, size!.height] : null,- // `chain: 2` marks the coverage chain (halveCoverage) that replaced the rescaled one: an entry cooked before it is re-encoded.- ...(coverage ? { mipCoverage: coverage, chain: 2 } : {}), ...(supercompress ? { supercompress } : {}), ...mips }), input.encoder!.id];+ // `chain: 3` marks the rescaled chain that replaced the share-of-coverage one (chain 2): an entry cooked before it is re-encoded.+ ...(coverage ? { mipCoverage: coverage, chain: 3 } : {}), ...(supercompress ? { supercompress } : {}), ...mips }), input.encoder!.id];const produce = (): Promise<Uint8Array> => {const image = scaled ? scaledImage() : null;return coveragediff --git a/pipeline/tests/ktx2-mips.test.ts b/pipeline/tests/ktx2-mips.test.tsindex 6d2defb4e..993dd767e 100644--- a/pipeline/tests/ktx2-mips.test.ts+++ b/pipeline/tests/ktx2-mips.test.ts@@ -12,7 +12,7 @@ import { mkdtempSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSynimport { tmpdir } from 'node:os';import path from 'node:path';import {- readKtx2Layout, wantsMipChain, halveRgba, spliceMipChain, joinMipLevels, alphaCoverage, preserveAlphaCoverage, halveCoverage,+ readKtx2Layout, wantsMipChain, halveRgba, spliceMipChain, joinMipLevels, alphaCoverage, preserveAlphaCoverage,} from '../src/assets/ktx2Mips';import { cookCached } from '../src/assets/cookCache';import { cookAssets } from '../src/assets/cookAssets';@@ -127,6 +127,15 @@ describe('a cutout\'s mips keep its coverage', () => {expect(alphaCoverage(half.rgba, 0.5)).toBeGreaterThanOrEqual(0.25);});+ it('comes back down to the full image\'s share when averaging has closed it up', () => {+ // A dense, fine cut-out averages above its cutoff: three of four texels pass where the full image keeps half.+ const closed = new Uint8Array([60, 140, 40, 255, 60, 140, 40, 200, 60, 140, 40, 150, 60, 140, 40, 100]);+ expect(alphaCoverage(closed, 0.5)).toBe(0.75);+ preserveAlphaCoverage(closed, 0.5, 0.5);+ expect(alphaCoverage(closed, 0.5)).toBe(0.5);+ expect(closed[3]).toBeGreaterThan(closed[7]!);+ });+it('leaves the alpha of a fully opaque image alone, so a cutout material on it still draws at every level', () => {const opaque = new Uint8Array(8 * 8 * 4).fill(255);const half = halveRgba(opaque, 8, 8, false);@@ -143,19 +152,3 @@ describe('a cutout\'s mips keep its coverage', () => {expect(() => joinMipLevels([chainParts[0]!, chainParts[2]!])).toThrow(/not the level under/);});});--describe('a cut-out chain whose alpha is coverage', () => {- it('gives a soft band the share its cut keeps, not its average alpha', () => {- // Four texels at alpha 0.3 (a faint painted band) and nothing above the cutoff: the cut keeps none of them.- const faint = new Uint8Array([90, 60, 50, 77, 90, 60, 50, 77, 90, 60, 50, 77, 90, 60, 50, 77]);- expect(halveCoverage(faint, 2, 2, false, 0.45).rgba[3]).toBe(0);- // One solid strand of four: a quarter, and the colour is the strand's.- const strand = new Uint8Array([20, 10, 5, 255, 200, 120, 110, 60, 200, 120, 110, 60, 200, 120, 110, 60]);- expect(Array.from(halveCoverage(strand, 2, 2, false, 0.45).rgba)).toEqual([20, 10, 5, 64]);- });-- it('averages shares below the first level, which is exact', () => {- const shares = new Uint8Array([255, 255, 255, 255, 255, 255, 255, 0, 255, 255, 255, 128, 255, 255, 255, 128]);- expect(halveCoverage(shares, 2, 2, false, null).rgba[3]).toBe(128);- });-});diff --git a/sdk/src/character/characterShaders.ts b/sdk/src/character/characterShaders.tsindex 7001f2d16..394887e27 100644--- a/sdk/src/character/characterShaders.ts+++ b/sdk/src/character/characterShaders.ts@@ -109,8 +109,6 @@ void main() {#endifvec4 base = texture(u_textures[0], v_texCoord, u_sharpen) * v_color * u_tint;// Before any discard: a derivative needs every fragment of its quad.- vec2 mapSize = vec2(textureSize(u_textures[0], 0));- float texels = max(length(dFdx(v_texCoord) * mapSize), length(dFdy(v_texCoord) * mapSize));float alpha = 1.0;#ifdef ES_TIP_PASS// The band below the cutoff, fading in toward it, and a texel past it so it meets the opaque card without a gap.@@ -119,7 +117,7 @@ void main() {alpha = min(alpha, 1.0);#elseif (u_alphaCutoff > 0.0) {- alpha = cutoutCoverage(base.a, u_alphaCutoff, fwidth(base.a), texels, gl_FragCoord.xy, u_time.w);+ alpha = cutoutCoverage(base.a, u_alphaCutoff, fwidth(base.a));if (alpha <= 0.0) discard;alpha = min(alpha, 1.0);}@@ -184,8 +182,6 @@ fn packNormal(n : vec3f) -> vec2f {#endifvar base = textureSampleBias(t0, s0, v.v_texCoord, mc.u_sharpen) * v.v_color * mc.u_tint;let edge = max(abs(dpdx(base.a)) + abs(dpdy(base.a)), 1e-4);- let mapSize = vec2f(textureDimensions(t0));- let texels = max(length(duvx * mapSize), length(duvy * mapSize));let flowTex = textureSampleGrad(u_flowMap, u_flowMap_s, v.v_texCoord, duvx, duvy).rg * 2.0 - vec2f(1.0);let orm = textureSampleGrad(u_ormMap, u_ormMap_s, v.v_texCoord, duvx, duvy);let shiftTex = textureSampleGrad(u_shiftMap, u_shiftMap_s, v.v_texCoord * mc.u_shiftTile, duvx * mc.u_shiftTile, duvy * mc.u_shiftTile).r;@@ -214,7 +210,7 @@ fn packNormal(n : vec3f) -> vec2f {alpha = min(alpha, 1.0);#elseif (mc.u_alphaCutoff > 0.0) {- alpha = cutoutCoverage(base.a, mc.u_alphaCutoff, edge, texels, v.pos.xy, tc.u_time.w);+ alpha = cutoutCoverage(base.a, mc.u_alphaCutoff, edge);if (alpha <= 0.0) { discard; }alpha = min(alpha, 1.0);}diff --git a/sdk/src/foliage/foliageShader.ts b/sdk/src/foliage/foliageShader.tsindex 5bb6fd69e..98c446914 100644--- a/sdk/src/foliage/foliageShader.ts+++ b/sdk/src/foliage/foliageShader.ts@@ -105,16 +105,14 @@ void main() {float height = clamp(v_color.r, 0.0, 1.0);float light = v_color.b;vec4 tex = texture(u_albedo, v_texCoord);- // Before the branch: a derivative needs every fragment of its quad. How many texels of the map a pixel spans, for cutoutCoverage.- vec2 mapSize = vec2(textureSize(u_albedo, 0));- float texels = max(length(dFdx(v_texCoord) * mapSize), length(dFdy(v_texCoord) * mapSize));+ // Before the branch: a derivative needs every fragment of its quad.float edgeA = fwidth(tex.a);vec3 albedo = mix(u_baseColor.rgb, u_tipColor.rgb, height);float alpha = 1.0;if (u_useTexture > 0.5) {albedo *= tex.rgb;alpha = tex.a;- alpha = cutoutCoverage(alpha, u_alphaCutoff, edgeA, texels, gl_FragCoord.xy, u_time.w);+ alpha = cutoutCoverage(alpha, u_alphaCutoff, edgeA);if (alpha <= 0.0) discard;alpha = min(alpha, 1.0);}@@ -161,8 +159,6 @@ fn packNormal(n : vec3f) -> vec2f {#endiflet tex = textureSampleGrad(u_albedo, u_albedo_s, v.v_texCoord, duvx, duvy);let edge = max(fwidth(tex.a), 1e-4);- let mapSize = vec2f(textureDimensions(u_albedo));- let texels = max(length(duvx * mapSize), length(duvy * mapSize));#ifdef MESH_NORMALSlet P = v.v_worldXYZ;var N = normalize(v.v_worldNormal);@@ -177,7 +173,7 @@ fn packNormal(n : vec3f) -> vec2f {var alpha = 1.0;if (mc.u_useTexture > 0.5) {albedo = albedo * tex.rgb;- alpha = cutoutCoverage(tex.a, mc.u_alphaCutoff, edge, texels, v.pos.xy, tc.u_time.w);+ alpha = cutoutCoverage(tex.a, mc.u_alphaCutoff, edge);if (alpha <= 0.0) { discard; }alpha = min(alpha, 1.0);}diff --git a/sdk/src/render/builtinShaders.ts b/sdk/src/render/builtinShaders.tsindex 0cabee15b..da0e805b4 100644--- a/sdk/src/render/builtinShaders.ts+++ b/sdk/src/render/builtinShaders.ts@@ -449,12 +449,10 @@ void main() {highp vec3 dndy = dFdy(v_worldNormal);#endifvec4 base = texture(u_textures[0], v_texCoord) * v_color * u_tint;- // A cutout's alpha becomes coverage (cutoutCoverage): sharpened where the map is magnified, its own average where it is minified.- vec2 mapSize = vec2(textureSize(u_textures[0], 0));- float texels = max(length(dFdx(v_texCoord) * mapSize), length(dFdy(v_texCoord) * mapSize));+ // A cutout is glTF's MASK (cutoutCoverage): cut at the cutoff, sharpened to a pixel so alpha-to-coverage feathers the edge.float alpha = base.a;if (u_alphaCutoff > 0.0) {- alpha = cutoutCoverage(base.a, u_alphaCutoff, fwidth(base.a), texels, gl_FragCoord.xy, u_time.w);+ alpha = cutoutCoverage(base.a, u_alphaCutoff, fwidth(base.a));if (alpha <= 0.0) discard;alpha = min(alpha, 1.0);}@@ -596,11 +594,9 @@ fn packNormal(n : vec3f) -> vec2f {var base = textureSampleGrad(t0, s0, v.v_texCoord, duvx, duvy) * v.v_color * mc.u_tint;// Before any discard: a derivative needs every fragment of its quad.let edge = max(fwidth(base.a), 1e-4);- let mapSize = vec2f(textureDimensions(t0));- let texels = max(length(duvx * mapSize), length(duvy * mapSize));var alpha = base.a;if (mc.u_alphaCutoff > 0.0) {- alpha = cutoutCoverage(base.a, mc.u_alphaCutoff, edge, texels, v.pos.xy, tc.u_time.w);+ alpha = cutoutCoverage(base.a, mc.u_alphaCutoff, edge);if (alpha <= 0.0) { discard; }alpha = min(alpha, 1.0);}diff --git a/src/esengine/data/shaders/mesh.esshader b/src/esengine/data/shaders/mesh.esshaderindex 663c9a6eb..7ba88e054 100644--- a/src/esengine/data/shaders/mesh.esshader+++ b/src/esengine/data/shaders/mesh.esshader@@ -320,14 +320,9 @@ void main() {fragColor = vec4((was - now) * 0.5, gl_FragCoord.z, v_velPrev.w > 1e-6 ? 1.0 : 0.0);#elif defined(SHADOW_DEPTH)#ifdef SHADOW_ALPHA- // A cut-out's shadow keeps the share of the light its texture lets through. Where the map is seen smaller than a texel a texel of the- // shadow map (a hair card from the light), the cut moves to a per-texel threshold, so a card that covers 60% writes 60% of the texels it- // falls on and the receiver's filter turns that into a shadow 60% deep; a cut at the cutoff closed every gap and drew the card as a slab.- highp vec2 mapSize = vec2(textureSize(u_texture, 0));- highp float texels = max(length(dFdx(v_texCoord) * mapSize), length(dFdy(v_texCoord) * mapSize));- highp float minified = clamp(log2(max(texels, 1e-4)), 0.0, 1.0);- highp float noise = fract(52.9829189 * fract(dot(floor(gl_FragCoord.xy), vec2(0.06711056, 0.00583715))));- if (texture(u_texture, v_texCoord).a * v_color.a < mix(u_alphaCutoff, noise, minified)) discard;+ // A cut-out's shadow is cut where the cut-out is, at the cutoff (glTF's MASK), through the mip chain: seen small from the light, the+ // cut-out keeps its share of the light because its mips keep their coverage at the cutoff (preserveAlphaCoverage).+ if (texture(u_texture, v_texCoord).a * v_color.a < u_alphaCutoff) discard;#endif// The expression the receiver evaluates on u_shadowMatrix, evaluated here on the// same matrix and at the same point: whatever each backend's clip z means, both@@ -651,15 +646,10 @@ fn packNormal(n : vec3f) -> vec2f {return vec4f((was - now) * 0.5, v.pos.z, select(0.0, 1.0, v.v_velPrev.w > 1e-6));#elif defined(SHADOW_DEPTH)#ifdef SHADOW_ALPHA- // See the GLSL twin: through the mip chain (level 0 alone left a card's shadow a different shape from WebGL2's), and a per-texel threshold- // where the map is minified, so the shadow keeps the share of light the card lets through.+ // See the GLSL twin: through the mip chain (level 0 alone left a card's shadow a different shape from WebGL2's), cut at the cutoff.let duvx = dpdx(v.v_texCoord);let duvy = dpdy(v.v_texCoord);- let mapSize = vec2f(textureDimensions(t0));- let texels = max(length(duvx * mapSize), length(duvy * mapSize));- let minified = clamp(log2(max(texels, 1e-4)), 0.0, 1.0);- let noise = fract(52.9829189 * fract(dot(floor(v.pos.xy), vec2f(0.06711056, 0.00583715))));- if (textureSampleGrad(t0, s0, v.v_texCoord, duvx, duvy).a * v.v_color.a < mix(mc.u_alphaCutoff, noise, minified)) { discard; }+ if (textureSampleGrad(t0, s0, v.v_texCoord, duvx, duvy).a * v.v_color.a < mc.u_alphaCutoff) { discard; }#endif// The expression the receiver evaluates on u_shadowMatrix, evaluated here on the// same matrix and at the same point: whatever each backend's clip z means, bothdiff --git a/src/esengine/renderer/frame/FrameConstants.hpp b/src/esengine/renderer/frame/FrameConstants.hppindex ef9da18c5..75990e347 100644--- a/src/esengine/renderer/frame/FrameConstants.hpp+++ b/src/esengine/renderer/frame/FrameConstants.hpp@@ -85,7 +85,7 @@ inline constexpr const char* FRAME_CONSTANTS_BLOCK = "FrameConstants";/*** @brief CPU mirror of the injected TimeConstants block (std140).- * @details u_time = (elapsed s, delta s, view exposure EV, the scene's multisampling); u_viewport = (w, h, 1/w, 1/h) of the+ * @details u_time = (elapsed s, delta s, view exposure EV, 0); u_viewport = (w, h, 1/w, 1/h) of the* canvas in pixels. Engine-owned: ShaderParser injects the block into every* assembled stage — shaders never declare it.*/diff --git a/src/esengine/renderer/frame/RenderContext.cpp b/src/esengine/renderer/frame/RenderContext.cppindex 7f491e0b9..3ba058c1d 100644--- a/src/esengine/renderer/frame/RenderContext.cpp+++ b/src/esengine/renderer/frame/RenderContext.cpp@@ -222,7 +222,7 @@ void RenderContext::setFrameTime(f32 elapsedSec, u32 viewportW, u32 viewportH) {const f32 w = static_cast<f32>(viewportW);const f32 h = static_cast<f32>(viewportH);TimeConstants time{- glm::vec4(elapsedSec, dt, viewExposure_, coverageSamples_),+ glm::vec4(elapsedSec, dt, viewExposure_, 0.0f),glm::vec4(w, h, w > 0.0f ? 1.0f / w : 0.0f, h > 0.0f ? 1.0f / h : 0.0f),};device_.updateBuffer(timeUbo_, 0, &time, sizeof(TimeConstants));diff --git a/src/esengine/renderer/frame/RenderContext.hpp b/src/esengine/renderer/frame/RenderContext.hppindex 1c886e34d..fe96af017 100644--- a/src/esengine/renderer/frame/RenderContext.hpp+++ b/src/esengine/renderer/frame/RenderContext.hpp@@ -191,13 +191,6 @@ public:* exp2(0) = 1, an exact no-op.*/void setViewExposure(f32 ev) { viewExposure_ = ev; }-- /**- * @brief The multisampling the scene is drawn with, carried to every shader in u_time.w: a cut-out's minified alpha is coverage- * where there are samples to cover, and a per-pixel threshold where there are none (cutoutCoverage). Uploaded with the- * next frame's clock, so a change reaches the shaders a frame late.- */- void setCoverageSamples(u32 samples) { coverageSamples_ = static_cast<f32>(samples > 0 ? samples : 1); }f32 viewExposure() const { return viewExposure_; }/**@@ -270,7 +263,6 @@ public:private:f32 lastElapsed_ = 0.0f;f32 viewExposure_ = 0.0f;- f32 coverageSamples_ = 1.0f;MaterialStore materials_;LightStore lights_;ProbeStore probes_;diff --git a/src/esengine/renderer/frame/RenderFrame.cpp b/src/esengine/renderer/frame/RenderFrame.cppindex b85e08b55..cc4d8353d 100644--- a/src/esengine/renderer/frame/RenderFrame.cpp+++ b/src/esengine/renderer/frame/RenderFrame.cpp@@ -246,10 +246,7 @@ void RenderFrame::drawScene(DrawList::Phase phase) {// sub-pixel amount each frame, so its history samples what a single frame cannot.// The scene only: the overlay and the shadow maps are drawn with constants of their own.glm::vec2 jitter{0.0f};- u32 coverageSamples = 1;#ifdef ES_ENABLE_POSTPROCESS- // The scene's multisampling, chain or not: with no chain it draws to a surface given the same count.- if (post_process_) coverageSamples = post_process_->sceneSamples();// The atlas the meshes reflect, for an effect that adds a reflection of its own where the scene's ray found none.if (post_process_) post_process_->setEnvironmentTexture(environment_texture_id_);if (phase == DrawList::Phase::SceneColorOnly || phase == DrawList::Phase::BlendedOnly) {@@ -263,7 +260,6 @@ void RenderFrame::drawScene(DrawList::Phase phase) {}#endifscene_jitter_ = jitter;- context_.setCoverageSamples(coverageSamples);context_.updateCameraConstants(view_projection_, jitter);// Where THIS camera's pixels sit inside the 2D shadow mask. Per camera because the// mask is screen space: two cameras drew into two parts of one target, and adiff --git a/src/esengine/renderer/rhi/ShaderEmbeds.generated.hpp b/src/esengine/renderer/rhi/ShaderEmbeds.generated.hppindex a0eef6316..053808da6 100644--- a/src/esengine/renderer/rhi/ShaderEmbeds.generated.hpp+++ b/src/esengine/renderer/rhi/ShaderEmbeds.generated.hpp@@ -800,12 +800,7 @@ void main() {#ifdef SHADOW_ALPHA-- highp vec2 mapSize = vec2(textureSize(u_texture, 0));- highp float texels = max(length(dFdx(v_texCoord) * mapSize), length(dFdy(v_texCoord) * mapSize));- highp float minified = clamp(log2(max(texels, 1e-4)), 0.0, 1.0);- highp float noise = fract(52.9829189 * fract(dot(floor(gl_FragCoord.xy), vec2(0.06711056, 0.00583715))));- if (texture(u_texture, v_texCoord).a * v_color.a < mix(u_alphaCutoff, noise, minified)) discard;+ if (texture(u_texture, v_texCoord).a * v_color.a < u_alphaCutoff) discard;#endif@@ -1130,14 +1125,9 @@ fn packNormal(n : vec3f) -> vec2f {#elif defined(SHADOW_DEPTH)#ifdef SHADOW_ALPHA-let duvx = dpdx(v.v_texCoord);let duvy = dpdy(v.v_texCoord);- let mapSize = vec2f(textureDimensions(t0));- let texels = max(length(duvx * mapSize), length(duvy * mapSize));- let minified = clamp(log2(max(texels, 1e-4)), 0.0, 1.0);- let noise = fract(52.9829189 * fract(dot(floor(v.pos.xy), vec2f(0.06711056, 0.00583715))));- if (textureSampleGrad(t0, s0, v.v_texCoord, duvx, duvy).a * v.v_color.a < mix(mc.u_alphaCutoff, noise, minified)) { discard; }+ if (textureSampleGrad(t0, s0, v.v_texCoord, duvx, duvy).a * v.v_color.a < mc.u_alphaCutoff) { discard; }#endifdiff --git a/src/esengine/resource/ShaderParser.cpp b/src/esengine/resource/ShaderParser.cppindex 928ecd567..af54dbc96 100644--- a/src/esengine/resource/ShaderParser.cpp+++ b/src/esengine/resource/ShaderParser.cpp@@ -1458,15 +1458,12 @@ fn shadowFactor3D(worldPos : vec3f, N : vec3f, L : vec3f, source : vec2f,})"// Split again for the same cap; the WGSL is unchanged.-R"(// The coverage a cut-out's alpha gives this pixel. Magnified, the cut is sharpened to about a texel so alpha-to-coverage feathers its edge.-// Minified, the edges are finer than the pixel and the map's own alpha, averaged by its mips, already is the share of the pixel the cut-out-// covers: under multisampling it is that coverage as it is, and without it the cut moves to a per-pixel threshold so the share holds on-// average. `texels` is how many texels of the map one pixel spans, `samples` the multisampling of the pass (u_time.w).-fn cutoutCoverage(a : f32, cutoff : f32, edge : f32, texels : f32, pixel : vec2f, samples : f32) -> f32 {- let minified = clamp(log2(max(texels, 1e-4)), 0.0, 1.0);- if (samples > 1.5) { return mix((a - cutoff) / max(edge, 1e-4) + 0.5, a, minified); }- let noise = fract(52.9829189 * fract(dot(floor(pixel), vec2f(0.06711056, 0.00583715))));- return (a - mix(cutoff, noise, minified)) / max(edge, 1e-4) + 0.5;+R"(// The coverage a cut-out's alpha gives this pixel: glTF's MASK, kept where alpha reaches the cutoff and gone where it does not, at every+// distance. The cut is sharpened to about a pixel (`edge` is fwidth of the alpha), so under multisampling alpha-to-coverage feathers the+// edge instead of stair-stepping it, and without it the cut is the hard one. Seen small, the cut-out holds its area because its mips do:+// the cook rescales each level's alpha to the share the full image keeps at the cutoff (preserveAlphaCoverage).+fn cutoutCoverage(a : f32, cutoff : f32, edge : f32) -> f32 {+ return (a - cutoff) / max(edge, 1e-4) + 0.5;}fn sampleNormal(map : texture_2d<f32>, samp : sampler, uv : vec2f) -> vec3f {let xy = textureSampleLevel(map, samp, uv, 0.0).xy * 2.0 - 1.0;@@ -2617,18 +2614,13 @@ ShaderParser::AssembledStage ShaderParser::assembleStageEx(const ParsedShader& p" return 1.0;\n""#endif\n""}\n"+ // The coverage a cut-out's alpha gives this pixel: glTF's MASK, sharpened to about a pixel for alpha-to-coverage. See the WGSL twin.+ "highp float cutoutCoverage(in highp float a, in highp float cutoff, in highp float edge) {\n"+ " return (a - cutoff) / max(edge, 1e-4) + 0.5;\n"+ "}\n"// The one normal-map unpack: X and Y from RG, Z rebuilt to unit length, so a// two-channel map (BC5, or B left at 0) lights like the three-channel one. 2D// applies it screen-space; a flat surface uses vec3(0,0,1).- // The coverage a cut-out's alpha gives this pixel: sharpened to a texel where the map is magnified, and the map's own (mip-averaged)- // alpha where it is minified, as coverage under multisampling and against a per-pixel threshold without it. See the WGSL twin.- "highp float cutoutCoverage(in highp float a, in highp float cutoff, in highp float edge, in highp float texels,\n"- " in highp vec2 pixel, in highp float samples) {\n"- " highp float minified = clamp(log2(max(texels, 1e-4)), 0.0, 1.0);\n"- " if (samples > 1.5) return mix((a - cutoff) / max(edge, 1e-4) + 0.5, a, minified);\n"- " highp float noise = fract(52.9829189 * fract(dot(floor(pixel), vec2(0.06711056, 0.00583715))));\n"- " return (a - mix(cutoff, noise, minified)) / max(edge, 1e-4) + 0.5;\n"- "}\n""highp vec3 sampleNormal(in highp sampler2D map, in highp vec2 uv) {\n"" highp vec2 xy = texture(map, uv).xy * 2.0 - 1.0;\n"" return vec3(xy, sqrt(max(0.0, 1.0 - dot(xy, xy))));\n"diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex 74b5a562a..1cbf15577 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -69,17 +69,25 @@ export const NOTED = {'fix(webgpu): meshes, sprites and particles sample through their mip chain, and a compressed texture keeps every level':{"note":"On the WebGPU backend, a mesh without a material, a sprite and a particle are sampled through their texture's mip chain, as they always were on WebGL2: their WGSL read level 0 alone, so anything drawn smaller than its texture shimmered into stripes and moire there and not on the other backend. A compressed (KTX2) texture also keeps every level of its chain on WebGPU: the upload stopped at the first level whose side is not a multiple of four, which left a 1240x1268 hair atlas with level 0 alone. In the render lab a card of fine strands seen small now reads the same on both backends."},'fix(render): a cut-out seen small lets through as much as its texture covers, instead of closing into a sheet':- {"note":"A cut-out seen from far enough away that its texture is smaller than a texel a pixel lets through as much as its texture covers. Its alpha was sharpened to a texel around the cutoff at every distance, and once the mips had averaged fine strands and the gaps between them to one value above the cutoff, the whole card turned solid: a hair card at arm's length drew as a plate. Where the texture is minified the mip-averaged alpha is now the coverage under multisampling, and the cutoff moves to a per-pixel threshold without it. In the render lab a card of fine cut-out strands lets through within 3% of what Blender does, where it let through nothing; the shader helper is cutoutCoverage, and u_time.w carries the scene's multisampling."},+ {"note": "Cut-outs are glTF's MASK at every distance."},'fix(render): lit materials keep the energy a rough surface reflects, and a sun with a size casts a penumbra as wide as it throws':{"note":"Lit materials keep the light a rough surface reflects and pass on what it does not. The environment's specular came from Karis' analytic fit, 21% low for a metal at roughness 0.5 and up to 80% off at a grazing view; it is now a fit to the integral itself (tools/gen-dfg-fit.py, worst 3%). The light a rough metal loses to bounces between its microfacets is returned (Fdez-Aguera's multiple-scattering term, and the same ratio on a lamp's highlight), where a metal at roughness 0.9 under a white sky came out at half of Blender's brightness. The diffuse under a dielectric's specular is reduced by what the specular reflects, as in the Principled shader. And a lamp's highlight takes Smith's height-correlated masking at alpha = roughness squared in place of the Schlick k = (r + 1)^2 / 8 remap, which left a rough metal's rim a quarter dark. In the render lab six spheres under a white sky now match Blender within 0.5% at every roughness, and flat cards of five albedos within 0.002, on both backends. A sun with a size casts a penumbra as wide as Blender's. The disc a penumbra was averaged over stopped at 8 texels of the map, which held a sun's soft edge to sixteen texels: with a fine cascade that is less than the sun throws, and the render lab measured an edge 60% as wide as Blender's. The disc now reaches 24 texels, its spiral of taps is turned point by point so the wider disc grains rather than bands, and each blocker tap forgives only as far as it stands from the point, so a box standing on a floor stays shadowed to its foot."},'feat(character): hair takes the Principled highlight when it has an anisotropy, and an imported card with one is set to it':{"note":"The Hair shader takes the Principled shader's highlight when u_anisotropy is above zero: GGX stretched along the strand as Blender stretches it, with u_specular as the specular factor. A hair card imported with an anisotropy (KHR_materials_anisotropy, which Blender exports from its Principled anisotropy) is set to it, so the broad sheen across a fringe that Blender draws is drawn in the same place."},'fix(pipeline): a cut-out chain holds the share its cut keeps, and a cut-out takes its colour into its clear texels':- {"note":"A cut-out's mip chain holds, as alpha, the share of texels its cut keeps, and its colour is the colour of what the cut keeps. The minified alpha is what a cut-out is drawn with, and a plain average of a soft mask (a painted band of eyelashes fading out) averaged to more than the cut keeps: the probe's lash card drew a pink veil over the iris where Blender draws a few lashes. The chain no longer rescales alpha to keep a cutoff's coverage, and an imported cut-out's clear texels take the colour of the solid ones nearest them, so even a mip the GPU makes does not average in what the painter left under alpha 0."},+ {"note": "Cut-out colour in its clear texels."},'fix(render): a cut-out shadow keeps the share of light it lets through, the same on both backends':- {"note":"A cut-out's shadow keeps the share of light it lets through, and is the same shape on both backends. The shadow pass read a card's alpha at level 0 on WebGPU (mips on WebGL2), and cut at the cutoff on both; where the card is smaller than a texel from the light it now cuts against a per-texel threshold through the mip chain, so a fringe of hair throws a shadow as deep as it is dense."},+ {"note": "Cut-out shadows."},'fix(pipeline): an imported eye shades as the Principled shader it was authored against':{"note":"An imported eye shades as the Principled shader it was authored against: the Eye shader's tinted white, its warm wrap of light past the terminator (which reddened a painted iris) and its lid darkening are written as off, and both its glossy layers take the source's roughness instead of a near-mirror cornea."},+ "fix(render): the lit WGSL header splits under MSVC's literal cap again, and the six stale shader twins are regenerated":+ {"internal": "The WGSL is byte for byte what it was, split into two literals so a Windows build compiles it; the regenerated twins are test fixtures and one example material, drawn as before."},+ "fix(editor): the spring-bone label takes a step of the type scale, and the component link table names the spring bones":+ {"note": "Spring-bone collider handles."},+ "fix(webgpu): a normal map keeps its frame along a triangle's edge":+ {"note": "Normal maps along a triangle's edge on WebGPU."},+ "fix(render): a cut-out is glTF's MASK at every distance, its mips keeping their coverage both ways":+ {"note": "Cut-outs are glTF's MASK at every distance."},'fix: serialize binaryen optimization on windows': { internal: 'Uses one optimizer worker after wider builds reproduced heap corruption with four; release optimization flags stay unchanged.' },'feat: add budgeted 2d and 3d particle scene collisions': { note: 'Budgeted particle scene collisions.' },'feat(editor): add particle collision authoring and diagnostics': { note: 'Budgeted particle scene collisions.' },diff --git a/tools/renderScenes.mjs b/tools/renderScenes.mjsindex 9a97790c8..dd652e37f 100644--- a/tools/renderScenes.mjs+++ b/tools/renderScenes.mjs@@ -397,7 +397,9 @@ export const SCENES = [// The same ball with the probe off: both sides take the flat sky, and the room// stops being visible in it.{ id: "reflection-room-sky", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_SCENE: "/scenes/reflection-room.esscene", ESTELLA_VERIFY_W: "512", ESTELLA_VERIFY_H: "384", ESTELLA_VERIFY_STEPS: "2", ESTELLA_VERIFY_SET_FIELD: "{\"entity\": 8, \"component\": \"ReflectionProbe\", \"key\": \"enabled\", \"value\": false, \"steps\": 2}", ESTELLA_VERIFY_EXPECT: "[{\"x\": 0.2, \"y\": 0.55, \"rgb\": [37, 37, 39], \"tol\": 25}, {\"x\": 0.42, \"y\": 0.62, \"rgb\": [37, 37, 39], \"tol\": 25}]" } },- { id: "mat-env-mirror", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_SCENE: "/scenes/mat-env-mirror.esscene", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "2", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.25,\"y\":0.5,\"rgb\":[0,228,0],\"tol\":20},{\"x\":0.75,\"y\":0.5,\"rgb\":[29,23,24],\"tol\":20},{\"x\":0.5,\"y\":0.5,\"rgb\":[0,0,0],\"tol\":20}]" } },+ // The rough metal keeps the energy its microfacets bounce between them: a white metal reflects+ // the whole environment, where single scattering alone gave back Ess (0.45 at roughness 1).+ { id: "mat-env-mirror", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_SCENE: "/scenes/mat-env-mirror.esscene", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "2", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.25,\"y\":0.5,\"rgb\":[0,228,0],\"tol\":20},{\"x\":0.75,\"y\":0.5,\"rgb\":[65,53,53],\"tol\":20},{\"x\":0.5,\"y\":0.5,\"rgb\":[0,0,0],\"tol\":20}]" } },// Sky and DIELECTRIC apart: they read the atlas and the irradiance coefficients// through different code, and one turning without the other is the defect. The// fixture is half bright — a symmetric sky reads the same at every angle.@@ -649,7 +651,7 @@ export const SCENES = [// The same two materials with NO light on them, only the ambient environment.// A metal has no diffuse, so reflecting that environment is all it has: remove// the reflection and the left probe is black while the right one barely moves.- { id: "mat-model-env", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_SCENE: "/scenes/mat-model-env.esscene", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "2", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.25,\"y\":0.5,\"rgb\":[0,80,0],\"tol\":20},{\"x\":0.75,\"y\":0.5,\"rgb\":[4,106,4],\"tol\":20},{\"x\":0.5,\"y\":0.5,\"rgb\":[0,0,0],\"tol\":20}]" } },+ { id: "mat-model-env", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_SCENE: "/scenes/mat-model-env.esscene", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "2", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.25,\"y\":0.5,\"rgb\":[0,101,0],\"tol\":20},{\"x\":0.75,\"y\":0.5,\"rgb\":[4,106,4],\"tol\":20},{\"x\":0.5,\"y\":0.5,\"rgb\":[0,0,0],\"tol\":20}]" } },{ id: "material-builtin-lit", tier: "nightly", webgpu: true, env: { ESTELLA_VERIFY_SCENE: "/scenes/mat-builtin-lit.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/mat-builtin-lit.textures.json", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "2", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.5,\"y\":0.5,\"rgb\":[0,255,0],\"tol\":30}]" } },{ id: "material-dissolve", tier: "nightly", webgpu: true, env: { ESTELLA_VERIFY_SCENE: "/scenes/mat-dissolve.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/mat-dissolve.textures.json", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "2", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.5,\"y\":0.5,\"rgb\":[255,0,0],\"tol\":30}]" } },{ id: "material-graph", tier: "nightly", webgpu: true, env: { ESTELLA_VERIFY_SCENE: "/scenes/mat-graph.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/mat-graph.textures.json", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "2", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.5,\"y\":0.5,\"rgb\":[255,0,0],\"tol\":40}]" } },