Skip to content

3D engine that AI agents drive

Instance shared meshes in the gpu path tracer (#2239)

Nguyen Xuan An4421b8ab9621
diff --git a/changes/2239.md b/changes/2239.md
new file mode 100644
index 00000000..341320a3
--- /dev/null
+++ b/changes/2239.md
@@ -0,0 +1 @@
+- The WebGL2 path tracer (`backend: "gpu"`) keeps parts that share one mesh as instances, with one bottom-level BVH per mesh and a top-level BVH over the copies, so the triangle limit counts the mesh once and a scene of nine nodes sharing three 300,000 face meshes renders instead of being refused at 2,000,000 (#2239)
diff --git a/src/path-tracer-gpu-instance-pack.js b/src/path-tracer-gpu-instance-pack.js
new file mode 100644
index 00000000..b6e90c4e
--- /dev/null
+++ b/src/path-tracer-gpu-instance-pack.js
@@ -0,0 +1,129 @@
+import { buildTriangleBvh } from './triangle-bvh.js';
+import { createTable, writeTriangles } from './path-tracer-gpu-pack.js';
+import { TRIANGLE_TEXELS } from './path-tracer-gpu-shader.js';
+import { INSTANCE_TEXELS } from './path-tracer-gpu-instancing.js';
+
+// Lays an instanced trace scene (`scene.instances`, see buildInstancedTraceScene) out as the tables the instanced GPU kernel reads:
+// one triangle table and one bottom-level BVH per distinct mesh, a top-level BVH over the copies, and one record per copy.
+// Plain typed arrays, so it runs and is tested without a GPU.
+
+// The mesh as the flat packer reads it: a mesh without UVs or colours gets the (0, 0) UV and white vertex colour a flattened part gets.
+function meshAsTriangleSource(geometry, bvh) {
+ const vertexCount = geometry.positions.length / 3;
+ return {
+ positions: geometry.positions,
+ normals: geometry.normals,
+ uvs: geometry.uvs ?? new Float32Array(vertexCount * 2),
+ uvs1: geometry.uvs1 ?? geometry.lightUvs ?? null,
+ colors: geometry.colors ?? new Float32Array(vertexCount * 3).fill(1),
+ indices: geometry.indices,
+ triangleMaterial: new Uint32Array(geometry.indices.length / 3),
+ bvh,
+ };
+}
+
+/** Writes the nodes of `bvh` at node `nodeBase`, with child links and triangle slots moved by `nodeBase` and `slotBase`. */
+function writeNodes(data, bvh, nodeBase, slotBase) {
+ for (let node = 0; node < bvh.nodeCount; node++) {
+ const target = (nodeBase + node) * 8;
+ for (let axis = 0; axis < 3; axis++) {
+ data[target + axis] = bvh.nodeBounds[node * 6 + axis];
+ data[target + 4 + axis] = bvh.nodeBounds[node * 6 + 3 + axis];
+ }
+ const right = bvh.rightChild[node];
+ data[target + 3] = right < 0 ? -bvh.rangeCount[node] : nodeBase + right;
+ data[target + 7] = slotBase + bvh.rangeStart[node];
+ }
+}
+
+function cross(first, second) {
+ return [first[1] * second[2] - first[2] * second[1], first[2] * second[0] - first[0] * second[2], first[0] * second[1] - first[1] * second[0]];
+}
+
+/**
+ * The inverse of the upper 3x3 of a column-major matrix, as nine numbers in row order: the rows of the inverse are the cross products
+ * of the other two columns over the determinant. A matrix that squashes space gives zeros (its copy then misses every ray).
+ */
+function invertUpperMatrix(matrix) {
+ const columns = [[matrix[0], matrix[1], matrix[2]], [matrix[4], matrix[5], matrix[6]], [matrix[8], matrix[9], matrix[10]]];
+ const rows = [cross(columns[1], columns[2]), cross(columns[2], columns[0]), cross(columns[0], columns[1])];
+ const determinant = columns[0][0] * rows[0][0] + columns[0][1] * rows[0][1] + columns[0][2] * rows[0][2];
+ if (!(Math.abs(determinant) > 0)) return new Array(9).fill(0);
+ return rows.flat().map(value => value / determinant);
+}
+
+function writeInstance(data, record, matrix, blasRoot, materialIndex) {
+ const base = record * INSTANCE_TEXELS * 4;
+ const inverse = invertUpperMatrix(matrix);
+ for (let row = 0; row < 3; row++) {
+ for (let column = 0; column < 3; column++) data[base + row * 4 + column] = inverse[row * 3 + column];
+ data[base + row * 4 + 3] = -(inverse[row * 3] * matrix[12] + inverse[row * 3 + 1] * matrix[13] + inverse[row * 3 + 2] * matrix[14]);
+ }
+ for (let column = 0; column < 3; column++) {
+ for (let row = 0; row < 3; row++) data[base + (3 + column) * 4 + row] = matrix[column * 4 + row];
+ }
+ data[base + 24] = blasRoot;
+ data[base + 25] = materialIndex;
+}
+
+// The world box of an instance: the corners of its mesh's root box, moved by the matrix.
+function worldBox(rootBounds, matrix) {
+ const low = [Infinity, Infinity, Infinity];
+ const high = [-Infinity, -Infinity, -Infinity];
+ for (let corner = 0; corner < 8; corner++) {
+ const x = corner & 1 ? rootBounds[3] : rootBounds[0];
+ const y = corner & 2 ? rootBounds[4] : rootBounds[1];
+ const z = corner & 4 ? rootBounds[5] : rootBounds[2];
+ for (let axis = 0; axis < 3; axis++) {
+ const value = matrix[axis] * x + matrix[4 + axis] * y + matrix[8 + axis] * z + matrix[12 + axis];
+ low[axis] = Math.min(low[axis], value);
+ high[axis] = Math.max(high[axis], value);
+ }
+ }
+ return { low, high };
+}
+
+/** The top-level BVH: the world box of each instance goes through the triangle builder as a one-triangle mesh, one instance to a leaf where it can. */
+function buildTopLevelBvh(instances, bottomLevel) {
+ const positions = new Float64Array(instances.length * 9);
+ const indices = new Uint32Array(instances.length * 3);
+ instances.forEach((instance, index) => {
+ const { low, high } = worldBox(bottomLevel.get(instance.geometry).bvh.nodeBounds, instance.matrix);
+ positions.set([...low, ...high, ...low], index * 9);
+ indices.set([index * 3, index * 3 + 1, index * 3 + 2], index * 3);
+ });
+ return buildTriangleBvh(positions, indices, { leafSize: 1 });
+}
+
+/**
+ * The tables of an instanced scene. `nodes` holds every bottom-level BVH followed by the top-level one, which starts at node
+ * `topRoot`; a top-level leaf names instance slots, and `instances` holds the instance records in that leaf order. `triangles`
+ * holds each distinct mesh once, in leaf order of its own BVH, with the same ten-texel record as a flattened scene.
+ */
+export function packInstancedScene(scene) {
+ const { instances } = scene;
+ const bottomLevel = new Map();
+ let nodeTotal = 0;
+ let triangleTotal = 0;
+ for (const { geometry } of instances) {
+ if (bottomLevel.has(geometry)) continue;
+ const bvh = buildTriangleBvh(geometry.positions, geometry.indices);
+ bottomLevel.set(geometry, { bvh, nodeBase: nodeTotal, slotBase: triangleTotal });
+ nodeTotal += bvh.nodeCount;
+ triangleTotal += geometry.indices.length / 3;
+ }
+ const top = buildTopLevelBvh(instances, bottomLevel);
+ const nodes = createTable((nodeTotal + top.nodeCount) * 2);
+ const triangles = createTable(triangleTotal * TRIANGLE_TEXELS);
+ for (const [geometry, { bvh, nodeBase, slotBase }] of bottomLevel) {
+ writeNodes(nodes.data, bvh, nodeBase, slotBase);
+ writeTriangles(triangles.data, slotBase, meshAsTriangleSource(geometry, bvh), { secondUvSet: true });
+ }
+ writeNodes(nodes.data, top, nodeTotal, 0);
+ const records = createTable(instances.length * INSTANCE_TEXELS);
+ top.triangleOrder.forEach((instanceIndex, slot) => {
+ const instance = instances[instanceIndex];
+ writeInstance(records.data, slot, instance.matrix, bottomLevel.get(instance.geometry).nodeBase, instance.materialIndex);
+ });
+ return { nodes, triangles, instances: records, topRoot: nodeTotal, triangleCount: triangleTotal };
+}
diff --git a/src/path-tracer-gpu-instancing.js b/src/path-tracer-gpu-instancing.js
new file mode 100644
index 00000000..79e9399f
--- /dev/null
+++ b/src/path-tracer-gpu-instancing.js
@@ -0,0 +1,127 @@
+// The GLSL the GPU path tracer adds for an instanced scene (see path-tracer-gpu-instance-pack.js for the tables it reads). A scene
+// whose copies share one mesh holds that mesh's triangles and bottom-level BVH once; a top-level BVH over the copies holds one
+// record per copy: the world to mesh matrix, the mesh to world matrix, the root of its bottom-level BVH and its material.
+// The ray of a copy is moved into mesh space without being normalised, so a distance there is the same distance in the world.
+
+/** Texels per instance: three rows of the world to mesh matrix, three columns of the mesh to world matrix, then (bottom-level root node, material, 0, 0). */
+export const INSTANCE_TEXELS = 7;
+
+export const INSTANCE_UNIFORMS = `uniform sampler2D uInstances;
+uniform int uTopRoot;
+const int INSTANCE_TEXELS = ${INSTANCE_TEXELS};
+`;
+
+// A flat scene keeps the material in each triangle record and its triangles already sit in world space.
+export const FLAT_HIT_STATE = `int nearestMaterialIndex() {
+ return int(fetchData(uTriangles, nearestSlot * TRIANGLE_TEXELS).w);
+}
+
+vec3 surfaceVectorToWorld(vec3 local) {
+ return local;
+}
+
+vec3 normalToWorld(vec3 local) {
+ return local;
+}`;
+
+export const INSTANCE_HIT_STATE = `int nearestInstance = -1;
+int nearestMaterial = 0;
+
+int nearestMaterialIndex() {
+ return nearestMaterial;
+}
+
+// An edge of the nearest triangle, moved from mesh space to the world by the columns of the instance's matrix.
+vec3 surfaceVectorToWorld(vec3 local) {
+ int base = nearestInstance * INSTANCE_TEXELS;
+ return fetchData(uInstances, base + 3).xyz * local.x + fetchData(uInstances, base + 4).xyz * local.y + fetchData(uInstances, base + 5).xyz * local.z;
+}
+
+// A vertex normal moves by the transpose of the inverse, which is the transpose of the three rows stored for the ray, and is unit length
+// again, as the flattened scene stores it, before the corners are blended (a stretched copy would otherwise weigh its corners unevenly).
+vec3 normalToWorld(vec3 local) {
+ int base = nearestInstance * INSTANCE_TEXELS;
+ vec3 world = fetchData(uInstances, base).xyz * local.x + fetchData(uInstances, base + 1).xyz * local.y + fetchData(uInstances, base + 2).xyz * local.z;
+ float worldLength = length(world);
+ return world / (worldLength == 0.0 ? 1.0 : worldLength);
+}`;
+
+export const INSTANCED_TRACE_RAY = `// Walks the bottom-level BVH of one instance with the ray moved into mesh space; true when an any-hit query found a hit.
+bool traceInstance(int instance, vec3 origin, vec3 direction, bool anyHit) {
+ int base = instance * INSTANCE_TEXELS;
+ vec4 rowX = fetchData(uInstances, base);
+ vec4 rowY = fetchData(uInstances, base + 1);
+ vec4 rowZ = fetchData(uInstances, base + 2);
+ vec4 link = fetchData(uInstances, base + 6);
+ vec3 localOrigin = vec3(dot(rowX.xyz, origin) + rowX.w, dot(rowY.xyz, origin) + rowY.w, dot(rowZ.xyz, origin) + rowZ.w);
+ vec3 localDirection = vec3(dot(rowX.xyz, direction), dot(rowY.xyz, direction), dot(rowZ.xyz, direction));
+ vec3 inverse = safeInverse(localDirection);
+ float distanceBefore = nearestDistance;
+ int nodeStack[STACK_SIZE];
+ float entryStack[STACK_SIZE];
+ int stackSize = 1;
+ nodeStack[0] = int(link.x);
+ entryStack[0] = 0.0;
+ bool found = false;
+ while (stackSize > 0 && !found) {
+ stackSize--;
+ int node = nodeStack[stackSize];
+ if (!(entryStack[stackSize] < nearestDistance)) continue;
+ vec4 header = fetchData(uNodes, node * 2);
+ if (header.w < 0.0) {
+ found = visitLeaf(node, localOrigin, localDirection, anyHit);
+ continue;
+ }
+ int left = node + 1;
+ int right = int(header.w);
+ float leftEntry = boxEntry(left, localOrigin, inverse);
+ float rightEntry = boxEntry(right, localOrigin, inverse);
+ bool nearFirst = leftEntry <= rightEntry;
+ nodeStack[stackSize] = nearFirst ? right : left;
+ entryStack[stackSize] = nearFirst ? rightEntry : leftEntry;
+ nodeStack[stackSize + 1] = nearFirst ? left : right;
+ entryStack[stackSize + 1] = nearFirst ? leftEntry : rightEntry;
+ stackSize += 2;
+ }
+ if (nearestDistance < distanceBefore) {
+ nearestInstance = instance;
+ nearestMaterial = int(link.y);
+ }
+ return found;
+}
+
+void traceRay(vec3 origin, vec3 direction, float limit, bool anyHit) {
+ nearestDistance = limit;
+ nearestSlot = -1;
+ nearestInstance = -1;
+ vec3 inverse = safeInverse(direction);
+ int nodeStack[STACK_SIZE];
+ float entryStack[STACK_SIZE];
+ int stackSize = 1;
+ nodeStack[0] = uTopRoot;
+ entryStack[0] = 0.0;
+ while (stackSize > 0) {
+ stackSize--;
+ int node = nodeStack[stackSize];
+ if (!(entryStack[stackSize] < nearestDistance)) continue;
+ vec4 header = fetchData(uNodes, node * 2);
+ if (header.w < 0.0) {
+ int first = int(fetchData(uNodes, node * 2 + 1).w);
+ int last = first + int(-header.w);
+ for (int instance = first; instance < last; instance++) {
+ if (traceInstance(instance, origin, direction, anyHit)) return;
+ }
+ continue;
+ }
+ int left = node + 1;
+ int right = int(header.w);
+ float leftEntry = boxEntry(left, origin, inverse);
+ float rightEntry = boxEntry(right, origin, inverse);
+ bool nearFirst = leftEntry <= rightEntry;
+ nodeStack[stackSize] = nearFirst ? right : left;
+ entryStack[stackSize] = nearFirst ? rightEntry : leftEntry;
+ nodeStack[stackSize + 1] = nearFirst ? left : right;
+ entryStack[stackSize + 1] = nearFirst ? leftEntry : rightEntry;
+ stackSize += 2;
+ }
+}`;
diff --git a/src/path-tracer-gpu-pack.js b/src/path-tracer-gpu-pack.js
index f23beed2..900887cc 100644
--- a/src/path-tracer-gpu-pack.js
+++ b/src/path-tracer-gpu-pack.js
@@ -34,7 +34,7 @@ export function gpuTriangleCapacity({ maximumTextureSize, maximumBufferBytes, ma
}
/** A table of `texelCount` RGBA texels, padded to whole rows. */
-function createTable(texelCount, channels = 4) {
+export function createTable(texelCount, channels = 4) {
const rows = Math.max(1, Math.ceil(texelCount / DATA_TEXTURE_WIDTH));
if (rows > MAXIMUM_TEXTURE_SIZE) throw new RangeError('The scene is too large for the GPU path tracer tables.');
return { width: DATA_TEXTURE_WIDTH, height: rows, channels, data: new Float32Array(DATA_TEXTURE_WIDTH * rows * channels) };
@@ -92,15 +92,21 @@ export const NATIVE_TRIANGLE_TEXELS = 9;
* leaves those floats at 0 and no material asks for them.
*/
export function packTriangles(scene, { secondUvSet = false } = {}) {
+ const texelsPerTriangle = secondUvSet ? TRIANGLE_TEXELS : NATIVE_TRIANGLE_TEXELS;
+ const table = createTable(scene.bvh.triangleOrder.length * texelsPerTriangle);
+ writeTriangles(table.data, 0, scene, { secondUvSet });
+ return table;
+}
+
+/** Writes the triangles of `scene` in leaf order into `data`, starting at triangle slot `firstSlot`. */
+export function writeTriangles(data, firstSlot, scene, { secondUvSet = false } = {}) {
const { positions, normals, uvs, uvs1, colors, indices, triangleMaterial, bvh } = scene;
const order = bvh.triangleOrder;
const nativeSecondSetMaterials = !secondUvSet && uvs1 ? scene.materials?.map(materialUvSet) : null;
const texelsPerTriangle = secondUvSet ? TRIANGLE_TEXELS : NATIVE_TRIANGLE_TEXELS;
- const table = createTable(order.length * texelsPerTriangle);
- const { data } = table;
for (let slot = 0; slot < order.length; slot++) {
const triangle = order[slot];
- const base = slot * texelsPerTriangle * 4;
+ const base = (firstSlot + slot) * texelsPerTriangle * 4;
const corners = [indices[triangle * 3], indices[triangle * 3 + 1], indices[triangle * 3 + 2]];
const uvSource = nativeSecondSetMaterials?.[triangleMaterial[triangle]] === 1 ? uvs1 : uvs;
for (let axis = 0; axis < 3; axis++) {
@@ -121,7 +127,6 @@ export function packTriangles(scene, { secondUvSet = false } = {}) {
}
if (secondUvSet && uvs1) packSecondUvSet(data, base, uvs1, corners);
}
- return table;
}
function packSecondUvSet(data, base, uvs1, corners) {
diff --git a/src/path-tracer-gpu-shader.js b/src/path-tracer-gpu-shader.js
index 4a0f3c8c..6bd0afcd 100644
--- a/src/path-tracer-gpu-shader.js
+++ b/src/path-tracer-gpu-shader.js
@@ -1,5 +1,6 @@
import { CACHE_DECLARATIONS, CACHE_OUTPUT, CACHE_RECORD, CACHE_TERMINAL } from './path-tracer-radiance-cache.js';
import { LIGHT_TREE_FIRST_HIT_LIGHTS, LIGHT_TREE_MINIMUM_SHARE, LIGHT_TREE_NODE_TEXELS } from './path-tracer-light-tree.js';
+import { FLAT_HIT_STATE, INSTANCED_TRACE_RAY, INSTANCE_HIT_STATE, INSTANCE_UNIFORMS } from './path-tracer-gpu-instancing.js';
import { SUBSURFACE_FUNCTIONS, SUBSURFACE_LOBE, SUBSURFACE_SPLIT, SUBSURFACE_UNIFORM } from './path-tracer-gpu-subsurface.js';
// The GPU path tracer kernel: a WebGL2 fragment shader that follows the same paths as the CPU tracer in
@@ -147,7 +148,39 @@ int chooseEmitterByTree(vec3 normal, out float probability) {
}
`;
-const buildSource = (hasSubsurface, texelBake, blueNoise, lightImportance, radianceCache, lightTree) => `#version 300 es
+// The ray query of a scene with one triangle table and one BVH: the default, and the only one before instancing.
+const FLAT_TRACE_RAY = `void traceRay(vec3 origin, vec3 direction, float limit, bool anyHit) {
+ nearestDistance = limit;
+ nearestSlot = -1;
+ vec3 inverse = safeInverse(direction);
+ int nodeStack[STACK_SIZE];
+ float entryStack[STACK_SIZE];
+ int stackSize = 1;
+ nodeStack[0] = 0;
+ entryStack[0] = 0.0;
+ while (stackSize > 0) {
+ stackSize--;
+ int node = nodeStack[stackSize];
+ if (!(entryStack[stackSize] < nearestDistance)) continue;
+ vec4 header = fetchData(uNodes, node * 2);
+ if (header.w < 0.0) {
+ if (visitLeaf(node, origin, direction, anyHit)) return;
+ continue;
+ }
+ int left = node + 1;
+ int right = int(header.w);
+ float leftEntry = boxEntry(left, origin, inverse);
+ float rightEntry = boxEntry(right, origin, inverse);
+ bool nearFirst = leftEntry <= rightEntry;
+ nodeStack[stackSize] = nearFirst ? right : left;
+ entryStack[stackSize] = nearFirst ? rightEntry : leftEntry;
+ nodeStack[stackSize + 1] = nearFirst ? left : right;
+ entryStack[stackSize + 1] = nearFirst ? leftEntry : rightEntry;
+ stackSize += 2;
+ }
+}`;
+
+const buildSource = (hasSubsurface, texelBake, blueNoise, lightImportance, radianceCache, lightTree, instanced) => `#version 300 es
precision highp float;
precision highp int;
precision highp sampler2D;
@@ -174,7 +207,7 @@ const float MIRROR_ALPHA = 2e-3;
const float DIELECTRIC_COAT_REFLECTANCE = 0.04;
uniform sampler2D uNodes;
-uniform sampler2D uTriangles;
+${instanced ? INSTANCE_UNIFORMS : ''}uniform sampler2D uTriangles;
uniform sampler2D uMaterials;
uniform sampler2D uLights;
${lightTree ? 'uniform sampler2D uLightTree;' : ''}
@@ -276,6 +309,7 @@ float nearestDistance;
int nearestSlot;
float nearestU;
float nearestV;
+${instanced ? INSTANCE_HIT_STATE : FLAT_HIT_STATE}
float safeInverseComponent(float component) {
if (abs(component) > 1e-20) return 1.0 / component;
@@ -328,36 +362,7 @@ bool visitLeaf(int node, vec3 origin, vec3 direction, bool anyHit) {
return false;
}
-void traceRay(vec3 origin, vec3 direction, float limit, bool anyHit) {
- nearestDistance = limit;
- nearestSlot = -1;
- vec3 inverse = safeInverse(direction);
- int nodeStack[STACK_SIZE];
- float entryStack[STACK_SIZE];
- int stackSize = 1;
- nodeStack[0] = 0;
- entryStack[0] = 0.0;
- while (stackSize > 0) {
- stackSize--;
- int node = nodeStack[stackSize];
- if (!(entryStack[stackSize] < nearestDistance)) continue;
- vec4 header = fetchData(uNodes, node * 2);
- if (header.w < 0.0) {
- if (visitLeaf(node, origin, direction, anyHit)) return;
- continue;
- }
- int left = node + 1;
- int right = int(header.w);
- float leftEntry = boxEntry(left, origin, inverse);
- float rightEntry = boxEntry(right, origin, inverse);
- bool nearFirst = leftEntry <= rightEntry;
- nodeStack[stackSize] = nearFirst ? right : left;
- entryStack[stackSize] = nearFirst ? rightEntry : leftEntry;
- nodeStack[stackSize + 1] = nearFirst ? left : right;
- entryStack[stackSize + 1] = nearFirst ? leftEntry : rightEntry;
- stackSize += 2;
- }
-}
+${instanced ? INSTANCED_TRACE_RAY : FLAT_TRACE_RAY}
// ---- Hits ----
@@ -449,9 +454,8 @@ bool mapReadsSecondUvSet(float mask, int bit) {
/** Fills the hit globals from the triangle in \`nearestSlot\`; returns the alpha of the colour map. */
float fillHit(vec3 origin, vec3 direction, float distance) {
int base = nearestSlot * TRIANGLE_TEXELS;
- vec4 cornerData = fetchData(uTriangles, base);
- vec3 edgeOne = fetchData(uTriangles, base + 1).xyz;
- vec3 edgeTwo = fetchData(uTriangles, base + 2).xyz;
+ vec3 edgeOne = surfaceVectorToWorld(fetchData(uTriangles, base + 1).xyz);
+ vec3 edgeTwo = surfaceVectorToWorld(fetchData(uTriangles, base + 2).xyz);
vec4 normalOneData = fetchData(uTriangles, base + 3);
vec4 normalTwoData = fetchData(uTriangles, base + 4);
vec4 normalThreeData = fetchData(uTriangles, base + 5);
@@ -465,13 +469,13 @@ float fillHit(vec3 origin, vec3 direction, float distance) {
float firstWeight = 1.0 - secondWeight - thirdWeight;
hitDistance = distance;
hitPoint = origin + direction * distance;
- vec3 normal = firstWeight * normalOneData.xyz + secondWeight * normalTwoData.xyz + thirdWeight * normalThreeData.xyz;
+ vec3 normal = firstWeight * normalToWorld(normalOneData.xyz) + secondWeight * normalToWorld(normalTwoData.xyz) + thirdWeight * normalToWorld(normalThreeData.xyz);
float normalLength = length(normal);
hitNormal = normal / (normalLength == 0.0 ? 1.0 : normalLength);
vec3 vertexColor = firstWeight * colorOneData.xyz + secondWeight * colorTwoData.xyz + thirdWeight * colorThreeData.xyz;
vec2 uv = firstWeight * vec2(normalOneData.w, colorOneData.w) + secondWeight * vec2(normalTwoData.w, colorTwoData.w) + thirdWeight * vec2(normalThreeData.w, colorThreeData.w);
vec2 secondUv = firstWeight * secondSetCorners.xy + secondWeight * secondSetCorners.zw + thirdWeight * secondSetThird;
- hitMaterialIndex = int(cornerData.w);
+ hitMaterialIndex = nearestMaterialIndex();
int material = hitMaterialIndex * MATERIAL_TEXELS;
vec4 colorMetallic = fetchData(uMaterials, material);
vec4 emissionRoughness = fetchData(uMaterials, material + 1);
@@ -516,8 +520,8 @@ float fillHit(vec3 origin, vec3 direction, float distance) {
/** True when the nearest hit belongs to a shadow-only part (the flag sits in texel 5 of the material); camera rays step through it. */
bool nearestHitIsShadowOnly() {
- vec4 cornerData = fetchData(uTriangles, nearestSlot * TRIANGLE_TEXELS);
- vec4 flags = fetchData(uMaterials, int(cornerData.w) * MATERIAL_TEXELS + 5);
+ int materialIndex = nearestMaterialIndex();
+ vec4 flags = fetchData(uMaterials, materialIndex * MATERIAL_TEXELS + 5);
return flags.y > 0.0;
}
@@ -553,7 +557,7 @@ float alphaAtNearestHit() {
vec4 second = fetchData(uTriangles, base + 4);
vec4 third = fetchData(uTriangles, base + 5);
vec2 uv = firstWeight * vec2(first.w, fetchData(uTriangles, base + 6).w) + secondWeight * vec2(second.w, fetchData(uTriangles, base + 7).w) + thirdWeight * vec2(third.w, fetchData(uTriangles, base + 8).w);
- int material = int(fetchData(uTriangles, base).w) * MATERIAL_TEXELS;
+ int material = nearestMaterialIndex() * MATERIAL_TEXELS;
vec4 mapRectangle = fetchData(uMaterials, material + 6);
if (mapRectangle.z <= 0.0) return 1.0;
if (mapReadsSecondUvSet(fetchData(uMaterials, material + 5).z, 1)) {
@@ -572,7 +576,7 @@ bool occluded(vec3 origin, vec3 direction, float limit) {
for (int attempt = 0; attempt < ALPHA_STEP_LIMIT; attempt++) {
traceRay(start, direction, remaining, anyHit);
if (nearestSlot < 0) return false;
- int material = int(fetchData(uTriangles, nearestSlot * TRIANGLE_TEXELS).w) * MATERIAL_TEXELS;
+ int material = nearestMaterialIndex() * MATERIAL_TEXELS;
float cutoff = fetchData(uMaterials, material + 3).z;
if (cutoff == 0.0) return true;
if (alphaAtNearestHit() >= cutoff) return true;
@@ -1318,8 +1322,8 @@ ${radianceCache ? CACHE_OUTPUT : ''}
* The kernel; `hasSubsurface` compiles in the random walk, which only scenes with a subsurface part need. `texelBake`
* starts every path at a lightmap texel instead of the camera (see light-bake-gpu.js).
*/
-export function buildFragmentSource({ hasSubsurface = false, texelBake = false, blueNoise = false, lightImportance = false, radianceCache = false, lightTree = false } = {}) {
- return buildSource(hasSubsurface, texelBake, blueNoise, lightImportance, radianceCache, lightTree);
+export function buildFragmentSource({ hasSubsurface = false, texelBake = false, blueNoise = false, lightImportance = false, radianceCache = false, lightTree = false, instanced = false } = {}) {
+ return buildSource(hasSubsurface, texelBake, blueNoise, lightImportance, radianceCache, lightTree, instanced);
}
export const FRAGMENT_SOURCE = buildFragmentSource();
diff --git a/src/path-tracer-gpu.js b/src/path-tracer-gpu.js
index cebfe8ff..eb88a171 100644
--- a/src/path-tracer-gpu.js
+++ b/src/path-tracer-gpu.js
@@ -1,7 +1,8 @@
import { resolveLightSelection } from './path-tracer-light-tree.js';
import { buildFragmentSource, VERTEX_SOURCE } from './path-tracer-gpu-shader.js';
import { gpuTriangleCapacity, packAtlas, packEnvironment, packLightTree, packLights, packMaterials, packNodes, packSubsurface, packTriangles, sceneUsesSubsurface } from './path-tracer-gpu-pack.js';
-import { MAX_GPU_TRACE_TRIANGLES, MAX_TRACE_TRIANGLES } from './path-tracer-scene.js';
+import { packInstancedScene } from './path-tracer-gpu-instance-pack.js';
+import { isInstancedScene, MAX_GPU_TRACE_TRIANGLES, MAX_TRACE_TRIANGLES, uniqueTriangleCount } from './path-tracer-scene.js';
// The GPU backend of the path tracer: one WebGL2 fragment pass per sample draws every pixel of a band, and four float
// targets add the samples up. It needs a page with WebGL2 (a canvas), EXT_color_buffer_float and EXT_float_blend. The
@@ -79,7 +80,7 @@ export async function withBlueNoiseTile(options) {
* instead of tracing a black image.
*/
function refuseUnallocatedTables(gl, scene) {
- const triangleCount = scene.indices.length / 3;
+ const triangleCount = uniqueTriangleCount(scene);
if (triangleCount <= MAX_TRACE_TRIANGLES) return;
const glError = gl.getError();
if (glError === gl.NO_ERROR) return;
@@ -91,10 +92,12 @@ export function uploadScene(gl, program, scene, options = {}) {
const atlas = packAtlas(scene.materials);
const lights = packLights(scene.lights);
const environment = packEnvironment(scene.environment);
- const nodes = packNodes(scene.bvh);
- const triangles = packTriangles(scene, { secondUvSet: true });
+ const instanced = isInstancedScene(scene) ? packInstancedScene(scene) : null;
+ const nodes = instanced?.nodes ?? packNodes(scene.bvh);
+ const triangles = instanced?.triangles ?? packTriangles(scene, { secondUvSet: true });
const materials = packMaterials(scene.materials, atlas, scene.shadowOnlyParts);
const floatTables = [['uNodes', nodes], ['uTriangles', triangles], ['uMaterials', materials], ['uLights', lights.table]];
+ if (instanced) floatTables.push(['uInstances', instanced.instances]);
if (sceneUsesSubsurface(scene.materials)) floatTables.push(['uSubsurface', packSubsurface(scene.materials)]);
if (options.lightSelection === 'tree') floatTables.push(['uLightTree', packLightTree(scene.lights)]);
let unit = 0;
@@ -104,6 +107,7 @@ export function uploadScene(gl, program, scene, options = {}) {
bind(name);
}
refuseUnallocatedTables(gl, scene);
+ if (instanced) gl.uniform1i(gl.getUniformLocation(program, 'uTopRoot'), instanced.topRoot);
createTexture(gl, unit, gl.RGBA8, gl.RGBA, gl.UNSIGNED_BYTE, atlas.width, atlas.height, atlas.data);
bind('uAtlas');
const colors = environment?.colors ?? new Float32Array(4);
@@ -237,10 +241,11 @@ export function getKernel(hasSubsurface, texelBake = false, options = {}) {
const lightImportance = options.lightSelection === 'importance';
const lightTree = options.lightSelection === 'tree';
const radianceCache = options.radianceCache === true;
- const key = `${hasSubsurface}:${texelBake}:${blueNoise}:${lightImportance}:${radianceCache}:${lightTree}`;
+ const instanced = options.instanced === true;
+ const key = `${hasSubsurface}:${texelBake}:${blueNoise}:${lightImportance}:${radianceCache}:${lightTree}${instanced ? ':instanced' : ''}`;
if (!programs.has(key)) {
const started = performance.now();
- const program = createProgram(gl, { hasSubsurface, texelBake, blueNoise, lightImportance, radianceCache, lightTree });
+ const program = createProgram(gl, { hasSubsurface, texelBake, blueNoise, lightImportance, radianceCache, lightTree, instanced });
gl.getProgramParameter(program, gl.LINK_STATUS);
programs.set(key, { program, compileSeconds: (performance.now() - started) / 1000 });
if (!texelBake) kernelCompileCount++;
@@ -298,7 +303,7 @@ export async function traceOnGpu(scene, camera, rawOptions, shouldStop) {
const tiledOptions = await withBlueNoiseTile(rawOptions);
const options = { ...tiledOptions, lightSelection: resolveLightSelection(tiledOptions.lightSelection, scene.lights) };
const { gl, gpu } = getContext();
- const { program, compileSeconds } = getKernel(sceneUsesSubsurface(scene.materials), false, options);
+ const { program, compileSeconds } = getKernel(sceneUsesSubsurface(scene.materials), false, { ...options, instanced: isInstancedScene(scene) });
const { width, height, samples } = options;
gl.useProgram(program);
const { lightCount } = uploadScene(gl, program, scene, options);
@@ -320,7 +325,7 @@ const TEXEL_ROW_WIDTH = 2048;
*/
export async function traceTexelsOnGpu(scene, texels, options, shouldStop) {
const { gl, gpu } = getContext();
- const { program, compileSeconds } = getKernel(sceneUsesSubsurface(scene.materials), true);
+ const { program, compileSeconds } = getKernel(sceneUsesSubsurface(scene.materials), true, { instanced: isInstancedScene(scene) });
const { count, points, normals } = texels;
const { samples, seed } = options;
const width = Math.min(count, TEXEL_ROW_WIDTH);
@@ -354,6 +359,9 @@ export async function traceTexelsOnGpu(scene, texels, options, shouldStop) {
}
/** The triangles this page's WebGL2 context can hold in its data textures (MAX_TEXTURE_SIZE rows of the triangle table), up to MAX_GPU_TRACE_TRIANGLES. */
+// The WebGL2 tracer reads instanced scenes (path-tracer-gpu-instance-pack.js); buildTraceSceneForDevice keeps copies of one mesh as instances for it.
+export const supportsInstancing = true;
+
export function gpuTriangleLimit() {
const { gl } = getContext();
return gpuTriangleCapacity({ maximumTextureSize: gl.getParameter(gl.MAX_TEXTURE_SIZE) }, MAX_GPU_TRACE_TRIANGLES);
diff --git a/src/path-tracer-scene.js b/src/path-tracer-scene.js
index dad3d1c1..90fff6e9 100644
--- a/src/path-tracer-scene.js
+++ b/src/path-tracer-scene.js
@@ -855,6 +855,8 @@ function buildInstancedTraceScene(parts, geometries, environment, localVolumes,
instances,
materials,
traceMaterials,
+ // The GPU tracers read this per part flag from the material table; the native kernel reads the instance visibility instead.
+ ...(parts.some(part => part.shadowOnly === true) ? { shadowOnlyParts: Uint8Array.from(parts, part => (part.shadowOnly === true ? 1 : 0)) } : {}),
lights: resolveLights(environment, limits.lights, parts),
environment: resolveEnvironment(environment.map, environment.cameraIntensity),
volume: resolveTraceVolume(environment.volumeFog),
@@ -864,6 +866,19 @@ function buildInstancedTraceScene(parts, geometries, environment, localVolumes,
};
}
+/** True for a trace scene that keeps copies of one mesh as instances instead of flattened triangles. */
+export function isInstancedScene(scene) {
+ return Array.isArray(scene.instances);
+}
+
+/** The triangles a scene holds once per distinct mesh: what the GPU tables carry, and what the triangle limit counts. */
+export function uniqueTriangleCount(scene) {
+ if (!isInstancedScene(scene)) return scene.indices.length / 3;
+ let total = 0;
+ for (const geometry of new Set(scene.instances.map(instance => instance.geometry))) total += geometry.indices.length / 3;
+ return total;
+}
+
/**
* `buildTraceScene` with the triangle bound of the device behind `gpuModule` (a tracer backend module that exports
* `gpuTriangleLimit`). Every GPU caller builds its scene through here, so the bound and the error text are the same for a
@@ -877,7 +892,9 @@ export async function buildTraceSceneForDevice(allParts, environment, gpuModule)
} catch {
deviceLimit = undefined;
}
- return buildTraceScene(allParts, environment, deviceLimit === undefined ? {} : { gpuTriangleLimit: deviceLimit });
+ const options = deviceLimit === undefined ? {} : { gpuTriangleLimit: deviceLimit };
+ if (gpuModule.supportsInstancing === true) options.instancing = true;
+ return buildTraceScene(allParts, environment, options);
}
/**
diff --git a/src/path-tracer.js b/src/path-tracer.js
index 27757705..f702123c 100644
--- a/src/path-tracer.js
+++ b/src/path-tracer.js
@@ -3,7 +3,7 @@ import { cameraFieldOfView, resolveThinLens } from './camera.js';
import { fresnelSchlick } from './material-layers.js';
import { pointLightFalloff } from './ray-query.js';
import { profileGain } from './light-profile.js';
-import { buildTraceScene, buildTraceSceneForDevice, refuseLocalVolumes, SUN_ANGULAR_RADIUS } from './path-tracer-scene.js';
+import { buildTraceScene, buildTraceSceneForDevice, refuseLocalVolumes, SUN_ANGULAR_RADIUS, uniqueTriangleCount } from './path-tracer-scene.js';
import { denoiseRadiance, estimateRelativeNoise } from './path-tracer-denoise.js';
import { acesChannel, displayColor } from './view-transform.js';
import { VIEW_TRANSFORM_NAMES } from './view-transform-names.js';
@@ -1286,7 +1286,7 @@ export async function renderPathTracedImage({ parts, environment = {}, camera },
denoiser: options.denoiser, threads,
backend: options.backend, ...(gpuName ? { gpu: gpuName, gpuCompileSeconds, gpuKernelCompiles } : {}),
averageSamples, noiseThreshold: options.noiseThreshold, ...(estimatedNoise === null ? {} : { estimatedNoise }),
- triangles: scene.indices.length / 3, tracedSeconds, seconds: (performance.now() - started) / 1000,
+ triangles: uniqueTriangleCount(scene), tracedSeconds, seconds: (performance.now() - started) / 1000,
ignored: describeIgnoredFeatures(parts, environment, options.backend, { clipStart: view.clipStart }),
},
};
diff --git a/tests/gpu-triangle-bound-webgl-bake.test.js b/tests/gpu-triangle-bound-webgl-bake.test.js
index aa6a4ff4..765141f3 100644
--- a/tests/gpu-triangle-bound-webgl-bake.test.js
+++ b/tests/gpu-triangle-bound-webgl-bake.test.js
@@ -34,12 +34,11 @@ globalThis.OffscreenCanvas = class {
const { bakeLightmapsAsync } = await import('../src/light-bake-gpu.js');
-const cube = box(0, 1);
-
+// Each cube has a geometry of its own: copies that share one are held once by the WebGL2 tracer (#2239), so they would not reach the bound.
function cubeParts(count) {
return Array.from({ length: count }, (_, index) => ({
name: `cube-${index}`,
- geometry: cube,
+ geometry: box(0, 1),
matrix: new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, index * 2, 0, 0, 1]),
material: { tag: 'surface', color: [0.7, 0.7, 0.7], metallic: 0, roughness: 0.8, emission: 0 },
}));
diff --git a/tests/path-tracer-gpu-instancing.test.js b/tests/path-tracer-gpu-instancing.test.js
new file mode 100644
index 00000000..a76063af
--- /dev/null
+++ b/tests/path-tracer-gpu-instancing.test.js
@@ -0,0 +1,167 @@
+import assert from 'node:assert/strict';
+import { createHash } from 'node:crypto';
+import test from 'node:test';
+
+import { box, icoSphere } from '../src/geometry.js';
+import { packInstancedScene } from '../src/path-tracer-gpu-instance-pack.js';
+import { packMaterials, packAtlas, packNodes, packTriangles } from '../src/path-tracer-gpu-pack.js';
+import { buildFragmentSource } from '../src/path-tracer-gpu-shader.js';
+import { buildTraceScene, buildTraceSceneForDevice, isInstancedScene, uniqueTriangleCount } from '../src/path-tracer-scene.js';
+import { withDevServerPage } from './helpers/dev-server-browser.js';
+
+// Issue #2239: the WebGL2 path tracer keeps copies of one mesh as instances (one triangle table and bottom-level BVH per mesh, a
+// top-level BVH over the copies) instead of flattening every copy into the triangle table.
+
+const SPHERE = icoSphere(2);
+const SPHERE_TRIANGLES = SPHERE.indices.length / 3;
+const INSTANCING_MODULE = { supportsInstancing: true, gpuTriangleLimit: () => 4 * SPHERE_TRIANGLES };
+const FLATTENING_MODULE = { gpuTriangleLimit: () => 4 * SPHERE_TRIANGLES };
+
+function translation(x, y = 0, z = 0) {
+ return [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, z, 1];
+}
+
+function copies(count) {
+ return Array.from({ length: count }, (_, index) => ({
+ name: `copy-${index}`,
+ geometry: SPHERE,
+ matrix: translation(index * 3, 0.5, -index),
+ material: { color: [0.2 + index * 0.1, 0.5, 0.7], roughness: 0.4 },
+ }));
+}
+
+function digest(...tables) {
+ const hash = createHash('sha256');
+ for (const table of tables) hash.update(Buffer.from(table.data.buffer));
+ return hash.digest('hex');
+}
+
+test('a scene that shares a mesh packs the mesh once, with one record per copy', () => {
+ const scene = buildTraceScene(copies(2), {}, { instancing: true, gpuTriangleLimit: 4 * SPHERE_TRIANGLES });
+ assert.equal(isInstancedScene(scene), true);
+ const packed = packInstancedScene(scene);
+ const flat = packTriangles(buildTraceScene(copies(2), {}), { secondUvSet: true });
+ assert.equal(packed.triangleCount, SPHERE_TRIANGLES);
+ assert.equal(uniqueTriangleCount(scene), SPHERE_TRIANGLES);
+ assert.ok(packed.triangles.height < flat.height, 'the instanced triangle table holds one copy of the mesh, the flattened one two');
+
+ const recordFloats = 7 * 4;
+ const rows = [0, 1].map(slot => packed.instances.data.subarray(slot * recordFloats, (slot + 1) * recordFloats));
+ assert.equal(rows[0][24], rows[1][24], 'both copies start at the same bottom-level root');
+ assert.deepEqual(rows.map(row => row[25]).sort(), [0, 1], 'each copy keeps its own material');
+ const translations = rows.map(row => -row[3]).sort((first, second) => first - second);
+ assert.deepEqual(translations, [0, 3], 'the world to mesh matrix undoes the placement');
+ assert.ok(packed.topRoot > 0, 'the top-level BVH follows the bottom-level one');
+});
+
+test('the triangle limit of a GPU scene counts a shared mesh once', async () => {
+ const nineCopies = copies(9);
+ const flattened = buildTraceSceneForDevice(nineCopies, {}, FLATTENING_MODULE);
+ await assert.rejects(flattened, { name: 'RangeError', message: /GPU path trace takes at most/ });
+ const scene = await buildTraceSceneForDevice(nineCopies, {}, INSTANCING_MODULE);
+ assert.equal(isInstancedScene(scene), true);
+ assert.equal(scene.instances.length, 9);
+ assert.equal(uniqueTriangleCount(scene), SPHERE_TRIANGLES);
+});
+
+test('a mesh that is not shared still holds its own triangles against the limit', async () => {
+ const different = [{ ...copies(1)[0] }, { ...copies(2)[1], geometry: box(0.1, 4) }];
+ const tightModule = { supportsInstancing: true, gpuTriangleLimit: () => SPHERE_TRIANGLES };
+ await assert.rejects(buildTraceSceneForDevice(different, {}, tightModule), { name: 'RangeError', message: /GPU path trace takes at most/ });
+});
+
+// The digest of the node, triangle and material tables of the scene below, taken on origin/main before instancing existed.
+const UNSHARED_SCENE_DIGEST = '11c7ed55b398eb8a1d2ba836d3fd1b277035aa61912bf8bae6318d0c68c0eed5';
+
+test('a scene without shared geometry flattens and packs the same bytes with or without the instancing module', async () => {
+ const parts = [
+ { name: 'a', geometry: SPHERE, matrix: translation(0, 0.5), material: { color: [0.2, 0.5, 0.7], roughness: 0.4 } },
+ { name: 'b', geometry: box(0.1, 4), matrix: translation(3, 0.5), material: { color: [0.3, 0.5, 0.7], roughness: 0.4 } },
+ ];
+ const options = { gpuTriangleLimit: 1_000_000 };
+ const plain = buildTraceScene(parts, {}, options);
+ const opted = await buildTraceSceneForDevice(parts, {}, { supportsInstancing: true, gpuTriangleLimit: () => 1_000_000 });
+ assert.equal(isInstancedScene(opted), false);
+ const packOf = scene => {
+ const atlas = packAtlas(scene.materials);
+ return [packNodes(scene.bvh), packTriangles(scene, { secondUvSet: true }), packMaterials(scene.materials, atlas, scene.shadowOnlyParts)];
+ };
+ assert.equal(digest(...packOf(opted)), digest(...packOf(plain)));
+ assert.equal(digest(...packOf(plain)), UNSHARED_SCENE_DIGEST, 'the tables are the bytes origin/main packed');
+ assert.deepEqual(Array.from(opted.positions), Array.from(plain.positions));
+ assert.deepEqual(Array.from(opted.triangleMaterial), Array.from(plain.triangleMaterial));
+});
+
+test('the flattened kernel does not read the instance tables, and the instanced one does', () => {
+ assert.doesNotMatch(buildFragmentSource({}), /uInstances|uTopRoot/);
+ assert.match(buildFragmentSource({ instanced: true }), /uniform sampler2D uInstances;/);
+ assert.match(buildFragmentSource({ instanced: true, texelBake: true }), /traceInstance/);
+});
+
+test('the instanced kernel keeps every texture fetch free of another fetch in its index', () => {
+ const source = buildFragmentSource({ instanced: true, hasSubsurface: true });
+ const fetchCall = /fetch(?:Data|Scalar)\(/g;
+ let match;
+ while ((match = fetchCall.exec(source)) !== null) {
+ let depth = 1;
+ let cursor = match.index + match[0].length;
+ const argumentStart = cursor;
+ while (depth > 0 && cursor < source.length) {
+ if (source[cursor] === '(') depth++;
+ if (source[cursor] === ')') depth--;
+ cursor++;
+ }
+ assert.doesNotMatch(source.slice(argumentStart, cursor - 1), /fetch(?:Data|Scalar)\(/);
+ }
+});
+
+// Runs in the page: the same scene traced from flattened triangles and from instances, on the WebGL2 tracer.
+async function traceBothWays() {
+ const { icoSphere: sphere, box: cube } = await import('/src/geometry.js');
+ const { buildTraceScene: build, uniqueTriangleCount: count } = await import('/src/path-tracer-scene.js');
+ const { createCamera, normalizePathTracerOptions } = await import('/src/path-tracer.js');
+ const gpuModule = await import('/src/path-tracer-gpu.js');
+ const shared = sphere(2);
+ const place = (x, y, z, scale, extra = {}) => [scale, 0, 0, 0, 0, scale, 0, 0, 0, 0, scale, 0, x, y, z, 1].map((value, index) => extra[index] ?? value);
+ const rotated = [0.8, 0.6, 0, 0, -0.6, 0.8, 0, 0, 0, 0, 1, 0, 0.4, 1.2, -0.2, 1];
+ const parts = [
+ { name: 'floor', geometry: cube(0, 1), matrix: [8, 0, 0, 0, 0, 0.2, 0, 0, 0, 0, 8, 0, 0, -0.1, 0, 1], material: { color: [0.6, 0.6, 0.6] } },
+ { name: 'left', geometry: shared, matrix: place(-1.4, 0.6, 0, 0.6), material: { color: [0.9, 0.2, 0.2], roughness: 0.3 } },
+ { name: 'middle', geometry: shared, matrix: rotated.map((value, index) => (index % 5 === 0 && index < 10 ? value * 0.7 : value)), material: { color: [0.2, 0.8, 0.3], metallic: 1, roughness: 0.2 } },
+ { name: 'right', geometry: shared, matrix: place(1.5, 0.5, 0.3, 0.5, { 0: -0.5 }), material: { color: [0.2, 0.3, 0.9], roughness: 0.6 } },
+ ];
+ const environment = { keyColor: [1, 0.95, 0.9], lightDirection: [0.4, 1, 0.3], keyIntensity: 3, pointLights: [{ position: [0, 3, 1], color: [1, 1, 1], intensity: 10, radius: 0.1 }] };
+ const camera = { eye: [0, 1.8, 5], target: [0, 0.6, 0], fov: 50 };
+ const width = 48;
+ const height = 32;
+ const options = normalizePathTracerOptions({ width, height, samples: 8, bounces: 3, seed: 7, backend: 'gpu', denoiser: 'none', threads: 1 });
+ const view = createCamera(camera, width, height);
+ const limit = 1_000_000;
+ const flat = build(parts, environment, { gpuTriangleLimit: limit });
+ const instanced = build(parts, environment, { gpuTriangleLimit: limit, instancing: true });
+ const flatImage = await gpuModule.traceOnGpu(flat, view, options, () => {});
+ const instancedImage = await gpuModule.traceOnGpu(instanced, view, options, () => {});
+ let squared = 0;
+ let sum = 0;
+ for (let index = 0; index < flatImage.color.length; index++) {
+ squared += (flatImage.color[index] - instancedImage.color[index]) ** 2;
+ sum += flatImage.color[index];
+ }
+ return {
+ rmse: Math.sqrt(squared / flatImage.color.length),
+ mean: sum / flatImage.color.length,
+ flatTriangles: count(flat),
+ instancedTriangles: count(instanced),
+ instancedFlag: Array.isArray(instanced.instances),
+ };
+}
+
+test('on the WebGL2 tracer an instanced scene renders what the flattened scene renders', { timeout: 240_000 }, async context => {
+ await withDevServerPage(context, async page => {
+ const result = await page.evaluate(traceBothWays);
+ assert.equal(result.instancedFlag, true);
+ assert.ok(result.instancedTriangles < result.flatTriangles);
+ assert.ok(result.mean > 0.05, `the picture is not black (mean ${result.mean})`);
+ assert.ok(result.rmse < result.mean * 0.001, `instanced and flattened pictures match within noise (rmse ${result.rmse}, mean ${result.mean})`);
+ });
+});