Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Explain the two shade gaps of the sphere light comparison (#1070)

Nguyen Xuan An0e0aeaa48dfe
diff --git a/bench/cycles-parity/make-sphere-light-scenes.mjs b/bench/cycles-parity/make-sphere-light-scenes.mjs
index 58d8b831..1c0c1d6b 100644
--- a/bench/cycles-parity/make-sphere-light-scenes.mjs
+++ b/bench/cycles-parity/make-sphere-light-scenes.mjs
@@ -26,7 +26,9 @@ function createBoxPart(name, center, size, materialIndex, rayVisibility) {
return part;
}
-// Four walls and a lid, open at the bottom, centred on the lamp.
+// Four walls and a lid, open at the bottom, centred on the lamp. The left and right walls run the full span and the front and back
+// walls stop at the inside of the side walls, so no two boxes overlap or share a coplanar face. Overlapping boxes made the two
+// renderers disagree along the shared edge (#1070).
function createShadeParts(halfWidth, rayVisibility) {
const [lampX, lampY, lampZ] = LAMP_POSITION;
const bottom = lampY - SHADE_CLEARANCE_BELOW_LAMP;
@@ -34,12 +36,13 @@ function createShadeParts(halfWidth, rayVisibility) {
const height = top - bottom;
const middleY = (top + bottom) / 2;
const span = 2 * halfWidth + 2 * SHADE_WALL_THICKNESS;
+ const endWallSpanX = 2 * halfWidth;
return [
createBoxPart('shade-lid', [lampX, top + SHADE_WALL_THICKNESS / 2, lampZ], [span, SHADE_WALL_THICKNESS, span], 0, rayVisibility),
createBoxPart('shade-left', [lampX - halfWidth - SHADE_WALL_THICKNESS / 2, middleY, lampZ], [SHADE_WALL_THICKNESS, height, span], 0, rayVisibility),
createBoxPart('shade-right', [lampX + halfWidth + SHADE_WALL_THICKNESS / 2, middleY, lampZ], [SHADE_WALL_THICKNESS, height, span], 0, rayVisibility),
- createBoxPart('shade-back', [lampX, middleY, lampZ - halfWidth - SHADE_WALL_THICKNESS / 2], [span, height, SHADE_WALL_THICKNESS], 0, rayVisibility),
- createBoxPart('shade-front', [lampX, middleY, lampZ + halfWidth + SHADE_WALL_THICKNESS / 2], [span, height, SHADE_WALL_THICKNESS], 0, rayVisibility),
+ createBoxPart('shade-back', [lampX, middleY, lampZ - halfWidth - SHADE_WALL_THICKNESS / 2], [endWallSpanX, height, SHADE_WALL_THICKNESS], 0, rayVisibility),
+ createBoxPart('shade-front', [lampX, middleY, lampZ + halfWidth + SHADE_WALL_THICKNESS / 2], [endWallSpanX, height, SHADE_WALL_THICKNESS], 0, rayVisibility),
];
}
diff --git a/bench/cycles-parity/probe-shade-gaps.py b/bench/cycles-parity/probe-shade-gaps.py
new file mode 100644
index 00000000..a104678b
--- /dev/null
+++ b/bench/cycles-parity/probe-shade-gaps.py
@@ -0,0 +1,127 @@
+"""Probe matrix for the two small gaps left by #1040 (#1070): prints Cook and Cycles mean radiance and Cook over Cycles ratios.
+
+Run from the repository root on a machine with Blender 5.3, Node, a GPU and the built render-native addon:
+ uv run --no-project --with numpy python bench/cycles-parity/probe-shade-gaps.py <outputDirectory> [--samples 1024]
+
+Every row renders one scene with Cook and with Cycles (grey diffuse, Soft Falloff off) at one bounce count and prints
+ PROBE <label> cookMean=<r g b> cyclesMean=<r g b> ratio=<mean ratio> tiles5=<n>/<eligible> minmax=[<min>, <max>]
+plus, with --grids, the 8 x 8 tile ratios. Rows can change what each renderer does with the lamp:
+ cookDirect both | nee-only | bsdf-only (Cook --direct-lighting)
+ cyclesMis on | off (Cycles light multiple importance sampling)
+Options: --only a|b (rows whose label contains a or b), --tag name (Cook output name), --transparent-bounces N (Cycles limit), --grids.
+Cook ignores --direct-lighting nee-only and bsdf-only for point and spot lights: a lamp hit by a BSDF ray is still counted, so the
+nee-only rows double count and sit about 5 percent high; compare Cycles with --light-mis off against the both rows instead.
+"""
+import importlib.util
+import json
+import os
+import subprocess
+import sys
+
+import numpy
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+sys.path.insert(0, HERE)
+sys.stdout.reconfigure(encoding="utf-8", errors="replace")
+
+parity_spec = importlib.util.spec_from_file_location("run_sphere_light_parity", os.path.join(HERE, "run-sphere-light-parity.py"))
+parity = importlib.util.module_from_spec(parity_spec)
+parity_spec.loader.exec_module(parity)
+
+# (label, scene, bounces, cookDirect, cyclesMis)
+PROBE_ROWS = [
+ ("bare-r0.18 b1", "bare-r0.18", 1, "both", "on"),
+ ("enclosed-r0.18 b0", "enclosed-r0.18", 0, "both", "on"),
+ ("enclosed-r0.18 b1", "enclosed-r0.18", 1, "both", "on"),
+ ("enclosed-r0.18 b2", "enclosed-r0.18", 2, "both", "on"),
+ ("enclosed-r0.18 b3", "enclosed-r0.18", 3, "both", "on"),
+ ("enclosed-r0.18 b8", "enclosed-r0.18", 8, "both", "on"),
+ ("enclosed-r0 b1", "enclosed-r0", 1, "both", "on"),
+ ("enclosed-r0.18 b1 nee-only vs mis-off", "enclosed-r0.18", 1, "nee-only", "off"),
+ ("enclosed-r0.18 b2 nee-only vs mis-off", "enclosed-r0.18", 2, "nee-only", "off"),
+ ("enclosed-r0.18 b8 nee-only vs mis-off", "enclosed-r0.18", 8, "nee-only", "off"),
+ ("bare-r0.18 b1 nee-only vs mis-off", "bare-r0.18", 1, "nee-only", "off"),
+ ("enclosed-hidden-r0 b0", "enclosed-hidden-r0", 0, "both", "on"),
+ ("enclosed-hidden-r0 b1", "enclosed-hidden-r0", 1, "both", "on"),
+ ("enclosed-hidden-r0 b2", "enclosed-hidden-r0", 2, "both", "on"),
+ ("enclosed-hidden-r0 b3", "enclosed-hidden-r0", 3, "both", "on"),
+ ("enclosed-hidden-r0 b8", "enclosed-hidden-r0", 8, "both", "on"),
+ ("enclosed-r0 b8", "enclosed-r0", 8, "both", "on"),
+ ("enclosed-hidden-r0.18 b8", "enclosed-hidden-r0.18", 8, "both", "on"),
+ ("poking-hidden-r0.18 b8", "poking-hidden-r0.18", 8, "both", "on"),
+ ("poking-r0.18 b8", "poking-r0.18", 8, "both", "on"),
+]
+
+
+def render_cook(scene_path, prefix, options, bounces, instancing, direct_lighting):
+ command = ["node", os.path.join(HERE, "trace-native.mjs"), scene_path, prefix, "--kernel", "cycles",
+ "--samples", str(options["samples"]), "--bounces", str(bounces), "--seed", "1",
+ "--width", str(options["width"]), "--height", str(options["height"]),
+ "--firefly-clamp", "1000000000", "--noise-threshold", "0", "--grey-diffuse", "--direct-lighting", direct_lighting]
+ if instancing:
+ command.append("--instancing")
+ parity.run(command)
+
+
+def render_cycles(blender, scene_path, prefix, options, bounces, cycles_mis, transparent_bounces):
+ if os.path.exists(f"{prefix}.npy"):
+ return
+ command = [blender, "-b", "--factory-startup", "--python", os.path.join(HERE, "render-cycles.py"), "--", scene_path, prefix,
+ "--samples", str(options["samples"]), "--bounces", str(bounces), "--seed", "1",
+ "--width", str(options["width"]), "--height", str(options["height"]),
+ "--soft-falloff", "off", "--grey-diffuse", "--light-mis", cycles_mis]
+ if transparent_bounces is not None:
+ command += ["--transparent-bounces", transparent_bounces]
+ parity.run(command)
+
+
+def mean_rgb(path):
+ image = parity.load_linear_rgb_image(path)
+ return [round(float(value), 5) for value in image.reshape(-1, 3).mean(axis=0)]
+
+
+def main():
+ argument_list = sys.argv[1:]
+ options = {
+ "output_directory": os.path.abspath(argument_list[0]),
+ "samples": int(parity.read_flag(argument_list, "--samples", "1024")),
+ "width": 480,
+ "height": 270,
+ }
+ show_grids = "--grids" in argument_list
+ only = parity.read_flag(argument_list, "--only", "")
+ tag = parity.read_flag(argument_list, "--tag", "")
+ # Cycles transparent bounce limit; without it the limit equals the bounce count, and a lamp hit counts as one transparent bounce.
+ transparent_bounces = parity.read_flag(argument_list, "--transparent-bounces", None)
+ output_directory = options["output_directory"]
+ os.makedirs(os.path.join(output_directory, "renders"), exist_ok=True)
+ parity.run(["node", os.path.join(HERE, "export-scene.mjs"), output_directory, "--scene", "lit-interior"])
+ parity.run(["node", os.path.join(HERE, "make-sphere-light-scenes.mjs"),
+ os.path.join(output_directory, "scenes", "lit-interior.json"), output_directory])
+ blender = parity.find_blender()
+ report = []
+ for label, scene, bounces, cook_direct, cycles_mis in PROBE_ROWS:
+ if only and not any(part in label for part in only.split("|")):
+ continue
+ scene_path = os.path.join(output_directory, "scenes", f"{scene}.json")
+ hidden = scene.startswith(parity.HIDDEN_PREFIXES)
+ slug = f"{scene}-b{bounces}-{cook_direct}-mis{cycles_mis}"
+ cycles_slug = slug if transparent_bounces is None else f"{slug}-transparent{transparent_bounces}"
+ cook_prefix = os.path.join(output_directory, "renders", f"probe-cook{tag}-{slug}")
+ cycles_prefix = os.path.join(output_directory, "renders", f"probe-cycles-{cycles_slug}")
+ render_cook(scene_path, cook_prefix, options, bounces, hidden, cook_direct)
+ render_cycles(blender, scene_path, cycles_prefix, options, bounces, cycles_mis, transparent_bounces)
+ summary = parity.summarize(f"{cycles_prefix}.npy", f"{cook_prefix}.npy")
+ line = (f"PROBE {label} cookMean={mean_rgb(cook_prefix + '.npy')} cyclesMean={mean_rgb(cycles_prefix + '.npy')} "
+ f"ratio={summary['meanRatio']} tiles5={summary['tilesWithinFivePercent']}/{summary['tilesEligible']} minmax={summary['tileMinMax']}")
+ print(line, flush=True)
+ if show_grids:
+ for row in summary["tileRatios"]:
+ print(" ", row, flush=True)
+ report.append({"label": label, "summary": summary})
+ with open(os.path.join(output_directory, "probe-shade-gaps.json"), "w", encoding="utf-8") as handle:
+ json.dump(report, handle, indent=1)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/bench/cycles-parity/render-cycles.py b/bench/cycles-parity/render-cycles.py
index ff188ab5..2c18731c 100644
--- a/bench/cycles-parity/render-cycles.py
+++ b/bench/cycles-parity/render-cycles.py
@@ -27,6 +27,10 @@ RAY_VISIBILITY_ATTRIBUTES = {
# Set by --soft-falloff. Blender 4 and later build a point or spot light with a radius as an oriented disk while Light.use_soft_falloff
# is on (the default) and as a sphere while it is off. Cook models the sphere, so the default here is off; None keeps the Blender default.
soft_falloff_setting = None
+# Set by --light-mis off: lights stop being hit by BSDF rays and are sampled by next event estimation only (a diagnostic).
+light_mis_enabled = True
+# Set by --cycles-property name=value (repeatable): diagnostic overrides of scene.cycles properties, such as light_sampling_threshold=0.
+cycles_property_assignments = []
Y_UP_TO_Z_UP = Matrix((
(1.0, 0.0, 0.0, 0.0),
(0.0, 0.0, -1.0, 0.0),
@@ -101,6 +105,7 @@ def parse_cli_arguments():
"aperture_rotation": float(read_flag_value(argument_list, "--aperture-rotation", "0")),
"sensor_width": float(read_flag_value(argument_list, "--sensor-width", "36")),
"soft_falloff": read_soft_falloff(argument_list),
+ "light_mis": read_flag_value(argument_list, "--light-mis", "on") != "off",
}
@@ -405,6 +410,8 @@ def attach_light_receivers(light_object, receiver_names):
def apply_soft_falloff_setting(light_data):
if soft_falloff_setting is not None:
light_data.use_soft_falloff = soft_falloff_setting
+ if not light_mis_enabled:
+ light_data.cycles.use_multiple_importance_sampling = False
def add_spot_light(scene, light_index, spot_entry):
@@ -572,6 +579,10 @@ def configure_cycles_parity(scene, options):
scene.cycles.caustics_refractive = True
bounces = options["bounces"]
scene.cycles.max_bounces = bounces
+ for property_assignment in cycles_property_assignments:
+ property_name, property_value = property_assignment.split("=", 1)
+ current_value = getattr(scene.cycles, property_name)
+ setattr(scene.cycles, property_name, type(current_value)(json.loads(property_value)))
scene.cycles.diffuse_bounces = bounces
scene.cycles.glossy_bounces = bounces
scene.cycles.transmission_bounces = bounces
@@ -734,6 +745,10 @@ def main():
scene = bpy.context.scene
global soft_falloff_setting
soft_falloff_setting = options["soft_falloff"]
+ global light_mis_enabled
+ light_mis_enabled = options["light_mis"]
+ global cycles_property_assignments
+ cycles_property_assignments = [sys.argv[index + 1] for index, token in enumerate(sys.argv) if token == "--cycles-property"]
build_scene_objects(scene, description)
build_world_shader(scene, description["world"], repository_root)
build_scene_lights(scene, description["environment"])
diff --git a/bench/cycles-parity/run-sphere-light-parity.py b/bench/cycles-parity/run-sphere-light-parity.py
index f8405a64..2a9e025d 100644
--- a/bench/cycles-parity/run-sphere-light-parity.py
+++ b/bench/cycles-parity/run-sphere-light-parity.py
@@ -32,6 +32,11 @@ sys.stdout.reconfigure(encoding="utf-8", errors="replace")
DIRECT_ONLY_SCENES = ("bare-r0", "bare-r0.18", "enclosed-r0", "enclosed-r0.18", "enclosed-hidden-r0", "enclosed-hidden-r0.18")
INSTANCED_CONTROL_SCENES = ("enclosed-r0.18", "poking-r0.18")
HIDDEN_PREFIXES = ("enclosed-hidden", "poking-hidden")
+# Cycles counts a ray that hits a lamp as one transparent bounce and ends the path there once the count reaches the limit
+# (`integrator_shade_light_forward`, kernel/integrator/shade_light.h), so with one bounce and a transparent limit of one the energy that
+# passes through a sphere light and goes on to a wall behind it is lost. Cook does not count lamps. The Cycles reference keeps the
+# Blender default of 8 at least, which leaves the one bounce rows comparable (#1070).
+MINIMUM_TRANSPARENT_BOUNCES = 8
SPHERE_SCENE_PREFIXES = ("bare-", "enclosed-", "poking-")
@@ -71,7 +76,7 @@ def render_cycles(blender, scene_path, prefix, options, bounces, seed, soft_fall
command = [blender, "-b", "--factory-startup", "--python", os.path.join(HERE, "render-cycles.py"), "--", scene_path, prefix,
"--samples", str(options["samples"]), "--bounces", str(bounces), "--seed", str(seed),
"--width", str(options["width"]), "--height", str(options["height"]),
- "--soft-falloff", soft_falloff]
+ "--soft-falloff", soft_falloff, "--transparent-bounces", str(max(bounces, MINIMUM_TRANSPARENT_BOUNCES))]
if grey_diffuse:
command.append("--grey-diffuse")
run(command)
diff --git a/docs/cycles-parity.md b/docs/cycles-parity.md
index 0a0311ae..5451654e 100644
--- a/docs/cycles-parity.md
+++ b/docs/cycles-parity.md
@@ -1365,8 +1365,31 @@ Cook over Cycles mean radiance (the three channels agree to 4 digits on grey dif
The relMSE of the shade scenes sits at its seed floor because the light only leaves through the opening and most tiles are dark. After the fix the sphere light of 0.18 m in the bare room is within 0.01 percent in the mean and every tile is within 0.12 percent. The enclosed and poking lamps are within 1 percent. What is left:
-- The shade hidden from shadow rays is 0.8 percent dark in Cook for a radius of 0 as well (tiles 0.776 and 0.833 on the shade's front wall), so it is not a sphere light effect: it comes from `rayVisibility: { shadow: false }` through `--instancing` and is not explained yet. With the lamp poking through the walls the mean is 3.1 percent dark (0.9689, 60 of 64 tiles), 2.1 points more than the same shade not hidden (0.9901), so the hidden shade case stays above the 2 percent line and is open.
-- At 1 bounce the enclosed 0.18 m lamp is 11.5 percent bright in Cook (floor tiles up to 1.165) while radius 0 matches (0.9998) and the bare room is 0.26 percent bright. At the default 8 bounces it matches. The cause was not found (a guess: how the last bounce counts a path that hits the sphere through the opening). It is open and outside the default setting.
+Two gaps were left at that point. Both are closed (#1070): the first was in the test scene, the second is how Cycles counts a lamp hit, and neither needed a change in the kernel.
+
+**The shade hidden from shadow rays** was 0.8 percent dark in Cook for a radius of 0 (tiles 0.776 and 0.833 on the shade's front wall) and 3.1 percent dark with the lamp poking through the walls (0.9689). The cause is in the scene. `createShadeParts` built the front and back walls as wide as the lid, so each overlapped the thickness of the left and right walls and the two boxes shared a coplanar face (z = -0.18 m at the front). Cook and Cycles resolve that face differently `[measured]`:
+
+- The bounce count isolates it: with no indirect bounce Cook over Cycles is 1.0000 (64 of 64 tiles) and the two tiles are already at 0.753 and 0.822 with one bounce. The mean is 0.9937, 0.9947, 0.9927 and 0.9917 for 1, 2, 3 and 8 bounces.
+- The pictures place it: with one bounce a column of 2 pixels at the right edge of the shade, 0.02 m wide at that distance, reads 3.4 and 4.9 in Cycles (7.8 and 10.8 at 8 bounces) and 0.11 to 0.13 in Cook, about the wall beside it. At no bounce both read 0.002 to 0.025. That one column is the whole gap of the two tiles (25 and 18 percent of a tile), and its width is the thickness of the side wall.
+- Removing the overlap removes the gap: the front and back walls now span only the inside of the side walls. Hidden shade, radius 0: 0.9999 with 1 bounce (64 of 64 tiles within 0.2 percent) and 1.0005 with 8 (64 of 64, tiles 0.991 to 1.007). Radius 0.18 m: 1.0005 (64 of 64). Lamp poking through the walls: 0.9948 hidden (64 of 64, tiles 0.980 to 1.010) and 1.0010 not hidden (the old 0.9689 and 0.9901). The kernel and the packer are unchanged; only the scene file changed.
+
+Whether the shade is hidden from shadow rays was therefore never the cause, and ray visibility of the shade is handled the same way in both renderers. The shade rows of the table above were measured with the overlapping boxes, so its hidden rows (0.9918, 0.9689, 0.9917) are 0.8 to 3 points low for this reason; the numbers in this section replace them. `tests/cycles-sphere-light-parity.test.js` checks that no two boxes of a shade overlap.
+
+**The enclosed lamp at one bounce** read 11.5 percent bright in Cook (floor tiles up to 1.165). Cook is right and Cycles loses energy there, because Cycles counts a ray that hits a lamp as one transparent bounce `[read in the source: integrator_shade_light_forward in kernel/integrator/shade_light.h, which adds one to transparent_bounce after a lamp hit and ends the path when it reaches transparent_max_bounce]`. `render-cycles.py` sets the transparent limit equal to the bounce count, so with one bounce a path that hits the sphere stops at the sphere, and the part that would pass through it and light a wall behind it is lost. Cook does not count a lamp hit, so it keeps that part. Cycles on the enclosed 0.18 m lamp at 1 bounce, mean radiance, 1024 spp `[measured]`:
+
+| Cycles setting | Mean | Over the unbiased value |
+| --- | ---: | ---: |
+| light MIS on, transparent limit 1 (the old reference) | 0.10926 | 0.897 |
+| light MIS on, transparent limit 64 | 0.12183 | 1.000 |
+| light MIS off (next event estimation only, no lamp hits) | 0.12183 | 1.000 |
+| Cook (native `cycles` kernel) | 0.12179 | 1.000 |
+
+- With the limit raised Cycles equals its own MIS off result and Cook to 0.03 percent. Turning off light sampling thresholds or the light tree changes nothing (0.10926 in all four cases).
+- The deficit follows the lamp's reach: bare room, radius 0.18 m, 1 bounce: 0.2695 with limit 1 and 0.2702 with limit 64 (0.26 percent); radius 0, no lamp hit is possible: Cook over Cycles 0.9998. It fades with the bounce count because later bounces carry less energy: with the old reference Cook over Cycles is 1.1149, 1.0069 and 1.0013 for 1, 2 and 3 bounces and 1.0011 for 8.
+- An experiment that drops the lamp emission found by the ray of the last bounce explains only 2.4 of the 11.5 points (Cook 0.1189 against 0.1218), so it is not the last bounce itself: it is the path through the lamp.
+- Cycles' behaviour is a workaround in its source (the comment above that code speaks of a possible endless loop on precision problems), and Blender's own transparent limit is 8, which a path would need eight lamp hits to reach. Cook does not copy it. The reference script `run-sphere-light-parity.py` now asks Cycles for a transparent limit of at least 8, so the one bounce rows compare like with like.
+
+Two traps found on the way: `--direct-lighting nee-only` and `bsdf-only` of `trace-native.mjs` act on emissive triangles and on the weight of next event estimation only, not on point or spot lights hit by a BSDF ray, so `nee-only` counts a sphere light twice (about 5 percent high at 8 bounces) and is not a valid probe for a lamp. `bench/cycles-parity/probe-shade-gaps.py` is the probe matrix of this section (`--light-mis off` and `--transparent-bounces` of `render-cycles.py` and `run-sphere-light-parity.py` are its Cycles side).
Scenes of `bench/reference/scenes.js` whose Cycles reference changes with the new default (a light with a radius), real materials, same settings, Cook over Cycles mean, R channel, before to after `[measured]`: `lit-interior` 1.0034 to 1.0003, `many-lights-500` 1.0011 to 1.0005, `light-linking` 1.0008 to 0.9998, `spot-area` 1.0000 to 0.9999 (all tiles within 5 percent before and after). `metal`, `glass` and `outdoor-hdri` have no light with a radius and their numbers do not change. Cook's own output is byte identical to `origin/main` for `lit-interior`, `glass` and `many-lights-500` on both kernels (64 spp, seed 3, 4 bounces, 480 x 270, built beside each other in one run).
diff --git a/tests/cycles-sphere-light-parity.test.js b/tests/cycles-sphere-light-parity.test.js
index 7b4f3cb5..c45f9860 100644
--- a/tests/cycles-sphere-light-parity.test.js
+++ b/tests/cycles-sphere-light-parity.test.js
@@ -1,6 +1,10 @@
import assert from 'node:assert/strict';
-import { readFileSync } from 'node:fs';
+import { execFileSync } from 'node:child_process';
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
import test from 'node:test';
+import { fileURLToPath } from 'node:url';
import { buildNativeInput, findNativeAddon, traceNative } from '../packages/render-native/index.mjs';
import { box } from '../src/geometry.js';
@@ -85,3 +89,38 @@ for (const radius of [0, 0.18, 0.5]) {
assert.ok(Math.abs(measured / expected - 1) < 0.03, `floor radiance ${measured} against the closed form ${expected}`);
});
}
+
+// Boxes of the lamp scenes that overlap or share a coplanar front face made Cook and Cycles disagree by a column of pixels
+// on the shade (#1070), so the scenes must be made of boxes that only touch.
+function boxBounds(part) {
+ const matrix = part.matrix;
+ return [0, 1, 2].map((axis) => ({ low: matrix[12 + axis] - matrix[axis * 5] / 2, high: matrix[12 + axis] + matrix[axis * 5] / 2 }));
+}
+
+function boxesOverlapInVolume(firstBounds, secondBounds) {
+ const overlapPerAxis = [0, 1, 2].map((axis) => Math.min(firstBounds[axis].high, secondBounds[axis].high) - Math.max(firstBounds[axis].low, secondBounds[axis].low));
+ return overlapPerAxis.every((overlap) => overlap > 1e-9);
+}
+
+test('the shade of the lamp scenes is built from boxes that do not overlap', () => {
+ const workDirectory = mkdtempSync(join(tmpdir(), 'sphere-light-scenes-'));
+ try {
+ const baseScenePath = join(workDirectory, 'base.json');
+ const roomParts = Array.from({ length: 5 }, (_, index) => ({ name: `room-${index}`, geometry: 0, matrix: [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 100 * index, 0, 0, 1], material: 0 }));
+ writeFileSync(baseScenePath, JSON.stringify({ id: 'base', parts: roomParts, environment: {} }));
+ execFileSync('node', [fileURLToPath(new URL('../bench/cycles-parity/make-sphere-light-scenes.mjs', import.meta.url)), baseScenePath, workDirectory], { stdio: 'ignore' });
+ for (const sceneName of ['enclosed-r0.18', 'enclosed-hidden-r0.18', 'poking-r0.18', 'poking-hidden-r0.18']) {
+ const scene = JSON.parse(readFileSync(join(workDirectory, 'scenes', `${sceneName}.json`), 'utf8'));
+ const shadeParts = scene.parts.filter((part) => part.name.startsWith('shade-'));
+ assert.equal(shadeParts.length, 5, `${sceneName} has a lid and four walls`);
+ for (let first = 0; first < shadeParts.length; first++) {
+ for (let second = first + 1; second < shadeParts.length; second++) {
+ const overlaps = boxesOverlapInVolume(boxBounds(shadeParts[first]), boxBounds(shadeParts[second]));
+ assert.equal(overlaps, false, `${sceneName}: ${shadeParts[first].name} and ${shadeParts[second].name} overlap`);
+ }
+ }
+ }
+ } finally {
+ rmSync(workDirectory, { recursive: true, force: true });
+ }
+});