3D engine that AI agents drive
Regroup parts inside updateParts when a matrix crosses a mirror instead of throwing (#680)
Nguyen Xuan An1e2df9420e73
diff --git a/src/renderer.js b/src/renderer.jsindex e20102f4..debd3b20 100644--- a/src/renderer.js+++ b/src/renderer.js@@ -113,8 +113,9 @@ function renderPass(material) {return TRANSLUCENT_TAGS.has(material.tag) ? material.tag : 'opaque';}-function partNeedsFullUpload(part) {- return Boolean(part.skin || part.morph || part.geometry.morphTargets || part.geometry.skinIndices || hasMaterialMap(part.material) && !texturedReplaceSupport.begin);+// Regrouping parts that already draw (a mirrored sign change) reuses their cached textures, so it needs no texture bookkeeping.+function partNeedsFullUpload(part, texturesReplaceable = Boolean(texturedReplaceSupport.begin)) {+ return Boolean(part.skin || part.morph || part.geometry.morphTargets || part.geometry.skinIndices || hasMaterialMap(part.material) && !texturesReplaceable);}function batchPass(batch) {@@ -1104,7 +1105,7 @@ export class Renderer67 {}/** Reconcile immutable rigid, untextured geometry without rebuilding programs or render targets. */- replaceParts(parts) {+ replaceParts(parts, { regroupOnly = false } = {}) {if (!Array.isArray(parts) || new Set(parts).size !== parts.length) {throw new TypeError('Scene parts must be an array with distinct object identities.');}@@ -1136,13 +1137,13 @@ export class Renderer67 {});// Skinned and morphed batches stay valid only while retained unchanged. Textured ones need the replace-textured-parts addon to be added or dropped.for (const item of replacements) {- if (!item.batch && item.group.some(partNeedsFullUpload)) {+ if (!item.batch && item.group.some(part => partNeedsFullUpload(part, regroupOnly || Boolean(texturedReplaceSupport.begin)))) {throw new Error('replaceParts can add or change only rigid, untextured parts. Keep textured, skinned and morphed parts unchanged, or import replace-textured-parts to add textured ones.');}}for (const [part, location] of this.partLocations) {if (retained.has(location.batch)) continue;- if (location.skin || location.morph || location.morphTargets || location.skinIndices || (location.mapState.slice(0, 5).some(Boolean) && !texturedReplaceSupport.begin)) {+ if (location.skin || location.morph || location.morphTargets || location.skinIndices || (location.mapState.slice(0, 5).some(Boolean) && !texturedReplaceSupport.begin && !regroupOnly)) {throw new Error(`replaceParts can remove or regroup only existing rigid, untextured parts; ${part.name} is textured, skinned or morphed and needs a new renderer.`);}}@@ -1276,6 +1277,7 @@ export class Renderer67 {this.updateBatches.clear();const locations = this.updateLocations ??= [];locations.length = parts.length;+ let mirrorChanged = false;// Preflight every part before touching packed data or submitting GPU writes.for (let partIndex = 0; partIndex < parts.length; partIndex++) {const part = parts[partIndex];@@ -1295,7 +1297,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 (isMirroredMatrix(part.matrix) !== Boolean(location.batch.mirrored)) mirrorChanged = true;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) {@@ -1326,6 +1328,12 @@ export class Renderer67 {validateTransform(part, location.normalMatrix);location.materialSnapshot = MaterialSnapshot.of(part.material);}+ // A part that crossed a mirror (a flip animation, a toggled billboard) belongs to the other winding batch: regroup every part once.+ // replaceParts packs all parts again, so the rest of this update is done.+ if (mirrorChanged) {+ this.replaceParts([...this.partLocations.keys()].filter(part => part !== this.groundPart), { regroupOnly: true });+ return parts.length;+ }// A palette upload also changes consumers absent from the submitted part list.if (checks && this.updateSkins.size) {for (const [part, location] of this.partLocations) {diff --git a/tests/mirrored-winding.test.js b/tests/mirrored-winding.test.jsindex 62c4bcbf..042dfa90 100644--- a/tests/mirrored-winding.test.js+++ b/tests/mirrored-winding.test.js@@ -1,5 +1,7 @@import assert from 'node:assert/strict';import test from 'node:test';+import { mat3 } from 'gl-matrix';+import { materialLayerState } from '../src/material-layers.js';import { groupParts, isMirroredMatrix, Renderer67 } from '../src/renderer.js';const quad = {@@ -48,13 +50,25 @@ test('a mirrored batch draws with clockwise front faces and restores the defaultassert.deepEqual(calls, ['frontFace cw', 'draw', 'frontFace ccw', 'draw']);});-test('updateParts rejects a part whose matrix changes sign after batching', () => {+test('updateParts regroups once when a part crosses a mirror instead of throwing', () => {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 }]]);+ const part = quadPart('card', 1);+ const batch = { mirrored: false, castShadow: true, receivesShadow: true, compositeMode: 0, alphaMode: 'opaque', alphaCutoff: 0, opacity: 1, doubleSided: false, instanceData: new Float32Array(42), instanceBuffer: {} };+ renderer.partLocations = new Map([[part, { batch, index: 0, geometry: quad, skin: null, morph: null, map: null, layerState: materialLayerState({}), mapState: [null, null, null, null, null, 1, 1, 1, 0, 0.05, 0.085, 0.02], normalMatrix: mat3.create() }]]);renderer.updateSkins = new Set();renderer.updateBatches = new Set();- part.matrix[0] = -1;- assert.throws(() => renderer.updateParts([part]), /Mirroring changes.*replaceParts: sprite/);+ const regroups = [];+ renderer.replaceParts = (parts, options) => {+ regroups.push({ parts, options });+ // The real replaceParts groups by the new sign and packs every part again.+ batch.mirrored = isMirroredMatrix(part.matrix);+ };+ renderer.context = { ARRAY_BUFFER: 1, bindBuffer() {}, bufferSubData() {} };+ for (const scaleX of [1, 0.5, -0.5, -1, -0.25, 0.75]) {+ part.matrix[0] = scaleX;+ assert.equal(renderer.updateParts([part]), 1);+ }+ assert.equal(regroups.length, 2, 'one regroup for each crossing: 0.5 to -0.5 and -0.25 to 0.75');+ assert.deepEqual(regroups[0].parts, [part]);+ assert.deepEqual(regroups[0].options, { regroupOnly: true });});