Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Add depth and grey-diffuse options to the Cycles parity harness (#896)

Nguyen Xuan Ane5b8bab776ae
diff --git a/bench/cycles-parity/compare_depth.py b/bench/cycles-parity/compare_depth.py
new file mode 100644
index 00000000..6d06a4ef
--- /dev/null
+++ b/bench/cycles-parity/compare_depth.py
@@ -0,0 +1,120 @@
+"""Compare a Cook depth buffer with a Cycles camera Z depth: the share of pixels that agree within a relative tolerance.
+
+Conventions (found in the code, not assumed):
+- Cycles writes the Z depth: distance along the camera's view axis. render-cycles.py --z-depth writes it as <prefix>-depth.npy.
+- Cook's depth buffer is the first-hit distance along the unit ray direction (integrator.wgsl first_depth = surface_hit.t,
+ camera.wgsl normalises the direction). trace-native.mjs --write-depth writes it as <prefix>-depth.npy and records
+ depthConvention "ray-distance" and cameraVerticalFovDegrees in its JSON.
+This module converts the Cook side to Z depth: z = distance * cos(angle between the pixel's ray and the view axis).
+- Both write 0 where nothing is hit, and the pixel value is the mean over the samples (misses count as 0), so a pixel on a
+ silhouette holds a coverage-weighted mean in both renderers.
+"""
+import json
+import math
+import sys
+
+import numpy
+
+sys.stdout.reconfigure(encoding="utf-8", errors="replace")
+
+DEPTH_AGREEMENT_GATE = 0.999
+DEFAULT_RELATIVE_TOLERANCE = 0.01
+REPORTED_TOLERANCES = (0.001, 0.005, 0.01, 0.05)
+BACKGROUND_DEPTH_LIMIT = 1.0e9
+EDGE_RELATIVE_JUMP = 0.05
+
+
+def ray_distance_to_z_depth(ray_distance, vertical_fov_degrees):
+ """Converts distance along each pixel-centre ray into distance along the view axis (symmetric perspective camera)."""
+ height, width = ray_distance.shape
+ half_height_tangent = math.tan(math.radians(vertical_fov_degrees) / 2.0)
+ half_width_tangent = half_height_tangent * width / height
+ horizontal = ((numpy.arange(width) + 0.5) / width * 2.0 - 1.0) * half_width_tangent
+ vertical = (1.0 - (numpy.arange(height) + 0.5) / height * 2.0) * half_height_tangent
+ cosine_to_axis = 1.0 / numpy.sqrt(1.0 + horizontal[numpy.newaxis, :] ** 2 + vertical[:, numpy.newaxis] ** 2)
+ return ray_distance.astype(numpy.float64) * cosine_to_axis
+
+
+def hit_mask_of(depth):
+ return numpy.isfinite(depth) & (depth > 0.0) & (depth < BACKGROUND_DEPTH_LIMIT)
+
+
+def mark_edges(reference_depth, candidate_depth, reference_hit, candidate_hit):
+ """Pixels whose 8-neighbourhood holds a hit/miss change or a depth jump over 5 percent in either image."""
+ edge = numpy.zeros(reference_depth.shape, dtype=bool)
+ for depth, hit in ((reference_depth, reference_hit), (candidate_depth, candidate_hit)):
+ for row_shift in (-1, 0, 1):
+ for column_shift in (-1, 0, 1):
+ if row_shift == 0 and column_shift == 0:
+ continue
+ shifted_depth = numpy.roll(depth, (row_shift, column_shift), axis=(0, 1))
+ shifted_hit = numpy.roll(hit, (row_shift, column_shift), axis=(0, 1))
+ both = hit & shifted_hit
+ jump = both & (numpy.abs(depth - shifted_depth) > EDGE_RELATIVE_JUMP * numpy.maximum(depth, 1e-12))
+ edge |= jump | (hit != shifted_hit)
+ return edge
+
+
+def agreement_at(reference_depth, candidate_depth, reference_hit, candidate_hit, relative_tolerance):
+ both_hit = reference_hit & candidate_hit
+ both_background = ~reference_hit & ~candidate_hit
+ close = both_hit & (numpy.abs(candidate_depth - reference_depth) <= relative_tolerance * reference_depth)
+ return close | both_background
+
+
+def compare_depth_maps(reference_z_depth, candidate_z_depth, relative_tolerance=DEFAULT_RELATIVE_TOLERANCE):
+ """Both arguments are (height, width) Z depths, 0 or non-finite or huge where nothing is hit. Gate: DEPTH_AGREEMENT_GATE."""
+ if reference_z_depth.shape != candidate_z_depth.shape or reference_z_depth.ndim != 2:
+ raise ValueError(f"Depth maps must be two-dimensional and equal in shape, got {reference_z_depth.shape} and {candidate_z_depth.shape}.")
+ reference = reference_z_depth.astype(numpy.float64)
+ candidate = candidate_z_depth.astype(numpy.float64)
+ reference_hit = hit_mask_of(reference)
+ candidate_hit = hit_mask_of(candidate)
+ reference = numpy.where(reference_hit, reference, 0.0)
+ candidate = numpy.where(candidate_hit, candidate, 0.0)
+ total_pixels = reference.size
+ both_hit = reference_hit & candidate_hit
+ agree = agreement_at(reference, candidate, reference_hit, candidate_hit, relative_tolerance)
+ edge = mark_edges(reference, candidate, reference_hit, candidate_hit)
+ relative_error = numpy.abs(candidate[both_hit] - reference[both_hit]) / reference[both_hit]
+ ratio = candidate[both_hit] / reference[both_hit]
+ agreement_fraction = float(agree.sum()) / total_pixels
+ interior = ~edge
+ result = {
+ "relativeTolerance": relative_tolerance,
+ "agreementFraction": agreement_fraction,
+ "gate": DEPTH_AGREEMENT_GATE,
+ "depthPass": bool(agreement_fraction >= DEPTH_AGREEMENT_GATE),
+ "totalPixelCount": int(total_pixels),
+ "disagreeingPixelCount": int(total_pixels - agree.sum()),
+ "bothHitCount": int(both_hit.sum()),
+ "bothBackgroundCount": int((~reference_hit & ~candidate_hit).sum()),
+ "onlyReferenceHitCount": int((reference_hit & ~candidate_hit).sum()),
+ "onlyCandidateHitCount": int((~reference_hit & candidate_hit).sum()),
+ "agreementByTolerance": {str(tolerance): float(agreement_at(reference, candidate, reference_hit, candidate_hit, tolerance).sum()) / total_pixels for tolerance in REPORTED_TOLERANCES},
+ "edgePixelCount": int(edge.sum()),
+ "disagreeingEdgePixelCount": int((~agree & edge).sum()),
+ "disagreeingInteriorPixelCount": int((~agree & interior).sum()),
+ "agreementFractionAwayFromEdges": float((agree & interior).sum()) / max(int(interior.sum()), 1),
+ "medianCandidateOverReference": float(numpy.median(ratio)) if ratio.size else None,
+ "p99RelativeError": float(numpy.percentile(relative_error, 99)) if relative_error.size else None,
+ "maxRelativeError": float(relative_error.max()) if relative_error.size else None,
+ }
+ return result
+
+
+def run_cli(argument_list):
+ if len(argument_list) < 3 or argument_list[0].startswith("--"):
+ raise ValueError("Usage: compare_depth.py <cyclesZDepth.npy> <cookRayDistanceDepth.npy> <verticalFovDegrees> [--tolerance 0.01] [--json-out <path>]")
+ tolerance = float(argument_list[argument_list.index("--tolerance") + 1]) if "--tolerance" in argument_list else DEFAULT_RELATIVE_TOLERANCE
+ reference = numpy.load(argument_list[0])
+ cook_ray_distance = numpy.load(argument_list[1])
+ comparison = compare_depth_maps(reference, ray_distance_to_z_depth(cook_ray_distance, float(argument_list[2])), tolerance)
+ print(json.dumps(comparison))
+ if "--json-out" in argument_list:
+ with open(argument_list[argument_list.index("--json-out") + 1], "w", encoding="utf-8") as handle:
+ json.dump(comparison, handle, indent=2)
+
+
+if __name__ == "__main__":
+ run_cli(sys.argv[1:])
diff --git a/bench/cycles-parity/grey-diffuse-override.mjs b/bench/cycles-parity/grey-diffuse-override.mjs
new file mode 100644
index 00000000..3c8c49f8
--- /dev/null
+++ b/bench/cycles-parity/grey-diffuse-override.mjs
@@ -0,0 +1,32 @@
+// A grey diffuse material for every part of an exported scene: the Cook side of Blender's view-layer material override.
+// render-cycles.py --grey-diffuse builds the same material (GREY_DIFFUSE_ENTRY there), so both renderers shade one thing.
+
+export const GREY_DIFFUSE_ALBEDO = 0.8;
+
+export function createGreyDiffuseMaterial() {
+ return {
+ tag: 'surface',
+ color: [GREY_DIFFUSE_ALBEDO, GREY_DIFFUSE_ALBEDO, GREY_DIFFUSE_ALBEDO],
+ metallic: 0,
+ roughness: 1,
+ specular: 0,
+ emission: 0,
+ };
+}
+
+// Returns a copy of the scene description in which every material is the grey diffuse one and no mesh carries vertex
+// colours, so textures, emission, transmission and colour attributes cannot change the shading. Lights stay as they are.
+export function applyGreyDiffuseOverride(description) {
+ if (!Array.isArray(description.materials) || !Array.isArray(description.geometries)) {
+ throw new TypeError('applyGreyDiffuseOverride needs a scene description with materials and geometries arrays.');
+ }
+ return {
+ ...description,
+ materials: description.materials.map(() => createGreyDiffuseMaterial()),
+ images: [],
+ geometries: description.geometries.map((geometryEntry) => {
+ const { colors, ...geometryWithoutColors } = geometryEntry;
+ return geometryWithoutColors;
+ }),
+ };
+}
diff --git a/bench/cycles-parity/render-cycles.py b/bench/cycles-parity/render-cycles.py
index 5c7f2ce5..fd2e3f89 100644
--- a/bench/cycles-parity/render-cycles.py
+++ b/bench/cycles-parity/render-cycles.py
@@ -44,6 +44,9 @@ def read_flag_value(argument_list, flag_name, fallback_value):
PIXEL_FILTER_TYPES = {"box": "BOX", "gaussian": "GAUSSIAN", "blackman-harris": "BLACKMAN_HARRIS"}
+# Keep in step with GREY_DIFFUSE_MATERIAL in grey-diffuse-override.mjs: both renderers must shade the same thing.
+GREY_DIFFUSE_ENTRY = {"color": [0.8, 0.8, 0.8], "metallic": 0.0, "roughness": 1.0, "specular": 0.0}
+DEFAULT_DEPTH_SAMPLES = 64
def parse_cli_arguments():
@@ -51,7 +54,7 @@ def parse_cli_arguments():
raise ValueError("Pass script arguments after '--': <sceneJsonPath> <outputPrefix> [options].")
argument_list = sys.argv[sys.argv.index("--") + 1:]
if len(argument_list) < 2 or argument_list[0].startswith("--") or argument_list[1].startswith("--"):
- raise ValueError("Usage: blender -b --factory-startup --python bench/cycles-parity/render-cycles.py -- <sceneJsonPath> <outputPrefix> [--samples 256] [--bounces 8] [--seed 1] [--width 960] [--height 540] [--filter-type box|gaussian|blackman-harris] [--filter-width 1.0] [--keep-exr] [--part-ids]")
+ raise ValueError("Usage: blender -b --factory-startup --python bench/cycles-parity/render-cycles.py -- <sceneJsonPath> <outputPrefix> [--samples 256] [--bounces 8] [--seed 1] [--width 960] [--height 540] [--filter-type box|gaussian|blackman-harris] [--filter-width 1.0] [--keep-exr] [--part-ids] [--grey-diffuse] [--z-depth] [--depth-samples 64]")
return {
"scene_json_path": os.path.abspath(argument_list[0]),
"output_prefix": os.path.abspath(argument_list[1]),
@@ -64,6 +67,9 @@ def parse_cli_arguments():
"filter_width": float(read_flag_value(argument_list, "--filter-width", "1.0")),
"keep_exr": "--keep-exr" in argument_list,
"part_ids": "--part-ids" in argument_list,
+ "grey_diffuse": "--grey-diffuse" in argument_list,
+ "z_depth": "--z-depth" in argument_list,
+ "depth_samples": int(read_flag_value(argument_list, "--depth-samples", str(DEFAULT_DEPTH_SAMPLES))),
}
@@ -514,6 +520,46 @@ def render_part_identifier_map(scene, output_prefix, width, height):
print("PART_IDS " + json.dumps({"parts": part_names, "outputPrefix": output_prefix}))
+def apply_grey_diffuse_override(scene):
+ """Shades every object with one grey diffuse material, as the view layer's material override does."""
+ grey_material = build_blender_material("grey-diffuse-override", GREY_DIFFUSE_ENTRY, False, [], {})
+ scene.view_layers[0].material_override = grey_material
+
+
+def build_camera_z_depth_material():
+ """An emission material whose colour is the camera Z depth: the distance along the view axis, not along the ray."""
+ material = bpy.data.materials.new("camera-z-depth")
+ node_tree = material.node_tree
+ node_tree.nodes.clear()
+ camera_data_node = node_tree.nodes.new("ShaderNodeCameraData")
+ emission_node = node_tree.nodes.new("ShaderNodeEmission")
+ emission_node.inputs["Strength"].default_value = 1.0
+ output_node = node_tree.nodes.new("ShaderNodeOutputMaterial")
+ node_tree.links.new(camera_data_node.outputs["View Z Depth"], emission_node.inputs["Color"])
+ node_tree.links.new(emission_node.outputs["Emission"], output_node.inputs["Surface"])
+ return material
+
+
+def render_camera_z_depth(scene, output_prefix, width, height, depth_samples):
+ """Renders the camera Z depth through Cycles into <prefix>-depth.npy (rows from the top, 0 where nothing is hit).
+
+ A real Z pass needs a multilayer EXR or compositor nodes; the Camera Data node's View Z Depth is the same
+ quantity (Cycles' pass is camera_z_depth too) and goes through the single-layer path used for the colour image.
+ The world is switched off so a miss reads 0, which is also what Cook writes.
+ """
+ scene.view_layers[0].material_override = build_camera_z_depth_material()
+ scene.world.node_tree.nodes["Background"].inputs[1].default_value = 0.0
+ scene.cycles.samples = depth_samples
+ depth_exr_path = f"{output_prefix}-depth.exr"
+ depth_npy_path = f"{output_prefix}-depth.npy"
+ scene.render.filepath = depth_exr_path
+ bpy.ops.render.render(write_still=True)
+ load_exr_into_npy(depth_exr_path, depth_npy_path, width, height, False)
+ z_depth = numpy.load(depth_npy_path)[:, :, 0].copy()
+ numpy.save(depth_npy_path, z_depth)
+ return depth_npy_path
+
+
def execute_timed_cycles_render(scene, exr_path):
scene.render.filepath = exr_path
stats_events = []
@@ -586,6 +632,8 @@ def main():
render_part_identifier_map(scene, options["output_prefix"], options["width"], options["height"])
return
used_devices = configure_cycles_parity(scene, options)
+ if options["grey_diffuse"]:
+ apply_grey_diffuse_override(scene)
scene_build_seconds = time.perf_counter() - build_started
exr_path = f"{options['output_prefix']}.exr"
npy_path = f"{options['output_prefix']}.npy"
@@ -593,7 +641,20 @@ def main():
load_exr_into_npy(exr_path, npy_path, options["width"], options["height"], options["keep_exr"])
setup_seconds = scene_build_seconds + timing["cycles_sync_seconds"]
total_trace_seconds = scene_build_seconds + timing["render_call_seconds"]
+ report_samples = scene.cycles.samples
+ depth_npy_path = None
+ depth_error = None
+ if options["z_depth"]:
+ try:
+ depth_npy_path = render_camera_z_depth(scene, options["output_prefix"], options["width"], options["height"], options["depth_samples"])
+ except Exception as error: # the colour image is already on disk; keep its report even when the depth pass fails
+ depth_error = repr(error)
+ print("DEPTH_PASS_FAILED " + depth_error)
report = {
+ "greyDiffuse": options["grey_diffuse"],
+ "depthNpyPath": depth_npy_path,
+ "depthError": depth_error,
+ "depthSamples": options["depth_samples"] if options["z_depth"] else None,
"engine": "cycles-optix",
"blenderVersion": bpy.app.version_string,
"devices": used_devices,
@@ -602,7 +663,7 @@ def main():
"exrPath": exr_path if options["keep_exr"] else None,
"width": options["width"],
"height": options["height"],
- "samples": scene.cycles.samples,
+ "samples": report_samples,
"seed": scene.cycles.seed,
"bounces": scene.cycles.max_bounces,
"diffuseBounces": scene.cycles.diffuse_bounces,
diff --git a/bench/cycles-parity/test_compare_depth.py b/bench/cycles-parity/test_compare_depth.py
new file mode 100644
index 00000000..53228f5a
--- /dev/null
+++ b/bench/cycles-parity/test_compare_depth.py
@@ -0,0 +1,112 @@
+"""Unit tests for compare_depth.py on synthetic arrays. Run: uv run --no-project --with numpy python -m unittest bench/cycles-parity/test_compare_depth.py"""
+import math
+import os
+import sys
+import unittest
+
+import numpy
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+
+from compare_depth import DEPTH_AGREEMENT_GATE, compare_depth_maps, ray_distance_to_z_depth # noqa: E402
+
+HEIGHT = 32
+WIDTH = 48
+
+
+def flat_wall(z_depth):
+ return numpy.full((HEIGHT, WIDTH), z_depth, dtype=numpy.float64)
+
+
+class RayDistanceToZDepthTest(unittest.TestCase):
+ def test_a_flat_wall_seen_as_ray_distance_becomes_constant_z(self):
+ vertical_fov = 60.0
+ wall_z = 5.0
+ half_height_tangent = math.tan(math.radians(vertical_fov) / 2.0)
+ horizontal = ((numpy.arange(WIDTH) + 0.5) / WIDTH * 2.0 - 1.0) * half_height_tangent * WIDTH / HEIGHT
+ vertical = (1.0 - (numpy.arange(HEIGHT) + 0.5) / HEIGHT * 2.0) * half_height_tangent
+ ray_distance = wall_z * numpy.sqrt(1.0 + horizontal[numpy.newaxis, :] ** 2 + vertical[:, numpy.newaxis] ** 2)
+ converted = ray_distance_to_z_depth(ray_distance, vertical_fov)
+ numpy.testing.assert_allclose(converted, wall_z, rtol=1e-12)
+
+ def test_the_centre_pixels_barely_change_and_corners_shrink(self):
+ converted = ray_distance_to_z_depth(flat_wall(10.0), 90.0)
+ self.assertLess(converted[0, 0], converted[HEIGHT // 2, WIDTH // 2])
+ self.assertAlmostEqual(converted[HEIGHT // 2, WIDTH // 2], 10.0, delta=0.05)
+
+ def test_background_zero_stays_zero(self):
+ self.assertEqual(float(ray_distance_to_z_depth(flat_wall(0.0), 60.0).max()), 0.0)
+
+
+class CompareDepthMapsTest(unittest.TestCase):
+ def test_identical_maps_agree_everywhere(self):
+ result = compare_depth_maps(flat_wall(4.0), flat_wall(4.0))
+ self.assertEqual(result["agreementFraction"], 1.0)
+ self.assertTrue(result["depthPass"])
+ self.assertEqual(result["disagreeingPixelCount"], 0)
+
+ def test_a_constant_scale_beyond_the_tolerance_fails_and_shows_in_the_median(self):
+ result = compare_depth_maps(flat_wall(4.0), flat_wall(4.0) * 1.05, relative_tolerance=0.01)
+ self.assertEqual(result["agreementFraction"], 0.0)
+ self.assertFalse(result["depthPass"])
+ self.assertAlmostEqual(result["medianCandidateOverReference"], 1.05, places=9)
+ self.assertEqual(result["agreementByTolerance"]["0.05"], 0.0)
+
+ def test_a_scale_inside_the_tolerance_passes(self):
+ result = compare_depth_maps(flat_wall(4.0), flat_wall(4.0) * 1.004, relative_tolerance=0.01)
+ self.assertEqual(result["agreementFraction"], 1.0)
+
+ def test_background_pixels_agree_when_both_miss_whatever_the_marker(self):
+ reference = flat_wall(4.0)
+ candidate = flat_wall(4.0)
+ reference[:, :10] = 1.0e10
+ candidate[:, :10] = 0.0
+ result = compare_depth_maps(reference, candidate)
+ self.assertEqual(result["agreementFraction"], 1.0)
+ self.assertEqual(result["bothBackgroundCount"], 10 * HEIGHT)
+
+ def test_a_pixel_missed_by_only_one_side_disagrees(self):
+ reference = flat_wall(4.0)
+ candidate = flat_wall(4.0)
+ candidate[3, 7] = 0.0
+ reference[5, 9] = 0.0
+ result = compare_depth_maps(reference, candidate)
+ self.assertEqual(result["disagreeingPixelCount"], 2)
+ self.assertEqual(result["onlyReferenceHitCount"], 1)
+ self.assertEqual(result["onlyCandidateHitCount"], 1)
+
+ def test_non_finite_depth_counts_as_background(self):
+ reference = flat_wall(4.0)
+ candidate = flat_wall(4.0)
+ reference[0, 0] = numpy.inf
+ candidate[0, 0] = numpy.nan
+ self.assertEqual(compare_depth_maps(reference, candidate)["agreementFraction"], 1.0)
+
+ def test_the_gate_sits_at_99_9_percent(self):
+ reference = flat_wall(4.0)
+ candidate = flat_wall(4.0)
+ disagreeing_count = int(HEIGHT * WIDTH * (1.0 - DEPTH_AGREEMENT_GATE)) + 1
+ candidate.reshape(-1)[:disagreeing_count] = 8.0
+ result = compare_depth_maps(reference, candidate)
+ self.assertEqual(DEPTH_AGREEMENT_GATE, 0.999)
+ self.assertEqual(result["disagreeingPixelCount"], disagreeing_count)
+ self.assertFalse(result["depthPass"])
+
+ def test_a_disagreeing_silhouette_is_counted_as_an_edge_pixel(self):
+ reference = flat_wall(4.0)
+ candidate = flat_wall(4.0)
+ reference[:, 24:] = 12.0
+ candidate[:, 24:] = 12.0
+ candidate[10, 23] = 12.0
+ result = compare_depth_maps(reference, candidate)
+ self.assertEqual(result["disagreeingPixelCount"], 1)
+ self.assertEqual(result["disagreeingEdgePixelCount"], 1)
+ self.assertEqual(result["disagreeingInteriorPixelCount"], 0)
+
+ def test_shape_mismatch_is_an_error(self):
+ with self.assertRaises(ValueError):
+ compare_depth_maps(flat_wall(1.0), numpy.ones((HEIGHT, WIDTH + 1)))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/bench/cycles-parity/trace-native.mjs b/bench/cycles-parity/trace-native.mjs
index 265c0095..ef66c3c6 100644
--- a/bench/cycles-parity/trace-native.mjs
+++ b/bench/cycles-parity/trace-native.mjs
@@ -9,6 +9,7 @@ import { buildTraceSceneWithManyLights } from './trace-scene-many-lights.mjs';
import * as renderNative from '../../packages/render-native/index.mjs';
import { writeFloat32Npy } from './npy.mjs';
import { reconstructTraceSceneSource } from './scene-bridge.mjs';
+import { applyGreyDiffuseOverride } from './grey-diffuse-override.mjs';
const SUPPORTED_KERNELS = new Set(['legacy', 'cycles']);
const SUPPORTED_FILTERS = new Set(['box', 'gaussian', 'blackman-harris']);
@@ -96,7 +97,7 @@ function parseLightSamplingOption(argumentList) {
function parseTraceArguments(argumentList) {
if (argumentList.length < 2 || argumentList[0].startsWith('--') || argumentList[1].startsWith('--')) {
- throw new RangeError('Usage: node bench/cycles-parity/trace-native.mjs <sceneJsonPath> <outputPrefix> [--kernel legacy|cycles] [--samples 256] [--bounces 8] [--seed 1] [--width 960] [--height 540] [--sampler white|sobol-burley] [--light-sampling auto|tree|uniform] [--filter-type box|gaussian|blackman-harris] [--filter-width 1.0] [--clamp-direct 0] [--clamp-indirect 0] [--firefly-clamp 1e9] [--noise-threshold 0]');
+ throw new RangeError('Usage: node bench/cycles-parity/trace-native.mjs <sceneJsonPath> <outputPrefix> [--kernel legacy|cycles] [--samples 256] [--bounces 8] [--seed 1] [--width 960] [--height 540] [--sampler white|sobol-burley] [--light-sampling auto|tree|uniform] [--filter-type box|gaussian|blackman-harris] [--filter-width 1.0] [--clamp-direct 0] [--clamp-indirect 0] [--firefly-clamp 1e9] [--noise-threshold 0] [--grey-diffuse] [--write-depth]');
}
return {
sceneJsonPath: resolve(argumentList[0]),
@@ -122,6 +123,8 @@ function parseTraceArguments(argumentList) {
? parseIntegerOption(argumentList, '--samples-per-dispatch', 16, 1)
: undefined,
maxSeconds: parseNumberOption(argumentList, '--max-seconds', 1800, 1),
+ greyDiffuse: argumentList.includes('--grey-diffuse'),
+ writeDepth: argumentList.includes('--write-depth'),
};
}
@@ -150,7 +153,8 @@ async function runCli() {
if (!renderNative.findNativeAddon()) {
throw new Error('The render-native addon is missing. Build packages/render-native before running trace-native.mjs.');
}
- const description = JSON.parse(await readFile(options.sceneJsonPath, 'utf8'));
+ const loadedDescription = JSON.parse(await readFile(options.sceneJsonPath, 'utf8'));
+ const description = options.greyDiffuse ? applyGreyDiffuseOverride(loadedDescription) : loadedDescription;
await mkdir(dirname(options.outputPrefix), { recursive: true });
const totalStarted = performance.now();
const buildStarted = performance.now();
@@ -186,7 +190,20 @@ async function runCli() {
const npyPath = `${options.outputPrefix}.npy`;
await writeFloat32Npy(npyPath, linearRgb, [options.height, options.width, 3]);
const setupSeconds = sceneBuildSeconds + traced.setupSeconds + traced.compileSeconds + traced.uploadSeconds + traced.accelerationBuildSeconds;
+ // The depth buffer is the mean first-hit distance ALONG THE RAY (unit direction), 0 where the ray missed; Cycles' Z is
+ // the distance along the view axis. compare-depth.py converts. Cook's film averages over all samples, misses included.
+ const depthNpyPath = options.writeDepth ? `${options.outputPrefix}-depth.npy` : null;
+ if (depthNpyPath) {
+ if (!traced.depth || traced.depth.length !== options.width * options.height) {
+ throw new Error(`--write-depth needs the native tracer to return a depth buffer of ${options.width * options.height} floats (kernel "${options.kernel}" returned ${traced.depth?.length ?? 'none'}).`);
+ }
+ await writeFloat32Npy(depthNpyPath, Float32Array.from(traced.depth), [options.height, options.width]);
+ }
const report = {
+ greyDiffuse: options.greyDiffuse,
+ depthNpyPath,
+ depthConvention: depthNpyPath ? 'ray-distance' : null,
+ cameraVerticalFovDegrees: traceSource.camera.fov,
engine: options.kernel === 'cycles' ? 'cook-render-native' : '67js-render-native',
kernel: traced.kernel ?? options.kernel,
inputSchemaVersion: nativeInput.schemaVersion ?? 1,
diff --git a/tests/cycles-grey-diffuse.test.js b/tests/cycles-grey-diffuse.test.js
new file mode 100644
index 00000000..afe34ca5
--- /dev/null
+++ b/tests/cycles-grey-diffuse.test.js
@@ -0,0 +1,57 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { applyGreyDiffuseOverride, createGreyDiffuseMaterial, GREY_DIFFUSE_ALBEDO } from '../bench/cycles-parity/grey-diffuse-override.mjs';
+
+function buildDescription() {
+ return {
+ id: 'sample',
+ parts: [{ name: 'a', geometry: 0, material: 0 }, { name: 'b', geometry: 1, material: 1 }],
+ geometries: [
+ { positions: { type: 'Float32Array', base64: 'AA==' }, colors: { type: 'Float32Array', base64: 'AA==' } },
+ { positions: { type: 'Float32Array', base64: 'AA==' } },
+ ],
+ materials: [
+ { tag: 'surface', color: [1, 0, 0], metallic: 1, roughness: 0.1, emission: 5, map: { image: { imageId: 0 } } },
+ { tag: 'surface', color: [0, 1, 0], transmission: 1, roughness: 0.2, emission: 0 },
+ ],
+ images: [{ width: 1, height: 1, data: { type: 'Uint8Array', base64: 'AAAAAA==' } }],
+ environment: { pointLights: [{ position: [0, 1, 0], intensity: 3 }] },
+ };
+}
+
+test('grey diffuse override gives every material the same rough, non-metallic, non-emissive grey', () => {
+ const overridden = applyGreyDiffuseOverride(buildDescription());
+ assert.equal(overridden.materials.length, 2);
+ for (const material of overridden.materials) {
+ assert.deepEqual(material, createGreyDiffuseMaterial());
+ assert.deepEqual(material.color, [GREY_DIFFUSE_ALBEDO, GREY_DIFFUSE_ALBEDO, GREY_DIFFUSE_ALBEDO]);
+ assert.equal(material.metallic, 0);
+ assert.equal(material.roughness, 1);
+ assert.equal(material.emission, 0);
+ assert.equal(material.specular, 0);
+ assert.equal(material.transmission, undefined);
+ assert.equal(material.map, undefined);
+ }
+});
+
+test('grey diffuse override drops vertex colours and images but keeps parts, geometry and lights', () => {
+ const source = buildDescription();
+ const overridden = applyGreyDiffuseOverride(source);
+ assert.equal(overridden.geometries[0].colors, undefined);
+ assert.deepEqual(overridden.geometries[0].positions, source.geometries[0].positions);
+ assert.deepEqual(overridden.images, []);
+ assert.deepEqual(overridden.parts, source.parts);
+ assert.deepEqual(overridden.environment, source.environment);
+});
+
+test('grey diffuse override leaves its input untouched and each call returns separate materials', () => {
+ const source = buildDescription();
+ const snapshot = JSON.stringify(source);
+ const overridden = applyGreyDiffuseOverride(source);
+ assert.equal(JSON.stringify(source), snapshot);
+ assert.notEqual(overridden.materials[0], overridden.materials[1]);
+});
+
+test('grey diffuse override names what is missing from a malformed description', () => {
+ assert.throws(() => applyGreyDiffuseOverride({ parts: [] }), /materials and geometries/);
+});