Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Keep mirrored parts facing outward in the flattened trace scene (#1014)

Nguyen Xuan An53cc7331e963
diff --git a/bench/instancing/render-copies.mjs b/bench/instancing/render-copies.mjs
index 46fd64e1..5cc47997 100644
--- a/bench/instancing/render-copies.mjs
+++ b/bench/instancing/render-copies.mjs
@@ -1,6 +1,6 @@
// Renders N copies of one small mesh through the native "cycles" kernel, either as shared instances or flattened into one
// triangle soup, and writes the linear RGBA floats beside a JSON report. Usage:
-// node bench/instancing/render-copies.mjs <instanced|flattened> <output folder> [copies] [width] [height] [samples] [variant] [seed]
+// node bench/instancing/render-copies.mjs <instanced|flattened> <output folder> [copies] [width] [height] [samples] [variant] [seed] [kernel]
// A variant sets how the copies are placed: translate (default), rotscale (rotated, non-uniform scale), mirror (negative
// determinant), mirror-rotscale, or emissive (translate, with one emissive material).
import { mkdirSync, writeFileSync } from 'node:fs';
@@ -9,7 +9,7 @@ import { buildCopyScene } from './copies-scene.mjs';
import { createCamera } from '../../src/path-tracer.js';
import { buildTraceScene } from '../../src/path-tracer-scene.js';
-const [mode, outputFolder, copiesText = '1000', widthText = '160', heightText = '120', samplesText = '64', variant = 'translate', seedText = '1'] = process.argv.slice(2);
+const [mode, outputFolder, copiesText = '1000', widthText = '160', heightText = '120', samplesText = '64', variant = 'translate', seedText = '1', kernel = 'cycles'] = process.argv.slice(2);
if (mode !== 'instanced' && mode !== 'flattened') throw new RangeError('Pass "instanced" or "flattened" as the first argument.');
const copyCount = Number(copiesText);
const width = Number(widthText);
@@ -24,13 +24,14 @@ const packStarted = performance.now();
const scene = buildTraceScene(parts, environment, { instancing: mode === 'instanced' });
const input = buildNativeInputV2(scene, camera, { width, height, samples, seed });
const packSeconds = (performance.now() - packStarted) / 1000;
-const traced = traceNative(input, { width, height, samples, kernel: 'cycles' });
-const stem = `${variant}-${mode}-seed${seed}`;
+const traced = traceNative(input, { width, height, samples, kernel });
+const kernelSuffix = kernel === 'cycles' ? '' : `-${kernel}`;
+const stem = `${variant}-${mode}-seed${seed}${kernelSuffix}`;
mkdirSync(outputFolder, { recursive: true });
writeFileSync(`${outputFolder}/${stem}.f32`, Buffer.from(traced.rgba.buffer, traced.rgba.byteOffset, traced.rgba.byteLength));
const report = {
- mode, variant, seed, copyCount, width, height, samples, adapter: traced.adapter, packSeconds,
+ mode, variant, seed, kernel, copyCount, width, height, samples, adapter: traced.adapter, packSeconds,
instanceCount: input.instanceCount, triangleCount: input.triangleCount, geometryTriangles: geometry.indices.length / 3,
trianglesBytes: input.triangles.byteLength, instancesBytes: input.instances.byteLength,
setupSeconds: traced.setupSeconds, accelerationBuildSeconds: traced.accelerationBuildSeconds, uploadSeconds: traced.uploadSeconds,
diff --git a/changes/1014.md b/changes/1014.md
new file mode 100644
index 00000000..3dcc0d6f
--- /dev/null
+++ b/changes/1014.md
@@ -0,0 +1 @@
+- A mirrored copy (negative determinant matrix) in a flattened path trace now keeps its triangles facing outward, so the native `cycles` kernel renders it like the instanced scene (#1014)
diff --git a/docs/path-tracer.md b/docs/path-tracer.md
index f7697d12..62ca4ad4 100644
--- a/docs/path-tracer.md
+++ b/docs/path-tracer.md
@@ -65,6 +65,8 @@ Also checked before any ray is traced: samples times pixels times bounces at mos
- A part's material is its own entry in `materials`, so copies may differ in material; a multi-material mesh stays one geometry with the materials the part names.
- `buildNativeInput` (the `legacy` kernel) refuses an instanced scene with an error; build the scene without `instancing` for that kernel. Render jobs still export flattened tables.
+A part whose matrix mirrors (negative determinant) is flattened with its vertex normals kept outward and the last two corners of each triangle swapped, so the cross-product normal of every triangle points outward too. The native `cycles` kernel derives its geometric normal from that winding, and an instanced mirrored part reaches the same result through its negative-scale flag; a scene without a mirrored part is unchanged byte for byte.
+
The same scene and options give the same bytes. Random numbers come from a hash of the pixel, the sample and the seed, never from `Math.random` or the clock, and a pixel does not depend on which thread drew it.
## Choosing a backend
diff --git a/src/path-tracer-scene.js b/src/path-tracer-scene.js
index 1ba8fac8..6d62b304 100644
--- a/src/path-tracer-scene.js
+++ b/src/path-tracer-scene.js
@@ -65,6 +65,12 @@ function normalMatrix(matrix) {
return cofactors.map(value => value * sign);
}
+/** True when the matrix mirrors (negative determinant of its upper 3x3), which turns every triangle inside out. */
+function mirrorsGeometry(matrix) {
+ const [a, b, c, , d, e, f, , g, h, i] = matrix;
+ return a * (e * i - f * h) + b * (f * g - d * i) + c * (d * h - e * g) < 0;
+}
+
function srgbToLinearTable() {
const table = new Float32Array(256);
for (let value = 0; value < 256; value++) {
@@ -240,7 +246,14 @@ function writeWorldPart(world, part, geometry, partIndex, vertexOffset, triangle
}
if (geometry.uvs) world.uvs.set(geometry.uvs, (vertexOffset) * 2);
if (geometry.colors) world.colors.set(geometry.colors, vertexOffset * 3);
- for (let slot = 0; slot < geometry.indices.length; slot++) world.indices[triangleOffset * 3 + slot] = geometry.indices[slot] + vertexOffset;
+ // A mirrored part keeps outward vertex normals, so its triangles swap their last two corners to keep the winding
+ // (and the cross-product normal) outward too.
+ const mirrored = mirrorsGeometry(matrix);
+ const cornerOrder = mirrored ? [0, 2, 1] : [0, 1, 2];
+ for (let slot = 0; slot < geometry.indices.length; slot++) {
+ const sourceSlot = slot - (slot % 3) + cornerOrder[slot % 3];
+ world.indices[triangleOffset * 3 + slot] = geometry.indices[sourceSlot] + vertexOffset;
+ }
world.triangleMaterial.fill(partIndex, triangleOffset, triangleOffset + geometry.indices.length / 3);
}
diff --git a/tests/native-instancing-equivalence.test.js b/tests/native-instancing-equivalence.test.js
index 764c7e73..f168e8ce 100644
--- a/tests/native-instancing-equivalence.test.js
+++ b/tests/native-instancing-equivalence.test.js
@@ -56,7 +56,7 @@ function tileMeanRatios(candidate, reference) {
const addonSkip = findNativeAddon() ? false : 'the native addon is not built';
-for (const variant of ['translate', 'rotscale', 'emissive']) {
+for (const variant of ['translate', 'rotscale', 'mirror', 'mirror-rotscale', 'emissive']) {
test(`instanced ${variant} copies render the flattened image within tolerance`, { skip: addonSkip }, t => {
let flattened;
try {
diff --git a/tests/path-tracer-scene-mirror.test.js b/tests/path-tracer-scene-mirror.test.js
new file mode 100644
index 00000000..fb461f34
--- /dev/null
+++ b/tests/path-tracer-scene-mirror.test.js
@@ -0,0 +1,67 @@
+import assert from 'node:assert/strict';
+import { createHash } from 'node:crypto';
+import test from 'node:test';
+import { buildCopyScene } from '../bench/instancing/copies-scene.mjs';
+import { buildTraceScene } from '../src/path-tracer-scene.js';
+
+const COPIES = 8;
+
+function sceneDigest(scene) {
+ const hash = createHash('sha256');
+ for (const name of ['positions', 'normals', 'uvs', 'colors', 'indices', 'triangleMaterial']) {
+ hash.update(Buffer.from(scene[name].buffer, scene[name].byteOffset, scene[name].byteLength));
+ }
+ return hash.digest('hex');
+}
+
+// Every triangle's cross-product normal, dotted with the mean of its three vertex normals.
+function windingAgreement(scene) {
+ const { positions, normals, indices } = scene;
+ const agreements = [];
+ for (let triangle = 0; triangle < indices.length / 3; triangle++) {
+ const [first, second, third] = [0, 1, 2].map(corner => indices[triangle * 3 + corner] * 3);
+ const edgeOne = [0, 1, 2].map(axis => positions[second + axis] - positions[first + axis]);
+ const edgeTwo = [0, 1, 2].map(axis => positions[third + axis] - positions[first + axis]);
+ const cross = [
+ edgeOne[1] * edgeTwo[2] - edgeOne[2] * edgeTwo[1],
+ edgeOne[2] * edgeTwo[0] - edgeOne[0] * edgeTwo[2],
+ edgeOne[0] * edgeTwo[1] - edgeOne[1] * edgeTwo[0],
+ ];
+ let agreement = 0;
+ for (let axis = 0; axis < 3; axis++) agreement += cross[axis] * (normals[first + axis] + normals[second + axis] + normals[third + axis]);
+ agreements.push(agreement);
+ }
+ return agreements;
+}
+
+for (const variant of ['translate', 'rotscale', 'mirror', 'mirror-rotscale']) {
+ test(`${variant} copies flatten with a cross-product normal that agrees with the vertex normals`, () => {
+ const { parts, environment } = buildCopyScene(variant, COPIES);
+ const agreements = windingAgreement(buildTraceScene(parts, environment));
+ assert.ok(agreements.length > 0);
+ assert.ok(agreements.every(agreement => agreement > 0), `${agreements.filter(agreement => agreement <= 0).length} triangles face inward`);
+ });
+}
+
+test('a mirrored part swaps the last two corners of each triangle and keeps its first corner', () => {
+ const { geometry, parts, environment } = buildCopyScene('mirror', 1);
+ const scene = buildTraceScene(parts, environment);
+ for (let triangle = 0; triangle < geometry.indices.length / 3; triangle++) {
+ assert.equal(scene.indices[triangle * 3], geometry.indices[triangle * 3]);
+ assert.equal(scene.indices[triangle * 3 + 1], geometry.indices[triangle * 3 + 2]);
+ assert.equal(scene.indices[triangle * 3 + 2], geometry.indices[triangle * 3 + 1]);
+ }
+});
+
+// Digests of the scene built before mirrored parts changed winding: scenes without a mirrored part stay byte identical.
+const UNMIRRORED_DIGESTS = {
+ translate: '4916b01dfdf073757660a7ff31385c8ee3bce96c00e0d36b8eb805692d4e4fb9',
+ rotscale: '2c6fa5d10f9598ae5e27cf2f641bf2468384d836a470fffac25b943dc01e53d6',
+};
+
+for (const [variant, expected] of Object.entries(UNMIRRORED_DIGESTS)) {
+ test(`${variant} copies build the same trace scene bytes as before`, () => {
+ const { parts, environment } = buildCopyScene(variant, COPIES);
+ assert.equal(sceneDigest(buildTraceScene(parts, environment)), expected);
+ });
+}