Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Let a scene built for the native path tracer take more than 65,536 instances (#1055)

Nguyen Xuan An784e5b5cc964
diff --git a/changes/1055.md b/changes/1055.md
new file mode 100644
index 00000000..7ecca91b
--- /dev/null
+++ b/changes/1055.md
@@ -0,0 +1 @@
+- A scene built for the native path tracer can hold up to 500,000 instances of shared geometry instead of 65,536: `buildTraceScene` accepts `maximumInstances`, native render jobs on the `cycles` kernel use it, and the CPU and WebGL path tracers keep 65,536 (#1055)
diff --git a/docs/cycles-parity.md b/docs/cycles-parity.md
index 5451654e..64fd6eaf 100644
--- a/docs/cycles-parity.md
+++ b/docs/cycles-parity.md
@@ -1434,3 +1434,34 @@ Tracing the packed input on the card (480 by 270, 16 samples, GPU memory of the
| 3,998,792 | 7 | 1.31 | 0.13 | 0.55 | 1,961 |
Same picture: the 1,002,528 triangle scene (four meshes, two of them shared by a second instance) exported through the job path as instances, and again as a flattened scene of the same parts (about 1.5 million triangles after expansion), gave the same PNG, SHA-256 `165939ce…01404`, both times. The instanced export took 10.7 s and 2.6 GB of peak RSS; the flattened one 19.5 s and 4.2 GB.
+
+## Instance bound of a native scene (#1055)
+
+`buildTraceScene` bounds an instanced scene at 65,536 instances (one per part) for the CPU and WebGL tracers. A scene built for the native tracer asks for another bound with `maximumInstances`, an integer from 1 to `MAX_NATIVE_TRACE_INSTANCES` (1,000,000). A render job on the Cycles-matching kernel passes 500,000 (`NATIVE_JOB_MAXIMUM_INSTANCES` in `scripts/native-bake-page.js`); the legacy kernel never instances, and the CPU and WebGL tracers keep 65,536 and its error text. The option is separate from `maximumTriangles`: the unique and total triangle bounds apply as before, so copies of a large mesh still hit the total bound (four times `maximumTriangles`) long before the instance bound.
+
+Every place on the way to the kernel that could assume 65,536 instances, read in the code `[measured by reading]`:
+
+| place | limit |
+| --- | --- |
+| `MAX_TRACE_INSTANCES` check in `requireInstancedCaps` (`src/path-tracer-scene.js`) | the only 65,536; a guard for the CPU and WebGL paths, now a caller-set bound |
+| `packInstancedGeometry` and `writeInstanceRecordBytes` (`pack-input-v2.mjs`), `job-input.mjs` | none; counts are 32-bit and the loops are linear |
+| instance table, 160 bytes per instance | 160 MB at 1,000,000 |
+| material table, 256 bytes per part (a material record per part, not per distinct material) | the largest table: 256 MB at 1,000,000 |
+| emissive and light tree records that store an instance index | `u32`; the light tree takes 4,194,304 emitters (`LIGHT_TREE_MAX_EMITTERS`), which bounds emissive copies, not plain ones |
+| WGSL `instance_custom_data` and `int_resolve_instance_index` | the hardware custom index has 24 bits: 16,777,216 (`MAX_TLAS_INSTANCES` in `host/accel.rs`) |
+| V8 string of the job export | see below; this is the bound of the job |
+
+Measured on an RTX 4090 box, one process per row, a field of two-triangle cards sharing one geometry (`bench/cycles-parity/native-instance-measure.mjs`), packed the way the job page does and traced at 160 by 120 with 16 samples `[measured]`:
+
+| instances | pack s | base64 s | material table MB | all tables, base64 characters | peak RSS MB | traced s | acceleration build s | card MB (process included) |
+| --- | --- | --- | --- | --- | --- | --- | --- | --- |
+| 65,538 | 0.34 | 0.94 | 16.8 | 36.4 M | 520 | 0.37 | 0.011 | 610 |
+| 250,001 | 1.17 | 3.53 | 64.0 | 138.7 M | 1,295 | 0.58 | 0.050 | 704 |
+| 500,001 | 3.24 | 7.13 | 128.0 | 277.3 M | 2,363 | 0.73 | 0.100 | 796 |
+| 1,000,000 | 7.17 | 14.34 | 256.0 | 554.7 M | 4,511 | 1.59 | 0.193 | 1,557 |
+
+Each instance costs 416 bytes packed (160 for the instance and 256 for its material) and 555 base64 characters. What bounds it `[measured, inferred for the reason]`: the table bytes and V8 strings, not the card or the acceleration build. At 1,000,000 instances the largest table is 341 M characters, which encodes, but the tables together are 554.7 M characters, above the 536,870,888 of one V8 string, so a page that returns the export as one string (a JSON message) would fail; 500,000 instances are 277 M characters, 52% of that limit. The job stops at 500,000 for this reason, and the library ceiling is 1,000,000, the size measured on the card. The card was never the limit: the acceleration build took 0.19 s at 1,000,000 instances and the traces ran in 1.6 s. The hardware allows 16,777,216 instances, and nothing above 1,000,000 instances was measured.
+
+Pictures: scenes under the old bounds are byte for byte the same. The PNG SHA-256 of three scenes (the 20,000 triangle cap scene with copies, a field of 3,000 shared cards and the same cards merged) on the job export of `cycles` instanced, `cycles` flattened and `legacy` are equal on `main` and on this change, and the refusal of the scene the flattened and legacy routes cannot take has the same words (`bench/cycles-parity/native-identity-pngs.mjs`, `[measured]`). Over the old bound, `tests/native-instancing-limit.test.js` traces 85,537 parts (the last 20,000 red, all past index 65,536) and the same cards merged into two meshes: 3,381 red pixels in both, mean ratio within 2% per channel, tiles within 5%, and a relative mean squared error of 1.5e-7, against 1.4e-3 between two seeds of the merged picture.
+
+Not measured: Chrome's memory for a page that builds 500,000 parts (the numbers above are Node's), and a scene whose copies are emissive (each emissive copy adds light tree emitters and emissive records).
diff --git a/docs/path-tracer.md b/docs/path-tracer.md
index decd6521..7c6eee5a 100644
--- a/docs/path-tracer.md
+++ b/docs/path-tracer.md
@@ -61,7 +61,7 @@ Also checked before any ray is traced: samples times pixels times bounces at mos
`buildTraceScene(parts, environment, { instancing: true })` keeps parts that share one geometry object as instances of it, and `buildNativeInputV2` packs them as one bottom-level structure per geometry plus one instance record per part, for `traceNative` with `kernel: "cycles"`. Without the option the scene is flattened as before, and a scene where no two parts share a geometry is flattened too, with output identical to the default.
- Sharing is decided after the trace geometry is resolved. A skinned, flush-lifted or box-mapped part gets a geometry of its own, and a geometry with per-triangle materials is not shared either: those parts are moved into world space once and traced as instances with an identity matrix.
-- Limits: 400,000 triangles counted once per shared geometry, 1,024 distinct geometries (the part limit, counted on geometries) and 65,536 instances. `buildTraceScene(parts, environment, { instancing: true, maximumTriangles })` replaces the 400,000 for a scene exported to the native tracer: an integer from 1 to 4,000,000 (`MAX_NATIVE_TRACE_TRIANGLES`) bounds the unique triangles (all triangles of a flattened scene), and four times that bounds the triangles with every copy counted. A value outside that range is refused, and the CPU and WebGL tracers never pass it, so they keep 400,000 and their error text. A native render job passes 1,500,000 (see "Triangle bound of a native scene" in [cycles-parity.md](./cycles-parity.md)). An instanced scene has no world-space triangle arrays or CPU BVH, so only `buildNativeInputV2` reads it.
+- Limits: 400,000 triangles counted once per shared geometry, 1,024 distinct geometries (the part limit, counted on geometries) and 65,536 instances. `buildTraceScene(parts, environment, { instancing: true, maximumTriangles, maximumInstances })` replaces the 400,000 for a scene exported to the native tracer: an integer from 1 to 4,000,000 (`MAX_NATIVE_TRACE_TRIANGLES`) bounds the unique triangles (all triangles of a flattened scene), and four times that bounds the triangles with every copy counted. A value outside that range is refused, and the CPU and WebGL tracers never pass it, so they keep 400,000 and their error text. `maximumInstances` does the same for the 65,536 instances: an integer from 1 to 1,000,000 (`MAX_NATIVE_TRACE_INSTANCES`), counted over the parts of an instanced scene (each part is one instance, and the unique-geometry bound stays 1,024). A value outside that range is refused, and a flattened scene ignores it. A native render job passes 1,500,000 triangles and 500,000 instances (see "Triangle bound of a native scene" and "Instance bound of a native scene" in [cycles-parity.md](./cycles-parity.md)). An instanced scene has no world-space triangle arrays or CPU BVH, so only `buildNativeInputV2` reads it.
- A part's material is its own entry in `materials`, so copies may differ in material; a multi-material mesh stays one geometry with the materials the part names.
- `buildNativeInput` (the `legacy` kernel) refuses an instanced scene with an error; build the scene without `instancing` for that kernel. `traceNative` with `kernel: "legacy"` refuses a FORMAT-v2 input the same way.
- Render jobs with `renderer.backend: "native"` keep repeated geometry as instances when the job traces with the `cycles` kernel (the default): the job page exports FORMAT-v2 tables of the unique triangles and one record per part, the job runner rebuilds the input for `traceNative`, and the report names the `instances` and counts `triangles` once per shared geometry. With `JS67_NATIVE_KERNEL=legacy`, `JS67_NATIVE_INSTANCING=off` (flattened triangles on the `cycles` kernel, to compare the two), or a scene where no geometry is shared, the job exports flattened geometry as before; on the `cycles` kernel the materials are still sent whole (next point), and only the legacy kernel reads the v1 tables.
diff --git a/scripts/native-bake-page.js b/scripts/native-bake-page.js
index d4b54f82..15aeeb01 100644
--- a/scripts/native-bake-page.js
+++ b/scripts/native-bake-page.js
@@ -46,6 +46,8 @@ export function encodeNativeInputV2(input) {
// The triangle bound of a scene exported to the "cycles" kernel (see buildTraceScene's maximumTriangles); the legacy kernel and every
// other tracer keep the 400,000 of the CPU and WebGL paths.
export const NATIVE_JOB_MAXIMUM_TRIANGLES = 1_500_000;
+// The instance bound of the same export (see buildTraceScene's maximumInstances).
+export const NATIVE_JOB_MAXIMUM_INSTANCES = 500_000;
/**
* The scene of a native render job as the tables the job runner traces. With the "cycles" kernel (`kernel`) every scene is
@@ -59,8 +61,8 @@ export const NATIVE_JOB_MAXIMUM_TRIANGLES = 1_500_000;
export function exportNativeSceneTables({ parts, environment, camera, options, kernel, instancing, modules }) {
const { buildTraceScene, refuseLocalVolumes, resolveTexture, buildNativeInput, buildJobNativeInput, buildFlattenedJobNativeInput, pack } = modules;
const wholeMaterials = kernel === 'cycles';
- const triangleLimit = wholeMaterials ? { maximumTriangles: NATIVE_JOB_MAXIMUM_TRIANGLES } : {};
- let traceScene = buildTraceScene(parts, environment, { instancing: wholeMaterials && instancing === true, ...triangleLimit });
+ const nativeLimits = wholeMaterials ? { maximumTriangles: NATIVE_JOB_MAXIMUM_TRIANGLES, maximumInstances: NATIVE_JOB_MAXIMUM_INSTANCES } : {};
+ let traceScene = buildTraceScene(parts, environment, { instancing: wholeMaterials && instancing === true, ...nativeLimits });
refuseLocalVolumes(traceScene, 'the native path tracer');
let flattenedBecause;
if (traceScene.instances) {
@@ -71,7 +73,7 @@ export function exportNativeSceneTables({ parts, environment, camera, options, k
// A scene over the texture pool stays over it flattened: the caller gets that refusal, not a v1 atlas one.
if (!(error instanceof RangeError) || error.texturePoolFull) throw error;
flattenedBecause = error.message;
- traceScene = flattenRefusedScene(buildTraceScene, parts, environment, triangleLimit, flattenedBecause);
+ traceScene = flattenRefusedScene(buildTraceScene, parts, environment, nativeLimits, flattenedBecause);
}
}
const instancingNote = flattenedBecause === undefined ? {} : { instancing: 'flattened', instancingReason: flattenedBecause };
@@ -108,9 +110,9 @@ function buildNativeInputOrExplain(buildNativeInput, traceScene, camera, options
// The flattened scene of parts the packer refused as instances. Every copy counts against the bound once flattened, so a scene
// that fitted as instances can be over it; the error then names the packer's refusal, since the geometry was already shared.
-function flattenRefusedScene(buildTraceScene, parts, environment, triangleLimit, refusal) {
+function flattenRefusedScene(buildTraceScene, parts, environment, nativeLimits, refusal) {
try {
- return buildTraceScene(parts, environment, triangleLimit);
+ return buildTraceScene(parts, environment, nativeLimits);
} catch (error) {
if (!(error instanceof RangeError)) throw error;
throw new RangeError(`The scene could not stay instanced (${refusal}) and is too large once every copy is flattened: ${error.message}`);
diff --git a/src/path-tracer-scene.js b/src/path-tracer-scene.js
index 0d37cddb..041c4ecf 100644
--- a/src/path-tracer-scene.js
+++ b/src/path-tracer-scene.js
@@ -22,6 +22,9 @@ export const NATIVE_INSTANCED_TOTAL_FACTOR = 4;
export const MAX_TRACE_PARTS = 1024;
// An instanced trace counts triangles once per shared geometry and bounds the copies on their own.
export const MAX_TRACE_INSTANCES = 65_536;
+// The bound a scene built for the native "cycles" tracer may ask for with `options.maximumInstances`. The CPU and WebGL tracers
+// never pass it and keep MAX_TRACE_INSTANCES.
+export const MAX_NATIVE_TRACE_INSTANCES = 1_000_000;
export const MAX_TRACE_LIGHTS = 32;
// A Blender sun of 1 degree, which is what the reference harness gives Cycles.
export const SUN_ANGULAR_RADIUS = Math.PI / 360;
@@ -276,6 +279,16 @@ function resolveTriangleLimits(options) {
return { native: true, unique: requested, total: requested * NATIVE_INSTANCED_TOTAL_FACTOR };
}
+/** The instance bound of one build: the CPU and WebGL default, or the native bound asked for with `maximumInstances`. */
+function resolveInstanceLimit(options) {
+ const requested = options?.maximumInstances;
+ if (requested === undefined) return { native: false, count: MAX_TRACE_INSTANCES };
+ if (!Number.isInteger(requested) || requested < 1 || requested > MAX_NATIVE_TRACE_INSTANCES) {
+ throw new RangeError(`buildTraceScene option maximumInstances is an integer from 1 to ${MAX_NATIVE_TRACE_INSTANCES} for the native path tracer, got ${requested}. Leave it out for the CPU and WebGL path tracers, which take at most ${MAX_TRACE_INSTANCES} instances.`);
+ }
+ return { native: true, count: requested };
+}
+
function flattenParts(parts, geometries = parts.map(traceGeometry), limits = resolveTriangleLimits()) {
let vertexTotal = 0;
let indexTotal = 0;
@@ -496,8 +509,8 @@ function measureInstancedParts(parts, geometries) {
}
function requireInstancedCaps(parts, { uniqueGeometries, uniqueTriangles, totalTriangles }, limits) {
- if (parts.length > MAX_TRACE_INSTANCES) {
- throw new RangeError(`An instanced path trace takes at most ${MAX_TRACE_INSTANCES} instances, got ${parts.length}. Pass fewer parts, or merge small copies into one mesh.`);
+ if (parts.length > limits.instances.count) {
+ throw new RangeError(`An instanced ${limits.instances.native ? 'native ' : ''}path trace takes at most ${limits.instances.count} instances, got ${parts.length}. Pass fewer parts, or merge small copies into one mesh.`);
}
if (uniqueGeometries > MAX_TRACE_PARTS) {
throw new RangeError(`An instanced path trace takes at most ${MAX_TRACE_PARTS} distinct geometries, got ${uniqueGeometries}. Share one geometry object between copies instead of building a new one per part.`);
@@ -595,9 +608,11 @@ function buildInstancedTraceScene(parts, geometries, environment, localVolumes,
* holds `instances` instead of flattened triangles (see `buildInstancedTraceScene`); with no shared geometry, or without the
* option, it is the flattened scene, unchanged. `options.maximumTriangles` (an integer up to MAX_NATIVE_TRACE_TRIANGLES) is for
* a scene exported to the native "cycles" tracer only: it replaces the 400,000 triangle bound of the CPU and WebGL tracers.
+ * `options.maximumInstances` (an integer up to MAX_NATIVE_TRACE_INSTANCES) does the same for the 65,536 instances of an
+ * instanced scene; a flattened scene has no instances and keeps its part bound.
*/
export function buildTraceScene(allParts, environment = {}, options = {}) {
- const limits = resolveTriangleLimits(options);
+ const limits = { ...resolveTriangleLimits(options), instances: resolveInstanceLimit(options) };
const { volumes: localVolumes, boundsOnlyParts } = resolveTraceLocalVolumes(environment.localVolumes, allParts);
const parts = boundsOnlyParts.length ? allParts.filter(part => !boundsOnlyParts.includes(part)) : allParts;
const tryInstancing = options.instancing === true && Array.isArray(parts) && parts.length > 0;
diff --git a/tests/native-instancing-limit.test.js b/tests/native-instancing-limit.test.js
new file mode 100644
index 00000000..73e0cd59
--- /dev/null
+++ b/tests/native-instancing-limit.test.js
@@ -0,0 +1,66 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { buildNativeInputV2, findNativeAddon, traceNative } from '../packages/render-native/index.mjs';
+import { meanRatioRgb, relativeMeanSquaredError, tileMeanRatios } from '../bench/instancing/image-compare.mjs';
+import {
+ CARD_FIELD_ENVIRONMENT,
+ CARD_FIELD_PACK_OPTIONS,
+ buildCardField,
+ buildCardFieldMerged,
+ cardFieldCamera,
+} from '../bench/cycles-parity/native-instance-scene.mjs';
+import { buildTraceScene, MAX_TRACE_INSTANCES } from '../src/path-tracer-scene.js';
+
+// More instances than the 65,536 of the CPU and WebGL tracers, on the native "cycles" kernel, against the same cards merged into
+// two world-space meshes. The cards from index 65,536 on are red, so a picture without those instances has no red in their band.
+// Skipped without the built addon or a ray query adapter. The instanced render has a noise stream of its own, so the bound on
+// the difference is a multiple of the difference between two seeds of the merged render, measured in the same run.
+const CARD_COUNT = MAX_TRACE_INSTANCES + 20_000;
+const SAMPLES = 128;
+const TILES = 8;
+const NOISE_FACTOR = 3;
+const { width: WIDTH, height: HEIGHT } = CARD_FIELD_PACK_OPTIONS;
+
+function render(parts, instancing, seed) {
+ const scene = buildTraceScene(parts, CARD_FIELD_ENVIRONMENT, instancing ? { instancing: true, maximumInstances: CARD_COUNT + 1 } : {});
+ assert.equal(scene.instances !== undefined, instancing);
+ const input = buildNativeInputV2(scene, cardFieldCamera(CARD_COUNT), { width: WIDTH, height: HEIGHT, samples: SAMPLES, seed, bounces: CARD_FIELD_PACK_OPTIONS.bounces });
+ return traceNative(input, { width: WIDTH, height: HEIGHT, samples: SAMPLES, kernel: 'cycles' }).rgba;
+}
+
+// Pixels whose red channel clearly leads: the red cards, which are all past the old instance bound.
+function redPixelCount(rgba) {
+ let count = 0;
+ for (let pixel = 0; pixel < WIDTH * HEIGHT; pixel++) {
+ if (rgba[pixel * 4] > 1.25 * rgba[pixel * 4 + 1] && rgba[pixel * 4] > 0.02) count++;
+ }
+ return count;
+}
+
+const addonSkip = findNativeAddon() ? false : 'the native addon is not built';
+
+test('more than 65,536 instances of one card render the picture of the same cards merged', { skip: addonSkip }, t => {
+ const redFrom = MAX_TRACE_INSTANCES;
+ let merged;
+ try {
+ merged = render(buildCardFieldMerged(CARD_COUNT, redFrom), false, 1);
+ } catch (error) {
+ if (/adapter|Vulkan|ray quer/i.test(error.message)) return t.skip(error.message);
+ throw error;
+ }
+ const mergedOtherSeed = render(buildCardFieldMerged(CARD_COUNT, redFrom), false, 2);
+ const instanced = render(buildCardField(CARD_COUNT, redFrom), true, 1);
+ const pixelCount = WIDTH * HEIGHT;
+
+ const redMerged = redPixelCount(merged);
+ assert.ok(redMerged > pixelCount * 0.03, `the merged picture shows the red cards (${redMerged} of ${pixelCount} pixels)`);
+ const redInstanced = redPixelCount(instanced);
+ assert.ok(redInstanced > 0.9 * redMerged && redInstanced < 1.1 * redMerged, `red pixels: ${redInstanced} instanced against ${redMerged} merged`);
+
+ for (const ratio of meanRatioRgb(instanced, merged, pixelCount)) assert.ok(ratio > 0.98 && ratio < 1.02, `mean ratio ${ratio}`);
+ const noiseFloor = relativeMeanSquaredError(mergedOtherSeed, merged, pixelCount);
+ const difference = relativeMeanSquaredError(instanced, merged, pixelCount);
+ t.diagnostic(`red pixels ${redInstanced} instanced, ${redMerged} merged; relMSE ${difference} instanced against merged, ${noiseFloor} between two merged seeds`);
+ assert.ok(difference < NOISE_FACTOR * noiseFloor, `relMSE ${difference} against the merged picture, ${NOISE_FACTOR} times the seed-to-seed ${noiseFloor} is the bound`);
+ for (const ratio of tileMeanRatios(instanced, merged, WIDTH, HEIGHT, TILES)) assert.ok(ratio > 0.95 && ratio < 1.05, `tile mean ratio ${ratio}`);
+});
diff --git a/tests/path-tracer-native-instance-limit.test.js b/tests/path-tracer-native-instance-limit.test.js
new file mode 100644
index 00000000..8d676a32
--- /dev/null
+++ b/tests/path-tracer-native-instance-limit.test.js
@@ -0,0 +1,97 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { buildNativeInput } from '../packages/render-native/pack-input.mjs';
+import { buildFlattenedJobNativeInput, buildJobNativeInput } from '../packages/render-native/job-input.mjs';
+import { exportNativeSceneTables, NATIVE_JOB_MAXIMUM_INSTANCES } from '../scripts/native-bake-page.js';
+import { createCamera } from '../src/path-tracer.js';
+import * as pack from '../src/path-tracer-gpu-pack.js';
+import {
+ buildTraceScene,
+ MAX_NATIVE_TRACE_INSTANCES,
+ MAX_TRACE_INSTANCES,
+ refuseLocalVolumes,
+ resolveTexture,
+} from '../src/path-tracer-scene.js';
+
+// One shared triangle: valid for the builder and cheap to copy many times.
+const TRIANGLE = {
+ positions: new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0]),
+ normals: new Float32Array([0, 0, 1, 0, 0, 1, 0, 0, 1]),
+ indices: new Uint32Array([0, 1, 2]),
+};
+const SHARED_MATERIAL = { color: [0.8, 0.8, 0.8] };
+const ENVIRONMENT = { keyColor: [1, 1, 1], lightDirection: [0, 1, 0] };
+
+function copiesOfTriangle(copyCount) {
+ return Array.from({ length: copyCount }, (_, index) => ({
+ name: `copy-${index}`,
+ geometry: TRIANGLE,
+ matrix: new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, index * 2, 0, 0, 1]),
+ material: SHARED_MATERIAL,
+ }));
+}
+
+test('the CPU and WebGL instance bound is still 65,536 and a build without the option keeps its message', () => {
+ assert.equal(MAX_TRACE_INSTANCES, 65_536);
+ assert.throws(() => buildTraceScene(copiesOfTriangle(MAX_TRACE_INSTANCES + 1), ENVIRONMENT, { instancing: true }), {
+ name: 'RangeError',
+ message: 'An instanced path trace takes at most 65536 instances, got 65537. Pass fewer parts, or merge small copies into one mesh.',
+ });
+});
+
+test('an instanced scene above 65,536 copies builds with maximumInstances and keeps every instance', () => {
+ const copyCount = MAX_TRACE_INSTANCES + 1_000;
+ const scene = buildTraceScene(copiesOfTriangle(copyCount), ENVIRONMENT, { instancing: true, maximumInstances: copyCount });
+ assert.equal(scene.instances.length, copyCount);
+ assert.equal(new Set(scene.instances.map(instance => instance.geometry)).size, 1);
+ assert.equal(scene.materials.length, copyCount);
+});
+
+test('a scene over the instance bound that was asked for is refused with the bound and what to pass', () => {
+ assert.equal(buildTraceScene(copiesOfTriangle(10), ENVIRONMENT, { instancing: true, maximumInstances: 10 }).instances.length, 10);
+ assert.throws(() => buildTraceScene(copiesOfTriangle(11), ENVIRONMENT, { instancing: true, maximumInstances: 10 }),
+ { name: 'RangeError', message: 'An instanced native path trace takes at most 10 instances, got 11. Pass fewer parts, or merge small copies into one mesh.' });
+});
+
+test('maximumInstances can lower the bound under 65,536 and leaves the triangle bound alone', () => {
+ assert.throws(() => buildTraceScene(copiesOfTriangle(3), ENVIRONMENT, { instancing: true, maximumInstances: 2 }), /at most 2 instances, got 3/);
+ assert.throws(() => buildTraceScene(copiesOfTriangle(5), ENVIRONMENT, { instancing: true, maximumInstances: 10, maximumTriangles: 1 }), /at most 4 triangles with every copy counted, got 5/);
+});
+
+test('the instance ceiling is MAX_NATIVE_TRACE_INSTANCES and a value outside 1 to the ceiling is refused with the range', () => {
+ assert.equal(MAX_NATIVE_TRACE_INSTANCES, 1_000_000);
+ const parts = copiesOfTriangle(2);
+ for (const value of [0, -5, 1.5, Number.NaN, Infinity, '1000', null, MAX_NATIVE_TRACE_INSTANCES + 1]) {
+ assert.throws(() => buildTraceScene(parts, ENVIRONMENT, { instancing: true, maximumInstances: value }),
+ { name: 'RangeError', message: /maximumInstances is an integer from 1 to 1000000 for the native path tracer.*65536 instances/ }, `value ${String(value)}`);
+ }
+});
+
+test('a flattened scene ignores maximumInstances and keeps its part bound', () => {
+ const parts = Array.from({ length: 3 }, (_, index) => ({ name: `own-${index}`, geometry: { ...TRIANGLE, positions: Float32Array.from(TRIANGLE.positions) }, material: SHARED_MATERIAL }));
+ assert.equal(buildTraceScene(parts, ENVIRONMENT, { maximumInstances: 1 }).indices.length, 9);
+});
+
+const camera = createCamera({ eye: [0, 0, 8], target: [0, 0, 0], fov: 50 }, 8, 8);
+const packOptions = { width: 8, height: 8, bounces: 2, seed: 1, fireflyClamp: 20, noiseThreshold: 0 };
+const modules = { buildTraceScene, refuseLocalVolumes, resolveTexture, buildNativeInput, buildJobNativeInput, buildFlattenedJobNativeInput, pack };
+
+test('a native render job with the cycles kernel exports more than 65,536 instances of one geometry', () => {
+ assert.ok(NATIVE_JOB_MAXIMUM_INSTANCES > MAX_TRACE_INSTANCES && NATIVE_JOB_MAXIMUM_INSTANCES <= MAX_NATIVE_TRACE_INSTANCES);
+ const copyCount = MAX_TRACE_INSTANCES + 100;
+ const exported = exportNativeSceneTables({ parts: copiesOfTriangle(copyCount), environment: ENVIRONMENT, camera, options: packOptions, kernel: 'cycles', instancing: true, modules });
+ assert.equal(exported.instances, copyCount);
+ assert.equal(exported.instancing, undefined);
+ assert.equal(exported.triangleCount, 1);
+});
+
+test('a native render job past its instance bound says so and does not hide the refusal', () => {
+ const smallBound = (sceneParts, environment, options) => buildTraceScene(sceneParts, environment, { ...options, maximumInstances: 5 });
+ assert.throws(() => exportNativeSceneTables({ parts: copiesOfTriangle(6), environment: ENVIRONMENT, camera, options: packOptions, kernel: 'cycles', instancing: true,
+ modules: { ...modules, buildTraceScene: smallBound } }), { name: 'RangeError', message: /at most 5 instances, got 6\. Pass fewer parts, or merge small copies into one mesh\./ });
+});
+
+test('a native render job with the legacy kernel keeps its flattened bounds, not the instance bound', () => {
+ assert.throws(() => exportNativeSceneTables({ parts: copiesOfTriangle(MAX_TRACE_INSTANCES + 1), environment: ENVIRONMENT, camera, options: packOptions, kernel: 'legacy', instancing: true, modules }),
+ { name: 'RangeError', message: /1 to 1024 parts/ });
+});