Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Lift ranked faces in the path tracer and probe effects on cut geometry (#751)

Nguyen Xuan An3465c7516a40
diff --git a/bench/flicker/effects-probe.mjs b/bench/flicker/effects-probe.mjs
new file mode 100644
index 00000000..dca6580f
--- /dev/null
+++ b/bench/flicker/effects-probe.mjs
@@ -0,0 +1,126 @@
+// Effects on the cut geometry (issue #751): does a screen-space stage (ambient occlusion, depth of field, line art) draw a seam,
+// halo or speckle where the flush pass cut or ranked faces? Each stacked trap has a flat tiling (TILED_TRAPS) that shows the same
+// picture with no face over another, so nothing is cut or ranked and nothing can fight. The probe renders the trap with the flush
+// pass and its tiling, once with no effect and once through each effect, and counts the pixels that differ between the two.
+// node bench/flicker/effects-probe.mjs --asset /@fs/D:/path/city.glb --spots spots.json the same on a model's camera spots, with the
+// flush pass off (offset=0) as the other picture: there faces that are not stacked match, so `staged` above `plain` is again the effect.
+// node bench/flicker/effects-probe.mjs --url http://127.0.0.1:5261 --effects ao,dof,lines --out artifacts/flicker-effects
+// `plain` is the difference with no effect: edge pixels where the cut and the tiling put a triangle edge in a different place.
+// `staged` is the difference through the effect. Only `staged` above `plain` is the effect's own doing. Counts are pixels whose
+// largest channel differs by more than 8 (`small`) and more than 32 (`large`) of 255.
+import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
+import path from 'node:path';
+import { chromium } from 'playwright';
+
+function argument(name, fallback) {
+ const index = process.argv.indexOf(`--${name}`);
+ return index === -1 ? fallback : process.argv[index + 1];
+}
+
+// Traps with a flat tiling (TILED_TRAPS in traps.js). Any other trap, and any asset, is compared with the flush pass off instead.
+const HAS_TILING = new Set(['plaque-2m', 'plaque-20m', 'stack-30-exact']);
+const baseUrl = argument('url', 'http://127.0.0.1:5261');
+const outputFolder = argument('out', 'artifacts/flicker-effects');
+const [width, height] = argument('viewport', '1280x720').split('x').map(Number);
+const effects = argument('effects', 'ao,dof,lines').split(',');
+const traps = argument('traps', 'plaque-2m,plaque-20m,stack-30-exact').split(',');
+const assetPath = argument('asset');
+const spots = assetPath ? JSON.parse(readFileSync(argument('spots'), 'utf8')) : [];
+const extraQuery = argument('query', 'reversed=1');
+mkdirSync(outputFolder, { recursive: true });
+
+const browser = await chromium.launch({
+ channel: 'chrome', headless: true,
+ args: process.env.RENDER_CPU === '1'
+ ? ['--use-angle=swiftshader', '--enable-unsafe-swiftshader', '--ignore-gpu-blocklist', '--disable-renderer-backgrounding']
+ : ['--use-angle=d3d11', '--enable-gpu', '--ignore-gpu-blocklist', '--enable-webgl', '--disable-renderer-backgrounding'],
+});
+const page = await browser.newPage({ viewport: { width, height }, deviceScaleFactor: 1 });
+page.setDefaultTimeout(240000);
+page.on('pageerror', error => console.error('pageerror', error.message));
+
+async function capture(trap, { tiled, effect, spot = null }) {
+ const subject = assetPath ? { asset: assetPath, ids: '1', shadows: '0' } : { trap };
+ const query = new URLSearchParams({ ...subject, ...(tiled ? { ...(assetPath || !HAS_TILING.has(trap) ? {} : { tiled: '1' }), offset: '0' } : {}), ...(effect ? { effect } : {}) });
+ await page.goto(`${baseUrl}/bench/flicker/index.html?${query}&${extraQuery}`);
+ await page.evaluate(() => window.flicker.ready);
+ if (assetPath) {
+ await page.waitForFunction(() => window.flicker.info.bounds, null, { polling: 500 });
+ if (!tiled) await page.waitForFunction(() => window.flicker.info.flush, null, { polling: 500 });
+ }
+ await page.waitForTimeout(300);
+ const shot = await page.evaluate(({ eye, target }) => {
+ if (eye) window.flicker.setCamera({ eye, target });
+ return { ...window.flicker.frameBase64(), flush: window.flicker.info.flush };
+ }, spot ?? {});
+ return { width: shot.width, height: shot.height, flush: shot.flush, bytes: Buffer.from(shot.base64, 'base64') };
+}
+
+function compare(first, second) {
+ const counts = { small: 0, large: 0, maximum: 0, firstX: null };
+ for (let offset = 0; offset < first.bytes.length; offset += 4) {
+ const difference = Math.max(Math.abs(first.bytes[offset] - second.bytes[offset]), Math.abs(first.bytes[offset + 1] - second.bytes[offset + 1]), Math.abs(first.bytes[offset + 2] - second.bytes[offset + 2]));
+ if (difference > counts.maximum) counts.maximum = difference;
+ if (difference > 8) counts.small++;
+ if (difference > 32) counts.large++;
+ }
+ return counts;
+}
+
+// Pixels the effect changed (largest channel by more than 8) with no colour edge of the plain frame within two pixels. Where a
+// frame has no edge the effect has nothing to work on, so a changed pixel there is a seam, halo or speckle (a surface with real
+// occlusion at a crease is the exception, and it counts the same in the two pictures being compared). Needs no reference scene.
+function spurious(effectShot, plainShot) {
+ const { width: columns, height: rows } = plainShot;
+ const bytes = plainShot.bytes;
+ const step = (first, second) => Math.max(Math.abs(bytes[first] - bytes[second]), Math.abs(bytes[first + 1] - bytes[second + 1]), Math.abs(bytes[first + 2] - bytes[second + 2]));
+ const nearEdge = new Uint8Array(columns * rows);
+ for (let row = 1; row < rows - 1; row++) {
+ for (let column = 1; column < columns - 1; column++) {
+ const at = (row * columns + column) * 4;
+ if (Math.max(step(at, at + 4), step(at, at - 4), step(at, at + columns * 4), step(at, at - columns * 4)) <= 12) continue;
+ for (let nearRow = row - 2; nearRow <= row + 2; nearRow++) {
+ for (let nearColumn = column - 2; nearColumn <= column + 2; nearColumn++) nearEdge[nearRow * columns + nearColumn] = 1;
+ }
+ }
+ }
+ let count = 0;
+ for (let pixel = 0; pixel < columns * rows; pixel++) {
+ if (nearEdge[pixel]) continue;
+ const at = pixel * 4;
+ const change = Math.max(Math.abs(effectShot.bytes[at] - bytes[at]), Math.abs(effectShot.bytes[at + 1] - bytes[at + 1]), Math.abs(effectShot.bytes[at + 2] - bytes[at + 2]));
+ if (change > 8) count++;
+ }
+ return count;
+}
+
+async function save(shot, name) {
+ const { default: sharp } = await import('sharp');
+ await sharp(shot.bytes, { raw: { width: shot.width, height: shot.height, channels: 4 } }).png().toFile(path.join(outputFolder, `${name}.png`));
+}
+
+const rows = [];
+try {
+ const subjects = assetPath ? spots : traps.map(name => ({ name }));
+ for (const subject of subjects) {
+ const trap = subject.name;
+ const spot = assetPath ? subject : null;
+ const plainStacked = await capture(trap, { tiled: false, effect: null, spot });
+ const plainTiled = await capture(trap, { tiled: true, effect: null, spot });
+ const plain = compare(plainStacked, plainTiled);
+ for (const effect of effects) {
+ const stacked = await capture(trap, { tiled: false, effect, spot });
+ const tiled = await capture(trap, { tiled: true, effect, spot });
+ const staged = compare(stacked, tiled);
+ rows.push({ trap, effect, plain, staged, spurious: { flushOn: spurious(stacked, plainStacked), reference: spurious(tiled, plainTiled) }, flush: stacked.flush && { cutParts: stacked.flush.cutParts, ranked: stacked.flush.ranked, leftovers: stacked.flush.leftovers?.length } });
+ console.log(JSON.stringify(rows.at(-1)));
+ if (process.argv.includes('--save')) {
+ await save(stacked, `${trap}-${effect}-stacked`);
+ await save(tiled, `${trap}-${effect}-tiled`);
+ }
+ }
+ }
+ writeFileSync(path.join(outputFolder, 'effects-results.json'), JSON.stringify(rows, null, 1));
+} finally {
+ await browser.close();
+}
diff --git a/bench/flicker/results/effects-cut-geometry-960x540.json b/bench/flicker/results/effects-cut-geometry-960x540.json
new file mode 100644
index 00000000..0b4418a0
--- /dev/null
+++ b/bench/flicker/results/effects-cut-geometry-960x540.json
@@ -0,0 +1,242 @@
+[
+ {
+ "trap": "plaque-2m",
+ "effect": "ao",
+ "spuriousFlushOn": 0,
+ "spuriousReference": 0,
+ "plainDiff": 108,
+ "stagedDiff": 110
+ },
+ {
+ "trap": "plaque-2m",
+ "effect": "dof",
+ "spuriousFlushOn": 0,
+ "spuriousReference": 0,
+ "plainDiff": 108,
+ "stagedDiff": 17
+ },
+ {
+ "trap": "plaque-2m",
+ "effect": "lines",
+ "spuriousFlushOn": 0,
+ "spuriousReference": 103,
+ "plainDiff": 108,
+ "stagedDiff": 469
+ },
+ {
+ "trap": "plaque-20m",
+ "effect": "ao",
+ "spuriousFlushOn": 0,
+ "spuriousReference": 0,
+ "plainDiff": 94,
+ "stagedDiff": 97
+ },
+ {
+ "trap": "plaque-20m",
+ "effect": "dof",
+ "spuriousFlushOn": 1358,
+ "spuriousReference": 1369,
+ "plainDiff": 94,
+ "stagedDiff": 99
+ },
+ {
+ "trap": "plaque-20m",
+ "effect": "lines",
+ "spuriousFlushOn": 0,
+ "spuriousReference": 83,
+ "plainDiff": 94,
+ "stagedDiff": 279
+ },
+ {
+ "trap": "stack-30-exact",
+ "effect": "ao",
+ "spuriousFlushOn": 0,
+ "spuriousReference": 0,
+ "plainDiff": 2744,
+ "stagedDiff": 2769
+ },
+ {
+ "trap": "stack-30-exact",
+ "effect": "dof",
+ "spuriousFlushOn": 2198,
+ "spuriousReference": 2198,
+ "plainDiff": 2744,
+ "stagedDiff": 1469
+ },
+ {
+ "trap": "stack-30-exact",
+ "effect": "lines",
+ "spuriousFlushOn": 0,
+ "spuriousReference": 0,
+ "plainDiff": 2744,
+ "stagedDiff": 7056
+ },
+ {
+ "trap": "panel-15mm-176m",
+ "effect": "ao",
+ "spuriousFlushOn": 0,
+ "spuriousReference": 0,
+ "plainDiff": 0,
+ "stagedDiff": 0
+ },
+ {
+ "trap": "panel-15mm-176m",
+ "effect": "dof",
+ "spuriousFlushOn": 1542,
+ "spuriousReference": 1542,
+ "plainDiff": 0,
+ "stagedDiff": 0
+ },
+ {
+ "trap": "panel-15mm-176m",
+ "effect": "lines",
+ "spuriousFlushOn": 0,
+ "spuriousReference": 0,
+ "plainDiff": 0,
+ "stagedDiff": 0
+ },
+ {
+ "trap": "walls-16mm-1km-5deg",
+ "effect": "ao",
+ "spuriousFlushOn": 0,
+ "spuriousReference": 0,
+ "plainDiff": 0,
+ "stagedDiff": 0
+ },
+ {
+ "trap": "walls-16mm-1km-5deg",
+ "effect": "dof",
+ "spuriousFlushOn": 60,
+ "spuriousReference": 60,
+ "plainDiff": 0,
+ "stagedDiff": 0
+ },
+ {
+ "trap": "walls-16mm-1km-5deg",
+ "effect": "lines",
+ "spuriousFlushOn": 0,
+ "spuriousReference": 0,
+ "plainDiff": 0,
+ "stagedDiff": 0
+ },
+ {
+ "trap": "decal-grazing-2deg",
+ "effect": "ao",
+ "spuriousFlushOn": 0,
+ "spuriousReference": 0,
+ "plainDiff": 0,
+ "stagedDiff": 0
+ },
+ {
+ "trap": "decal-grazing-2deg",
+ "effect": "dof",
+ "spuriousFlushOn": 2375,
+ "spuriousReference": 2375,
+ "plainDiff": 0,
+ "stagedDiff": 0
+ },
+ {
+ "trap": "decal-grazing-2deg",
+ "effect": "lines",
+ "spuriousFlushOn": 6,
+ "spuriousReference": 6,
+ "plainDiff": 0,
+ "stagedDiff": 0
+ },
+ {
+ "trap": "plaque-200m",
+ "effect": "ao",
+ "spuriousFlushOn": 0,
+ "spuriousReference": 0,
+ "plainDiff": 11,
+ "stagedDiff": 11
+ },
+ {
+ "trap": "plaque-200m",
+ "effect": "dof",
+ "spuriousFlushOn": 72,
+ "spuriousReference": 77,
+ "plainDiff": 11,
+ "stagedDiff": 14
+ },
+ {
+ "trap": "plaque-200m",
+ "effect": "lines",
+ "spuriousFlushOn": 0,
+ "spuriousReference": 0,
+ "plainDiff": 11,
+ "stagedDiff": 10
+ },
+ {
+ "trap": "kitbash-duplicates",
+ "effect": "ao",
+ "spuriousFlushOn": 0,
+ "spuriousReference": 0,
+ "plainDiff": 68191,
+ "stagedDiff": 68198
+ },
+ {
+ "trap": "kitbash-duplicates",
+ "effect": "dof",
+ "spuriousFlushOn": 1516,
+ "spuriousReference": 2011,
+ "plainDiff": 68191,
+ "stagedDiff": 71504
+ },
+ {
+ "trap": "kitbash-duplicates",
+ "effect": "lines",
+ "spuriousFlushOn": 0,
+ "spuriousReference": 0,
+ "plainDiff": 68191,
+ "stagedDiff": 68235
+ },
+ {
+ "trap": "instanced-flush",
+ "effect": "ao",
+ "spuriousFlushOn": 0,
+ "spuriousReference": 0,
+ "plainDiff": 241,
+ "stagedDiff": 241
+ },
+ {
+ "trap": "instanced-flush",
+ "effect": "dof",
+ "spuriousFlushOn": 2785,
+ "spuriousReference": 2786,
+ "plainDiff": 241,
+ "stagedDiff": 244
+ },
+ {
+ "trap": "instanced-flush",
+ "effect": "lines",
+ "spuriousFlushOn": 0,
+ "spuriousReference": 0,
+ "plainDiff": 241,
+ "stagedDiff": 335
+ },
+ {
+ "trap": "plaque-closeup-0.5m",
+ "effect": "ao",
+ "spuriousFlushOn": 0,
+ "spuriousReference": 0,
+ "plainDiff": 58405,
+ "stagedDiff": 58405
+ },
+ {
+ "trap": "plaque-closeup-0.5m",
+ "effect": "dof",
+ "spuriousFlushOn": 0,
+ "spuriousReference": 0,
+ "plainDiff": 58405,
+ "stagedDiff": 58477
+ },
+ {
+ "trap": "plaque-closeup-0.5m",
+ "effect": "lines",
+ "spuriousFlushOn": 0,
+ "spuriousReference": 11,
+ "plainDiff": 58405,
+ "stagedDiff": 60128
+ }
+]
\ No newline at end of file
diff --git a/bench/flicker/traps.js b/bench/flicker/traps.js
index cd27aa6b..c5bcb082 100644
--- a/bench/flicker/traps.js
+++ b/bench/flicker/traps.js
@@ -178,6 +178,45 @@ function plaqueCloseUp() {
};
}
+// The ground truth for the stacked traps: the same picture as a flat tiling, no face over another, so nothing can fight and the
+// flush pass has nothing to rank or cut. The effects probe compares an effect on the stacked scene with the same effect here.
+// A rectangle of the given size, minus an inner rectangle of the same centre, as four strips (top, bottom, left, right).
+function frameStrips(centre, width, height, innerWidth, innerHeight, colour) {
+ const bandHeight = (height - innerHeight) / 2;
+ const bandWidth = (width - innerWidth) / 2;
+ const [x, y, z] = centre;
+ return [
+ wallQuad([x, y + (height - bandHeight) / 2, z], width, bandHeight, colour),
+ wallQuad([x, y - (height - bandHeight) / 2, z], width, bandHeight, colour),
+ wallQuad([x - (width - bandWidth) / 2, y, z], bandWidth, innerHeight, colour),
+ wallQuad([x + (width - bandWidth) / 2, y, z], bandWidth, innerHeight, colour),
+ ];
+}
+
+function tiledPlaque(distance) {
+ return {
+ parts: [
+ part('wall', frameStrips([0, 2, 0], 10, 4, 2, 1, faceColour(0))),
+ part('plaque', [wallQuad([0, 2, 0], 2, 1, faceColour(1))]),
+ ],
+ eye: [distance * 0.3, 2 + distance * 0.1, distance],
+ target: [0, 2, 0],
+ };
+}
+
+// Ring `index` of exactStack is quad `index` minus quad `index + 1`; the last one is whole.
+function tiledStack() {
+ const count = 30;
+ const widthOf = index => 6 - index * 0.18;
+ const heightOf = index => 4 - index * 0.12;
+ const quads = [];
+ for (let index = 0; index < count - 1; index++) {
+ quads.push(...frameStrips([0, 2, 0], widthOf(index), heightOf(index), widthOf(index + 1), heightOf(index + 1), faceColour(index)));
+ }
+ quads.push(wallQuad([0, 2, 0], widthOf(count - 1), heightOf(count - 1), faceColour(count - 1)));
+ return { parts: [part('stack', quads)], eye: [3, 3, 9], target: [0, 2, 0] };
+}
+
export const TRAPS = {
'plaque-2m': () => plaqueOnWall(2),
'plaque-20m': () => plaqueOnWall(20),
@@ -191,3 +230,10 @@ export const TRAPS = {
'instanced-flush': instancedFlush,
'plaque-closeup-0.5m': plaqueCloseUp,
};
+
+// Each stacked trap that has a flat tiling, under the name of the trap it stands in for. Kept apart so probe.mjs --traps does not run them.
+export const TILED_TRAPS = {
+ 'plaque-2m': () => tiledPlaque(2),
+ 'plaque-20m': () => tiledPlaque(20),
+ 'stack-30-exact': tiledStack,
+};
diff --git a/bench/flicker/viewer.js b/bench/flicker/viewer.js
index ba8eac7e..2c028f8e 100644
--- a/bench/flicker/viewer.js
+++ b/bench/flicker/viewer.js
@@ -5,7 +5,11 @@ import { Renderer67 } from '../../src/index.js';
import { parseGltf } from '../../src/gltf.js';
import { resolveFlushParts } from '../../src/coplanar-overlap.js';
import { flushOrderOf } from '../../src/depth-layer.js';
-import { TRAPS } from './traps.js';
+import { installRenderPasses } from '../../src/render-passes.js';
+import { installCameraEffects } from '../../src/camera-effects.js';
+import { installLineArt, resolveLineArt } from '../../src/line-art.js';
+import { resolveEffects } from '../../src/effects.js';
+import { TRAPS, TILED_TRAPS } from './traps.js';
import { collectWorldTriangles, castPixelOwners, compareWithGroundTruth } from './ground-truth.js';
// One flat colour per part, no textures, so a pixel's colour says which part owns it and a changed colour is a changed owner.
@@ -97,10 +101,20 @@ const options = {
// facets=2: the colour of every triangle is its own number, drawn unlit, so the frame tells exactly which face is shown at a pixel.
triangleIds: parameters.get('facets') === '2',
};
+// effect=ao|dof|lines|all draws the frame through that screen-space stage (issue #751, effects on cut geometry): the renderer gets a
+// depth texture, the add-ons install, and frameFor carries the stage settings. Without it nothing changes.
+const EFFECTS = new Set(['ao', 'dof', 'lines', 'all']);
+const effectName = parameters.get('effect');
+if (effectName && !EFFECTS.has(effectName)) throw new Error(`Unknown effect ${effectName}. Use one of: ${[...EFFECTS].join(', ')}.`);
+const usesEffect = name => effectName === name || effectName === 'all';
const trapName = parameters.get('trap');
// The trap name comes from the URL, so only the table's own entries count, never an inherited method such as toString.
function trapBuilder() {
+ if (parameters.get('tiled') === '1') {
+ if (!Object.hasOwn(TILED_TRAPS, trapName)) throw new Error(`Trap ${trapName} has no flat tiling. Use one of: ${Object.keys(TILED_TRAPS).join(', ')}.`);
+ return TILED_TRAPS[trapName];
+ }
if (!Object.hasOwn(TRAPS, trapName)) throw new Error(`Unknown trap ${trapName}. Use one of: ${Object.keys(TRAPS).join(', ')}.`);
return TRAPS[trapName];
}
@@ -147,10 +161,23 @@ function markDirty() {
context.clearRect(0, 0, overlay.width, overlay.height);
}
+// The stage settings of the effect= parameter: strong enough that a seam shows, and the focus at the pivot so depth of field blurs
+// the surfaces in front and behind it.
+function effectSettings() {
+ const settings = {};
+ const effects = {};
+ if (usesEffect('ao')) Object.assign(effects, { ambientOcclusion: 1, ambientOcclusionRadius: Math.max(extent / 40, 0.05) });
+ if (usesEffect('dof')) effects.depthOfField = { blur: 0.6, focusDistance: camera.distance };
+ settings.effects = resolveEffects(effects);
+ if (usesEffect('lines')) settings.lines = resolveLineArt({ width: 1.5, boundaries: true, creaseAngle: 30, depthJump: 0.08 });
+ return settings;
+}
+
function frameFor(jitterPixels = 0) {
const frame = { eye: eyePosition(), target: camera.pivot, up: [0, 1, 0], fov: FIELD_OF_VIEW, far: Math.max(extent * 2.5, 100, camera.distance * 2 + extent) };
if (!options.nearFit) frame.near = 0.1;
if (jitterPixels) frame.shift = [jitterPixels / canvas.width, 0];
+ if (effectName) Object.assign(frame, effectSettings());
return frame;
}
@@ -200,7 +227,13 @@ async function build() {
ground: false, hdr: !options.triangleIds, samples: 4, pixelRatio: Math.min(devicePixelRatio, 1.5), memoryBudgetMiB: 1024,
reversedDepth: options.reversed ? 'auto' : false,
resolveCoplanar: options.offset ? resolveAndReport : false,
+ ...(effectName ? { depth: true } : {}),
});
+ if (effectName) {
+ installRenderPasses(renderer);
+ installCameraEffects(renderer);
+ installLineArt(renderer);
+ }
window.flickerRenderer = renderer;
window.flickerParts = loaded.parts;
document.querySelector('#drop').hidden = true;
@@ -558,8 +591,20 @@ async function loadTrap() {
bindControls();
requestAnimationFrame(tick);
document.querySelector('#speedValue').textContent = '';
+// The frame as raw RGBA bytes in base64, for the effects probe to compare two scenes pixel by pixel.
+function frameBase64() {
+ const scratch = document.createElement('canvas');
+ scratch.width = canvas.width;
+ scratch.height = canvas.height;
+ renderer.render(frameFor(0));
+ const bytes = new Uint8Array(readFrame(scratch.getContext('2d', { willReadFrequently: true })).buffer.slice(0));
+ let text = '';
+ for (let start = 0; start < bytes.length; start += 32768) text += String.fromCharCode(...bytes.subarray(start, start + 32768));
+ return { width: canvas.width, height: canvas.height, base64: btoa(text) };
+}
+
window.flicker = {
- setCamera, probe, truth, swapDetails, build, options, frameWholeScene,
+ frameBase64, setCamera, probe, truth, swapDetails, build, options, frameWholeScene,
get info() { return { depthMode: depthModeLabel(), ...(renderer ? nearAndFar() : {}), extent, bounds, canvas: [canvas.width, canvas.height], memory: renderer?.memoryReport?.(), flush: flushReport }; },
render: () => { markDirty(); renderer?.render(frameFor(0)); },
traps: Object.keys(TRAPS),
diff --git a/changes/751-effects-cut-geometry.md b/changes/751-effects-cut-geometry.md
new file mode 100644
index 00000000..d297bfab
--- /dev/null
+++ b/changes/751-effects-cut-geometry.md
@@ -0,0 +1 @@
+- The path tracer lifts faces the flush pass ranked instead of cutting, so the face in front is hit first and the one behind no longer shows through (#751)
diff --git a/changes/751-effects-cut-geometry.size.md b/changes/751-effects-cut-geometry.size.md
new file mode 100644
index 00000000..a393f143
--- /dev/null
+++ b/changes/751-effects-cut-geometry.size.md
@@ -0,0 +1 @@
+- entry:path-tracer: 680 bytes gzip so a face the flush pass ranked in front of another is the one a ray hits; without it the face behind showed through (the fix of #751 for traces).
diff --git a/docs/path-tracer.md b/docs/path-tracer.md
index fd0d6ac7..9a5171c4 100644
--- a/docs/path-tracer.md
+++ b/docs/path-tracer.md
@@ -19,6 +19,7 @@ Unidirectional path tracing against the triangle BVH that the [light bake](light
- Surfaces: diffuse, GGX specular with metals, clear coat, glass (`transmission`, `ior`, rough glass), emission, image maps (`map`, with `alphaMode: "mask"` cutouts, `normalMap` with `normalScale`, and `metallicRoughnessMap`, whose green channel scales roughness and blue scales metallic as in the rasterizer; box-projected materials read all of them through the UVs of their projection, the same ones the glTF export writes) and vertex colour. Skinned parts are drawn at their current pose.
- Lights: the sun (`keyColor`, `lightDirection`, as a 1 degree disk), point lights with a radius, spot lights with a soft cone, rectangular area lights, and the environment map with its rotation. All of them cast soft shadows, whatever their `castShadow` says, as in Cycles. Light linking is honoured: a light with `affects` (or the sun with `environment.keyAffects`) adds nothing at a part it skips, as a direct light or as a bounce source, and still shadows the other lights.
+- Faces on one plane: the trace uses the same cut geometry as the raster view (faces hidden under a face on their plane are removed), and a face the flush pass ranked in front of another instead of cutting it is lifted by 0.1 mm per rank, so the face in front is the one a ray hits (#751).
- Light that bounces between surfaces, and the sky seen in mirrors and through glass.
- Emission: `emission` times `emissiveColor` (the base colour when none is given) times the `emissiveMap` texel at the hit, so a screen or a sign glows with its picture and lights what is near it. An emissive surface is found by the paths that hit it, not sampled as a light, so a small bright panel is noisy at low sample counts.
- Volume fog: `environment.volumeFog` is traced as a homogeneous medium inside its box, with its `density`, `color` (the scattering albedo), `anisotropy` (Henyey-Greenstein) and `maxDistance`. The distance to each scattering event is drawn from the exact free-flight distribution, so there is no step count and no banding. Every event is lit by next-event estimation (sun, point, spot, area lights and the sky, with shadow rays) and light reaching a surface through the fog is dimmed by it. Fog events count as bounces. `noiseAmount`, `noiseScale`, `drift`, `steps` and the `ambient` glow are rasterizer tricks and are not used.
diff --git a/src/flush-lift.js b/src/flush-lift.js
new file mode 100644
index 00000000..a2bad748
--- /dev/null
+++ b/src/flush-lift.js
@@ -0,0 +1,78 @@
+import { determinantSign } from './flush-search.js';
+import { flushOrderOf } from './depth-layer.js';
+
+// The flush pass (flush-resolve.js) orders two faces on one plane with a rank, a depth bias at draw time. A ray has no such bias:
+// where the pass ranked two faces instead of cutting one away, the rays see both at the same distance and the face behind may win
+// the pixel. The path tracer lifts each ranked triangle along its front normal by the same step the rasteriser uses (one rank is
+// 0.1 mm plus 2^-19 of the largest coordinate), so the face in front is hit first. Vertices are copied for a ranked triangle, since a
+// vertex may be shared by triangles of different ranks.
+const RANK_STEP = 1e-4;
+const RANK_RELATIVE_STEP = 2 ** -19;
+
+/** The rank of every triangle of the geometry a part is traced with (see `traceGeometryOf`), or null when none is above zero. */
+function ranksOfTracedGeometry(order) {
+ if (!order) return null;
+ if (order.geometry) {
+ const ranks = new Uint8Array(order.geometry.indices.length / 3);
+ for (const { start, count, rank } of order.ranges) ranks.fill(rank, start / 3, (start + count) / 3);
+ return ranks;
+ }
+ return order.triangleRanks;
+}
+
+function averageScale(matrix) {
+ const lengths = [0, 4, 8].map(column => Math.hypot(matrix[column], matrix[column + 1], matrix[column + 2]));
+ return (lengths[0] + lengths[1] + lengths[2]) / 3 || 1;
+}
+
+function largestCoordinate(positions, matrix, scale) {
+ let largest = 0;
+ for (const value of positions) largest = Math.max(largest, Math.abs(value));
+ return largest * scale + Math.max(Math.abs(matrix[12]), Math.abs(matrix[13]), Math.abs(matrix[14]));
+}
+
+/**
+ * Returns `geometry` with every triangle ranked above zero moved toward its front by rank steps, on copied vertices. A part
+ * with no ranked triangle returns the same geometry object.
+ */
+export function liftRankedTriangles(part, geometry) {
+ const order = flushOrderOf(part);
+ const ranks = ranksOfTracedGeometry(order);
+ if (!ranks || !ranks.some(rank => rank > 0)) return geometry;
+ const matrix = part.matrix;
+ const scale = averageScale(matrix);
+ const step = (RANK_STEP + largestCoordinate(geometry.positions, matrix, scale) * RANK_RELATIVE_STEP) / scale;
+ const flip = determinantSign(matrix);
+ const { positions, indices } = geometry;
+ const vertexCount = positions.length / 3;
+ const liftedTriangles = ranks.reduce((count, rank) => count + (rank > 0 ? 1 : 0), 0);
+ const copied = { positions: new Float32Array((vertexCount + liftedTriangles * 3) * 3), indices: Uint32Array.from(indices) };
+ copied.positions.set(positions);
+ const optional = ['normals', 'uvs', 'colors'].filter(name => geometry[name]);
+ const widths = { normals: 3, uvs: 2, colors: 3 };
+ for (const name of optional) {
+ copied[name] = new Float32Array((vertexCount + liftedTriangles * 3) * widths[name]);
+ copied[name].set(geometry[name]);
+ }
+ let nextVertex = vertexCount;
+ for (let triangle = 0; triangle < ranks.length; triangle++) {
+ if (ranks[triangle] === 0) continue;
+ const corners = [0, 1, 2].map(corner => indices[triangle * 3 + corner]);
+ const [first, second, third] = corners.map(vertex => [positions[vertex * 3], positions[vertex * 3 + 1], positions[vertex * 3 + 2]]);
+ const edgeOne = [second[0] - first[0], second[1] - first[1], second[2] - first[2]];
+ const edgeTwo = [third[0] - first[0], third[1] - first[1], third[2] - first[2]];
+ const normal = [edgeOne[1] * edgeTwo[2] - edgeOne[2] * edgeTwo[1], edgeOne[2] * edgeTwo[0] - edgeOne[0] * edgeTwo[2], edgeOne[0] * edgeTwo[1] - edgeOne[1] * edgeTwo[0]];
+ const length = Math.hypot(...normal) || 1;
+ const distance = ranks[triangle] * step * flip / length;
+ corners.forEach((vertex, corner) => {
+ const target = nextVertex++;
+ for (let axis = 0; axis < 3; axis++) copied.positions[target * 3 + axis] = positions[vertex * 3 + axis] + normal[axis] * distance;
+ for (const name of optional) {
+ const width = widths[name];
+ for (let slot = 0; slot < width; slot++) copied[name][target * width + slot] = geometry[name][vertex * width + slot];
+ }
+ copied.indices[triangle * 3 + corner] = target;
+ });
+ }
+ return { ...geometry, ...copied };
+}
diff --git a/src/path-tracer-scene.js b/src/path-tracer-scene.js
index 1f79c1e9..3271b331 100644
--- a/src/path-tracer-scene.js
+++ b/src/path-tracer-scene.js
@@ -8,6 +8,7 @@ import { bindLocalVolumeParts } from './local-volume-parts.js';
import { resolveTraceSubsurface } from './path-tracer-subsurface.js';
import { lightShapeSupport } from './shader-registry.js';
import { flushOrderOf } from './depth-layer.js';
+import { liftRankedTriangles } from './flush-lift.js';
// The scene a path trace reads: every part flattened into one world-space triangle soup with per-vertex normals, UVs
// and colours, one resolved material per part, the lights in plain arrays, and the environment map as a sampling table.
@@ -181,7 +182,7 @@ function validatePart(part, geometry) {
function traceGeometry(part) {
// Faces hidden under a face on the same plane are cut away for the rasteriser (flush-resolve.js); rays get the same
// geometry, or the two faces would split the hits between them.
- const geometry = part.skin ? skinnedGeometry(part) : flushOrderOf(part)?.geometry ?? part.geometry;
+ const geometry = part.skin ? skinnedGeometry(part) : liftRankedTriangles(part, flushOrderOf(part)?.geometry ?? part.geometry);
const { boxMapScale = 0, boxMapAxis = 1 } = part.material ?? {};
if (!(boxMapScale > 0)) return geometry;
return boxProjectedGeometry(geometry, columnLengths(part.matrix ?? IDENTITY_MATRIX), boxMapScale, boxMapAxis);
diff --git a/tests/flush-path-tracer.test.js b/tests/flush-path-tracer.test.js
new file mode 100644
index 00000000..9b540ae5
--- /dev/null
+++ b/tests/flush-path-tracer.test.js
@@ -0,0 +1,68 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { resolveFlushParts } from '../src/coplanar-overlap.js';
+import { renderPathTracedImage } from '../src/path-tracer.js';
+import { liftRankedTriangles } from '../src/flush-lift.js';
+
+// The path tracer draws the cut geometry of the flush pass (path-tracer-scene.js), but a rank is a rasteriser bias it cannot use.
+// Where the pass ranks two faces on one plane instead of cutting one away, the rays see both at the same distance and the
+// face behind may win the pixel (issue #751, effects on cut geometry). Each case here looks at one flush pair head on and reads the
+// albedo of the first surface hit at the middle pixel: it must be the face the pass ranked in front.
+const IDENTITY = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
+const RED = [0.9, 0.1, 0.1];
+const GREEN = [0.1, 0.9, 0.1];
+const CAMERA = { eye: [0, 0, 4], target: [0, 0, 0], up: [0, 1, 0], fov: 30 };
+const OPTIONS = { width: 17, height: 17, samples: 1, bounces: 1, denoise: false, threads: 1 };
+
+function quadPart(name, half, color, material = {}) {
+ const geometry = {
+ positions: new Float32Array([-half, -half, 0, half, -half, 0, half, half, 0, -half, half, 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]),
+ };
+ return { name, geometry, matrix: new Float32Array(IDENTITY), material: { tag: 'surface', metallic: 0, roughness: 1, color, ...material } };
+}
+
+async function centreAlbedo(parts) {
+ const { features } = await renderPathTracedImage({ parts, environment: { keyColor: [1, 1, 1], lightDirection: [0, 0, 1] }, camera: CAMERA }, OPTIONS);
+ const centre = (8 * 17 + 8) * 3;
+ return Array.from(features.albedo.slice(centre, centre + 3), value => Math.round(value * 10) / 10);
+}
+
+async function centreAlbedoOfBothOrders(first, second) {
+ const forward = [first(), second()];
+ resolveFlushParts(forward);
+ const backward = [second(), first()];
+ resolveFlushParts(backward);
+ return [await centreAlbedo(forward), await centreAlbedo(backward)];
+}
+
+test('of two identical faces on one plane the later part shows, in either part order', async () => {
+ const lower = () => quadPart('lower', 1, RED);
+ const upper = () => quadPart('upper', 1, GREEN);
+ const [forward, backward] = await centreAlbedoOfBothOrders(lower, upper);
+ assert.deepEqual(forward, GREEN, 'upper comes last');
+ assert.deepEqual(backward, RED, 'lower comes last');
+});
+
+test('a one-sided patch on a double-sided leaf shows the patch', async () => {
+ const leaf = () => quadPart('leaf', 2, RED, { doubleSided: true });
+ const patch = () => quadPart('patch', 1, GREEN);
+ const [forward, backward] = await centreAlbedoOfBothOrders(leaf, patch);
+ assert.deepEqual(forward, GREEN);
+ assert.deepEqual(backward, GREEN);
+});
+
+test('a lift moves only ranked triangles, along their front normal, on copied vertices', () => {
+ const lower = quadPart('lower', 1, RED);
+ const upper = quadPart('upper', 1, GREEN);
+ const parts = [lower, upper];
+ resolveFlushParts(parts);
+ assert.equal(liftRankedTriangles(lower, lower.geometry), lower.geometry, 'a part with no rank keeps its geometry object');
+ const lifted = liftRankedTriangles(upper, upper.geometry);
+ assert.equal(lifted.positions.length, (4 + 6) * 3, 'two ranked triangles bring three vertices each');
+ assert.deepEqual(Array.from(lifted.positions.slice(0, 12)), Array.from(upper.geometry.positions), 'the original vertices stay as they were');
+ const step = 1e-4 + (1 * 1 + 0) * 2 ** -19;
+ for (let vertex = 4; vertex < 10; vertex++) assert.ok(Math.abs(lifted.positions[vertex * 3 + 2] - step) < 1e-9, 'lifted by one rank along +z');
+ assert.equal(lifted.normals.length, lifted.positions.length);
+});