Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Convert glTF anisotropy to the kernel's Cycles parameters in native jobs, add the bench path to the parity run (#1036)

Nguyen Xuan An4b0ff66928ff
diff --git a/bench/job-materials/figure.mjs b/bench/job-materials/figure.mjs
index e6d4bd1e..7291a346 100644
--- a/bench/job-materials/figure.mjs
+++ b/bench/job-materials/figure.mjs
@@ -18,12 +18,16 @@ function readNpy(path) {
const LABEL_HEIGHT = 28;
+const SCALE = 2;
+
async function panel(path, label) {
- const { width, height, data } = readNpy(path);
- const rgba = toneMapToRgba8(data, width, height);
+ const source = readNpy(path);
+ const rgba = toneMapToRgba8(source.data, source.width, source.height);
+ const width = source.width * SCALE;
+ const height = source.height * SCALE;
const labelSvg = Buffer.from(`<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${LABEL_HEIGHT}"><rect width="100%" height="100%" fill="#111"/>`
+ `<text x="10" y="19" font-family="sans-serif" font-size="15" fill="#eee">${label}</text></svg>`);
- const image = await sharp(Buffer.from(rgba.buffer), { raw: { width, height, channels: 4 } }).removeAlpha().png().toBuffer();
+ const image = await sharp(Buffer.from(rgba.buffer), { raw: { width: source.width, height: source.height, channels: 4 } }).removeAlpha().resize(width, height, { kernel: 'lanczos3' }).png().toBuffer();
return { width, height: height + LABEL_HEIGHT, input: await sharp({ create: { width, height: height + LABEL_HEIGHT, channels: 3, background: '#111' } })
.composite([{ input: image, top: 0, left: 0 }, { input: labelSvg, top: height, left: 0 }]).png().toBuffer() };
}
diff --git a/bench/job-materials/parity.mjs b/bench/job-materials/parity.mjs
index 9249a1a4..652ec6bc 100644
--- a/bench/job-materials/parity.mjs
+++ b/bench/job-materials/parity.mjs
@@ -22,7 +22,8 @@ async function describe(folder, names) {
}
// `before` exports the way a job did before #1036: the v1 tables, which drop the fields the kernel now receives.
-async function cook(folder, samples, names, before) {
+// `bench` packs the flattened scene with buildNativeInputV2 as the Cycles parity benches do, and traces it with traceNative.
+async function cook(folder, samples, names, before, bench) {
const [{ exportNativeSceneTables }, { createCamera }, pack, { buildTraceScene, refuseLocalVolumes, resolveTexture }, { buildNativeInput }, jobInput, { traceFrameNative }, tracer] = await Promise.all([
import('../../scripts/native-bake-page.js'), import('../../src/path-tracer.js'), import('../../src/path-tracer-gpu-pack.js'),
import('../../src/path-tracer-scene.js'), import('../../packages/render-native/pack-input.mjs'), import('../../packages/render-native/job-input.mjs'),
@@ -35,6 +36,16 @@ async function cook(folder, samples, names, before) {
const source = await reconstructTraceSceneSource(description);
const camera = createCamera(source.camera, WIDTH, HEIGHT);
const options = { width: WIDTH, height: HEIGHT, bounces: 8, seed: 1, fireflyClamp: 20, noiseThreshold: 0, samples };
+ if (bench) {
+ const { buildNativeInputV2 } = await import('../../packages/render-native/index.mjs');
+ const input = buildNativeInputV2(buildTraceScene(source.parts, source.environment), camera, { ...options, parts: source.parts });
+ const direct = tracer.traceNative(input, { width: WIDTH, height: HEIGHT, samples, kernel: 'cycles' });
+ const benchLinear = new Float32Array(WIDTH * HEIGHT * 3);
+ for (let pixel = 0; pixel < WIDTH * HEIGHT; pixel++) benchLinear.set(direct.rgba.subarray(pixel * 4, pixel * 4 + 3), pixel * 3);
+ await writeFloat32Npy(join(folder, `${name}-bench.npy`), benchLinear, [HEIGHT, WIDTH, 3]);
+ console.log(JSON.stringify({ scene: name, path: 'bench' }));
+ continue;
+ }
const exportedTables = exportNativeSceneTables({ parts: source.parts, environment: source.environment, camera, options, kernel: 'cycles', instancing: true, modules });
const exported = JSON.parse(JSON.stringify({ ...exportedTables, ignored: [] }));
let traced;
@@ -55,6 +66,6 @@ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href)
const folder = resolve(folderArgument ?? '');
await mkdir(folder, { recursive: true });
if (command === 'describe') await describe(folder, rest.length ? rest : PARITY_SCENE_NAMES);
- else if (command === 'cook' || command === 'before') await cook(folder, Number(rest[0]), rest.length > 1 ? rest.slice(1) : PARITY_SCENE_NAMES, command === 'before');
- else throw new RangeError('Usage: describe <folder> [scene...], or cook|before <folder> <samples> [scene...].');
+ else if (['cook', 'before', 'bench'].includes(command)) await cook(folder, Number(rest[0]), rest.length > 1 ? rest.slice(1) : PARITY_SCENE_NAMES, command === 'before', command === 'bench');
+ else throw new RangeError('Usage: describe <folder> [scene...], or cook|before|bench <folder> <samples> [scene...].');
}
diff --git a/bench/job-materials/vast-run.sh b/bench/job-materials/vast-run.sh
index aab287d1..60aa77ba 100644
--- a/bench/job-materials/vast-run.sh
+++ b/bench/job-materials/vast-run.sh
@@ -46,16 +46,18 @@ for stage in "$@"; do
blender_binary="$( (command -v blender; ls -d /opt/blender*/blender /usr/local/blender*/blender /root/blender*/blender /usr/local/bin/blender* 2>/dev/null ; find / -maxdepth 4 -name blender -type f 2>/dev/null) | head -1)"
echo "blender: ${blender_binary:-none}"
for scene in blend sheen specular-tint anisotropy iridescence absorption composite; do
+ [ -f "$folder/$scene-cycles.npy" ] && continue
"$blender_binary" -b --factory-startup --python bench/cycles-parity/render-cycles.py -- "$folder/$scene.json" "$folder/$scene-cycles" --samples 4096 --bounces 8 --seed 1 --width 192 --height 128 > "$folder/$scene-cycles.log" 2>&1 || tail -5 "$folder/$scene-cycles.log" | cut -c1-200
done
ls "$folder" | head -40
node bench/job-materials/parity.mjs cook "$folder" 4096 2>&1 | tail -10
node bench/job-materials/parity.mjs before "$folder" 4096 2>&1 | tail -10
+ node bench/job-materials/parity.mjs bench "$folder" 4096 2>&1 | tail -10
python_binary=python3
python3 -c 'import numpy' 2>/dev/null || python_binary="$(find /root/blender -maxdepth 4 -path '*bin*' -name 'python3*' -type f 2>/dev/null | head -1)"
echo "python: $python_binary"
for scene in blend sheen specular-tint anisotropy iridescence absorption composite; do
- for variant in cook before; do
+ for variant in cook before bench; do
"$python_binary" bench/cycles-parity/compare.py pair --no-flip --json-out "$folder/$scene-$variant-compare.json" "$folder/$scene-cycles.npy" "$folder/$scene-$variant.npy" >/dev/null 2>&1 || echo "COMPARE-FAILED $scene $variant"
done
done
diff --git a/packages/render-native/job-input.mjs b/packages/render-native/job-input.mjs
index 356af86c..76040df3 100644
--- a/packages/render-native/job-input.mjs
+++ b/packages/render-native/job-input.mjs
@@ -35,14 +35,25 @@ function blendFields(material, resolved) {
return { alphaMode: 'blend', opacity };
}
-function layerFields(material) {
+// The kernel reads anisotropy as the Cycles Principled parameters: a strength from 0 to 1 that stretches the roughness, and the
+// rotation in turns. A 67js material (glTF KHR_materials_anisotropy) gives a strength that sets the tangent roughness and a
+// rotation in radians. This is the same conversion bench/cycles-parity/render-cycles.py applies for Blender, so the kernel
+// draws the lobe Cycles draws for the material.
+function cyclesAnisotropyFields(material, roughness) {
+ const alpha = roughness * roughness;
+ const tangentAlpha = alpha + (1 - alpha) * material.anisotropy * material.anisotropy;
+ return {
+ anisotropy: Math.min((1 - alpha / tangentAlpha) / 0.9, 1),
+ anisotropyRotation: (material.anisotropyRotation ?? 0) / (2 * Math.PI),
+ roughness: (alpha * tangentAlpha) ** 0.25,
+ };
+}
+
+function layerFields(material, resolved) {
const fields = {};
if (material.specular !== undefined) fields.specular = material.specular;
if (material.specularColor !== undefined && !isWhite(material.specularColor)) fields.specularColor = material.specularColor;
- if (material.anisotropy > 0) {
- fields.anisotropy = material.anisotropy;
- fields.anisotropyRotation = material.anisotropyRotation ?? 0;
- }
+ if (material.anisotropy > 0) Object.assign(fields, cyclesAnisotropyFields(material, resolved.roughness));
if (material.iridescence > 0) {
fields.iridescence = material.iridescence;
fields.iridescenceIor = material.iridescenceIor ?? DEFAULT_IRIDESCENCE_IOR;
@@ -87,7 +98,7 @@ function layerTextures(material, resolved, resolveTexture) {
* that sets none of these gives an empty object, which packs to the record the v1 tables give.
*/
export function carriedMaterialFields(material, resolved, resolveTexture) {
- const fields = { ...blendFields(material, resolved), ...layerFields(material) };
+ const fields = { ...blendFields(material, resolved), ...layerFields(material, resolved) };
const textures = layerTextures(material, resolved, resolveTexture);
if (Object.keys(textures).length > 0) fields.textures = textures;
return fields;
diff --git a/summarize.cjs b/summarize.cjs
new file mode 100644
index 00000000..b710c004
--- /dev/null
+++ b/summarize.cjs
@@ -0,0 +1,13 @@
+const fs = require('fs');
+const dir = process.argv[2];
+for (const scene of ['blend', 'sheen', 'specular-tint', 'anisotropy', 'iridescence', 'absorption', 'composite']) {
+ for (const variant of ['before', 'cook']) {
+ const path = `${dir}/${scene}-${variant}-compare.json`;
+ if (!fs.existsSync(path)) { console.log(scene, variant, 'no compare json'); continue; }
+ const data = JSON.parse(fs.readFileSync(path, 'utf8'));
+ const entry = Array.isArray(data) ? data[0] : (data.comparisons ? data.comparisons[0] : data);
+ const keys = Object.keys(entry).join(',');
+ console.log(scene, variant, JSON.stringify(entry).slice(0, 420));
+ if (scene === 'blend' && variant === 'before') console.log('KEYS', keys);
+ }
+}
diff --git a/summarize2.cjs b/summarize2.cjs
new file mode 100644
index 00000000..e79a71f5
--- /dev/null
+++ b/summarize2.cjs
@@ -0,0 +1,11 @@
+const fs = require('fs');
+const dir = process.argv[2];
+for (const scene of ['blend', 'sheen', 'specular-tint', 'anisotropy', 'iridescence', 'absorption', 'composite']) {
+ for (const variant of ['before', 'cook']) {
+ const entry = JSON.parse(fs.readFileSync(`${dir}/${scene}-${variant}-compare.json`, 'utf8'));
+ const e = Array.isArray(entry) ? entry[0] : entry;
+ const t = e.tileGrid8x8 ?? {};
+ const tiles = t.tileRatios ?? t.ratios;
+ console.log(scene.padEnd(14), variant.padEnd(7), 'mean', JSON.stringify(e.channelMeanRatio), 'relMSE', e.relMse.toPrecision(3), 'tiles', JSON.stringify({ ...t, entries: undefined, tiles: undefined, worstTiles: undefined, ratios: undefined }).slice(0, 200), 'gates', JSON.stringify(e.parityGates).slice(0, 200));
+ }
+}
diff --git a/tests/native-job-materials.test.js b/tests/native-job-materials.test.js
index f59d3ad3..d90ee7ce 100644
--- a/tests/native-job-materials.test.js
+++ b/tests/native-job-materials.test.js
@@ -156,8 +156,12 @@ test('a flattened job sends blend opacity, sheen, specular, anisotropy, iridesce
assert.equal(glass.floats[31], 2);
assert.deepEqual(Array.from(glass.floats.slice(28, 31)).map(value => Number(value.toFixed(3))), [0.5, 0.8, 0.6]);
const foil = recordFloats(input, 3);
- assert.ok(Math.abs(foil.floats[11] - 0.6) < 1e-6, 'anisotropy');
- assert.ok(Math.abs(foil.floats[12] - 0.5) < 1e-6, 'anisotropy rotation');
+ // Strength 0.6 at roughness 0.3 as the Cycles parameters (the conversion of render-cycles.py), rotation in turns.
+ const alpha = 0.3 * 0.3;
+ const tangentAlpha = alpha + (1 - alpha) * 0.36;
+ assert.ok(Math.abs(foil.floats[11] - (1 - alpha / tangentAlpha) / 0.9) < 1e-6, 'anisotropy');
+ assert.ok(Math.abs(foil.floats[12] - 0.5 / (2 * Math.PI)) < 1e-6, 'anisotropy rotation in turns');
+ assert.ok(Math.abs(foil.floats[4] - (alpha * tangentAlpha) ** 0.25) < 1e-6, 'roughness of an anisotropic material');
assert.ok(Math.abs(foil.floats[6] - 0.4) < 1e-6, 'specular ior level is half the specular factor');
assert.deepEqual(Array.from(foil.floats.slice(8, 11)).map(value => Number(value.toFixed(3))), [1, 0.5, 0.2]);
assert.ok(foil.floats[22] > 0, 'thin film thickness');