3D engine that AI agents drive
Own mirrored winding in the renderer: batch by determinant sign, draw with frontFace CW (#680, #681)
Nguyen Xuan Anb88f78b16c11
diff --git a/changes/680-mirrored-winding.md b/changes/680-mirrored-winding.mdnew file mode 100644index 00000000..49fc3923--- /dev/null+++ b/changes/680-mirrored-winding.md@@ -0,0 +1 @@+- Parts with a mirrored (negative-determinant) matrix, such as a flipped billboard, now render with the right side lit and culled instead of ghosted or pale; the renderer batches them apart and glTF no longer flips winding itself (#680, #681)diff --git a/changes/680-mirrored-winding.size.md b/changes/680-mirrored-winding.size.mdnew file mode 100644index 00000000..30e812f9--- /dev/null+++ b/changes/680-mirrored-winding.size.md@@ -0,0 +1,11 @@+- entry:core: mirrored parts batch apart and draw with clockwise front faces, so the visible side of a flipped quad is lit and culled correctly+- entry:core+lazy: same renderer change as entry:core+- scene:lit-box: the renderer owns mirrored winding (a determinant sign test, a batch key and a frontFace call), which fixes the washed-out flipped quads+- scene:lit-box+lazy: same renderer change as scene:lit-box+- scene:gltf-box: the same renderer change, minus the loader's winding flip that this replaces+- scene:gltf-box+lazy: same renderer change as scene:gltf-box+- scene:agent-scene: the same renderer change as scene:lit-box+- scene:agent-scene+lazy: same renderer change as scene:agent-scene+- goal:lit-box: fixes a visible glitch (flipped billboards render ghosted or pale); about 140 B+- goal:gltf-box: fixes a visible glitch with mirrored glTF and flipped quads sharing one path; about 110 B+- goal:agent-scene: fixes a visible glitch (flipped billboards render ghosted or pale); about 140 Bdiff --git a/src/gltf.js b/src/gltf.jsindex a04c9715..9fc3be27 100644--- a/src/gltf.js+++ b/src/gltf.js@@ -875,7 +875,7 @@ function hasTriangleWithArea(positions, indices) {return false;}-function convertGeometry(source, mirrored, primitive, secondUvSet, onIgnoredVertexAlpha, onRepair) {+function convertGeometry(source, primitive, secondUvSet, onIgnoredVertexAlpha, onRepair) {const { position, normal, uv, uv1, color, skinIndex, skinWeight } = source.attributes;const zeroedBy = label => count => onRepair(`${count} non-finite ${label} value(s) were set to 0`);const positions = copyAttributeZeroingNonFinite(position, 3, zeroedBy('POSITION'));@@ -925,13 +925,6 @@ function convertGeometry(source, mirrored, primitive, secondUvSet, onIgnoredVertonRepair('it has morph targets but no base NORMAL; base and per-target normals are generated from the triangles');}}- if (mirrored) {- for (let index = 0; index < indices.length; index += 3) {- const second = indices[index + 1];- indices[index + 1] = indices[index + 2];- indices[index + 2] = second;- }- }if (uv && uv.count !== position.count) throw new Error('TEXCOORD_0 and POSITION counts must match.');if (uv) geometry.uvs = copyAttribute(uv, 2);// The renderer's second UV set is geometry.lightUvs, the one light maps use.@@ -1308,8 +1301,7 @@ export async function parseGltf(data, options = {}) {if (!keyed) continue;}const mirrored = singular ? false : determinant < 0;- const geometryMirrored = node.isSkinnedMesh ? false : mirrored;- const geometryKey = `${node.geometry.uuid}:${geometryMirrored}:${uvKey}:${secondUvSet}`;+ const geometryKey = `${node.geometry.uuid}:${uvKey}:${secondUvSet}`;if (!geometries.has(geometryKey)) {actualVertices += node.geometry.attributes.position.count * (1 + (primitive.targets?.length ?? 0));throwOverruns(overLimit([], 'decoded vertices', actualVertices, 'maxVertices', limits.maxVertices));@@ -1318,7 +1310,7 @@ export async function parseGltf(data, options = {}) {const warning = `Repaired ${primitiveLabel(document, association.meshes, association.primitives)}: ${reason}.`;if (!warnings.includes(warning)) warnings.push(warning);};- const converted = convertGeometry(node.geometry, geometryMirrored, primitive, secondUvSet, () => meshNamesWithIgnoredAlpha.add(node.name), onRepair);+ const converted = convertGeometry(node.geometry, primitive, secondUvSet, () => meshNamesWithIgnoredAlpha.add(node.name), onRepair);if (converted.uvs) bakeUvTransform(converted.uvs, uvTransform);geometries.set(geometryKey, converted);} catch (error) {diff --git a/src/renderer.js b/src/renderer.jsindex c4e7e544..e20102f4 100644--- a/src/renderer.js+++ b/src/renderer.js@@ -284,6 +284,17 @@ function copyVector3(target, offset, source) {target[offset + 2] = source[2];}+/**+ * True when the matrix reflects space (negative determinant of its upper 3x3, column major), which reverses the screen+ * winding of every triangle. The renderer owns this: it groups such parts apart and draws them with clockwise front faces.+ */+export function isMirroredMatrix(matrix) {+ const determinant = matrix[0] * (matrix[5] * matrix[10] - matrix[6] * matrix[9])+ - matrix[4] * (matrix[1] * matrix[10] - matrix[2] * matrix[9])+ + matrix[8] * (matrix[1] * matrix[6] - matrix[2] * matrix[5]);+ return determinant < 0;+}+function packInstance(data, index, part, normalMatrix) {const offset = index * INSTANCE_STRIDE;const material = part.material;@@ -406,7 +417,7 @@ export function groupParts(parts, batching = true) {const key = batching ? part.geometry : part;if (!groups.has(key)) groups.set(key, new Map());let maps = groups.get(key);- for (const value of [...materialMapState(part.material), ...materialLayerState(part.material), part.skin ?? null, part.material.snippet, part.crowd ?? null, part.morph ?? null, castsShadow(part), receivesShadow(part), compositeModeOf(part), depthLayerOf(part), renderPass(part.material), part.lods ?? null, part.shadowLods ?? null, ...materialAlphaState(part.material)]) {+ for (const value of [...materialMapState(part.material), ...materialLayerState(part.material), part.skin ?? null, part.material.snippet, part.crowd ?? null, part.morph ?? null, castsShadow(part), receivesShadow(part), compositeModeOf(part), depthLayerOf(part), renderPass(part.material), part.lods ?? null, part.shadowLods ?? null, isMirroredMatrix(part.matrix), ...materialAlphaState(part.material)]) {if (!maps.has(value)) maps.set(value, new Map());maps = maps.get(value);}@@ -1085,7 +1096,7 @@ export class Renderer67 {const [alphaMode, alphaCutoff, opacity, doubleSided] = materialAlphaState(parts[0].material);const layerState = materialLayerState(parts[0].material);const culling = this.createCullingState(parts);- const batch = { ...culling, alphaMode, alphaCutoff, opacity, doubleSided, layerState, parts: [...parts], vertexArray, instanceBuffer, instanceData, textures, mapState, splat, lightMapTexture, texture: textures[0], map, skin, skinTexture, influenceTexture, crowd, crowdTexture, morph, morphTexture, morphWeights, indexCount: geometry.indices.length, instanceCount: parts.length, floor: parts[0].material.tag === 'floor', castShadow: castsShadow(parts[0]), receivesShadow: receivesShadow(parts[0]), compositeMode: compositeModeOf(parts[0]), depthLayer: depthLayerOf(parts[0]), pass: renderPass(parts[0].material) };+ const batch = { ...culling, alphaMode, alphaCutoff, opacity, doubleSided, mirrored: isMirroredMatrix(parts[0].matrix), layerState, parts: [...parts], vertexArray, instanceBuffer, instanceData, textures, mapState, splat, lightMapTexture, texture: textures[0], map, skin, skinTexture, influenceTexture, crowd, crowdTexture, morph, morphTexture, morphWeights, indexCount: geometry.indices.length, instanceCount: parts.length, floor: parts[0].material.tag === 'floor', castShadow: castsShadow(parts[0]), receivesShadow: receivesShadow(parts[0]), compositeMode: compositeModeOf(parts[0]), depthLayer: depthLayerOf(parts[0]), pass: renderPass(parts[0].material) };if (parts[0].lods) culling.levelGeometries.forEach((geometryOfLevel, level) => this.levelDraw(batch, level));culling.shadowLevels?.levelGeometries.forEach((geometryOfLevel, level) => this.levelDraw(batch, level, batch.shadowLevels));parts.forEach((part, index) => this.partLocations.set(part, { batch, index, geometry: part.geometry, map, mapState, layerState, skin, jointMatrices: skin?.jointMatrices, skinIndices: geometry.skinIndices, skinWeights: geometry.skinWeights, morph, morphWeights: morph?.weights, morphTargets: geometry.morphTargets, normalMatrix: mat3.create(), committedMatrix: batch.instanceData.subarray(index * INSTANCE_STRIDE, index * INSTANCE_STRIDE + 16) }));@@ -1284,6 +1295,7 @@ export class Renderer67 {if (alphaState.some((value, index) => value !== batchAlphaState[index])) throw new Error(`Alpha mode, cutoff, double-sided and mask opacity changes require a new renderer (blend and add opacity may change): ${part.name}`);}if (part.geometry !== location.geometry) throw new Error(`Geometry changes require a new renderer: ${part.name}`);+ if (isMirroredMatrix(part.matrix) !== Boolean(location.batch.mirrored)) throw new Error(`Mirroring changes (negative determinant) require replaceParts: ${part.name}`);if (!materialUnchanged && renderPass(part.material) !== batchPass(location.batch)) throw new Error(`Moving a part into or out of the liquid or foam pass requires replaceParts: ${part.name}`);if ((part.skin ?? null) !== location.skin || part.skin?.jointMatrices !== location.jointMatrices || part.geometry.skinIndices !== location.skinIndices || part.geometry.skinWeights !== location.skinWeights) throw new Error(`Skin identity changes require a new renderer: ${part.name}`);if (part.skin) {@@ -2148,12 +2160,15 @@ export class Renderer67 {}}if (textured && !this.benchmark && this.shaderFeatures?.has('instanced') === false)this.setSingleInstanceUniforms(batch.instanceData);+ // A reflecting matrix reverses screen winding: clockwise triangles are the front faces of a mirrored batch.+ if (batch.mirrored) this.context.frontFace(this.context.CW);if (selection && !selection.isEverything) {this.drawSelectedLevels(batch, selection, levelSet);- return;+ } else {+ this.context.bindVertexArray(batch.vertexArray);+ this.context.drawElementsInstanced(this.context.TRIANGLES, batch.indexCount, this.context.UNSIGNED_INT, 0, batch.instanceCount);}- this.context.bindVertexArray(batch.vertexArray);- this.context.drawElementsInstanced(this.context.TRIANGLES, batch.indexCount, this.context.UNSIGNED_INT, 0, batch.instanceCount);+ if (batch.mirrored) this.context.frontFace(this.context.CCW);}// A render pass draws raw material data instead of the lit image; the addon validates frame.pass and returns the shader mode.diff --git a/tests/gltf.test.js b/tests/gltf.test.jsindex f0c8abf9..d0de6a57 100644--- a/tests/gltf.test.js+++ b/tests/gltf.test.js@@ -129,11 +129,12 @@ test('rigid animation seeks are absolute, order independent, clip selectable andassert.throws(() => asset.applyAnimation(1), /disposed/);});-test('mirrored static transforms reverse triangle winding without altering world matrices', async () => {+test('mirrored static transforms keep the authored winding and the world matrix; the renderer owns the reversal', async () => {const asset = await parseGltf(triangleAsset(document => { document.nodes[2].scale = [-1, 1, 1]; }));assert.deepEqual(Array.from(asset.parts[0].geometry.indices), [0, 1, 2]);- assert.deepEqual(Array.from(asset.parts[1].geometry.indices), [0, 2, 1]);+ assert.deepEqual(Array.from(asset.parts[1].geometry.indices), [0, 1, 2]);assert.equal(asset.parts[1].matrix[0], -1);+ assert.equal(asset.parts[0].geometry, asset.parts[1].geometry);asset.dispose();});diff --git a/tests/mirrored-winding.test.js b/tests/mirrored-winding.test.jsnew file mode 100644index 00000000..62c4bcbf--- /dev/null+++ b/tests/mirrored-winding.test.js@@ -0,0 +1,60 @@+import assert from 'node:assert/strict';+import test from 'node:test';+import { groupParts, isMirroredMatrix, Renderer67 } from '../src/renderer.js';++const quad = {+ positions: new Float32Array([-1, -1, 0, 1, -1, 0, 1, 1, 0, -1, 1, 0]),+ normals: new Float32Array([0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1]),+ indices: new Uint32Array([0, 1, 2, 0, 2, 3]),+};++function quadPart(name, scaleX, material = {}) {+ return {+ name,+ geometry: quad,+ matrix: new Float32Array([scaleX, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]),+ material: { tag: 'surface', color: [1, 1, 1], metallic: 0, roughness: 0.5, emission: 1, ...material },+ };+}++test('a matrix is mirrored when the determinant of its upper 3x3 is negative', () => {+ assert.equal(isMirroredMatrix(quadPart('plain', 1).matrix), false);+ assert.equal(isMirroredMatrix(quadPart('flipped x', -1).matrix), true);+ const flippedTwice = quadPart('flipped x and y', -1).matrix;+ flippedTwice[5] = -1;+ assert.equal(isMirroredMatrix(flippedTwice), false);+ assert.equal(isMirroredMatrix(new Float32Array(16)), false);+});++test('parts that share a geometry and material batch apart by the sign of their determinant', () => {+ const parts = [quadPart('plain', 1), quadPart('flipped', -1), quadPart('plain again', 2), quadPart('flipped again', -3)];+ const groups = groupParts(parts);+ assert.equal(groups.length, 2);+ assert.deepEqual(groups.map(group => group.map(part => part.name)), [['plain', 'plain again'], ['flipped', 'flipped again']]);+});++test('a mirrored batch draws with clockwise front faces and restores the default winding', () => {+ const renderer = Object.create(Renderer67.prototype);+ renderer.benchmark = true;+ const calls = [];+ renderer.context = {+ CW: 'cw', CCW: 'ccw', TRIANGLES: 'triangles', UNSIGNED_INT: 'uint',+ TEXTURE0: 33984, activeTexture() {}, bindTexture() {}, bindVertexArray() {},+ frontFace(mode) { calls.push(`frontFace ${mode}`); },+ drawElementsInstanced() { calls.push('draw'); },+ };+ renderer.drawBatch({ mirrored: true, indexCount: 6, instanceCount: 1 });+ renderer.drawBatch({ mirrored: false, indexCount: 6, instanceCount: 1 });+ assert.deepEqual(calls, ['frontFace cw', 'draw', 'frontFace ccw', 'draw']);+});++test('updateParts rejects a part whose matrix changes sign after batching', () => {+ const renderer = Object.create(Renderer67.prototype);+ const part = quadPart('sprite', 1);+ const batch = { mirrored: false, castShadow: true, receivesShadow: true, compositeMode: 0, alphaMode: 'opaque', alphaCutoff: 0, opacity: 1, doubleSided: false };+ renderer.partLocations = new Map([[part, { batch, geometry: quad, skin: null, morph: null }]]);+ renderer.updateSkins = new Set();+ renderer.updateBatches = new Set();+ part.matrix[0] = -1;+ assert.throws(() => renderer.updateParts([part]), /Mirroring changes.*replaceParts: sprite/);+});