Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Document the native triangle bound and its measurements, add the change note (#1041)

Nguyen Xuan An20f2f31d2935
diff --git a/bench/cycles-parity/native-cap-measure.mjs b/bench/cycles-parity/native-cap-measure.mjs
index 58a666a9..a88be6d2 100644
--- a/bench/cycles-parity/native-cap-measure.mjs
+++ b/bench/cycles-parity/native-cap-measure.mjs
@@ -1,7 +1,8 @@
// Measures the page-side pack of a scene above the CPU and WebGL triangle bound (#1041), and optionally traces it on the native tracer.
// One child process per case, so the peak memory of a case is its own. Each child prints one NATIVE_CAP_CASE line of JSON.
// node bench/cycles-parity/native-cap-measure.mjs --sizes 400000,1000000 [--variants instanced,flattened] [--trace] [--out <json file>]
-// [--png-directory <dir>] [--samples 16]
+// [--png-directory <dir>] [--samples 16] [--no-encode]
+// --no-encode stops after the pack (a table above 536,870,888 base64 characters cannot be encoded in V8) and traces the packed input as it is.
// Run with NODE_OPTIONS=--max-old-space-size=16384 for sizes above 2,000,000 triangles.
// instanced: buildTraceScene({ instancing: true, maximumTriangles }) + buildJobNativeInput + encodeNativeInputV2, the job export path.
// flattened: the four meshes alone, buildTraceScene({ maximumTriangles }) (world-space triangles and a CPU BVH) + buildFlattenedJobNativeInput + encodeNativeInputV2.
@@ -44,7 +45,7 @@ function packedBytesOf(input) {
return Object.values(input).reduce((total, value) => total + (ArrayBuffer.isView(value) ? value.byteLength : 0), 0);
}
-function packScene(variant, uniqueTriangles, maximumTriangles) {
+function packScene(variant, uniqueTriangles, maximumTriangles, encode) {
const instanced = variant === 'instanced';
const { parts, uniqueTriangles: actualUnique } = buildNativeCapParts(uniqueTriangles, variant !== 'flattened');
const camera = nativeCapCamera();
@@ -57,6 +58,7 @@ function packScene(variant, uniqueTriangles, maximumTriangles) {
? buildJobNativeInput(traceScene, camera, NATIVE_CAP_PACK_OPTIONS, pack, resolveTexture)
: buildFlattenedJobNativeInput(traceScene, camera, NATIVE_CAP_PACK_OPTIONS, pack, resolveTexture);
phases.packSeconds = secondsSince(startedAt);
+ if (!encode) return { input, phases, actualUnique, packedBytes: packedBytesOf(input), instances: input.instanceCount ?? 0 };
startedAt = performance.now();
const encoded = encodeNativeInputV2(input);
phases.encodeSeconds = secondsSince(startedAt);
@@ -64,6 +66,16 @@ function packScene(variant, uniqueTriangles, maximumTriangles) {
return { exported, phases, actualUnique, packedBytes: packedBytesOf(input), instances: input.instanceCount ?? 0 };
}
+// Without the base64 step (a table above the 536,870,888 characters of a V8 string cannot be encoded): the packed input goes to the tracer as it is.
+async function traceInput(input, samples) {
+ const tracer = await import('../../packages/render-native/index.mjs');
+ const { width, height } = NATIVE_CAP_PACK_OPTIONS;
+ const startedAt = performance.now();
+ const traced = tracer.traceNative(input, { width, height, samples, kernel: 'cycles', noiseThreshold: 0 });
+ return { tracedSeconds: secondsSince(startedAt), accelerationBuildSeconds: traced.accelerationBuildSeconds, uploadSeconds: traced.uploadSeconds, adapter: traced.adapter,
+ rgbaSha256: createHash('sha256').update(Buffer.from(traced.rgba.buffer, traced.rgba.byteOffset, traced.rgba.byteLength)).digest('hex') };
+}
+
async function traceExported(exported, samples, pngPath) {
const tracer = await import('../../packages/render-native/index.mjs');
const { traceFrameNative } = await import('../../scripts/agent-native-trace.mjs');
@@ -86,15 +98,16 @@ async function runChild(argumentList) {
const maximumTriangles = Number(readFlag(argumentList, '--maximum', 4_000_000));
const result = { variant, requestedUniqueTriangles: size };
const startedAt = performance.now();
- const packed = packScene(variant, size, maximumTriangles);
+ const encode = !argumentList.includes('--no-encode');
+ const packed = packScene(variant, size, maximumTriangles, encode);
Object.assign(result, { uniqueTriangles: packed.actualUnique, instances: packed.instances, ...packed.phases, packTotalSeconds: secondsSince(startedAt),
- packedMegabytes: megabytes(packed.packedBytes), ...describeTables(packed.exported) });
+ packedMegabytes: megabytes(packed.packedBytes), ...(encode ? describeTables(packed.exported) : {}) });
result.overStringLimit = result.largestTableCharacters > V8_STRING_LIMIT || result.jsonCharacters > V8_STRING_LIMIT;
result.heapUsedMegabytes = megabytes(process.memoryUsage().heapUsed);
result.peakResidentMegabytes = megabytes(process.resourceUsage().maxRSS * 1024);
if (argumentList.includes('--trace')) {
const pngPath = pngDirectory ? join(pngDirectory, `${variant}-${size}.png`) : null;
- Object.assign(result, { trace: await traceExported(packed.exported, samples, pngPath) });
+ Object.assign(result, { trace: encode ? await traceExported(packed.exported, samples, pngPath) : await traceInput(packed.input, samples) });
}
console.log(`NATIVE_CAP_CASE ${JSON.stringify(result)}`);
}
@@ -108,6 +121,16 @@ async function readCardMegabytes() {
}
}
+async function readProcessMegabytes(processId) {
+ try {
+ const { stdout } = await runCommand('nvidia-smi', ['--query-compute-apps=pid,used_memory', '--format=csv,noheader,nounits']);
+ const row = stdout.trim().split('\n').map(line => line.split(',').map(part => part.trim())).find(parts => Number(parts[0]) === processId);
+ return row ? Number(row[1]) : null;
+ } catch (error) {
+ return null;
+ }
+}
+
async function runCaseInChild(variant, size, extraArguments) {
const childArguments = [THIS_FILE, '--child', '--variant', variant, '--size', String(size), ...extraArguments];
const idleCardMegabytes = await readCardMegabytes();
@@ -117,8 +140,10 @@ async function runCaseInChild(variant, size, extraArguments) {
let finished = false;
const exited = new Promise(resolve => child.once('exit', code => { finished = true; resolve(code); }));
let peakCardMegabytes = idleCardMegabytes;
+ let peakProcessMegabytes = null;
while (!finished) {
- const card = await readCardMegabytes();
+ const [card, processMegabytes] = await Promise.all([readCardMegabytes(), readProcessMegabytes(child.pid)]);
+ if (processMegabytes !== null) peakProcessMegabytes = Math.max(peakProcessMegabytes ?? 0, processMegabytes);
if (Number.isFinite(card)) peakCardMegabytes = Math.max(peakCardMegabytes, card);
await new Promise(resolve => setTimeout(resolve, 150));
}
@@ -130,6 +155,7 @@ async function runCaseInChild(variant, size, extraArguments) {
result.trace.cardIdleMegabytes = idleCardMegabytes;
result.trace.cardPeakMegabytes = peakCardMegabytes;
result.trace.cardDeltaMegabytes = peakCardMegabytes - idleCardMegabytes;
+ result.trace.processMegabytes = peakProcessMegabytes;
}
return result;
}
@@ -138,7 +164,7 @@ async function runParent(argumentList) {
const sizes = readFlag(argumentList, '--sizes', '400000').split(',').map(Number);
const variants = readFlag(argumentList, '--variants', 'instanced,flattened').split(',');
const passThrough = ['--samples', '--png-directory', '--maximum'].flatMap(flag => (argumentList.includes(flag) ? [flag, readFlag(argumentList, flag, '')] : []));
- if (argumentList.includes('--trace')) passThrough.push('--trace');
+ for (const flag of ['--trace', '--no-encode']) if (argumentList.includes(flag)) passThrough.push(flag);
const results = [];
for (const size of sizes) {
for (const variant of variants) {
diff --git a/changes/1041.md b/changes/1041.md
new file mode 100644
index 00000000..7e80f2b9
--- /dev/null
+++ b/changes/1041.md
@@ -0,0 +1 @@
+- A scene built for the native path tracer can take more than 400,000 triangles: `buildTraceScene` accepts `maximumTriangles` (up to 4,000,000 unique triangles, and four times that with every copy counted), native render jobs on the `cycles` kernel use it, and the CPU and WebGL path tracers keep the 400,000 limit and its error text (#1041)
diff --git a/docs/agent-render-jobs.md b/docs/agent-render-jobs.md
index a7c5d736..522e396f 100644
--- a/docs/agent-render-jobs.md
+++ b/docs/agent-render-jobs.md
@@ -185,7 +185,7 @@ An `image`, `stills` or `video` job can ask for the offline [path tracer](https:
"renderer": { "type": "pathTracer", "backend": "gpu", "samples": 64, "bounces": 8, "denoise": true, "seed": 0, "maxSeconds": 120 } }
```
-Every field after `type` is optional. `backend` is `cpu` (the default, byte-identical on SwiftShader smokes), `gpu`, which traces in a WebGL2 shader and needs a runtime started on the GPU backend (a `--backend cpu` runtime refuses it), or `native`, which traces on hardware ray queries (Vulkan) through the optional `@codepawlhq/67js-render-native` package. A native job exports the scene from the job page, traces it in the job runner with the Cycles-matching kernel (`JS67_NATIVE_KERNEL=legacy` keeps the older one), then denoises (OIDN runs on a device kept alive between frames when the OIDN library is installed, so only the first frame pays for the device and the filter commit; `metrics.pathTracer.oidnMode` says `in-process` or `cli`) and writes the PNG as the other backends do: `denoise: true` means OIDN with the albedo and normal guides when `@codepawlhq/67js-denoise-oidn` and its binary are installed, else (or when OIDN fails) the GPU a-trous filter of the native tracer with a note in `metrics.pathTracer.denoiserNote` (`denoiser: "atrous"`; it is biased, it smooths; `denoise: "wavelet"` asks for the CPU filter). The report carries `kernel` and `averageSamples`. On the Cycles-matching kernel the job sends each material whole (FORMAT-v2 tables, instanced or not): blend opacity (`alphaMode: "blend"` with `opacity` below 1), sheen, `specular` and `specularColor`, anisotropy, iridescence, attenuation, and the clearcoat, transmission, sheen, anisotropy and coat normal maps all reach the kernel, and `metrics.pathTracer.ignored` lists only what it does not shade (the legacy kernel keeps the v1 tables and the old notes). A scene whose materials cannot be exported whole is traced from the v1 tables for that frame with the reason in `materialsReason`; the native tracer stays usable. It never fails for lack of the package: without it, without its built binary or without a Vulkan ray query adapter the job runs on `gpu` (`cpu` on a cpu runtime) and `metrics.pathTracer.backendNote` says why; `metrics.pathTracer.backend` always names what ran. The look up costs one import and is cached per process. Native traces volume fog and subsurface scattering with the same walk as the WebGPU megakernel, honours `maxSeconds`, and honours `noiseThreshold` on the GPU (after 16 samples, and then every 8, a converged pixel draws no more; `report.averageSamples` is the mean a pixel drew). The `gpu` fallback ignores `noiseThreshold`. The report in `metrics.pathTracer` names the `backend` that ran, the `gpu`, `gpuCompileSeconds` and `gpuKernelCompiles`. A `stills` or `video` job traces every frame with the same options: the kernel compiles once per job page and each frame reuses it, so a film shows `gpuKernelCompiles: 1`. A native `stills` or `video` job (the Cycles-matching kernel) also keeps one native session for the whole job: a frame that only moves the camera reuses the uploaded scene, the compiled kernel and the acceleration structures; changed materials, lights or instance transforms are sent to the session; a frame whose counts, geometry, textures or environment changed gets a new session, and a failed session update or render falls back to a new session or a one-shot trace for that frame. `metrics.pathTracer.nativeSession` says which one each frame took (`path` is `new-session`, `reused`, `updated` or `one-shot`, with `reason`, `changedTables`, `pipelineReused` and `accelerationReused`); `metrics.nativeSessionRoutes` lists the `path` of every frame. A job reuses the session only when the tables the page exports are equal to the previous frame's apart from the camera (`reused`), or differ in material values, lights or instance transforms only (`updated`). Anything that rebuilds geometry from the time, such as particle systems (sparks, swaying hair), a moved node in a scene exported as flattened triangles, or a changed emissive triangle count, gives every frame a new session, which costs what a one-shot trace costs and is byte-identical to it; `reason` names the first table that differed. A single-frame job and `JS67_NATIVE_KERNEL=legacy` trace one-shot and carry no `nativeSession`; `JS67_NATIVE_SESSIONS=off` in the server's environment traces every frame one-shot (default on). The session is closed when the job ends or fails, and every frame equals the one-shot render byte for byte. A video of traced frames goes through the ffmpeg encoder (the browser H.264 encoder has no drawn frame to read), `maxSeconds` limits each frame, and the job deadline is `maxSeconds` times the frame count plus 60 seconds, up to the job ceiling. Limits: `samples` 1 to 1024, `bounces` 1 to 16, `seed` 0 to 2147483647, `maxSeconds` 1 to 600 (the job's deadline is `maxSeconds` plus 60 seconds; a 1920 by 1080 still of a 180,000 triangle room at 64 samples took 246 s, so give a large still `maxSeconds` 600). `passes` are refused with it. The tracer loads in the job page on demand, uses eight threads at below-normal priority, stops pixels that have converged (`report.averageSamples`), and writes `render.png`; `scene_render_result` metrics carry `pathTracer` with the samples, threads, seconds and what the scene asked for that was not drawn. The same recipe and seed give the same PNG on the cpu and gpu backends; the native Cycles-matching kernel is not always byte-identical between runs (on the demo room at 960 by 540 and 256 samples two jobs differed in a few bytes; a 480 by 270 job with OIDN did not). A job that passes `maxSeconds` fails and writes no image.
+Every field after `type` is optional. `backend` is `cpu` (the default, byte-identical on SwiftShader smokes), `gpu`, which traces in a WebGL2 shader and needs a runtime started on the GPU backend (a `--backend cpu` runtime refuses it), or `native`, which traces on hardware ray queries (Vulkan) through the optional `@codepawlhq/67js-render-native` package. A native job exports the scene from the job page, traces it in the job runner with the Cycles-matching kernel (`JS67_NATIVE_KERNEL=legacy` keeps the older one), then denoises (OIDN runs on a device kept alive between frames when the OIDN library is installed, so only the first frame pays for the device and the filter commit; `metrics.pathTracer.oidnMode` says `in-process` or `cli`) and writes the PNG as the other backends do: `denoise: true` means OIDN with the albedo and normal guides when `@codepawlhq/67js-denoise-oidn` and its binary are installed, else (or when OIDN fails) the GPU a-trous filter of the native tracer with a note in `metrics.pathTracer.denoiserNote` (`denoiser: "atrous"`; it is biased, it smooths; `denoise: "wavelet"` asks for the CPU filter). The report carries `kernel` and `averageSamples`. The Cycles-matching kernel takes up to 1,500,000 unique triangles (copies of a shared mesh count once, and the scene may hold four times that with every copy counted); the `cpu` and `gpu` backends and the older kernel keep 400,000. A larger scene is refused with an error that names the limit. On the Cycles-matching kernel the job sends each material whole (FORMAT-v2 tables, instanced or not): blend opacity (`alphaMode: "blend"` with `opacity` below 1), sheen, `specular` and `specularColor`, anisotropy, iridescence, attenuation, and the clearcoat, transmission, sheen, anisotropy and coat normal maps all reach the kernel, and `metrics.pathTracer.ignored` lists only what it does not shade (the legacy kernel keeps the v1 tables and the old notes). A scene whose materials cannot be exported whole is traced from the v1 tables for that frame with the reason in `materialsReason`; the native tracer stays usable. It never fails for lack of the package: without it, without its built binary or without a Vulkan ray query adapter the job runs on `gpu` (`cpu` on a cpu runtime) and `metrics.pathTracer.backendNote` says why; `metrics.pathTracer.backend` always names what ran. The look up costs one import and is cached per process. Native traces volume fog and subsurface scattering with the same walk as the WebGPU megakernel, honours `maxSeconds`, and honours `noiseThreshold` on the GPU (after 16 samples, and then every 8, a converged pixel draws no more; `report.averageSamples` is the mean a pixel drew). The `gpu` fallback ignores `noiseThreshold`. The report in `metrics.pathTracer` names the `backend` that ran, the `gpu`, `gpuCompileSeconds` and `gpuKernelCompiles`. A `stills` or `video` job traces every frame with the same options: the kernel compiles once per job page and each frame reuses it, so a film shows `gpuKernelCompiles: 1`. A native `stills` or `video` job (the Cycles-matching kernel) also keeps one native session for the whole job: a frame that only moves the camera reuses the uploaded scene, the compiled kernel and the acceleration structures; changed materials, lights or instance transforms are sent to the session; a frame whose counts, geometry, textures or environment changed gets a new session, and a failed session update or render falls back to a new session or a one-shot trace for that frame. `metrics.pathTracer.nativeSession` says which one each frame took (`path` is `new-session`, `reused`, `updated` or `one-shot`, with `reason`, `changedTables`, `pipelineReused` and `accelerationReused`); `metrics.nativeSessionRoutes` lists the `path` of every frame. A job reuses the session only when the tables the page exports are equal to the previous frame's apart from the camera (`reused`), or differ in material values, lights or instance transforms only (`updated`). Anything that rebuilds geometry from the time, such as particle systems (sparks, swaying hair), a moved node in a scene exported as flattened triangles, or a changed emissive triangle count, gives every frame a new session, which costs what a one-shot trace costs and is byte-identical to it; `reason` names the first table that differed. A single-frame job and `JS67_NATIVE_KERNEL=legacy` trace one-shot and carry no `nativeSession`; `JS67_NATIVE_SESSIONS=off` in the server's environment traces every frame one-shot (default on). The session is closed when the job ends or fails, and every frame equals the one-shot render byte for byte. A video of traced frames goes through the ffmpeg encoder (the browser H.264 encoder has no drawn frame to read), `maxSeconds` limits each frame, and the job deadline is `maxSeconds` times the frame count plus 60 seconds, up to the job ceiling. Limits: `samples` 1 to 1024, `bounces` 1 to 16, `seed` 0 to 2147483647, `maxSeconds` 1 to 600 (the job's deadline is `maxSeconds` plus 60 seconds; a 1920 by 1080 still of a 180,000 triangle room at 64 samples took 246 s, so give a large still `maxSeconds` 600). `passes` are refused with it. The tracer loads in the job page on demand, uses eight threads at below-normal priority, stops pixels that have converged (`report.averageSamples`), and writes `render.png`; `scene_render_result` metrics carry `pathTracer` with the samples, threads, seconds and what the scene asked for that was not drawn. The same recipe and seed give the same PNG on the cpu and gpu backends; the native Cycles-matching kernel is not always byte-identical between runs (on the demo room at 960 by 540 and 256 samples two jobs differed in a few bytes; a 480 by 270 job with OIDN did not). A job that passes `maxSeconds` fails and writes no image.
## Controller API
diff --git a/docs/cycles-parity.md b/docs/cycles-parity.md
index c5668333..9ae845bd 100644
--- a/docs/cycles-parity.md
+++ b/docs/cycles-parity.md
@@ -1011,9 +1011,9 @@ Picture (Cook left, Cycles right, 1024 samples, depth of field on, grey diffuse)
[`classroom_bridge.py`](../bench/cycles-parity/classroom_bridge.py) runs inside Blender 5.3 on the opened scene, with auto-run scripts disabled (`blender -b --disable-autoexec classroom.blend --python ... -- export <dir>`). `export` writes the evaluated scene in the JSON format the other parity benches read: one geometry per mesh datablock and modifier stack (so linked copies share it), one part per instance with its world matrix, the camera, the lights, the world and one grey material (base 0.8, roughness 1, as the harness defines). `render-cycles.py` builds the Cycles side from that same JSON, so both renderers see exactly the same scene. `reference` renders the original `.blend` in Cycles with the same drops and the same override, to measure the bridge itself.
-[`run-classroom-parity.py`](../bench/cycles-parity/run-classroom-parity.py) (started by `run-classroom-parity.sh`) does everything in one call: download once, export, Cook and Cycles renders, comparisons, depth, a figure and the diagnostic experiments. Small changes elsewhere in `bench/`: `trace-native.mjs --instancing` keeps shared geometry as instances (through `instanced-scene-in-batches.mjs`, below), parts may carry `rayVisibility` (read by `render-cycles.py` and by Cook's instance visibility bits), and `render-cycles.py` reads `environment.sunAngularRadius` as Cook does.
+[`run-classroom-parity.py`](../bench/cycles-parity/run-classroom-parity.py) (started by `run-classroom-parity.sh`) does everything in one call: download once, export, Cook and Cycles renders, comparisons, depth, a figure and the diagnostic experiments. Small changes elsewhere in `bench/`: `trace-native.mjs --instancing` keeps shared geometry as instances (through `instanced-scene.mjs`, below), parts may carry `rayVisibility` (read by `render-cycles.py` and by Cook's instance visibility bits), and `render-cycles.py` reads `environment.sunAngularRadius` as Cook does.
-`buildTraceScene` refuses an instanced scene with more than 400,000 unique triangles, counted once per shared geometry, and the Classroom holds 427,769. The kernel has no such limit. `instanced-scene-in-batches.mjs` builds the scene in two batches that each fit and joins their instance lists, so `src/` is untouched (tests: `tests/cycles-parity-instanced-batches.test.js`, `tests/cycles-parity-instancing-option.test.js`).
+The Classroom holds 427,769 unique triangles, above the 400,000 of the CPU and WebGL tracers. `instanced-scene.mjs` builds it directly with the native bound (`maximumTriangles`, see "Triangle bound of a native scene" below) and applies the parts' `rayVisibility`; the two-batch workaround of the first slice is gone (tests: `tests/cycles-parity-instanced-scene.test.js`, `tests/cycles-parity-instancing-option.test.js`). The instance order is now the part order, as in a flattened scene, where the batches listed one batch after the other. This has not been re-run against Cycles `[not measured]`: the Classroom needs Blender and its download.
### Counts `[measured]`
@@ -1308,3 +1308,34 @@ Same scene, same 4096 samples, 192 x 128, box filter, 8 bounces, seed 1, against
![Opaque pane before, blend pane after, Cycles 5.3 (left to right) for a blend pane over a sheen sphere](native-job-materials.jpg)
Jobs that use none of these fields are unchanged: the tables of a flattened job (all of them, including the kernel parameters), the instanced input of a shared-geometry job, and the PNG of a real job on the demo room, a textured scene, a scene with 40 copies of one mesh and a scene with glass and clearcoat have the same bytes as on the base branch (`tests/native-job-materials.test.js`, `bench/job-materials`).
+
+## Triangle bound of a native scene (#1041)
+
+`buildTraceScene` bounds a scene at 400,000 triangles for the CPU and WebGL tracers, which hold the triangles in JavaScript and in browser memory. A scene built for the native tracer asks for another bound with `maximumTriangles`, an integer from 1 to `MAX_NATIVE_TRACE_TRIANGLES` (4,000,000, the size the large sequence section measured on the card). Two costs are bounded apart: the unique triangles (once per shared geometry, or all triangles of a flattened scene) by `maximumTriangles`, and the triangles with every copy counted by four times that, 16,000,000 at the ceiling. The second bound is a guard and not a measured edge `[inferred: the kernel builds one bottom-level structure per geometry, so a copy costs an instance record]`. A render job on the Cycles-matching kernel passes 1,500,000 (`NATIVE_JOB_MAXIMUM_TRIANGLES` in `scripts/native-bake-page.js`); the legacy kernel keeps 400,000.
+
+A scene under 400,000 triangles packs to the same bytes as before `[measured]`: the SHA-256 of every table of the lit-interior scene (flattened, as v1 tables and as v2 job tables) and of an instanced scene is equal before the change, after it, and with the option set (`bench/cycles-parity/packed-table-hashes.mjs`).
+
+Why the job stops at 1,500,000 and the library at 4,000,000: the job page encodes each packed table as one base64 string, and V8 refuses a string above 536,870,888 characters. The triangle table is about 299 characters per triangle, so it breaks near 1.79 million unique triangles `[inferred from the measurements below]`. A 2,000,000 triangle scene aborted Node in `btoa` and a 4,000,000 one threw `RangeError: Invalid string length`. 1,500,000 leaves 17% under that. Packing in Node for the package API has no such string.
+
+`bench/cycles-parity/native-cap-measure.mjs` builds four rippled grids (two of them used a second time) and packs them the way the job page does, one process per case. It ran on an RTX 4090 box shared with another job, one run per row, so the times are indicative `[measured]`. Memory is Node's `[a Chrome tab has not been measured]`.
+
+| unique triangles | path | scene build s | pack s | base64 s | packed MB | base64 MB (largest table, characters) | JS heap MB | peak RSS MB |
+| --- | --- | --- | --- | --- | --- | --- | --- | --- |
+| 401,408 | instanced | 0.01 | 1.0 | 3.3 | 85.8 | 114 (119.9 M) | 749 | 1,164 |
+| 401,408 | flattened | 0.59 | 1.3 | 3.1 | 85.8 | 114 (119.9 M) | 748 | 1,284 |
+| 1,002,528 | instanced | 0.02 | 2.0 | 7.8 | 214.2 | 286 (299.4 M) | 1,856 | 2,617 |
+| 1,002,528 | flattened | 1.5 | 3.0 | 8.0 | 214.2 | 286 (299.4 M) | 1,855 | 2,895 |
+| 1,499,912 | instanced | 0.02 | 3.3 | 12.3 | 320.4 | 427 (448.0 M) | 2,773 | 3,817 |
+| 1,499,912 | flattened | 2.2 | 3.5 | 12.1 | 320.4 | 427 (448.0 M) | 2,773 | 4,222 |
+| 2,000,000 | instanced | 0.03 | 4.5 | aborts | 427.3 | over the string limit | 2,738 (no base64) | 3,444 (no base64) |
+| 3,998,792 | instanced | 0.05 | 8.1 | fails | 854.2 | over the string limit | 5,381 (no base64) | 6,677 (no base64) |
+
+Tracing the packed input on the card (480 by 270, 16 samples, GPU memory of the process from nvidia-smi, no base64 step):
+
+| unique triangles | instances | traced s | acceleration build s | upload s | GPU memory MB |
+| --- | --- | --- | --- | --- | --- |
+| 1,002,528 | 7 | 0.54 | 0.03 | 0.04 | 585 |
+| 2,000,000 | 7 | 0.95 | 0.10 | 0.13 | 1,235 |
+| 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.
diff --git a/docs/path-tracer.md b/docs/path-tracer.md
index 8f569fbe..60692e29 100644
--- a/docs/path-tracer.md
+++ b/docs/path-tracer.md
@@ -54,14 +54,14 @@ A part with a material `subsurface` weight above 0 sends that share of its diffu
| `backend` | `cpu` | `cpu`, `gpu`, `webgpu` | `gpu` traces in a WebGL2 shader, `webgpu` in WGSL compute (see Choosing a backend). |
| `fireflyClamp` | 20 | 1 to 1000 | Largest radiance one bounce may add to a sample. |
-Also checked before any ray is traced: samples times pixels times bounces at most 4 billion, 400,000 triangles, 1,024 parts, 32 lights, and finite numbers and in-range indices in every part. A render job limits `maxSeconds` to 600: the job runs on workers without blocking the page, and its deadline is `maxSeconds` plus 60 seconds for the page and the PNG, so a trace that reaches its limit still ends before the job does.
+Also checked before any ray is traced: samples times pixels times bounces at most 4 billion, 400,000 triangles (the CPU and WebGL tracers; a scene exported to the native tracer takes more, see below), 1,024 parts, 32 lights, and finite numbers and in-range indices in every part. A render job limits `maxSeconds` to 600: the job runs on workers without blocking the page, and its deadline is `maxSeconds` plus 60 seconds for the page and the PNG, so a trace that reaches its limit still ends before the job does.
### Instanced scenes for the native tracer
`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. 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 })` 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.
- 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/packages/render-native/README.md b/packages/render-native/README.md
index 5d165806..a3c2d159 100644
--- a/packages/render-native/README.md
+++ b/packages/render-native/README.md
@@ -62,7 +62,7 @@ The split does not change the image. The `cycles` kernel carries each pixel's ru
## Instanced scenes
-`buildTraceScene(parts, environment, { instancing: true })` keeps parts that share one geometry object as instances, and `buildNativeInputV2` packs the unique triangles once with one instance record per part, for `traceNative` with `kernel: "cycles"`. The `legacy` kernel and `buildNativeInput` refuse that input and name the fix. Render jobs on the native backend send every scene to the `cycles` kernel as FORMAT-v2 tables by default, with whole materials (see "Native job materials" in [docs/cycles-parity.md](../../docs/cycles-parity.md)). The sharing rules are in [FORMAT-v2.md](./FORMAT-v2.md), the equivalence numbers against flattened in [docs/cycles-parity.md](../../docs/cycles-parity.md), section "Instancing equivalence (#896, slice I2)".
+`buildTraceScene(parts, environment, { instancing: true, maximumTriangles })` keeps parts that share one geometry object as instances (`maximumTriangles`, up to 4,000,000, replaces the 400,000 unique triangle bound of the CPU and WebGL tracers for a scene built for this package), and `buildNativeInputV2` packs the unique triangles once with one instance record per part, for `traceNative` with `kernel: "cycles"`. The `legacy` kernel and `buildNativeInput` refuse that input and name the fix. Render jobs on the native backend send every scene to the `cycles` kernel as FORMAT-v2 tables by default, with whole materials (see "Native job materials" in [docs/cycles-parity.md](../../docs/cycles-parity.md)). The sharing rules are in [FORMAT-v2.md](./FORMAT-v2.md), the equivalence numbers against flattened in [docs/cycles-parity.md](../../docs/cycles-parity.md), section "Instancing equivalence (#896, slice I2)".
## Sessions
diff --git a/scripts/native-bake-page.js b/scripts/native-bake-page.js
index acac1ab6..396ebce4 100644
--- a/scripts/native-bake-page.js
+++ b/scripts/native-bake-page.js
@@ -45,7 +45,7 @@ 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_000_000;
+export const NATIVE_JOB_MAXIMUM_TRIANGLES = 1_500_000;
/**
* The scene of a native render job as the tables the job runner traces. With the "cycles" kernel (`kernel`) every scene is