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): what a three.js container port showed — tiled maps, the sky through walls, wet floors indoors
yhh478a0a1c0e49
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 2b11201a4..7482323ac 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -18,6 +18,15 @@ published separately; it ships inside the editor.- **A grip is edited where it is held.** Select an object with a `GripProfile` and its Details section edits the grip while a character in the scene holds it in the edit viewport, without Play: pick the character (it is given a `GripHolder`), create and pick the two palm anchors, see each palm drawn where it goes, switch the leading hand, and change every finger joint by joint in degrees, starting from a grip pose. Anchors are placed once and mirrored in the object's own plane for the other hand (`GripProfile.hand`, `mirror`); fingers said joint by joint (`GripFinger.bend`, `fan`, kept in `mainFingers`/`supportFingers`) are measured on the hand's own axes, so they mirror and fit any rig. The preview is the viewport's Preview FX and gives the bones back when it is turned off.+- **A material reads its maps through Tiling, Offset and Rotation.** The Model shader's `u_uvTiling`, `u_uvOffset` and `u_uvRotation` move where every map is read (colour, normal, occlusion, metal-roughness, emission), as Unity's Tiling and Offset do; Ground Blend takes them too. A glTF's `KHR_texture_transform` is imported into them, turned into the engine's V-up uv, where before it was dropped with a warning and a tiled texture set was stretched once over each mesh: a three.js port of a container port lost 224 of them. Maps of one material that disagree are all read through the first map's, and the import says so. A cut-out's shadow and depth prepass read through the same transform, so a tiled fence casts the shadow of the fence drawn.++### Fixed++- **An opaque surface no longer lets the sky through where its map's alpha is below 1.** An unblended draw wrote its base colour's alpha into the frame, and Sky Atmosphere reads a pixel's alpha as how much of it geometry covers, so wherever a texture used its alpha for something else (glTF's OPAQUE ignores it) the clouds showed through the wall. An opaque Model surface now writes 1, except a cut-out's coverage and the subsurface mark.+- **The sky no longer shows through everything when water or glass and a blended surface are both in view.** The frame keeps the opaque scene aside and puts it back around the blended draws; it was put back through the copy made for refraction, which marks its alpha 0.5, so every pixel came back half covered and the sky showed through half of the picture.+- **Ground under a roof stays dry in the reflections too.** Screen Space Reflections' Wetness and Puddles read the rain's map of what stands over each place, as the rain itself does, so a floor indoors or under an awning is no longer a wet mirror. The map is drawn only for an effect that states a reach (Rain, Snow Cover); reflections borrow it, with its reach and bias, and cost no second picture of the scene on their own.+- **A colour written among a post-process volume's uniforms is read as a colour.** It was blended as a number into NaN and the effect drew garbage (a Height Fog turned the whole scene teal); it is now used as the colour it is, with a warning that it belongs in `colors`, and any other value that is not a number is left out.+## [0.101.1] - 2026-11-10### Fixeddiff --git a/fixtures/scenes/sky-opaque-alpha.esprefab b/fixtures/scenes/sky-opaque-alpha.esprefabnew file mode 100644index 000000000..5d10b8d53--- /dev/null+++ b/fixtures/scenes/sky-opaque-alpha.esprefab@@ -0,0 +1,32 @@+{+ "version": "2",+ "name": "sky-opaque-alpha",+ "rootEntityId": "n0",+ "entities": [+ {+ "prefabEntityId": "n0",+ "name": "Quad",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {}+ },+ {+ "type": "MeshRenderer",+ "data": {+ "mesh": "scenes/normalmap-quad.esmesh",+ "lit": true,+ "material": "scenes/sky-opaque-alpha_m0.esmaterial",+ "color": { "r": 0.8, "g": 0.2, "b": 0.2, "a": 0.5 },+ "opaque": true,+ "cullBackfaces": false,+ "enabled": true+ }+ }+ ]+ }+ ]+}diff --git a/fixtures/scenes/sky-opaque-alpha.esscene b/fixtures/scenes/sky-opaque-alpha.esscenenew file mode 100644index 000000000..999f81ead--- /dev/null+++ b/fixtures/scenes/sky-opaque-alpha.esscene@@ -0,0 +1,31 @@+{+ "version": 4,+ "name": "SkyOpaqueAlpha",+ "entities": [+ {+ "id": 0,+ "name": "Camera",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ { "type": "Transform", "data": { "position": { "x": 0, "y": 0, "z": 600 } } },+ { "type": "Camera", "data": { "projectionType": 0, "fov": 60, "nearPlane": 0.1, "farPlane": 5000, "isActive": true, "priority": 0 } },+ { "type": "PostProcessVolume", "data": { "isGlobal": true, "priority": 0, "weight": 1, "effects": [+ { "type": "skyAtmosphere", "enabled": true, "uniforms": { "u_clouds": 0 } }+ ] } }+ ]+ },+ {+ "id": 1,+ "name": "Sun",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ { "type": "Transform", "data": { "position": { "x": 0, "y": 0, "z": 0 }, "rotation": { "w": 0.9659, "x": -0.2588, "y": 0, "z": 0 } } },+ { "type": "Light", "data": { "type": 1, "color": { "r": 1, "g": 1, "b": 1, "a": 1 }, "intensity": 1 } }+ ]+ }+ ]+}diff --git a/fixtures/scenes/sky-opaque-alpha_m0.esmaterial b/fixtures/scenes/sky-opaque-alpha_m0.esmaterialnew file mode 100644index 000000000..2a86d9bcd--- /dev/null+++ b/fixtures/scenes/sky-opaque-alpha_m0.esmaterial@@ -0,0 +1,13 @@+{+ "version": "1.0",+ "type": "material",+ "shader": "builtin:model",+ "blendMode": 9,+ "depthTest": true,+ "depthWrite": true,+ "cull": 0,+ "properties": {+ "u_metallic": 0,+ "u_roughness": 1+ }+}diff --git a/fixtures/scenes/sky-restore-alpha.esscene b/fixtures/scenes/sky-restore-alpha.esscenenew file mode 100644index 000000000..0992e91f8--- /dev/null+++ b/fixtures/scenes/sky-restore-alpha.esscene@@ -0,0 +1,172 @@+{+ "version": 4,+ "name": "SkyRestoreAlpha",+ "entities": [+ {+ "id": 0,+ "name": "Camera",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 0,+ "y": 0,+ "z": 600+ }+ }+ },+ {+ "type": "Camera",+ "data": {+ "projectionType": 0,+ "fov": 60,+ "nearPlane": 0.1,+ "farPlane": 5000,+ "isActive": true,+ "priority": 0+ }+ },+ {+ "type": "PostProcessVolume",+ "data": {+ "isGlobal": true,+ "priority": 0,+ "weight": 1,+ "effects": [+ {+ "type": "skyAtmosphere",+ "enabled": true,+ "uniforms": {+ "u_clouds": 0+ }+ }+ ]+ }+ }+ ]+ },+ {+ "id": 1,+ "name": "Sun",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 0,+ "y": 0,+ "z": 0+ },+ "rotation": {+ "w": 0.9659,+ "x": -0.2588,+ "y": 0,+ "z": 0+ }+ }+ },+ {+ "type": "Light",+ "data": {+ "type": 1,+ "color": {+ "r": 1,+ "g": 1,+ "b": 1,+ "a": 1+ },+ "intensity": 1+ }+ }+ ]+ },+ {+ "id": 2,+ "name": "Glass",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": -160,+ "y": -260,+ "z": 0+ },+ "scale": {+ "x": 0.3,+ "y": 0.3,+ "z": 1+ }+ }+ },+ {+ "type": "MeshRenderer",+ "data": {+ "mesh": "/scenes/normalmap-quad.esmesh",+ "lit": true,+ "color": {+ "r": 0.2,+ "g": 0.4,+ "b": 0.9,+ "a": 1+ },+ "opaque": false,+ "cullBackfaces": false,+ "enabled": true,+ "material": "/scenes/sky-restore-glass_m0.esmaterial"+ }+ }+ ]+ },+ {+ "id": 3,+ "name": "Pane",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 160,+ "y": -260,+ "z": 0+ },+ "scale": {+ "x": 0.3,+ "y": 0.3,+ "z": 1+ }+ }+ },+ {+ "type": "MeshRenderer",+ "data": {+ "mesh": "/scenes/normalmap-quad.esmesh",+ "lit": true,+ "color": {+ "r": 0.2,+ "g": 0.4,+ "b": 0.9,+ "a": 0.5+ },+ "opaque": false,+ "cullBackfaces": false,+ "enabled": true+ }+ }+ ]+ }+ ]+}\ No newline at end of filediff --git a/fixtures/scenes/sky-restore-glass_m0.esmaterial b/fixtures/scenes/sky-restore-glass_m0.esmaterialnew file mode 100644index 000000000..88e978ce1--- /dev/null+++ b/fixtures/scenes/sky-restore-glass_m0.esmaterial@@ -0,0 +1,14 @@+{+ "version": "1.0",+ "type": "material",+ "shader": "builtin:model",+ "blendMode": 0,+ "depthTest": true,+ "depthWrite": false,+ "cull": 0,+ "properties": {+ "u_metallic": 0,+ "u_roughness": 0.2,+ "u_transmission": 1+ }+}diff --git a/fixtures/scenes/ssr-shelter-floor_m0.esmaterial b/fixtures/scenes/ssr-shelter-floor_m0.esmaterialnew file mode 100644index 000000000..3c4d6b36f--- /dev/null+++ b/fixtures/scenes/ssr-shelter-floor_m0.esmaterial@@ -0,0 +1,13 @@+{+ "version": "1.0",+ "type": "material",+ "shader": "builtin:model",+ "blendMode": 9,+ "depthTest": true,+ "depthWrite": true,+ "cull": 0,+ "properties": {+ "u_metallic": 1,+ "u_roughness": 0.8+ }+}\ No newline at end of filediff --git a/fixtures/scenes/ssr-shelter.esscene b/fixtures/scenes/ssr-shelter.esscenenew file mode 100644index 000000000..1d9c2b601--- /dev/null+++ b/fixtures/scenes/ssr-shelter.esscene@@ -0,0 +1,248 @@+{+ "version": 4,+ "name": "SsrShelter",+ "entities": [+ {+ "id": 0,+ "name": "Camera",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 0,+ "y": 300,+ "z": 500+ },+ "rotation": {+ "w": 0.9732489894677302,+ "x": -0.22975292054736118,+ "y": 0,+ "z": 0+ }+ }+ },+ {+ "type": "Camera",+ "data": {+ "projectionType": 0,+ "fov": 60,+ "nearPlane": 1,+ "farPlane": 5000,+ "isActive": true,+ "priority": 0+ }+ },+ {+ "type": "PostProcessVolume",+ "data": {+ "isGlobal": true,+ "priority": 0,+ "weight": 1,+ "effects": [+ {+ "type": "rain",+ "enabled": true,+ "uniforms": {+ "u_intensity": 0,+ "u_wetness": 0,+ "u_puddles": 0+ }+ },+ {+ "type": "ssr",+ "enabled": true,+ "uniforms": {+ "u_intensity": 1,+ "u_wetness": 1,+ "u_puddles": 0,+ "u_skyReflection": 0+ }+ }+ ]+ }+ }+ ]+ },+ {+ "id": 1,+ "name": "Sun",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 0,+ "y": 0,+ "z": 0+ },+ "rotation": {+ "w": 0.8646239550683974,+ "x": -0.476200656600911,+ "y": -0.14030915235402952,+ "z": -0.07727672832384176+ }+ }+ },+ {+ "type": "Light",+ "data": {+ "type": 1,+ "color": {+ "r": 1,+ "g": 1,+ "b": 1,+ "a": 1+ },+ "intensity": 1+ }+ }+ ]+ },+ {+ "id": 2,+ "name": "Floor",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 0,+ "y": 0,+ "z": 0+ },+ "rotation": {+ "w": 0.7071067811865476,+ "x": -0.7071067811865475,+ "y": 0,+ "z": 0+ },+ "scale": {+ "x": 4,+ "y": 4,+ "z": 1+ }+ }+ },+ {+ "type": "MeshRenderer",+ "data": {+ "mesh": "/scenes/normalmap-quad.esmesh",+ "lit": true,+ "opaque": true,+ "cullBackfaces": false,+ "enabled": true,+ "material": "/scenes/ssr-shelter-floor_m0.esmaterial",+ "color": {+ "r": 0.5,+ "g": 0.5,+ "b": 0.5,+ "a": 1+ }+ }+ }+ ]+ },+ {+ "id": 3,+ "name": "Wall",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 0,+ "y": 150,+ "z": -300+ },+ "rotation": {+ "w": 1,+ "x": 0,+ "y": 0,+ "z": 0+ },+ "scale": {+ "x": 4,+ "y": 1.5,+ "z": 1+ }+ }+ },+ {+ "type": "MeshRenderer",+ "data": {+ "mesh": "/scenes/normalmap-quad.esmesh",+ "lit": false,+ "opaque": true,+ "cullBackfaces": false,+ "enabled": true,+ "color": {+ "r": 1,+ "g": 0.1,+ "b": 0.1,+ "a": 1+ }+ }+ }+ ]+ },+ {+ "id": 4,+ "name": "Roof",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": -300,+ "y": 700,+ "z": 100+ },+ "rotation": {+ "w": 0.7071067811865476,+ "x": -0.7071067811865475,+ "y": 0,+ "z": 0+ },+ "scale": {+ "x": 2,+ "y": 3,+ "z": 1+ }+ }+ },+ {+ "type": "MeshRenderer",+ "data": {+ "mesh": "/scenes/normalmap-quad.esmesh",+ "lit": true,+ "opaque": true,+ "cullBackfaces": false,+ "enabled": true,+ "color": {+ "r": 0.3,+ "g": 0.3,+ "b": 0.3,+ "a": 1+ }+ }+ }+ ]+ }+ ]+}\ No newline at end of filediff --git a/pipeline/src/assets/gltfImport.ts b/pipeline/src/assets/gltfImport.tsindex bfc43acdf..b6dd0e477 100644--- a/pipeline/src/assets/gltfImport.ts+++ b/pipeline/src/assets/gltfImport.ts@@ -43,7 +43,7 @@ interface GltfTextureRef {index: number; texCoord?: number;/** How much of an occlusionTexture's shadowing applies (occlusionTextureInfo only). */strength?: number;- /** KHR_texture_transform and friends: a uv rewrite this importer does not do. */+ /** KHR_texture_transform (read per material, see uvTransformOf) and any extension this importer does not read. */extensions?: Record<string, unknown>;}@@ -525,14 +525,8 @@ function readTexture(ctx: MaterialContext, cache: Map<number, ImportedImageRef |ctx.warnings.push(`${label}: samples TEXCOORD_${texCoord}; materials read the first set, so it will sample UV0`);}for (const name of Object.keys(ref.extensions ?? {})) {- // Exporters also emit this extension when it only selects UV0. Nothing- // is lost in that case; warn only when the source needs a UV rewrite.- if (name === 'KHR_texture_transform' && transform- && (transform.rotation ?? 0) === 0- && (transform.offset === undefined || (transform.offset.length === 2- && transform.offset[0] === 0 && transform.offset[1] === 0))- && (transform.scale === undefined || (transform.scale.length === 2- && transform.scale[0] === 1 && transform.scale[1] === 1))) continue;+ // The transform is the MATERIAL's to carry (one per material, see uvTransformOf), not the image's.+ if (name === 'KHR_texture_transform') continue;ctx.warnings.push(`${label}: ${name} not imported (uvs are used as authored)`);}const cached = cache.get(ref.index);@@ -583,6 +577,53 @@ function readTexture(ctx: MaterialContext, cache: Map<number, ImportedImageRef |* One glTF material, read into the two things that can hold it (@ref* materialProducts).*/+type UvTransform = NonNullable<ImportedMaterial['uvTransform']>;++/** One texture slot's KHR_texture_transform as the Model shader's Tiling, Offset and Rotation; identity when it has none. */+function slotTransform(ref: GltfTextureRef): UvTransform {+ const t = ref.extensions?.KHR_texture_transform as { offset?: unknown; scale?: unknown; rotation?: unknown } | undefined;+ const pair = (v: unknown, d: number): [number, number] => Array.isArray(v) && v.length === 2+ && v.every(x => typeof x === 'number' && Number.isFinite(x)) ? [v[0], v[1]] : [d, d];+ return {+ tiling: pair(t?.scale, 1),+ offset: pair(t?.offset, 0),+ rotation: typeof t?.rotation === 'number' && Number.isFinite(t.rotation) ? t.rotation : 0,+ };+}++const sameTransform = (a: UvTransform, b: UvTransform): boolean =>+ a.tiling[0] === b.tiling[0] && a.tiling[1] === b.tiling[1] && a.offset[0] === b.offset[0] && a.offset[1] === b.offset[1]+ && a.rotation === b.rotation;++/**+ * The transform a material's maps are read through. glTF lets each slot have its own; the Model shader has one for all of+ * them, which is what every exporter that writes the extension does in practice (three.js, Blender: a tiled texture set).+ * Maps that disagree keep the base colour's (or the first map's) and say so — the others will read where it does.+ */+function uvTransformOf(refs: (GltfTextureRef | undefined)[], label: string, warnings: string[]): UvTransform | undefined {+ const present = refs.filter((r): r is GltfTextureRef => !!r);+ if (present.length === 0) return undefined;+ const chosen = slotTransform(present[0]);+ if (present.some(r => !sameTransform(slotTransform(r), chosen))) {+ warnings.push(`${label}: its maps have different KHR_texture_transform; all are read through the first map's`);+ }+ const identity = sameTransform(chosen, { tiling: [1, 1], offset: [0, 0], rotation: 0 });+ return identity ? undefined : toEngineUv(chosen);+}++/**+ * glTF's transform, which acts on its own uv (origin at the image's top-left), as the same transform on the engine's+ * (V flipped on import, see readUvs). With F(v) = (v.x, 1 - v.y) the read point is F(O + R(θ)·S·F(u)): the tiling is+ * unchanged, the turn runs the other way, and the offset picks up where the flipped origin lands.+ */+function toEngineUv(t: UvTransform): UvTransform {+ const [ox, oy] = t.offset, [, sy] = t.tiling;+ const c = Math.cos(t.rotation), s = Math.sin(t.rotation);+ const offset: [number, number] = [ox + s * sy, 1 - oy - c * sy];+ return { tiling: [t.tiling[0], t.tiling[1]], offset: offset.map(v => Math.abs(v) < 1e-12 ? 0 : v) as [number, number],+ rotation: t.rotation === 0 ? 0 : -t.rotation };+}+function readMaterial(ctx: MaterialContext, textureCache: Map<number, ImportedImageRef | null>,index: number): ImportedMaterial {const src = ctx.json.materials?.[index] ?? {};@@ -612,6 +653,15 @@ function readMaterial(ctx: MaterialContext, textureCache: Map<number, ImportedImconst texture = colorTexture ? readTexture(ctx, textureCache, colorTexture, label) : null;// PBR properties are only fallbacks on an unlit material. Reading them as// shading would change the authored style and upload textures never sampled.+ if (src.extensions?.KHR_materials_unlit !== undefined) {+ if (colorTexture && uvTransformOf([colorTexture], label, ctx.warnings)) {+ ctx.warnings.push(`${label}: KHR_texture_transform not imported on an unlit material (uvs are used as authored)`);+ }+ }+ const uvTransform = src.extensions?.KHR_materials_unlit !== undefined ? undefined : uvTransformOf([+ colorTexture, src.normalTexture, src.occlusionTexture, src.emissiveTexture,+ specGloss ? specGloss.specularGlossinessTexture : pbr.metallicRoughnessTexture,+ ], label, ctx.warnings);if (src.extensions?.KHR_materials_unlit !== undefined) return {index, name: src.name ?? `material_${index}`, unlit: true,...((src.extras as any)?.estella?.blendMode === 1 ? { blendMode: 1 } : {}),@@ -684,6 +734,7 @@ function readMaterial(ctx: MaterialContext, textureCache: Map<number, ImportedIm...(specGlossMap ? { specularGlossinessTexture: specGlossMap } : {}),} : { metallic, roughness, ...(metalRoughMap ? { metallicRoughnessTexture: metalRoughMap } : {}) }),...(src.alphaMode === 'MASK' ? { alphaCutoff: src.alphaCutoff ?? 0.5 } : {}),+ ...(uvTransform ? { uvTransform } : {}),...(flow ? { flowTexture: flow } : {}),...(shift ? { shiftTexture: shift } : {}),...(typeof tipSoftness === 'number' && tipSoftness >= 0 ? { tipSoftness } : {}),diff --git a/pipeline/src/assets/modelImport.ts b/pipeline/src/assets/modelImport.tsindex 21b3b8a2c..a830ac361 100644--- a/pipeline/src/assets/modelImport.ts+++ b/pipeline/src/assets/modelImport.ts@@ -90,6 +90,10 @@ export interface ImportedMaterial {/** How far in from the cutoff a hair card's edge fades (`extras.suggested_tipSoftness`). */tipSoftness?: number;occlusionStrength?: number;+ /** Where every map is read: the UV scaled, turned (radians) and moved — glTF's KHR_texture_transform, the Model shader's+ * Tiling, Offset and Rotation — in the ENGINE's uv (V up), not the source's. Absent when the maps are read where the+ * mesh's UVs say. */+ uvTransform?: { tiling: [number, number]; offset: [number, number]; rotation: number };/** How metal and how rough the surface is, as constants. */metallic?: number;roughness?: number;@@ -642,7 +646,7 @@ const MATERIAL_LAYER_PROPERTIES: readonly [keyof ImportedMaterial, string][] = [function needsMaterial(material: ImportedMaterial | undefined): material is ImportedMaterial {return !!material && !!(material.unlit || material.normalTexture || material.emissive || material.emissiveTexture|| material.occlusionTexture || material.alphaCutoff || material.metallicRoughnessTexture || material.specularGlossiness- || (material.normalScale ?? 1) !== 1+ || (material.normalScale ?? 1) !== 1 || material.uvTransform|| (material.metallic ?? 0) !== 0 || (material.roughness ?? 1) !== 1|| MATERIAL_LAYER_PROPERTIES.some(([field]) => material[field] !== undefined));}@@ -890,6 +894,12 @@ export function materialProducts(meshes: ImportedMesh[], stem: string,properties.u_occlusionStrength = material.occlusionStrength;}if (material.alphaCutoff !== undefined) properties.u_alphaCutoff = material.alphaCutoff;+ if (material.uvTransform && !shading) {+ const { tiling, offset, rotation } = material.uvTransform;+ properties.u_uvTiling = { x: tiling[0], y: tiling[1] };+ properties.u_uvOffset = { x: offset[0], y: offset[1] };+ if (rotation !== 0) properties.u_uvRotation = rotation;+ }if (shading) characterProperties(shading, material, properties, bind);else for (const [field, parameter] of MATERIAL_LAYER_PROPERTIES) {const value = material[field];diff --git a/pipeline/tests/gltf-import.test.ts b/pipeline/tests/gltf-import.test.tsindex 8411f0fca..39e7c7c57 100644--- a/pipeline/tests/gltf-import.test.ts+++ b/pipeline/tests/gltf-import.test.ts@@ -400,12 +400,45 @@ describe('glTF material import', () => {expect(warnings.join('\n')).toContain('a skin naming joints');});- it('reports a uv rewrite it does not apply', async () => {+ it("carries a uv transform to the material, in the engine's flipped uv", async () => {const doc = withInlineImage();(doc.materials as { pbrMetallicRoughness: { baseColorTexture: Record<string, unknown> } }[])[0]!- .pbrMetallicRoughness.baseColorTexture.extensions = { KHR_texture_transform: { scale: [2, 2] } };- const { warnings } = await importGltfMeshes(gltf(doc), 'model');- expect(warnings.join('\n')).toContain('KHR_texture_transform not imported');+ .pbrMetallicRoughness.baseColorTexture.extensions = { KHR_texture_transform: { scale: [2, 3], offset: [0.25, 0.5] } };+ const { meshes, warnings } = await importGltfMeshes(gltf(doc), 'model');+ expect(warnings).toEqual([]);+ // glTF reads (0.25 + 2u, 0.5 + 3v) of its own uv; with v' = 1 - v that is 1 - (0.5 + 3(1 - v')) = -2.5 + 3v'.+ expect(meshes[0]!.material!.uvTransform).toEqual({ tiling: [2, 3], offset: [0.25, -2.5], rotation: 0 });+ // The mesh's own uvs are left as authored: the material moves where they are read.+ expect(texCoords(meshes[0]!)).toEqual([0, 1, 1, 1, 0, 0]);+ });++ it('turns a rotated transform the other way, about the flipped origin', async () => {+ const doc = withInlineImage();+ (doc.materials as { pbrMetallicRoughness: { baseColorTexture: Record<string, unknown> } }[])[0]!+ .pbrMetallicRoughness.baseColorTexture.extensions = { KHR_texture_transform: { rotation: Math.PI / 2 } };+ const { meshes } = await importGltfMeshes(gltf(doc), 'model');+ const t = meshes[0]!.material!.uvTransform!;+ expect(t.rotation).toBeCloseTo(-Math.PI / 2);+ // glTF turns its uv (x, 1 - y) to (1 - y, -x); flipped back, the engine reads (1 - y, 1 + x).+ const at = (x: number, y: number): [number, number] => {+ const c = Math.cos(t.rotation), s = Math.sin(t.rotation);+ return [c * x + s * y + t.offset[0], -s * x + c * y + t.offset[1]];+ };+ for (const [x, y] of [[0, 0], [0.3, 0.7], [1, 0.2]] as const) {+ const [ex, ey] = at(x, y);+ expect(ex).toBeCloseTo(1 - y);+ expect(ey).toBeCloseTo(1 + x);+ }+ });++ it('reads every map through the first one when their transforms disagree, and says so', async () => {+ const doc = withInlineImage();+ const material = (doc.materials as Record<string, any>[])[0]!;+ material.pbrMetallicRoughness.baseColorTexture.extensions = { KHR_texture_transform: { scale: [4, 4] } };+ material.normalTexture = { index: 0 };+ const { meshes, warnings } = await importGltfMeshes(gltf(doc), 'model');+ expect(meshes[0]!.material!.uvTransform?.tiling).toEqual([4, 4]);+ expect(warnings.join('\n')).toContain('different KHR_texture_transform');});it.each([{}, { texCoord: 0 }, { offset: [0, 0], scale: [1, 1], rotation: 0 }])@@ -476,6 +509,15 @@ describe('glTF material products', () => {});});+ it('writes a tiled texture set as the Model shader\'s Tiling and Offset, which alone needs a material', async () => {+ const { products } = await productsOf(shaded({+ pbrMetallicRoughness: { baseColorTexture: { index: 0, extensions: { KHR_texture_transform: { scale: [0.5, 0.5] } } } },+ }));+ expect(products).toHaveLength(1);+ expect(products[0]!.data.properties).toMatchObject({ u_uvTiling: { x: 0.5, y: 0.5 }, u_uvOffset: { x: 0, y: 0.5 } });+ expect(products[0]!.data.properties).not.toHaveProperty('u_uvRotation');+ });+it('takes the normal map WITH it, off the component', async () => {// A material shader samples its own units; a map left on the component// would be one nothing reads.diff --git a/sdk/src/postprocess/sources/lighting.ts b/sdk/src/postprocess/sources/lighting.tsindex 8b438ca16..1cca729d3 100644--- a/sdk/src/postprocess/sources/lighting.ts+++ b/sdk/src/postprocess/sources/lighting.ts@@ -274,6 +274,14 @@ fn project(P : vec3f) -> vec3f {#pragma param u_envTint color default(0,0,0,0)#pragma param u_reflParams color default(1,0,0,0)#pragma param u_environment texture default(black)+#pragma param u_coverActive float default(0) range(0,1)+#pragma param u_coverRange float default(3000) range(10,30000)+#pragma param u_coverBias float default(40) range(0,500)+#pragma param u_coverMatrix0 color default(1,0,0,0)+#pragma param u_coverMatrix1 color default(0,1,0,0)+#pragma param u_coverMatrix2 color default(0,0,1,0)+#pragma param u_coverMatrix3 color default(0,0,0,1)+#pragma param u_rainCover texture default(white)#pragma gbuffer#pragma fragment@@ -292,6 +300,19 @@ ${GBUFFER_GLSL}${ENV_GLSL}${GLSL}+/// 1 under a roof, an awning, a tree — the rain's own map of what stands over each place (see the Rain effect) — and 0 in the+/// open. The ground there is as dry as the rain left it: no film of water, no pools. Without a Rain effect there is no map, and+/// everything is open. The reach and the bias are the Rain effect's, handed over with its map.+float coveredAt(vec3 W) {+ if (u_coverActive < 0.5) return 0.0;+ vec4 c = mat4(u_coverMatrix0, u_coverMatrix1, u_coverMatrix2, u_coverMatrix3) * vec4(W, 1.0);+ vec2 uv = c.xy / c.w * 0.5 + 0.5;+ if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0) return 0.0;+ float stored = dot(texture(u_rainCover, uv).rgb, vec3(1.0, 1.0 / 255.0, 1.0 / 65025.0));+ float here = clamp(c.z / c.w * 0.5 + 0.5, 0.0, 1.0);+ return stored < here - u_coverBias / (4.0 * u_coverRange) ? 1.0 : 0.0;+}+void main() {vec4 scene = texture(u_texture, v_texCoord);ivec2 size = textureSize(u_sceneDepth, 0);@@ -329,13 +350,15 @@ void main() {// Standing water is flat and mirror-like whatever the ground under it is: its normal is// straight up, and a still surface reflects far more than the 4% a dry one does.float flatUp = smoothstep(0.86, 0.95, N.y);+ // Wet and pooled only where the rain reaches.+ float wetUp = (u_puddles > 0.0 || u_wetness > 0.0) ? flatUp * (1.0 - coveredAt(P)) : 0.0;float puddle = 0.0;if (u_puddles > 0.0) {- puddle = puddleMask(P.xz, basinCoverage(c, size, P, u_puddles, u_puddleScale), u_puddleScale) * flatUp;+ puddle = puddleMask(P.xz, basinCoverage(c, size, P, u_puddles, u_puddleScale), u_puddleScale) * wetUp;N = normalize(mix(N, vec3(0.0, 1.0, 0.0), puddle));}// Wet ground is smoother than dry: a film of water fills the pores a rough surface scatters from.- rough = mix(rough, rough * 0.35, u_wetness * flatUp);+ rough = mix(rough, rough * 0.35, u_wetness * wetUp);rough = mix(rough, 0.04, puddle);// Too rough to show anything: skipped before the march, which is the whole cost.if (rough > u_maxRoughness) { fragColor = scene; return; }@@ -427,6 +450,19 @@ ${GBUFFER_WGSL}${ENV_WGSL}${WGSL}+fn coveredAt(W : vec3f) -> f32 {+ if (mc.u_coverActive < 0.5) { return 0.0; }+ let m = mat4x4f(mc.u_coverMatrix0, mc.u_coverMatrix1, mc.u_coverMatrix2, mc.u_coverMatrix3);+ let c = m * vec4f(W, 1.0);+ let uv = c.xy / c.w * 0.5 + 0.5;+ if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0) { return 0.0; }+ // This device's texture rows run the other way from the clip space the map was drawn in.+ let stored = dot(textureSampleLevel(u_rainCover, u_rainCover_s, vec2f(uv.x, 1.0 - uv.y), 0.0).rgb,+ vec3f(1.0, 1.0 / 255.0, 1.0 / 65025.0));+ let here = clamp(c.z / c.w * 0.5 + 0.5, 0.0, 1.0);+ return select(0.0, 1.0, stored < here - mc.u_coverBias / (4.0 * mc.u_coverRange));+}+@fragment fn fs_main(v : VSOut) -> @location(0) vec4f {let scene = textureSampleLevel(t0, s0, v.v_texCoord, 0.0);let size = vec2i(textureDimensions(t7, 0));@@ -457,12 +493,14 @@ ${WGSL}let metal = sf.metallic;let flatUp = smoothstep(0.86, 0.95, N.y);+ var wetUp = 0.0;+ if (mc.u_puddles > 0.0 || mc.u_wetness > 0.0) { wetUp = flatUp * (1.0 - coveredAt(P)); }var puddle = 0.0;if (mc.u_puddles > 0.0) {- puddle = puddleMask(P.xz, basinCoverage(c, size, P, mc.u_puddles, mc.u_puddleScale), mc.u_puddleScale) * flatUp;+ puddle = puddleMask(P.xz, basinCoverage(c, size, P, mc.u_puddles, mc.u_puddleScale), mc.u_puddleScale) * wetUp;N = normalize(mix(N, vec3f(0.0, 1.0, 0.0), puddle));}- rough = mix(rough, rough * 0.35, mc.u_wetness * flatUp);+ rough = mix(rough, rough * 0.35, mc.u_wetness * wetUp);rough = mix(rough, 0.04, puddle);if (rough > mc.u_maxRoughness) { return scene; }diff --git a/sdk/src/render/builtinShaders.ts b/sdk/src/render/builtinShaders.tsindex c9388d75a..e786ee4f6 100644--- a/sdk/src/render/builtinShaders.ts+++ b/sdk/src/render/builtinShaders.ts@@ -465,6 +465,10 @@ export const MODEL = `#pragma shader "Model"#pragma domain Lit#pragma switch ES_SPECULAR_GLOSSINESS#pragma param u_tint color default(1,1,1,1)+// Where every map is read: the mesh's UV scaled, then turned, then moved (glTF's KHR_texture_transform, Unity's Tiling and Offset).+#pragma param u_uvTiling vec2 default(1,1)+#pragma param u_uvOffset vec2 default(0,0)+#pragma param u_uvRotation float default(0) range(-3.1416,3.1416) ui(slider)#pragma param u_normalMap texture default(flatnormal) texel(data)#pragma param u_normalScale float default(1) range(-4,4) ui(slider)#pragma param u_emissive color default(0,0,0,1)@@ -567,7 +571,13 @@ void main() {highp vec3 dndx = dFdx(v_worldNormal);highp vec3 dndy = dFdy(v_worldNormal);#endif- vec4 base = texture(u_textures[0], v_texCoord) * v_color * u_tint;+ highp vec2 uv = v_texCoord * u_uvTiling;+ if (u_uvRotation != 0.0) {+ float c = cos(u_uvRotation), sn = sin(u_uvRotation);+ uv = vec2(c * uv.x + sn * uv.y, -sn * uv.x + c * uv.y);+ }+ uv += u_uvOffset;+ vec4 base = texture(u_textures[0], uv) * v_color * u_tint;// 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) {@@ -577,15 +587,15 @@ void main() {}#ifdef MESH_NORMALShighp vec3 Ng = normalize(v_worldNormal);- highp vec3 N = perturbNormal(Ng, v_worldXYZ, v_texCoord,- scaleNormal(sampleNormal(u_normalMap, v_texCoord), u_normalScale));+ highp vec3 N = perturbNormal(Ng, v_worldXYZ, uv,+ scaleNormal(sampleNormal(u_normalMap, uv), u_normalScale));// A double-sided surface is lit from the side it is seen from (glTF's rule).if (!gl_FrontFacing) { N = -N; Ng = -Ng; }#else- vec3 N = scaleNormal(sampleNormal(u_normalMap, v_texCoord), u_normalScale);+ vec3 N = scaleNormal(sampleNormal(u_normalMap, uv), u_normalScale);#endif- float ao = mix(1.0, texture(u_occlusionMap, v_texCoord).r, u_occlusionStrength);- vec4 mr = texture(u_metallicRoughnessMap, v_texCoord);+ float ao = mix(1.0, texture(u_occlusionMap, uv).r, u_occlusionStrength);+ vec4 mr = texture(u_metallicRoughnessMap, uv);#ifdef MESH_NORMALS// The surface's OWN place, which a point light, a probe volume and a// reflection's box projection all measure against; z = 0 is a plane's answer.@@ -618,7 +628,7 @@ void main() {}if (u_anisotropy != 0.0) {// The direction the grooves run, from the UV frame turned by the rotation, then made to lie across N.- highp vec3 T = perturbNormal(Ng, P, v_texCoord, vec3(cos(u_anisotropyRotation), sin(u_anisotropyRotation), 0.0));+ highp vec3 T = perturbNormal(Ng, P, uv, vec3(cos(u_anisotropyRotation), sin(u_anisotropyRotation), 0.0));T -= N * dot(N, T);if (dot(T, T) < 1e-6) T = cross(N, abs(N.y) < 0.99 ? vec3(0.0, 1.0, 0.0) : vec3(1.0, 0.0, 0.0));ext.aniso = vec4(normalize(T), clamp(u_anisotropy, -0.99, 0.99));@@ -643,13 +653,13 @@ void main() {vec3 bent = refract(-viewDir, N, 1.0 / max(u_ior, 1.0));float depth = max(u_thickness, 0.15) * 60.0 * u_refractionStrength;vec4 landed = u_projection * vec4(P + bent * depth, 1.0);- vec2 uv = landed.xy / max(landed.w, 1e-4) * 0.5 + 0.5;+ vec2 screenUv = landed.xy / max(landed.w, 1e-4) * 0.5 + 0.5;float spread = roughness * roughness * 0.04;- vec3 behind = texture(u_sceneColor, clamp(uv, vec2(0.001), vec2(0.999))).rgb;+ vec3 behind = texture(u_sceneColor, clamp(screenUv, vec2(0.001), vec2(0.999))).rgb;for (int i = 0; i < 8; ++i) {float a = float(i) * 2.39996;vec2 o = vec2(cos(a), sin(a)) * (spread * sqrt((float(i) + 0.5) / 8.0));- behind += texture(u_sceneColor, clamp(uv + o, vec2(0.001), vec2(0.999))).rgb;+ behind += texture(u_sceneColor, clamp(screenUv + o, vec2(0.001), vec2(0.999))).rgb;}seen = behind / 9.0 * u_attenuationColor.rgb * (1.0 - fresnel) * u_transmission;refracted = 1.0;@@ -667,9 +677,15 @@ void main() {vec3 diffuse = base.rgb * (1.0 - clamp(metallic, 0.0, 1.0));vec3 lit = applyLightingSurface(base.rgb * (1.0 - u_transmission * refracted), N, P, viewDir,metallic, roughness, u_specular, ao, ext);+#endif+#ifdef ES_OPAQUE+ // Drawn unblended, so this alpha lands in the frame as it is, where the sky reads it as how much of the pixel is covered.+ // glTF's OPAQUE ignores the base colour's alpha (a map's alpha is often a mask for something else): only a cut-out's+ // coverage and the subsurface mark below say anything here.+ if (u_alphaCutoff <= 0.0) alpha = 1.0;#endifif (u_subsurface > 0.0 && u_alphaCutoff <= 0.0) alpha = min(alpha, 0.996);- fragColor = vec4(lit + seen + u_emissive.rgb * texture(u_emissiveMap, v_texCoord).rgb, alpha);+ fragColor = vec4(lit + seen + u_emissive.rgb * texture(u_emissiveMap, uv).rgb, alpha);#ifdef ES_GBUFFER// Alpha says something was drawn here (0 is "nothing wrote"), and carries the metalness above 0.75: a pixel that// multisampling averaged with an unwritten one falls below it, and an effect can tell such an edge from a surface.@@ -709,8 +725,15 @@ fn packNormal(n : vec3f) -> vec2f {@fragment fn fs_main(v : VSOut, @builtin(front_facing) front : bool) -> @location(0) vec4f {#endif// Taken before any branch: a derivative needs every fragment of its quad.- let duvx = dpdx(v.v_texCoord);- let duvy = dpdy(v.v_texCoord);+ var uv = v.v_texCoord * mc.u_uvTiling;+ if (mc.u_uvRotation != 0.0) {+ let c = cos(mc.u_uvRotation);+ let sn = sin(mc.u_uvRotation);+ uv = vec2f(c * uv.x + sn * uv.y, -sn * uv.x + c * uv.y);+ }+ uv += mc.u_uvOffset;+ let duvx = dpdx(uv);+ let duvy = dpdy(uv);#ifdef MESH_NORMALSlet dndx = dpdx(v.v_worldNormal);let dndy = dpdy(v.v_worldNormal);@@ -725,7 +748,7 @@ fn packNormal(n : vec3f) -> vec2f {#ifdef MESH_TANGENTSg_worldTangent = v.v_worldTangent;#endif- var base = textureSampleGrad(t0, s0, v.v_texCoord, duvx, duvy) * v.v_color * mc.u_tint;+ var base = textureSampleGrad(t0, s0, uv, 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);var alpha = base.a;@@ -736,15 +759,15 @@ fn packNormal(n : vec3f) -> vec2f {}#ifdef MESH_NORMALSvar Ng = normalize(v.v_worldNormal);- var N = perturbNormal(Ng, v.v_worldXYZ, v.v_texCoord,- scaleNormal(sampleNormalGrad(u_normalMap, u_normalMap_s, v.v_texCoord, duvx, duvy), mc.u_normalScale));+ var N = perturbNormal(Ng, v.v_worldXYZ, uv,+ scaleNormal(sampleNormalGrad(u_normalMap, u_normalMap_s, uv, duvx, duvy), mc.u_normalScale));if (!front) { N = -N; Ng = -Ng; }#else- let N = scaleNormal(sampleNormalGrad(u_normalMap, u_normalMap_s, v.v_texCoord, duvx, duvy), mc.u_normalScale);+ let N = scaleNormal(sampleNormalGrad(u_normalMap, u_normalMap_s, uv, duvx, duvy), mc.u_normalScale);#endif- let occl = textureSampleGrad(u_occlusionMap, u_occlusionMap_s, v.v_texCoord, duvx, duvy).r;+ let occl = textureSampleGrad(u_occlusionMap, u_occlusionMap_s, uv, duvx, duvy).r;let ao = mix(1.0, occl, mc.u_occlusionStrength);- let mr = textureSampleGrad(u_metallicRoughnessMap, u_metallicRoughnessMap_s, v.v_texCoord, duvx, duvy);+ let mr = textureSampleGrad(u_metallicRoughnessMap, u_metallicRoughnessMap_s, uv, duvx, duvy);#ifdef MESH_NORMALSlet P = v.v_worldXYZ;#else@@ -773,7 +796,7 @@ fn packNormal(n : vec3f) -> vec2f {ext.coatN = vec4f(Ng, 0.0);}if (mc.u_anisotropy != 0.0) {- var T = perturbNormal(Ng, P, v.v_texCoord, vec3f(cos(mc.u_anisotropyRotation), sin(mc.u_anisotropyRotation), 0.0));+ var T = perturbNormal(Ng, P, uv, vec3f(cos(mc.u_anisotropyRotation), sin(mc.u_anisotropyRotation), 0.0));T -= N * dot(N, T);if (dot(T, T) < 1e-6) {var seed = vec3f(1.0, 0.0, 0.0);@@ -801,13 +824,13 @@ fn packNormal(n : vec3f) -> vec2f {let landed = frame.projection * vec4f(P + bent * depth, 1.0);let w = max(landed.w, 1e-4);// This device's rows run down the texture, so clip y is flipped on the way to a uv.- let uv = vec2f(landed.x / w * 0.5 + 0.5, 0.5 - landed.y / w * 0.5);+ let screenUv = vec2f(landed.x / w * 0.5 + 0.5, 0.5 - landed.y / w * 0.5);let spread = roughness * roughness * 0.04;- var behind = textureSampleLevel(u_sceneColor, u_sceneColor_s, clamp(uv, vec2f(0.001), vec2f(0.999)), 0.0).rgb;+ var behind = textureSampleLevel(u_sceneColor, u_sceneColor_s, clamp(screenUv, vec2f(0.001), vec2f(0.999)), 0.0).rgb;for (var i : i32 = 0; i < 8; i = i + 1) {let a = f32(i) * 2.39996;let o = vec2f(cos(a), sin(a)) * (spread * sqrt((f32(i) + 0.5) / 8.0));- behind = behind + textureSampleLevel(u_sceneColor, u_sceneColor_s, clamp(uv + o, vec2f(0.001), vec2f(0.999)), 0.0).rgb;+ behind = behind + textureSampleLevel(u_sceneColor, u_sceneColor_s, clamp(screenUv + o, vec2f(0.001), vec2f(0.999)), 0.0).rgb;}seen = behind / 9.0 * mc.u_attenuationColor.rgb * (1.0 - fresnel) * mc.u_transmission;refracted = 1.0;@@ -823,10 +846,13 @@ fn packNormal(n : vec3f) -> vec2f {let diffuse = base.rgb * (1.0 - clamp(metallic, 0.0, 1.0));let lit = applyLightingSurface(base.rgb * (1.0 - mc.u_transmission * refracted), N, P, viewDir,metallic, roughness, mc.u_specular, ao, ext);+#endif+#ifdef ES_OPAQUE+ if (mc.u_alphaCutoff <= 0.0) { alpha = 1.0; }#endifif (mc.u_subsurface > 0.0 && mc.u_alphaCutoff <= 0.0) { alpha = min(alpha, 0.996); }let emit = mc.u_emissive.rgb- * textureSampleGrad(u_emissiveMap, u_emissiveMap_s, v.v_texCoord, duvx, duvy).rgb;+ * textureSampleGrad(u_emissiveMap, u_emissiveMap_s, uv, duvx, duvy).rgb;#ifdef ES_GBUFFERvar frag : FragOut;frag.color = vec4f(lit + seen + emit, alpha);diff --git a/sdk/src/render/groundBlendShader.ts b/sdk/src/render/groundBlendShader.tsindex 3635e138e..23627e08d 100644--- a/sdk/src/render/groundBlendShader.ts+++ b/sdk/src/render/groundBlendShader.ts@@ -78,7 +78,7 @@ const GLSL_SURFACE = ` float groundFade = 1.0;if (u_layerReach > 0.0) layerWeight = max(layerWeight, near * (1.0 - smoothstep(0.0, 1.0, above / u_layerReach + wander)));}#endif- vec4 base = texture(u_textures[0], v_texCoord) * u_tint;+ vec4 base = texture(u_textures[0], uv) * u_tint;if (u_vertexBlend <= 0.5) base *= v_color;if (layerWeight > 0.0) {#ifdef MESH_NORMALS@@ -123,7 +123,7 @@ const WGSL_SURFACE = `#ifdef MESH_NORMALSif (mc.u_layerReach > 0.0) { layerWeight = max(layerWeight, near * (1.0 - smoothstep(0.0, 1.0, above / mc.u_layerReach + wander))); }}#endif- var base = textureSampleGrad(t0, s0, v.v_texCoord, duvx, duvy) * mc.u_tint;+ var base = textureSampleGrad(t0, s0, uv, duvx, duvy) * mc.u_tint;if (mc.u_vertexBlend <= 0.5) { base = base * v.v_color; }if (layerWeight > 0.0) {#ifdef MESH_NORMALS@@ -156,12 +156,12 @@ export function deriveGroundBlend(model: string): string {s = swap(s, '#pragma param u_iridescence float', `${PARAMS}#pragma param u_iridescence float`);s = swap(s, 'float specularAA(highp vec3', `${GLSL_HELPERS}float specularAA(highp vec3`);s = swap(s, 'fn specularAA(dndx : vec3f', `${WGSL_HELPERS}fn specularAA(dndx : vec3f`);- s = swap(s, ' vec4 base = texture(u_textures[0], v_texCoord) * v_color * u_tint;\n', GLSL_SURFACE);- s = swap(s, ' var base = textureSampleGrad(t0, s0, v.v_texCoord, duvx, duvy) * v.v_color * mc.u_tint;\n', WGSL_SURFACE);+ s = swap(s, ' vec4 base = texture(u_textures[0], uv) * v_color * u_tint;\n', GLSL_SURFACE);+ s = swap(s, ' var base = textureSampleGrad(t0, s0, uv, duvx, duvy) * v.v_color * mc.u_tint;\n', WGSL_SURFACE);s = swap(s, 'float roughness = u_roughness * mr.g;', 'float roughness = mix(u_roughness * mr.g, u_layer2Roughness, layerWeight);');s = swap(s, 'var roughness = mc.u_roughness * mr.g;', 'var roughness = mix(mc.u_roughness * mr.g, mc.u_layer2Roughness, layerWeight);');- s = swap(s, 'fragColor = vec4(lit + seen + u_emissive.rgb * texture(u_emissiveMap, v_texCoord).rgb, alpha);',- 'fragColor = vec4(mix(groundBehind, lit + seen + u_emissive.rgb * texture(u_emissiveMap, v_texCoord).rgb, groundFade), alpha);');+ s = swap(s, 'fragColor = vec4(lit + seen + u_emissive.rgb * texture(u_emissiveMap, uv).rgb, alpha);',+ 'fragColor = vec4(mix(groundBehind, lit + seen + u_emissive.rgb * texture(u_emissiveMap, uv).rgb, groundFade), alpha);');s = swap(s, 'frag.color = vec4f(lit + seen + emit, alpha);', 'frag.color = vec4f(mix(groundBehind, lit + seen + emit, groundFade), alpha);');s = swap(s, 'return vec4f(lit + seen + emit, alpha);', 'return vec4f(mix(groundBehind, lit + seen + emit, groundFade), alpha);');return s;diff --git a/sdk/src/voxel/voxelShader.ts b/sdk/src/voxel/voxelShader.tsindex e5579d104..4e6c796bd 100644--- a/sdk/src/voxel/voxelShader.ts+++ b/sdk/src/voxel/voxelShader.ts@@ -84,12 +84,12 @@ export function deriveVoxelGround(model: string): string {let s = swap(model, '#pragma shader "Model"', '#pragma shader "Voxel Ground"');s = swap(s, '#pragma param u_iridescence float', `${PARAMS}#pragma param u_iridescence float`);s = swap(s, '#pragma param u_emissiveMap texture default(white)\n', '');- s = swap(s, 'texture(u_emissiveMap, v_texCoord).rgb', 'vec3(1.0)');- s = swap(s, 'textureSampleGrad(u_emissiveMap, u_emissiveMap_s, v.v_texCoord, duvx, duvy).rgb', 'vec3f(1.0)');+ s = swap(s, 'texture(u_emissiveMap, uv).rgb', 'vec3(1.0)');+ s = swap(s, 'textureSampleGrad(u_emissiveMap, u_emissiveMap_s, uv, duvx, duvy).rgb', 'vec3f(1.0)');s = swap(s, 'float specularAA(highp vec3', `${GLSL_HELPERS}float specularAA(highp vec3`);s = swap(s, 'fn specularAA(dndx : vec3f', `${WGSL_HELPERS}fn specularAA(dndx : vec3f`);- s = swap(s, ' vec4 base = texture(u_textures[0], v_texCoord) * v_color * u_tint;\n', GLSL_SURFACE);- s = swap(s, ' var base = textureSampleGrad(t0, s0, v.v_texCoord, duvx, duvy) * v.v_color * mc.u_tint;\n', WGSL_SURFACE);+ s = swap(s, ' vec4 base = texture(u_textures[0], uv) * v_color * u_tint;\n', GLSL_SURFACE);+ s = swap(s, ' var base = textureSampleGrad(t0, s0, uv, duvx, duvy) * v.v_color * mc.u_tint;\n', WGSL_SURFACE);s = swap(s, 'float roughness = u_roughness * mr.g;', 'float roughness = u_roughness * mr.g * dot(voxelMix, u_voxelRoughness);');s = swap(s, 'var roughness = mc.u_roughness * mr.g;', 'var roughness = mc.u_roughness * mr.g * dot(voxelMix, mc.u_voxelRoughness);');return s;diff --git a/src/esengine/data/shaders/blit.esshader b/src/esengine/data/shaders/blit.esshaderindex 6edd05997..4af7ca467 100644--- a/src/esengine/data/shaders/blit.esshader+++ b/src/esengine/data/shaders/blit.esshader@@ -83,6 +83,12 @@ void main() {#endif// The editor view's exposure (u_time.z, stops): zero outside the editor, where// exp2(0) = 1 leaves every pixel as it was. Before the curve, like any exposure.+#ifdef ES_COPY_EXACT+ // The picture as it is, alpha included: the opaque scene kept aside and put back around the blended draws. Its alpha is how much+ // of each pixel geometry covers (the sky reads it), so a copy that marked it would leave every pixel half covered.+ fragColor = c;+ return;+#endif#ifdef ES_COPY// A copy of the picture for a surface that looks through to it. Alpha 0.5 says "a real copy": the texture param a shader falls// back to when the frame took none is white, whose alpha is 1.@@ -175,6 +181,9 @@ fn displayLookup(c : vec3f) -> vec3f {#elsevar c = textureSampleLevel(t0, s0, v.v_texCoord, 0.0);#endif+#ifdef ES_COPY_EXACT+ return c;+#endif#ifdef ES_COPYreturn vec4f(c.rgb, 0.5);#endifdiff --git a/src/esengine/data/shaders/mesh.esshader b/src/esengine/data/shaders/mesh.esshaderindex 8deb25123..735243467 100644--- a/src/esengine/data/shaders/mesh.esshader+++ b/src/esengine/data/shaders/mesh.esshader@@ -325,6 +325,21 @@ vec2 packNormal(vec3 n) {out vec4 fragColor;#endif+// Where a material's cut-out is read: its Tiling, Offset and Rotation when it has them (ES_UV_TRANSFORM, the Model shader's), so the+// depth programs that reproduce its coverage cut where its colour pass does.+highp vec2 coverageUv() {+#ifdef ES_UV_TRANSFORM+ highp vec2 uv = v_texCoord * u_uvTiling;+ if (u_uvRotation != 0.0) {+ float c = cos(u_uvRotation), sn = sin(u_uvRotation);+ uv = vec2(c * uv.x + sn * uv.y, -sn * uv.x + c * uv.y);+ }+ return uv + u_uvOffset;+#else+ return v_texCoord;+#endif+}+void main() {#ifdef ES_VELOCITY// How far this pixel's surface moved in the picture since last frame, in uv, and the depth it sits at@@ -337,7 +352,7 @@ void main() {#ifdef PREPASS_COVERAGE// The colour pass's own: base alpha is the texture's times the draw's colour times the material's tint, in that order, and the cut is sharpened to// about a pixel. The derivative is taken before the discard, where every fragment of the quad still runs. Nothing is written but the coverage.- highp float baseAlpha = texture(u_texture, v_texCoord).a * v_color.a * u_tint.a;+ highp float baseAlpha = texture(u_texture, coverageUv()).a * v_color.a * u_tint.a;highp float coverage = (baseAlpha - u_alphaCutoff) / max(fwidth(baseAlpha), 1e-4) + 0.5;if (coverage <= 0.0) discard;fragColor = vec4(0.0, 0.0, 0.0, min(coverage, 1.0));@@ -345,7 +360,7 @@ void main() {#ifdef SHADOW_ALPHA// 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;+ if (texture(u_texture, coverageUv()).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@@ -638,6 +653,21 @@ struct VSOut {@location(6) @interpolate(flat) v_probeSlot : f32,};+// See the GLSL twin.+fn coverageUv(uv0 : vec2f) -> vec2f {+#ifdef ES_UV_TRANSFORM+ var uv = uv0 * mc.u_uvTiling;+ if (mc.u_uvRotation != 0.0) {+ let c = cos(mc.u_uvRotation);+ let sn = sin(mc.u_uvRotation);+ uv = vec2f(c * uv.x + sn * uv.y, -sn * uv.x + c * uv.y);+ }+ return uv + mc.u_uvOffset;+#else+ return uv0;+#endif+}+#ifdef ES_GBUFFER// What the frame's second attachment takes, beside the colour (see the GLSL twin).struct FragOut {@@ -677,9 +707,10 @@ fn packNormal(n : vec3f) -> vec2f {#elif defined(SHADOW_DEPTH)#ifdef PREPASS_COVERAGE// See the GLSL twin: the colour pass's coverage, by its expression on its inputs.- let duvx = dpdx(v.v_texCoord);- let duvy = dpdy(v.v_texCoord);- let baseAlpha = textureSampleGrad(t0, s0, v.v_texCoord, duvx, duvy).a * v.v_color.a * mc.u_tint.a;+ let cuv = coverageUv(v.v_texCoord);+ let duvx = dpdx(cuv);+ let duvy = dpdy(cuv);+ let baseAlpha = textureSampleGrad(t0, s0, cuv, duvx, duvy).a * v.v_color.a * mc.u_tint.a;let edge = max(fwidth(baseAlpha), 1e-4);let coverage = (baseAlpha - mc.u_alphaCutoff) / max(edge, 1e-4) + 0.5;if (coverage <= 0.0) { discard; }@@ -687,9 +718,10 @@ fn packNormal(n : vec3f) -> vec2f {#else#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), cut at the cutoff.- let duvx = dpdx(v.v_texCoord);- let duvy = dpdy(v.v_texCoord);- if (textureSampleGrad(t0, s0, v.v_texCoord, duvx, duvy).a * v.v_color.a < mc.u_alphaCutoff) { discard; }+ let cuv = coverageUv(v.v_texCoord);+ let duvx = dpdx(cuv);+ let duvy = dpdy(cuv);+ if (textureSampleGrad(t0, s0, cuv, 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/RenderTypePlugin.hpp b/src/esengine/renderer/RenderTypePlugin.hppindex 3f7421c6c..fc664c30c 100644--- a/src/esengine/renderer/RenderTypePlugin.hpp+++ b/src/esengine/renderer/RenderTypePlugin.hpp@@ -162,6 +162,8 @@ struct MeshProgramFacts {bool lightmapped = false;/** Whether the geometry carries a tangent frame (with its normals): the program then declares and reads it. */bool tangents = false;+ /** Whether it draws unblended (MeshRenderer.opaque). A document row does not say, and most meshes are, so readying assumes so. */+ bool opaque = true;u32 materialId = 0;};diff --git a/src/esengine/renderer/frame/PostProcessPipeline.cpp b/src/esengine/renderer/frame/PostProcessPipeline.cppindex 84065a71c..eb3a07a9b 100644--- a/src/esengine/renderer/frame/PostProcessPipeline.cpp+++ b/src/esengine/renderer/frame/PostProcessPipeline.cpp@@ -246,6 +246,10 @@ void PostProcessPipeline::shutdown() {resourceManager_.releaseShader(copyShader_);copyShader_ = resource::ShaderHandle{};}+ if (exactCopyShader_.isValid()) {+ resourceManager_.releaseShader(exactCopyShader_);+ exactCopyShader_ = resource::ShaderHandle{};+ }if (copyDepthShader_.isValid()) {resourceManager_.releaseShader(copyDepthShader_);copyDepthShader_ = resource::ShaderHandle{};@@ -507,17 +511,25 @@ PostProcessPipeline::TemporalView PostProcessPipeline::peekTemporalView(const glreturn view;}+// The map is drawn for an effect that says how far it reaches (rain, snow): one that only reads it (reflections, keeping the+// ground under a roof dry) borrows it where it is drawn, and does not cost a second picture of the scene by being on alone.+bool PostProcessPipeline::passDrawsCover(const PostProcessPass& pass) {+ if (!passHasTexture(pass, "u_rainCover")) return false;+ const MaterialUniformLayout* layout = context_.materials().layoutFor(pass.shader);+ return layout && layout->find("u_shelterRange");+}+bool PostProcessPipeline::coverWanted() {if (!initialized_ || bypass_) return false;for (const auto& pass : passes_) {- if (pass.enabled && passHasTexture(pass, "u_rainCover")) return true;+ if (pass.enabled && passDrawsCover(pass)) return true;}return false;}f32 PostProcessPipeline::coverRange() {for (const auto& pass : passes_) {- if (!pass.enabled || !passHasTexture(pass, "u_rainCover")) continue;+ if (!pass.enabled || !passDrawsCover(pass)) continue;if (auto it = pass.floatUniforms.find("u_shelterRange"); it != pass.floatUniforms.end()) {return std::max(it->second, 10.0f);}@@ -525,6 +537,15 @@ f32 PostProcessPipeline::coverRange() {return 3000.0f;}+f32 PostProcessPipeline::coverBias() {+ for (const auto& pass : passes_) {+ if (!pass.enabled || !passDrawsCover(pass)) continue;+ if (auto it = pass.floatUniforms.find("u_shelterBias"); it != pass.floatUniforms.end()) return it->second;+ return 40.0f;+ }+ return 40.0f;+}+rg::ResourceId PostProcessPipeline::declareCover(u32 size) {cover_active_ = false;if (!graph_) return rg::kNoResource;@@ -832,6 +853,10 @@ void PostProcessPipeline::renderPass(PostProcessPass& pass, const rg::PassContexpass.vec4Uniforms["u_coverMatrix" + std::to_string(c)] = glm::vec4(cover_matrix_[c]);}pass.floatUniforms["u_coverActive"] = cover_active_ ? 1.0f : 0.0f;+ // The reach the map was drawn with and the bias it is read with, for a pass that reads it without stating either (reflections+ // read the rain's): both are the drawing effect's, in its world's units.+ if (layout->find("u_coverRange")) pass.floatUniforms["u_coverRange"] = coverRange();+ if (layout->find("u_coverBias")) pass.floatUniforms["u_coverBias"] = coverBias();pass.paramDirty = true;}if (layout && layout->usesLights) {@@ -1038,20 +1063,21 @@ void PostProcessPipeline::setOutputViewport(u32 x, u32 y, u32 w, u32 h) {output_vp_h_ = h;}-void PostProcessPipeline::grabScene() {- if (!copyShader_.isValid()) {- copyShader_ = compileBlit({"ES_COPY"});- if (!copyShader_.isValid()) {+void PostProcessPipeline::grabScene(bool marked) {+ resource::ShaderHandle& handle = marked ? copyShader_ : exactCopyShader_;+ if (!handle.isValid()) {+ handle = compileBlit({marked ? "ES_COPY" : "ES_COPY_EXACT"});+ if (!handle.isValid()) {ES_LOG_ERROR("PostProcessPipeline: no copy shader; a refractive surface sees nothing behind it");return;}}- Shader* shader = resourceManager_.getShader(copyShader_);+ Shader* shader = resourceManager_.getShader(handle);if (!shader) return;applyPassPipeline(*shader);if (shader->hasUniform("u_texture")) shader->setUniform("u_texture", 0);shader->commitParams();- bindBlitInputs(copyShader_);+ bindBlitInputs(handle);drawScreenQuad();}@@ -1102,7 +1128,7 @@ void PostProcessPipeline::bindBlitInputs(const resource::ShaderHandle& handle) {const MaterialUniformLayout* layout = context_.materials().layoutFor(handle);if (!layout) return;// Only the last pass applies the look: the copies share the file, and read the amount as none.- const bool lastPass = handle.id() != copyShader_.id() && handle.id() != copyDepthShader_.id();+ const bool lastPass = handle.id() != copyShader_.id() && handle.id() != exactCopyShader_.id() && handle.id() != copyDepthShader_.id();const f32 amount = lastPass && displayLutActive() ? display_lut_amount_ : 0.0f;if (layout->blockSize > 0) {if (blitParamUbo_ == BufferHandle::Invalid || blitParamAmount_ != amount) {diff --git a/src/esengine/renderer/frame/PostProcessPipeline.hpp b/src/esengine/renderer/frame/PostProcessPipeline.hppindex d94b2a8e8..d5700040e 100644--- a/src/esengine/renderer/frame/PostProcessPipeline.hpp+++ b/src/esengine/renderer/frame/PostProcessPipeline.hpp@@ -267,8 +267,9 @@ public:rg::TargetDesc grabTarget() const { return chainTarget(/*withDepth=*/false); }/// Copies what is bound at unit 0 (the scene, as the pass before drew it) into the target being drawn. No exposure, no curve, no- /// encode: a copy, with the alpha set to a marker (0.5) a shader can tell from the white a texture param falls back to.- void grabScene();+ /// encode: a copy, with the alpha set to a marker (0.5) a shader can tell from the white a texture param falls back to — unless+ /// @p marked is false, for a copy that stands in for the scene itself (kept aside and put back): its alpha is coverage, and is kept.+ void grabScene(bool marked = true);/// Whether this device can hold the distances a depth copy is made of: a float target. Without one a surface that measures/// the water in front of what is behind it gets no depth and falls back to a fixed column.@@ -334,6 +335,8 @@ public:bool coverWanted();/// How far from the camera, in world units, that map reaches each way (the effect's `u_shelterRange`).f32 coverRange();+ /// The bias the drawing effect reads the map with (its u_shelterBias), for a pass that only borrows the map.+ f32 coverBias();/// The map's target for this frame, declared in the graph (kNoResource when it cannot be made).rg::ResourceId declareCover(u32 size);/// The matrix the map was drawn through, for the effect to put a world point in it.@@ -643,6 +646,8 @@ private:BufferHandle blitParamUbo_ = BufferHandle::Invalid;f32 blitParamAmount_ = -1.0f;resource::ShaderHandle copyShader_;+ /// The copy that keeps alpha (grabScene(false)): the opaque scene kept aside and put back around the blended draws.+ resource::ShaderHandle exactCopyShader_;resource::ShaderHandle copyDepthShader_;std::vector<PostProcessPass> passes_;@@ -714,6 +719,8 @@ private:rg::ResourceId velocity_resource_ = rg::kNoResource;bool velocity_active_ = false;bool passHasTexture(const PostProcessPass& pass, const char* name);+ /// A pass that has the overhead cover map drawn for it (it states a reach, u_shelterRange), not one that only reads it.+ bool passDrawsCover(const PostProcessPass& pass);/// A history made (or kept) at @p w x @p h, or null when it cannot be.TemporalState* prepareHistory(TemporalState& state, u32 w, u32 h, GfxPixelFormat format);/// The pass writes a measurement, so its target is a float one where the device has them.diff --git a/src/esengine/renderer/frame/RenderFrame.cpp b/src/esengine/renderer/frame/RenderFrame.cppindex 954b60e08..21e278abc 100644--- a/src/esengine/renderer/frame/RenderFrame.cpp+++ b/src/esengine/renderer/frame/RenderFrame.cpp@@ -827,7 +827,8 @@ void RenderFrame::end() {copy.name = "scene-grab";copy.reads = {scene_resource_};copy.write = layered ? grabOpaque : grab;- copy.execute = [this](const rg::PassContext&) { post_process_->grabScene(); };+ // Layered, this copy is only ever put back (scene-restore): kept exact, alpha and all. Otherwise the water reads it, marked.+ copy.execute = [this, layered](const rg::PassContext&) { post_process_->grabScene(/*marked=*/!layered); };graph_.addPass(std::move(copy));if (grabDepth != rg::kNoResource) {rg::PassDesc copyDepth;@@ -850,7 +851,9 @@ void RenderFrame::end() {restore.name = "scene-restore";restore.reads = {grabOpaque};restore.write = scene_resource_;- restore.execute = [this](const rg::PassContext&) { post_process_->grabScene(); };+ // Exact: the scene's alpha is how much of each pixel geometry covers, which the sky reads. Restored through the marked+ // copy, every pixel came back half covered and the sky showed through every wall, wherever water and a pane were both in view.+ restore.execute = [this](const rg::PassContext&) { post_process_->grabScene(/*marked=*/false); };graph_.addPass(std::move(restore));}#endifdiff --git a/src/esengine/renderer/plugins/MeshPlugin.cpp b/src/esengine/renderer/plugins/MeshPlugin.cppindex 988bfe189..10a4340fc 100644--- a/src/esengine/renderer/plugins/MeshPlugin.cpp+++ b/src/esengine/renderer/plugins/MeshPlugin.cpp@@ -309,6 +309,7 @@ MeshProgramFacts meshFactsFromEntity(RenderFrameContext& ctx, ecs::Registry& regMeshProgramFacts facts;facts.hasNormals = resident && resident->hasNormals;facts.lit = mesh.lit;+ facts.opaque = mesh.opaque;facts.materialId = mesh.material;// Only meaningful with normals to perturb AND a draw that takes light.if (mesh.normalMap.isValid() && mesh.lit && resident && resident->hasNormals) {@@ -465,7 +466,8 @@ RenderPrewarmResult MeshPlugin::prewarmFacts(RenderFrameContext& ctx,facts[i].materialId, facts[i].hasNormals, facts[i].skinned, envMapped,facts[i].lightmapped, facts[i].tangents));ctx.materials->meshProgram(facts[i].materialId, ctx.resources, facts[i].hasNormals,- facts[i].skinned, envMapped, facts[i].lightmapped, false, facts[i].tangents);+ facts[i].skinned, envMapped, facts[i].lightmapped, false, facts[i].tangents,+ false, facts[i].opaque);}}if (ctx.materials) {@@ -1121,7 +1123,8 @@ void MeshPlugin::collect(RenderCollectContext& collect_ctx) {key.envTextureId != 0,resident->hasLightmapUV,ctx.gbuffer && !shadowDepth,- resident->hasTangents);+ resident->hasTangents, false,+ key.blend == BlendMode::None);if (materialProgram == 0) {if (!warned_material_) {warned_material_ = true;@@ -1188,7 +1191,7 @@ void MeshPlugin::collect(RenderCollectContext& collect_ctx) {if (!depthPass && !wire && key.materialId != 0 && ctx.materials && ctx.materials->hasTipPass(key.materialId)) {const u32 tipProgram = ctx.materials->meshProgram(key.materialId, ctx.resources, geo.hasNormals, skinned,key.envTextureId != 0, geo.hasLightmapUV, false,- geo.hasTangents, true);+ geo.hasTangents, true, false);if (tipProgram != 0) {BatchDrawKey tips = drawn;tips.shaderId = tipProgram;diff --git a/src/esengine/renderer/rhi/ShaderEmbeds.generated.hpp b/src/esengine/renderer/rhi/ShaderEmbeds.generated.hppindex 650888a2e..b78ff68d9 100644--- a/src/esengine/renderer/rhi/ShaderEmbeds.generated.hpp+++ b/src/esengine/renderer/rhi/ShaderEmbeds.generated.hpp@@ -352,6 +352,12 @@ void main() {#endif+#ifdef ES_COPY_EXACT+++ fragColor = c;+ return;+#endif#ifdef ES_COPY@@ -444,6 +450,9 @@ fn displayLookup(c : vec3f) -> vec3f {#elsevar c = textureSampleLevel(t0, s0, v.v_texCoord, 0.0);#endif+#ifdef ES_COPY_EXACT+ return c;+#endif#ifdef ES_COPYreturn vec4f(c.rgb, 0.5);#endif@@ -870,6 +879,21 @@ vec2 packNormal(vec3 n) {out vec4 fragColor;#endif+++highp vec2 coverageUv() {+#ifdef ES_UV_TRANSFORM+ highp vec2 uv = v_texCoord * u_uvTiling;+ if (u_uvRotation != 0.0) {+ float c = cos(u_uvRotation), sn = sin(u_uvRotation);+ uv = vec2(c * uv.x + sn * uv.y, -sn * uv.x + c * uv.y);+ }+ return uv + u_uvOffset;+#else+ return v_texCoord;+#endif+}+void main() {#ifdef ES_VELOCITY@@ -882,7 +906,7 @@ void main() {#ifdef PREPASS_COVERAGE- highp float baseAlpha = texture(u_texture, v_texCoord).a * v_color.a * u_tint.a;+ highp float baseAlpha = texture(u_texture, coverageUv()).a * v_color.a * u_tint.a;highp float coverage = (baseAlpha - u_alphaCutoff) / max(fwidth(baseAlpha), 1e-4) + 0.5;if (coverage <= 0.0) discard;fragColor = vec4(0.0, 0.0, 0.0, min(coverage, 1.0));@@ -890,7 +914,7 @@ void main() {#ifdef SHADOW_ALPHA- if (texture(u_texture, v_texCoord).a * v_color.a < u_alphaCutoff) discard;+ if (texture(u_texture, coverageUv()).a * v_color.a < u_alphaCutoff) discard;#endif@@ -1068,7 +1092,8 @@ fn esPrevBone(joint : u32) -> mat4x4f {let chosen = u32(esInstanceTint().x);let own = vec4f(v.a_joints == vec4u(chosen));let heat = dot(own, v.a_weights);- out.v_color = vec4f(select(mix(vec3f(0.2, 0.4, 1.0), vec3f(1.0, 0.25, 0.2), clamp(heat, 0.0, 1.0)),+)esshader"+ R"esshader( out.v_color = vec4f(select(mix(vec3f(0.2, 0.4, 1.0), vec3f(1.0, 0.25, 0.2), clamp(heat, 0.0, 1.0)),vec3f(0.1), heat < 0.01), 1.0);}#endif@@ -1090,8 +1115,7 @@ fn esPrevBone(joint : u32) -> mat4x4f {+ v.a_weights.z * esPrevBone(v.a_joints.z) + v.a_weights.w * esPrevBone(v.a_joints.w);let L = prevSkin * vec4f(local, 1.0);#else-)esshader"- R"esshader( let L = vec4f(local, 1.0);+ let L = vec4f(local, 1.0);#endiflet before = esInstanceTint();out.v_velCur = out.pos;@@ -1184,6 +1208,21 @@ struct VSOut {@location(6) @interpolate(flat) v_probeSlot : f32,};++fn coverageUv(uv0 : vec2f) -> vec2f {+#ifdef ES_UV_TRANSFORM+ var uv = uv0 * mc.u_uvTiling;+ if (mc.u_uvRotation != 0.0) {+ let c = cos(mc.u_uvRotation);+ let sn = sin(mc.u_uvRotation);+ uv = vec2f(c * uv.x + sn * uv.y, -sn * uv.x + c * uv.y);+ }+ return uv + mc.u_uvOffset;+#else+ return uv0;+#endif+}+#ifdef ES_GBUFFERstruct FragOut {@@ -1223,9 +1262,10 @@ fn packNormal(n : vec3f) -> vec2f {#elif defined(SHADOW_DEPTH)#ifdef PREPASS_COVERAGE- let duvx = dpdx(v.v_texCoord);- let duvy = dpdy(v.v_texCoord);- let baseAlpha = textureSampleGrad(t0, s0, v.v_texCoord, duvx, duvy).a * v.v_color.a * mc.u_tint.a;+ let cuv = coverageUv(v.v_texCoord);+ let duvx = dpdx(cuv);+ let duvy = dpdy(cuv);+ let baseAlpha = textureSampleGrad(t0, s0, cuv, duvx, duvy).a * v.v_color.a * mc.u_tint.a;let edge = max(fwidth(baseAlpha), 1e-4);let coverage = (baseAlpha - mc.u_alphaCutoff) / max(edge, 1e-4) + 0.5;if (coverage <= 0.0) { discard; }@@ -1233,9 +1273,10 @@ fn packNormal(n : vec3f) -> vec2f {#else#ifdef SHADOW_ALPHA- let duvx = dpdx(v.v_texCoord);- let duvy = dpdy(v.v_texCoord);- if (textureSampleGrad(t0, s0, v.v_texCoord, duvx, duvy).a * v.v_color.a < mc.u_alphaCutoff) { discard; }+ let cuv = coverageUv(v.v_texCoord);+ let duvx = dpdx(cuv);+ let duvy = dpdy(cuv);+ if (textureSampleGrad(t0, s0, cuv, duvx, duvy).a * v.v_color.a < mc.u_alphaCutoff) { discard; }#endifdiff --git a/src/esengine/renderer/store/MaterialStore.cpp b/src/esengine/renderer/store/MaterialStore.cppindex 43d3c105f..d40580ba8 100644--- a/src/esengine/renderer/store/MaterialStore.cpp+++ b/src/esengine/renderer/store/MaterialStore.cpp@@ -67,19 +67,31 @@ void MaterialStore::clear() {for (const auto& [shape, handle] : programs) resources_->releaseShader(handle);}+namespace {+// A material that moves where its maps are read (the Model shader's Tiling, Offset and Rotation) has its cut-out read+// there too, by the depth programs that reproduce its coverage — or a tiled fence casts the shadow of an untiled one.+bool declaresUvTransform(const resource::ParsedShader& material) {+ for (const auto& p : material.properties) if (p.name == "u_uvTiling") return true;+ return false;+}+} // namespace+u32 MaterialStore::meshProgram(u32 materialId, resource::ResourceManager& resources,bool withNormals, bool skinned, bool envMapped,- bool lightmapped, bool gbuffer, bool tangents, bool tipPass) const {+ bool lightmapped, bool gbuffer, bool tangents, bool tipPass, bool opaque) const {// Only for a shader that has something to write: one that never mentions the feature would// compile the same program twice and then be declared to write an output it does not have.bool albedo = false;bool direct = false;- if (gbuffer || lighting_direct_) {+ if (gbuffer || lighting_direct_ || opaque) {const MaterialRecord* rec = find(materialId);const auto src = rec && rec->shaderRef.isValid() ? sources_.find(rec->shaderRef.id()) : sources_.end();gbuffer = gbuffer && src != sources_.end() && src->second.mentionsGbuffer;albedo = gbuffer && src->second.writesAlbedo;direct = lighting_direct_ && src != sources_.end() && src->second.takesLight;+ // An unblended draw writes its alpha straight into the frame, where the sky reads it as coverage: a shader that+ // says what an opaque surface's alpha is gets a program for it, and one that does not keeps sharing the blended one.+ opaque = opaque && src != sources_.end() && src->second.mentionsOpaque;}// Keyed by shader AND vertex shape: a layout may not declare an attribute its// shader ignores, so geometry with normals — or posed by bones — needs its own.@@ -90,7 +102,8 @@ u32 MaterialStore::meshProgram(u32 materialId, resource::ResourceManager& resour| (gbuffer ? (1ull << 38) : 0ull)| (tangents && withNormals ? (1ull << 39) : 0ull)| (tipPass ? (1ull << 40) : 0ull)- | (direct ? (1ull << 42) : 0ull);+ | (direct ? (1ull << 42) : 0ull)+ | (opaque ? (1ull << 43) : 0ull);// A program already made for this shader and vertex shape is the answer, and almost every draw of a frame asks for one: it is looked up before// the feature list is built, since building it (nine strings and the vector that holds them) was most of what a cached answer cost.if (const MaterialRecord* rec = find(materialId); rec && rec->shaderRef.isValid()) {@@ -119,6 +132,7 @@ u32 MaterialStore::meshProgram(u32 materialId, resource::ResourceManager& resourif (gbuffer) features.push_back("ES_GBUFFER");if (tipPass) features.push_back("ES_TIP_PASS");if (direct) features.push_back("ES_LIGHT_DIRECT");+ if (opaque) features.push_back("ES_OPAQUE");const u32 program = variantProgram(materialId, resources, shape, features, "resident geometry");if (gbuffer && program != 0) markGBufferProgram(program, albedo);return program;@@ -165,6 +179,7 @@ u32 MaterialStore::shadowProgram(u32 materialId, resource::ResourceManager& resofeatures.emplace_back("SHADOW_DEPTH");if (hooked) features.emplace_back("ES_MATERIAL_VERTEX");if (cutout) features.emplace_back("SHADOW_ALPHA");+ if (cutout && declaresUvTransform(material)) features.emplace_back("ES_UV_TRANSFORM");const auto target = resources.preferredShaderTarget();const std::string vert = resource::ShaderParser::assembleStage(depth, resource::ShaderStage::Vertex, "", features, target);const std::string frag = resource::ShaderParser::assembleStage(depth, resource::ShaderStage::Fragment, "", features, target);@@ -220,6 +235,7 @@ u32 MaterialStore::prepassCoverageProgram(u32 materialId, resource::ResourceManaif (skinned) features.emplace_back("SKINNED");features.emplace_back("SHADOW_DEPTH");features.emplace_back("PREPASS_COVERAGE");+ if (declaresUvTransform(material)) features.emplace_back("ES_UV_TRANSFORM");const auto target = resources.preferredShaderTarget();const std::string vert = resource::ShaderParser::assembleStage(depth, resource::ShaderStage::Vertex, "", features, target);const std::string frag = resource::ShaderParser::assembleStage(depth, resource::ShaderStage::Fragment, "", features, target);diff --git a/src/esengine/renderer/store/MaterialStore.hpp b/src/esengine/renderer/store/MaterialStore.hppindex 83748c7b0..6b7aa44ee 100644--- a/src/esengine/renderer/store/MaterialStore.hpp+++ b/src/esengine/renderer/store/MaterialStore.hpp@@ -202,7 +202,8 @@ public:const bool mentionsGbuffer = source.find("ES_GBUFFER") != std::string::npos;const bool writesAlbedo = mentionsGbuffer && source.find("fragAlbedo") != std::string::npos;const bool takesLight = source.find("applyLighting") != std::string::npos;- sources_[shader.id()] = { std::move(source), std::move(features), mentionsGbuffer, writesAlbedo, takesLight };+ const bool mentionsOpaque = source.find("ES_OPAQUE") != std::string::npos;+ sources_[shader.id()] = { std::move(source), std::move(features), mentionsGbuffer, writesAlbedo, takesLight, mentionsOpaque };}}@@ -212,7 +213,7 @@ public:u32 meshProgram(u32 materialId, resource::ResourceManager& resources,bool withNormals = false, bool skinned = false,bool envMapped = false, bool lightmapped = false, bool gbuffer = false,- bool tangents = false, bool tipPass = false) const;+ bool tangents = false, bool tipPass = false, bool opaque = false) const;void setLightingDirect(bool on) { lighting_direct_ = on; }bool lightingDirect() const { return lighting_direct_; }@@ -475,6 +476,8 @@ private:/// attachment existed writes two outputs, and its pipeline must leave the third alone.bool writesAlbedo = false;bool takesLight = false;+ /// Whether the source has an ES_OPAQUE branch: only then is an unblended draw worth a program of its own.+ bool mentionsOpaque = false;};std::unordered_map<u32, ShaderSource> sources_;bool lighting_direct_ = false;diff --git a/src/esengine/resource/ShaderParser.cpp b/src/esengine/resource/ShaderParser.cppindex 6732a7684..ff67cf744 100644--- a/src/esengine/resource/ShaderParser.cpp+++ b/src/esengine/resource/ShaderParser.cpp@@ -795,7 +795,7 @@ const std::unordered_map<std::string, std::string>& engineUniformNames(const Parprobe.stages[ShaderStage::Fragment] = "void main() {}\n";const std::vector<std::string> everything{"MESH", "MESH_NORMALS", "MESH_TANGENTS", "MESH_LIGHTMAP", "SKINNED", "ES_RECEIVE_SHADOW",- "ES_ENV_MAP", "ES_SURFACE_3D", "ES_GBUFFER", "ES_VELOCITY"};+ "ES_ENV_MAP", "ES_SURFACE_3D", "ES_GBUFFER", "ES_VELOCITY", "ES_OPAQUE"};auto& names = byDomain[key];for (const ShaderStage stage : {ShaderStage::Vertex, ShaderStage::Fragment}) {collectUniformNames(ShaderParser::assembleStage(probe, stage, "", everything, ShaderTargetLanguage::GLSL_ES300), names);diff --git a/tools/renderScenes.mjs b/tools/renderScenes.mjsindex 98f421b22..600a60fb8 100644--- a/tools/renderScenes.mjs+++ b/tools/renderScenes.mjs@@ -872,6 +872,17 @@ export const SCENES = [// a 90-degree eye is 1.41x further from the frame's edge than from its centre:// an effect reading depth paints them alike, and tol 10 does not reach between.{ id: "distance-fog", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_SCENE: "/scenes/distance-fog.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/depth-outline.textures.json", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "4", ESTELLA_VERIFY_EXPECT: "[{\"x\": 0.5, \"y\": 0.5, \"rgb\": [107, 176, 143], \"tol\": 10}, {\"x\": 0.0625, \"y\": 0.5, \"rgb\": [134, 174, 176], \"tol\": 10}, {\"x\": 0.4375, \"y\": 0.5, \"rgb\": [190, 85, 92], \"tol\": 14}, {\"x\": 0.6875, \"y\": 0.5, \"rgb\": [200, 60, 62], \"tol\": 14}]" } },+ // An opaque Model surface whose base alpha is 0.5 (a map's alpha is often a mask for something else; glTF's OPAQUE ignores it). Drawn+ // unblended, its alpha lands in the frame, and Sky Atmosphere reads a pixel's alpha as how much of it the sky shows through: the quad+ // must stay its own colour, not the sky's. Without ES_OPAQUE the quad reads 216,87,67: the sky through it.+ { id: "sky-opaque-alpha", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_PREFAB: "/scenes/sky-opaque-alpha.esprefab", ESTELLA_VERIFY_SCENE: "/scenes/sky-opaque-alpha.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/mesh-backface.textures.json", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "4", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.5,\"y\":0.5,\"rgb\":[177,46,46],\"tol\":12},{\"x\":0.5,\"y\":0.05,\"rgb\":[21,42,73],\"tol\":12}]" } },+ // The same quad with a refracting pane and a blended one in view: the scene is built in layers (opaque, blended, the opaque put back, the+ // glass) and the opaque scene is kept aside and restored by a copy. That copy must keep alpha: through the refraction copy's 0.5 mark,+ // every pixel came back half covered and the quad read 216,87,67: the sky through it.+ { id: "sky-restore-alpha", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_PREFAB: "/scenes/sky-opaque-alpha.esprefab", ESTELLA_VERIFY_SCENE: "/scenes/sky-restore-alpha.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/mesh-backface.textures.json", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "4", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.5,\"y\":0.5,\"rgb\":[177,46,46],\"tol\":12}]" } },+ // Wet ground under a roof stays dry: reflections read the rain's map of what stands over each place, as the rain does. A floor too rough+ // to reflect dry, wet by the reflections' own Wetness, under a roof over its left half: only the open right half mirrors the red wall. Reading no map, the left half reads 148,40,40 too.+ { id: "ssr-shelter", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_SCENE: "/scenes/ssr-shelter.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/mesh-backface.textures.json", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "6", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.25,\"y\":0.5,\"rgb\":[53,53,53],\"tol\":12},{\"x\":0.75,\"y\":0.5,\"rgb\":[147,39,39],\"tol\":15}]" } },{ id: "sky-fog", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_SCENE: "/scenes/sky-fog.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/depth-outline.textures.json", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "4", ESTELLA_VERIFY_EXPECT: "[{\"x\": 0.2, \"y\": 0.1, \"rgb\": [144, 175, 187], \"tol\": 12}, {\"x\": 0.5, \"y\": 0.1, \"rgb\": [141, 174, 183], \"tol\": 12}, {\"x\": 0.8, \"y\": 0.2, \"rgb\": [143, 174, 186], \"tol\": 12}, {\"x\": 0.5, \"y\": 0.4, \"rgb\": [139, 171, 180], \"tol\": 12}, {\"x\": 0.2, \"y\": 0.8, \"rgb\": [62, 70, 70], \"tol\": 12}, {\"x\": 0.8, \"y\": 0.8, \"rgb\": [57, 64, 67], \"tol\": 12}]" } },// SSAO: one unlit grey floor read at seven places. Contact, corner and// step come back darker than the open floor they are made of, the floating