Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Surface the texture pool refusal, validate map sizes before reading, test the refusals (#1053)

Nguyen Xuan Anc1e9884fe66f
diff --git a/docs/path-tracer.md b/docs/path-tracer.md
index 1a0ce45e..db6872c7 100644
--- a/docs/path-tracer.md
+++ b/docs/path-tracer.md
@@ -65,7 +65,7 @@ Also checked before any ray is traced: samples times pixels times bounces at mos
- 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.
-- A job sends the materials of an instanced scene and of a flattened one the same way (`buildJobNativeInput` and `buildFlattenedJobNativeInput` in `packages/render-native/job-input.mjs`): what the v1 material tables carry is read from them, and `carriedMaterialFields` lays blend opacity, sheen, specular, anisotropy, iridescence, attenuation and the layer textures over it. A part looks the same whether or not other geometry in the scene is shared, and a material that sets none of those fields packs to the record the v1 tables gave. Every job on the `cycles` kernel is exported as FORMAT-v2; the legacy kernel and light bakes keep the v1 tables. A job's maps go from the materials into the FORMAT-v2 texture pool without the v1 atlas (`withVirtualAtlas` in `packages/render-native/pack-input.mjs`), so the pool (`TEXTURE_POOL_MAX_BYTES`, 1 GiB, mip levels counted) limits them and not the 4096 by 16384 texels of the atlas; a scene that fitted the atlas packs to the same bytes (`tests/native-job-texture-pool.test.js` holds the SHA-256 of every table). Over the pool the job throws "The texture pool is full" and says to pass smaller textures.
+- A job sends the materials of an instanced scene and of a flattened one the same way (`buildJobNativeInput` and `buildFlattenedJobNativeInput` in `packages/render-native/job-input.mjs`): what the v1 material tables carry is read from them, and `carriedMaterialFields` lays blend opacity, sheen, specular, anisotropy, iridescence, attenuation and the layer textures over it. A part looks the same whether or not other geometry in the scene is shared, and a material that sets none of those fields packs to the record the v1 tables gave. Every job on the `cycles` kernel is exported as FORMAT-v2; the legacy kernel and light bakes keep the v1 tables. A job's maps go from the materials into the FORMAT-v2 texture pool without the v1 atlas (`withVirtualAtlas` in `packages/render-native/pack-input.mjs`), so the pool (`TEXTURE_POOL_MAX_BYTES`, 1 GiB, mip levels counted) limits them and not the 4096 by 16384 texels of the atlas; a scene that fitted the atlas packs to the same bytes (`tests/native-job-texture-pool.test.js` holds the SHA-256 of every table). Over the pool the job throws a `TexturePoolFullError` (a `RangeError`, `texturePoolFull: true`) that says "The texture pool is full" and to pass smaller textures; the page export (`exportNativeSceneTables`) rethrows it and does not fall back to flattened or v1 tables, which would only fail on the atlas. A map is checked against the pool and against its data length (`width * height * 4` bytes) before it is read. The packers take `texturePoolMaxBytes` to lower the pool limit for a run (never to raise it). When the v1 fallback fails too, its error ends with the reason the FORMAT-v2 export failed first.
- Texture mip levels are opt in on the `cycles` kernel: pass `textureMips: true` to the packer (or `mips: true` on one texture) and every linearly filtered texture, RGBA8, sRGB and float, stores a mip chain after level 0 (level 1 integrates the level 0 reconstruction, the rest are 2 x 2 boxes); the kernel then keeps a ray cone per path and reads the level a hit asks for, blended between two levels. Blender Cycles reads level 0 only, so the default stays level 0 and an existing scene packs and renders byte for byte as before. The pool check counts the levels (a third more texels). The estimate, its limits and the measured error of a minified checker are in `docs/cycles-parity.md` ("Texture mip levels").
- When the instanced packer refuses a scene (copies of an emissive mesh that emit different triangles, a singular matrix), the job exports it flattened as before and the report says `instancing: "flattened"` and `instancingReason`. A scene that fails to export no longer marks the native tracer unusable for the process; only a tracer or adapter failure does.
- A part with `shadowOnly: true` becomes an instance that camera rays skip (visibility bits for every other ray kind stay set). An instance whose material differs from the first copy's emits light by its own material: a copy made emissive by its material is sampled as a light, and a copy made non-emissive is not. Triangles of a shared mesh that are emissive keep one `local_emissive_offset` for all copies, so a copy scaled to a size that drops an emissive triangle the other copies keep is refused with its index.
diff --git a/packages/render-native/job-input.mjs b/packages/render-native/job-input.mjs
index 7ec31d61..282a4568 100644
--- a/packages/render-native/job-input.mjs
+++ b/packages/render-native/job-input.mjs
@@ -167,6 +167,7 @@ export function buildJobNativeInput(scene, camera, options, pack, resolveTexture
materialCount: scene.traceMaterials.length,
carriedFields: carriedMaterialFieldsOfScene(scene, resolveTexture),
textureMips: options.textureMips,
+ texturePoolMaxBytes: options.texturePoolMaxBytes,
});
const instances = scene.instances.map(instance => {
const lightMask = reducedMaterials.materialLightMasks[instance.materialIndex] ?? ALL_LIGHT_GROUPS;
@@ -187,6 +188,7 @@ export function buildFlattenedJobNativeInput(scene, camera, options, pack, resol
const upgradeOptions = {
...(options.samples === undefined ? {} : { samples: options.samples }),
...(options.textureMips === undefined ? {} : { textureMips: options.textureMips }),
+ ...(options.texturePoolMaxBytes === undefined ? {} : { texturePoolMaxBytes: options.texturePoolMaxBytes }),
};
return upgradeNativeInputV1ToV2(buildNativeInput(scene, camera, options, withVirtualAtlas(pack)), upgradeOptions, carriedFields);
}
diff --git a/packages/render-native/pack-input-v2.mjs b/packages/render-native/pack-input-v2.mjs
index 0be7b382..6a8da16a 100644
--- a/packages/render-native/pack-input-v2.mjs
+++ b/packages/render-native/pack-input-v2.mjs
@@ -101,6 +101,23 @@ const TEXTURE_FORMAT_RG16_FLOAT = 3;
export const TEXTURE_POOL_MAX_BYTES = 1 << 30;
const BYTES_PER_MEBIBYTE = 1 << 20;
+/** Thrown when the textures of a scene do not fit the pool. `texturePoolFull` lets a caller tell it from other packer refusals. */
+export class TexturePoolFullError extends RangeError {
+ constructor(message) {
+ super(message);
+ this.name = 'TexturePoolFullError';
+ this.texturePoolFull = true;
+ }
+}
+
+function validateTexturePoolMaxBytes(value, callerName) {
+ if (value === undefined) return TEXTURE_POOL_MAX_BYTES;
+ if (!Number.isInteger(value) || value < 16 || value > TEXTURE_POOL_MAX_BYTES) {
+ throw new RangeError(`${callerName}: \`texturePoolMaxBytes\` must be an integer from 16 to ${TEXTURE_POOL_MAX_BYTES} (the pool limit); got ${value}. It can only lower the limit.`);
+ }
+ return value;
+}
+
const DEFAULT_HDRI_RADIANCE_LIMIT = 16;
const SUN_DEFAULT_HALF_ANGLE = Math.PI / 360;
const IDENTITY_MATRIX_4X4 = Object.freeze([
@@ -295,8 +312,9 @@ function joinMipLevels(levelZeroWords, mipChain) {
* that is filtered linearly and has more than one texel; a texture can say `mips: true` or `mips: false` to differ from that.
* The default is level 0 only, which is what Blender Cycles reads.
*/
-function createTextureCollector({ textureMips } = {}) {
+function createTextureCollector({ textureMips, texturePoolMaxBytes } = {}) {
validateTextureMipsOption(textureMips, 'textureMips', 'createTextureCollector');
+ const poolMaxBytes = validateTexturePoolMaxBytes(texturePoolMaxBytes, 'createTextureCollector');
const indexByKey = new Map();
const dataIdMap = new WeakMap();
let nextDataId = 1;
@@ -326,14 +344,14 @@ function createTextureCollector({ textureMips } = {}) {
// Checked before a texture is converted, so an oversize image fails fast instead of after allocating its words.
function assertRoomInPool(wordCount, width, height) {
- if ((totalWords + wordCount) * 4 <= TEXTURE_POOL_MAX_BYTES) {
+ if ((totalWords + wordCount) * 4 <= poolMaxBytes) {
return;
}
const neededMebibytes = Math.ceil(wordCount * 4 / BYTES_PER_MEBIBYTE);
const usedMebibytes = Math.ceil(totalWords * 4 / BYTES_PER_MEBIBYTE);
- throw new RangeError(
+ throw new TexturePoolFullError(
`The texture pool is full: the ${width}x${height} texture needs ${neededMebibytes} MiB and the ${descriptors.length} before it take ${usedMebibytes} MiB, ` +
- `but one pool holds at most ${TEXTURE_POOL_MAX_BYTES / BYTES_PER_MEBIBYTE} MiB. Pass smaller textures: downscale the largest maps or drop the ones the look does not need.`,
+ `but one pool holds at most ${poolMaxBytes / BYTES_PER_MEBIBYTE} MiB. Pass smaller textures: downscale the largest maps or drop the ones the look does not need.`,
);
}
@@ -483,13 +501,15 @@ function createTextureCollector({ textureMips } = {}) {
return record;
}
- function addPackedRgba8Words(words, width, height, isSrgb, repeat) {
+ // `wordsOrReader` is the level 0 words, or a function that makes them: it runs after the pool check, so a texture that does not fit is never read.
+ function addPackedRgba8Words(wordsOrReader, width, height, isSrgb, repeat) {
const pixelCount = width * height;
const mipCount = resolveMipCount(undefined, false, width, height);
const atlasKind = isSrgb ? TEXTURE_KIND_RGBA8_SRGB : TEXTURE_KIND_RGBA8;
const mipWords = mipCount > 1 ? mipChainWordCount(atlasKind, width, height) : 0;
const alignedWords = packedWordCount(TEXTURE_FORMAT_RGBA8_UNORM, pixelCount, mipWords);
assertRoomInPool(alignedWords, width, height);
+ const words = typeof wordsOrReader === 'function' ? wordsOrReader() : wordsOrReader;
let padded = new Uint32Array(alignedWords);
padded.set(words.subarray(0, pixelCount));
if (mipCount > 1) {
@@ -2546,7 +2566,7 @@ export function buildNativeInputV2(scene, camera, options = {}) {
throw new TypeError('buildNativeInputV2 option `reducedMaterials` must be the result of reduceV1MaterialTable (materialRecords and textureCollector).');
}
}
- const textureCollector = reducedMaterials?.textureCollector ?? createTextureCollector({ textureMips: options.textureMips });
+ const textureCollector = reducedMaterials?.textureCollector ?? createTextureCollector({ textureMips: options.textureMips, texturePoolMaxBytes: options.texturePoolMaxBytes });
const packedGeometry = explicitInstances
? packInstancedGeometry(explicitInstances, options.materials ?? scene.materials ?? [{}], textureCollector, reducedMaterials)
: packFlattenedTraceScene(scene, options.parts ?? scene.parts, textureCollector);
@@ -2610,8 +2630,12 @@ export function buildNativeInputV2(scene, camera, options = {}) {
// The words of a texture that was never copied into an atlas (`packVirtualAtlas` in pack-input.mjs): its RGBA8 bytes as
// little-endian words, the layout the atlas rows hold.
function virtualTextureWords(texture, width, height) {
+ const byteCount = width * height * 4;
+ if (texture.data.length < byteCount) {
+ throw new RangeError(`A ${width}x${height} material texture needs ${byteCount} bytes of RGBA8 pixels but its data holds ${texture.data.length}. Pass data of width * height * 4 bytes.`);
+ }
const words = new Uint32Array(width * height);
- new Uint8Array(words.buffer).set(texture.data.subarray(0, width * height * 4));
+ new Uint8Array(words.buffer).set(texture.data.subarray(0, byteCount));
return words;
}
@@ -2663,8 +2687,8 @@ function withCarriedFields(descriptor, carried, textureCollector) {
* `virtualTextures`, when given, replaces the atlas: the rectangle of a map is `{ x: its index in that list, y: 0 }` and the
* map is read from the list, so the texture pool is the only limit on the maps.
*/
-export function reduceV1MaterialTable({ materials: matSource, atlas: atlasWords, atlasWidth, subsurfaceVec4Offset, materialCount, carriedFields, textureMips, virtualTextures }) {
- const textureCollector = createTextureCollector({ textureMips });
+export function reduceV1MaterialTable({ materials: matSource, atlas: atlasWords, atlasWidth, subsurfaceVec4Offset, materialCount, carriedFields, textureMips, virtualTextures, texturePoolMaxBytes }) {
+ const textureCollector = createTextureCollector({ textureMips, texturePoolMaxBytes });
const atlasCache = new Map();
function registerAtlasRect(rectX, rectY, width, height, flagsValue) {
@@ -2682,10 +2706,9 @@ export function reduceV1MaterialTable({ materials: matSource, atlas: atlasWords,
}
const repeat = (flags & 1) !== 0;
const isSrgb = (flags & 2) !== 0;
- const subWords = virtualTextures
- ? virtualTextureWords(virtualTextures[x], w, h)
- : extractAtlasSubtexture(atlasWords, atlasWidth, x, y, w, h);
- const added = textureCollector.addPackedRgba8Words(subWords, w, h, isSrgb, repeat);
+ const added = virtualTextures
+ ? textureCollector.addPackedRgba8Words(() => virtualTextureWords(virtualTextures[x], w, h), w, h, isSrgb, repeat)
+ : textureCollector.addPackedRgba8Words(extractAtlasSubtexture(atlasWords, atlasWidth, x, y, w, h), w, h, isSrgb, repeat);
atlasCache.set(key, added);
return added;
}
@@ -2806,6 +2829,7 @@ export function upgradeNativeInputV1ToV2(v1Input, options = {}, carriedFields =
carriedFields,
textureMips: options.textureMips,
virtualTextures: v1Input.virtualTextures,
+ texturePoolMaxBytes: options.texturePoolMaxBytes,
});
const materialsBuffer = new Uint8Array(Math.max(1, materialRecords.length) * STRUCT_STRIDES_V2.material);
diff --git a/scripts/native-bake-page.js b/scripts/native-bake-page.js
index 476ff861..4ecb1785 100644
--- a/scripts/native-bake-page.js
+++ b/scripts/native-bake-page.js
@@ -68,7 +68,8 @@ export function exportNativeSceneTables({ parts, environment, camera, options, k
const input = buildJobNativeInput(traceScene, camera, options, pack, resolveTexture);
return { ...encodeNativeInputV2(input), triangleCount: input.triangleCount, triangles: input.triangleCount, instances: input.instanceCount, wholeMaterials };
} catch (error) {
- if (!(error instanceof RangeError)) throw error;
+ // 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);
}
@@ -80,15 +81,26 @@ export function exportNativeSceneTables({ parts, environment, camera, options, k
const input = buildFlattenedJobNativeInput(traceScene, camera, options, pack, resolveTexture);
return { ...encodeNativeInputV2(input), triangleCount: input.triangleCount, triangles: traceScene.indices.length / 3, wholeMaterials, ...instancingNote };
} catch (error) {
+ if (error.texturePoolFull) throw error;
// The scene stays traceable: the v1 tables carry what the kernel read before, and the report says why they were used.
materialsReason = error.message;
}
}
- const input = buildNativeInput(traceScene, camera, options, pack);
+ const input = buildNativeInputOrExplain(buildNativeInput, traceScene, camera, options, pack, materialsReason);
return { tables: encodeNativeTables(input), triangleCount: input.triangleCount, triangles: traceScene.indices.length / 3, wholeMaterials: false,
...(materialsReason === undefined ? {} : { materialsReason }), ...instancingNote };
}
+// The v1 tables are the fallback for a scene whose FORMAT-v2 materials failed; when they fail too, the error keeps the first reason.
+function buildNativeInputOrExplain(buildNativeInput, traceScene, camera, options, pack, materialsReason) {
+ try {
+ return buildNativeInput(traceScene, camera, options, pack);
+ } catch (error) {
+ if (materialsReason === undefined || !(error instanceof RangeError)) throw error;
+ throw new RangeError(`${error.message} The FORMAT-v2 export had already failed: ${materialsReason}`);
+ }
+}
+
// 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) {
diff --git a/tests/native-job-texture-pool.test.js b/tests/native-job-texture-pool.test.js
index 2d250582..8c01701d 100644
--- a/tests/native-job-texture-pool.test.js
+++ b/tests/native-job-texture-pool.test.js
@@ -2,8 +2,10 @@ import assert from 'node:assert/strict';
import { createHash } from 'node:crypto';
import test from 'node:test';
import { STRUCT_STRIDES_V2 } from '../packages/render-native/index.mjs';
-import { buildFlattenedJobNativeInput, buildJobNativeInput } from '../packages/render-native/job-input.mjs';
-import { TEXTURE_POOL_MAX_BYTES } from '../packages/render-native/pack-input-v2.mjs';
+import { buildFlattenedJobNativeInput, buildJobNativeInput, carriedMaterialFieldsOfScene } from '../packages/render-native/job-input.mjs';
+import { buildNativeInput, packNativeMaterialTables } from '../packages/render-native/pack-input.mjs';
+import { TEXTURE_POOL_MAX_BYTES, TexturePoolFullError, buildNativeInputV2, reduceV1MaterialTable } from '../packages/render-native/pack-input-v2.mjs';
+import { exportNativeSceneTables } 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, resolveTexture } from '../src/path-tracer-scene.js';
@@ -53,7 +55,8 @@ function hashesOfPackedTables(input) {
return Object.fromEntries(tableNames.map(name => [name, hashOfTable(input[name])]));
}
-// SHA-256 of every packed table of the two scenes, taken with the v1 atlas step in place (before issue 1053).
+// SHA-256 of every packed table of the two scenes, taken on the unmodified code of origin/main at the branch base (55efd532),
+// where every map still went through the v1 atlas: stash the change, run this file with PRINT_POOL_HASHES=1, copy the printed hashes.
const GOLDEN_INSTANCED_HASHES = {
emissiveTriangles: '2e38284e3690d5a05476c1c3068ea5e3b87e9667c3417183f287d60b1c5834b9',
environmentTexels: '374708fff7719dd5979ec875d56cd2286f6d3cf7ec317a3b25632aab28ec37bb',
@@ -136,18 +139,116 @@ test('a flattened job with maps beyond the v1 atlas packs them into the texture
assert.ok(input.textureTexels.byteLength >= OVER_ATLAS_MAP_COUNT * OVER_ATLAS_MAP_SIZE * OVER_ATLAS_MAP_SIZE * 4);
});
-test('a job whose map exceeds the texture pool says what to pass instead', () => {
- // One map a row taller than the 1 GiB pool: the pool check runs before any pixel is read, so a short array stands in for the pixels.
+const POOL_MESSAGE = /texture pool is full[\s\S]*Pass smaller textures/;
+
+// One map a row taller than the 1 GiB pool. Its data is 4 bytes: the pool check runs before the data is read or a word is allocated.
+function oversizeMapParts(shared) {
const side = 16384;
const oversize = { image: { width: side, height: side + 1, data: new Uint8ClampedArray(4) }, colorSpace: 'srgb' };
- const shared = quad(1);
- const parts = [
+ return [
{ name: 'copy-a', geometry: shared, matrix: translate(0), material: { color: [1, 1, 1], map: oversize } },
{ name: 'copy-b', geometry: shared, matrix: translate(2), material: { color: [1, 1, 1] } },
];
+}
+
+function assertPoolRefusal(callback) {
+ assert.throws(callback, error => error instanceof TexturePoolFullError && error instanceof RangeError && error.texturePoolFull === true && POOL_MESSAGE.test(error.message));
+}
+
+test('an instanced job whose map exceeds the texture pool says what to pass instead', () => {
+ const scene = buildTraceScene(oversizeMapParts(quad(1)), environment, { instancing: true });
+ assertPoolRefusal(() => buildJobNativeInput(scene, camera, packOptions, pack, resolveTexture));
+});
+
+test('a flattened job whose map exceeds the texture pool says what to pass instead', () => {
+ const scene = buildTraceScene(oversizeMapParts(quad(1)), environment);
+ assertPoolRefusal(() => buildFlattenedJobNativeInput(scene, camera, packOptions, pack, resolveTexture));
+});
+
+// The maps share one small buffer through distinct views, and `texturePoolMaxBytes` lowers the pool to 6 MiB: each 1024 x 1024
+// map (4 MiB) fits alone and the second one passes the pool. That option is the seam that keeps these tests from allocating a gigabyte.
+const SMALL_POOL_OPTIONS = { ...packOptions, texturePoolMaxBytes: 6 * 1024 * 1024 };
+
+test('maps that each fit the pool but not together are refused by both job builders', () => {
+ const parts = manyMapParts(3, 1024);
+ assertPoolRefusal(() => buildJobNativeInput(buildTraceScene(parts, environment, { instancing: true }), camera, SMALL_POOL_OPTIONS, pack, resolveTexture));
+ assertPoolRefusal(() => buildFlattenedJobNativeInput(buildTraceScene(parts, environment), camera, SMALL_POOL_OPTIONS, pack, resolveTexture));
+ const single = buildFlattenedJobNativeInput(buildTraceScene(manyMapParts(1, 1024), environment), camera, SMALL_POOL_OPTIONS, pack, resolveTexture);
+ assert.equal(single.textureCount, 1);
+});
+
+test('the pool limit can be lowered and never raised', () => {
+ const scene = buildTraceScene(manyMapParts(1, 8), environment);
+ for (const bad of [0, 1.5, TEXTURE_POOL_MAX_BYTES + 1, '4096']) {
+ assert.throws(() => buildFlattenedJobNativeInput(scene, camera, { ...packOptions, texturePoolMaxBytes: bad }, pack, resolveTexture), /texturePoolMaxBytes/);
+ }
+});
+
+test('a map whose data is shorter than its size is refused with both sizes', () => {
+ const short = { image: { width: 8, height: 8, data: new Uint8ClampedArray(100) }, colorSpace: 'srgb' };
+ const shared = quad(1);
+ const parts = [
+ { name: 'a', geometry: shared, matrix: translate(0), material: { color: [1, 1, 1], map: short } },
+ { name: 'b', geometry: shared, matrix: translate(2), material: { color: [1, 1, 1] } },
+ ];
const scene = buildTraceScene(parts, environment, { instancing: true });
- assert.throws(
- () => buildJobNativeInput(scene, camera, packOptions, pack, resolveTexture),
- error => error instanceof RangeError && /texture pool is full/.test(error.message) && /Pass smaller textures/.test(error.message),
- );
+ assert.throws(() => buildJobNativeInput(scene, camera, packOptions, pack, resolveTexture), /8x8 material texture needs 256 bytes[\s\S]*holds 100/);
+});
+
+test('with mip levels the virtual pack equals the pack through the real v1 atlas, byte for byte', () => {
+ const scene = buildTraceScene(texturedParts(), environment, { instancing: true });
+ const options = { ...packOptions, textureMips: true };
+ const tables = packNativeMaterialTables(scene.traceMaterials, null, pack);
+ const reducedMaterials = reduceV1MaterialTable({
+ materials: tables.materials,
+ atlas: tables.atlas,
+ atlasWidth: tables.atlasWidth,
+ subsurfaceVec4Offset: tables.subsurfaceVec4Offset,
+ materialCount: scene.traceMaterials.length,
+ carriedFields: carriedMaterialFieldsOfScene(scene, resolveTexture),
+ textureMips: true,
+ });
+ const instances = scene.instances.map(instance => {
+ const lightMask = reducedMaterials.materialLightMasks[instance.materialIndex] ?? 0xffffffff;
+ return { ...instance, lightMask, lightMaskHi: lightMask === 0xffffffff ? 0xffffffff : 0 };
+ });
+ const { fireflyClamp, ...withoutClamp } = options;
+ const throughAtlas = buildNativeInputV2(scene, camera, { ...withoutClamp, instances, reducedMaterials });
+ const virtual = buildJobNativeInput(scene, camera, options, pack, resolveTexture);
+ assert.deepEqual(hashesOfPackedTables(virtual), hashesOfPackedTables(throughAtlas));
+ const firstDescriptor = new Uint32Array(virtual.textureDescriptors.buffer, virtual.textureDescriptors.byteOffset, 8);
+ assert.ok(((firstDescriptor[3] >>> 8) & 0xff) > 1, 'the scene stores mip levels');
+});
+
+function exportModules(overrides = {}) {
+ return {
+ buildTraceScene,
+ refuseLocalVolumes: () => {},
+ resolveTexture,
+ buildNativeInput: (scene, view, options, tables) => buildNativeInput(scene, view, options, tables),
+ buildJobNativeInput,
+ buildFlattenedJobNativeInput,
+ pack,
+ ...overrides,
+ };
+}
+
+function exportParts(parts, options, modules = exportModules(), instancing = true) {
+ return exportNativeSceneTables({ parts, environment, camera, options, kernel: 'cycles', instancing, modules });
+}
+
+test('the page export of an instanced scene over the pool shows the pool message, not the atlas one', () => {
+ const parts = manyMapParts(3, 1024);
+ assert.throws(() => exportParts(parts, SMALL_POOL_OPTIONS), error => POOL_MESSAGE.test(error.message) && !/GPU atlas/.test(error.message));
+});
+
+test('the page export of a flattened scene over the pool shows the pool message, not the atlas one', () => {
+ const parts = manyMapParts(3, 1024).map((part, index) => ({ ...part, geometry: quad(1 + index / 10) }));
+ assert.throws(() => exportParts(parts, SMALL_POOL_OPTIONS), error => POOL_MESSAGE.test(error.message) && !/GPU atlas/.test(error.message));
+});
+
+test('the page export keeps the first reason when the v1 fallback fails on the atlas too', () => {
+ const parts = manyMapParts(OVER_ATLAS_MAP_COUNT, OVER_ATLAS_MAP_SIZE);
+ const modules = exportModules({ buildFlattenedJobNativeInput: () => { throw new RangeError('the records do not fit'); } });
+ assert.throws(() => exportParts(parts, packOptions, modules, false), /GPU atlas[\s\S]*already failed: the records do not fit/);
});