Skip to content

armgit / kiln

Public Imported from GitHub
0

Build and revise procedural 3D assets with your coding agent. Local MCP server, CLI and TypeScript engine with rendered review, editable source and GLB export.

Draw the 3D viewer with WebGPU, halve its draw calls and share batch shaders (#338)

Matthew Kissinger6bc85b0084e1
diff --git a/site/astro.config.mjs b/site/astro.config.mjs
index c1cea0d8..d1cc4713 100644
--- a/site/astro.config.mjs
+++ b/site/astro.config.mjs
@@ -2,6 +2,7 @@ import { defineConfig } from 'astro/config';
import react from '@astrojs/react';
import tailwindcss from '@tailwindcss/vite';
import { sceneSiteConfig } from './scripts/scene-source.mjs';
+import { VIEWER_THREE_ALIAS } from './scripts/viewer-three-alias.mjs';
import { workbenchContrast, workbenchTheme } from './src/lib/shiki-contrast.ts';
// Scene runtimes are built and staged outside this graph (scripts/scene-runtime.mjs, scripts/scene-pack.mjs);
@@ -17,6 +18,7 @@ export default defineConfig({
markdown: { shikiConfig: { theme: workbenchTheme, wrap: false, transformers: [workbenchContrast] } },
vite: {
plugins: [tailwindcss(), ...scene.plugins],
+ resolve: { alias: [VIEWER_THREE_ALIAS] },
build: { assetsInlineLimit: 0 },
// `astro preview --port N` serves on N or stops; it never moves to the next free port
// (site-build/ops/preview.ps1 prints its URLs before the server starts).
diff --git a/site/scripts/review-rig.test.ts b/site/scripts/review-rig.test.ts
index a4e562c6..7e26f0b6 100644
--- a/site/scripts/review-rig.test.ts
+++ b/site/scripts/review-rig.test.ts
@@ -2,8 +2,7 @@ import { describe, expect, test } from 'bun:test';
import { existsSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import { pathToFileURL } from 'node:url';
-import toneMappingChunk from 'three/src/renderers/shaders/ShaderChunk/tonemapping_pars_fragment.glsl.js';
-import { CUSTOM_TONE_MAPPING_STUB, REVIEW_RIG, REVIEW_RIG_SOURCE, installReviewNeutral, reviewNeutral, reviewNeutralBytes, reviewNeutralGlsl } from '../src/lib/review-rig';
+import { REVIEW_RIG, REVIEW_RIG_SOURCE, reviewNeutral, reviewNeutralBytes } from '../src/lib/review-rig';
import { DEFAULT_ENGINE_DIR } from './rig-render.mjs';
const engineDir = process.env.KILN_RIG_ENGINE_DIR ?? DEFAULT_ENGINE_DIR;
@@ -92,43 +91,3 @@ describe('Review Neutral, computed on the CPU', () => {
});
});
-describe('the WebGL tone mapping shader', () => {
- test('is generated from the rig constants, with the same construction as the engine’s node', () => {
- const glsl = reviewNeutralGlsl();
- expect(glsl).toContain('vec3 CustomToneMapping( vec3 color ) {');
- expect(glsl).toContain(`ReviewNeutralOffset = ${REVIEW_RIG.toneMapping.offset};`);
- expect(glsl).toContain(`ReviewNeutralStart = ${REVIEW_RIG.toneMapping.startCompression};`);
- expect(glsl).toContain(`ReviewNeutralDesaturation = ${REVIEW_RIG.toneMapping.desaturation};`);
- expect(glsl).toContain('color *= toneMappingExposure;');
- // Whole numbers are written as GLSL floats, or the compiler rejects the integer.
- expect(reviewNeutralGlsl({ offset: 1, startCompression: 0.5, desaturation: 2 })).toContain('ReviewNeutralOffset = 1.0;');
- });
-
- test('differs from three’s own Neutral mapping only in constants, which this documents', () => {
- const neutral = toneMappingChunk;
- expect(neutral).toContain('const float StartCompression = 0.8 - 0.04;');
- expect(neutral).toContain('float offset = x < 0.08 ? x - 6.25 * x * x : 0.04;');
- expect(neutral).toContain('const float Desaturation = 0.15;');
- });
-
- test('replaces only the empty CustomToneMapping stub of three’s chunk, once', () => {
- const chunks = chunkWithStub();
- const original = chunks.tonemapping_pars_fragment;
- expect(original).toContain(CUSTOM_TONE_MAPPING_STUB);
- expect(installReviewNeutral(chunks)).toBe(true);
- expect(chunks.tonemapping_pars_fragment).not.toContain(CUSTOM_TONE_MAPPING_STUB);
- expect(chunks.tonemapping_pars_fragment).toContain('ReviewNeutralOffset');
- // Everything else in the chunk (the built-in mappers) is untouched.
- expect(chunks.tonemapping_pars_fragment.replace(reviewNeutralGlsl(), CUSTOM_TONE_MAPPING_STUB)).toBe(original);
- const installed = chunks.tonemapping_pars_fragment;
- expect(installReviewNeutral(chunks)).toBe(true);
- expect(chunks.tonemapping_pars_fragment).toBe(installed);
- });
-
- test('refuses a chunk it was not written against instead of guessing', () => {
- const changed = { tonemapping_pars_fragment: 'vec3 CustomToneMapping( vec3 color ) { return color * 2.0; }' };
- expect(installReviewNeutral(changed)).toBe(false);
- expect(changed.tonemapping_pars_fragment).toBe('vec3 CustomToneMapping( vec3 color ) { return color * 2.0; }');
- expect(installReviewNeutral({})).toBe(false);
- });
-});
diff --git a/site/scripts/scene-source.mjs b/site/scripts/scene-source.mjs
index 47473fd1..06df32b5 100644
--- a/site/scripts/scene-source.mjs
+++ b/site/scripts/scene-source.mjs
@@ -170,8 +170,8 @@ function announce(message) {
/**
* Site (Astro) build settings for scenes. The scene code is not part of the site's module graph:
* scripts/scene-runtime.mjs builds it separately (bare `three` resolved to the scene kit's facade, as
- * in the kit's own build) and scripts/scene-pack.mjs stages the data, so the gallery viewer keeps the
- * classic three build. This exposes which runtimes are staged as `virtual:kiln-scenes`.
+ * in the kit's own build) and scripts/scene-pack.mjs stages the data, so the gallery viewer keeps its
+ * own copy of three. This exposes which runtimes are staged as `virtual:kiln-scenes`.
*/
export function sceneSiteConfig({ site = SITE } = {}) {
const scenes = stagedScenes(site);
diff --git a/site/scripts/tone-mapping.test.ts b/site/scripts/tone-mapping.test.ts
index 3a023245..7f5f0f4d 100644
--- a/site/scripts/tone-mapping.test.ts
+++ b/site/scripts/tone-mapping.test.ts
@@ -41,7 +41,7 @@ describe('the tone mappings the 3D view offers', () => {
});
describe('putting the renderer on a tone mapping', () => {
- const renderer = () => ({ toneMapping: THREE.NoToneMapping, toneMappingExposure: 1 }) as unknown as THREE.WebGLRenderer;
+ const renderer = () => ({ toneMapping: THREE.NoToneMapping, toneMappingExposure: 1 }) as unknown as Parameters<typeof applyToneMapping>[0];
const sceneWithMaterials = () => {
const scene = new THREE.Scene();
const single = new THREE.Mesh(new THREE.BoxGeometry(), new THREE.MeshStandardMaterial());
diff --git a/site/scripts/verify-viewer-draws.mjs b/site/scripts/verify-viewer-draws.mjs
new file mode 100644
index 00000000..bef1cacf
--- /dev/null
+++ b/site/scripts/verify-viewer-draws.mjs
@@ -0,0 +1,237 @@
+import { mkdir, readFile, rm, writeFile } from 'node:fs/promises';
+import { createServer } from 'node:http';
+import { dirname, join, resolve } from 'node:path';
+import { fileURLToPath, pathToFileURL } from 'node:url';
+import puppeteer from 'puppeteer-core';
+import { chromeExecutable } from './build-site-media.mjs';
+import { sceneBrowserOptions } from '../../scenes/scripts/browser-options.mjs';
+import { VIEWER_THREE_ALIAS } from './viewer-three-alias.mjs';
+
+/**
+ * What the 3D view draws, counted at the graphics API in a real browser.
+ *
+ * node scripts/verify-viewer-draws.mjs <model.glb> <output-directory> [--backend webgpu,webgl2]
+ * [--view label:px,py,pz:tx,ty,tz ...] [--budget <draws>]
+ *
+ * The site's own viewer runtime is built into a small page and given the model. WebGPU pass encoders and WebGL2
+ * contexts are wrapped before any page script runs, so the counts are the calls the browser receives, per frame:
+ * after the model loads the page must go idle (no draws while nothing changes), an orbit step must draw, and each
+ * saved camera is counted and photographed. `--budget` fails the run when any frame draws more than that.
+ */
+
+const SITE = resolve(dirname(fileURLToPath(import.meta.url)), '..');
+const sleep = (ms) => new Promise((done) => setTimeout(done, ms));
+
+/** Runs in the page before its scripts. Counts every draw and groups the counts by animation frame. */
+export function installDrawCounter() {
+ const state = { frames: [], current: { draws: 0, triangles: 0, instanced: 0 }, blocked: [] };
+ window.kilnDraws = state;
+ // Main-thread tasks over 50 ms, such as a shader compile the page has to wait for.
+ new PerformanceObserver((list) => {
+ for (const entry of list.getEntries()) state.blocked.push(Math.round(entry.duration));
+ }).observe({ type: 'longtask', buffered: true });
+ const count = (vertices, instances, mode) => {
+ state.current.draws += 1;
+ if (instances > 1) state.current.instanced += 1;
+ if (mode === undefined || mode === 4) state.current.triangles += (vertices / 3) * instances;
+ };
+ for (const prototype of [globalThis.WebGL2RenderingContext?.prototype].filter(Boolean)) {
+ const wrap = (name, read) => {
+ const original = prototype[name];
+ prototype[name] = function (...args) {
+ read(this, args);
+ return original.apply(this, args);
+ };
+ };
+ wrap('drawElements', (gl, a) => count(a[1], 1, a[0] === gl.TRIANGLES ? 4 : 0));
+ wrap('drawArrays', (gl, a) => count(a[2], 1, a[0] === gl.TRIANGLES ? 4 : 0));
+ wrap('drawElementsInstanced', (gl, a) => count(a[1], a[4], a[0] === gl.TRIANGLES ? 4 : 0));
+ wrap('drawArraysInstanced', (gl, a) => count(a[2], a[3], a[0] === gl.TRIANGLES ? 4 : 0));
+ }
+ const pass = globalThis.GPURenderPassEncoder?.prototype;
+ if (pass) {
+ for (const [name, read] of [
+ ['draw', (a) => count(a[0], a[1] ?? 1)],
+ ['drawIndexed', (a) => count(a[0], a[1] ?? 1)],
+ ]) {
+ const original = pass[name];
+ pass[name] = function (...args) {
+ read(args);
+ return original.apply(this, args);
+ };
+ }
+ }
+ const tick = () => {
+ if (state.current.draws > 0) state.frames.push({ ...state.current, at: Math.round(performance.now()) });
+ state.current = { draws: 0, triangles: 0, instanced: 0 };
+ requestAnimationFrame(tick);
+ };
+ requestAnimationFrame(tick);
+}
+
+/** Build the harness page into `outDir`. */
+export async function buildHarness(outDir) {
+ const { build } = await import('vite');
+ await rm(outDir, { recursive: true, force: true });
+ await build({
+ configFile: false,
+ envDir: false,
+ root: SITE,
+ logLevel: 'warn',
+ publicDir: false,
+ resolve: { alias: [VIEWER_THREE_ALIAS] },
+ define: { 'process.env.NODE_ENV': '"production"' },
+ build: {
+ outDir,
+ emptyOutDir: true,
+ target: 'esnext',
+ sourcemap: false,
+ reportCompressedSize: false,
+ modulePreload: false,
+ chunkSizeWarningLimit: 8192,
+ rollupOptions: { input: { harness: resolve(SITE, 'scripts/viewer-draws-harness.ts') }, output: { entryFileNames: 'harness.js' } },
+ },
+ });
+ await writeFile(join(outDir, 'index.html'), '<!doctype html><meta charset="utf-8"><title>viewer draws</title><style>.h-viewer{height:540px}body{margin:0}</style><div id="viewer"></div><script type="module" src="./harness.js"></script>');
+}
+
+function serve(root, glbPath) {
+ const server = createServer(async (request, response) => {
+ try {
+ const { pathname } = new URL(request.url, 'http://127.0.0.1');
+ if (pathname === '/favicon.ico') return void response.writeHead(204).end();
+ if (pathname === '/model.glb') return void response.writeHead(200, { 'content-type': 'model/gltf-binary' }).end(await readFile(glbPath));
+ const file = pathname === '/' ? '/index.html' : pathname;
+ if (file.includes('..')) return void response.writeHead(400).end();
+ const type = file.endsWith('.js') ? 'text/javascript' : file.endsWith('.css') ? 'text/css' : 'text/html';
+ response.writeHead(200, { 'content-type': type }).end(await readFile(join(root, file)));
+ } catch {
+ response.writeHead(404).end();
+ }
+ });
+ return new Promise((done) => server.listen(0, '127.0.0.1', () => done({ origin: `http://127.0.0.1:${server.address().port}`, stop: () => new Promise((closed) => server.close(closed)) })));
+}
+
+/** Frames recorded since `from`, reduced to the heaviest. */
+const heaviest = async (page, from) => page.evaluate((start) => {
+ const frames = window.kilnDraws.frames.slice(start);
+ return { frames: frames.length, draws: Math.max(0, ...frames.map((frame) => frame.draws)), triangles: Math.max(0, ...frames.map((frame) => frame.triangles)), instanced: Math.max(0, ...frames.map((frame) => frame.instanced)), all: frames.slice(0, 6).map((frame) => frame.draws) };
+}, from);
+const frameCount = (page) => page.evaluate(() => window.kilnDraws.frames.length);
+
+async function measure(browser, origin, backend, views, output) {
+ const page = await browser.newPage();
+ const problems = [];
+ page.on('pageerror', (error) => problems.push(`page error: ${error.message}`));
+ page.on('console', (message) => { if (message.type() === 'error') problems.push(`console error: ${message.text()}`); });
+ try {
+ await page.setViewport({ width: 1280, height: 800, deviceScaleFactor: 1 });
+ await page.evaluateOnNewDocument(installDrawCounter);
+ const query = new URLSearchParams({ backend, views: JSON.stringify(views) });
+ const started = Date.now();
+ await page.goto(`${origin}/?${query}`, { waitUntil: 'domcontentloaded' });
+ await page.waitForSelector('canvas[data-viewer-backend]', { timeout: 60000 });
+ const actual = await page.$eval('canvas[data-viewer-backend]', (canvas) => canvas.dataset.viewerBackend);
+ // The model is in when a frame draws more than the view's own ground and the page then goes quiet.
+ await page.waitForFunction(() => window.kilnDraws.frames.some((frame) => frame.draws > 4), { timeout: 180000 });
+ // The saved-camera buttons are enabled once the model's shaders are built. Before that the page draws nothing while
+ // it compiles, which would pass for going quiet, and a view clicked then is ignored. Only those buttons: Pause stays
+ // disabled until a clip plays.
+ await page.waitForFunction(
+ (labels) => {
+ const buttons = [...document.querySelectorAll('section[aria-label="3D inspection controls"] button')];
+ return labels.every((label) => buttons.some((button) => button.textContent.trim() === label && !button.disabled));
+ },
+ { timeout: 240000 },
+ views.map((view) => view.label),
+ );
+ let quiet = 0;
+ let last = await frameCount(page);
+ while (quiet < 2000 && Date.now() - started < 240000) {
+ await sleep(250);
+ const now = await frameCount(page);
+ quiet = now === last ? quiet + 250 : 0;
+ last = now;
+ }
+ const firstFrameMs = Date.now() - started - quiet;
+ // When the model first drew, on the page's own clock, and the longest the page could not respond while loading. The
+ // environment map's build comes first and draws many calls but few triangles, so the model's frame is told by those.
+ const { modelShownMs, longestBlockMs } = await page.evaluate(() => {
+ const { frames, blocked } = window.kilnDraws;
+ const most = Math.max(0, ...frames.map((frame) => frame.triangles));
+ return {
+ modelShownMs: frames.find((frame) => frame.triangles >= most / 2)?.at ?? null,
+ longestBlockMs: Math.max(0, ...blocked),
+ };
+ });
+ const load = await heaviest(page, 0);
+ const idleFrom = await frameCount(page);
+ await sleep(2000);
+ const idle = await heaviest(page, idleFrom);
+ const orbitFrom = await frameCount(page);
+ await page.click('button[aria-label="Orbit left"]');
+ await sleep(1500);
+ const orbit = await heaviest(page, orbitFrom);
+ await page.click('button[aria-label="Orbit right"]');
+ await sleep(1500);
+ const canvas = await page.$('canvas[data-viewer-backend]');
+ const pictures = {};
+ const framed = join(output, `${backend}-framed.png`);
+ await canvas.screenshot({ path: framed });
+ pictures.framed = framed;
+ const counted = {};
+ for (const view of views) {
+ const [button] = await page.$$(`xpath/.//button[normalize-space()='${view.label}']`);
+ const from = await frameCount(page);
+ await button.click();
+ await sleep(1500);
+ counted[view.label] = await heaviest(page, from);
+ const picture = join(output, `${backend}-${view.label.replace(/[^a-z0-9]+/gi, '-')}.png`);
+ await canvas.screenshot({ path: picture });
+ pictures[view.label] = picture;
+ }
+ const failures = await page.evaluate(() => window.kilnViewerFailures);
+ return { requested: backend, backend: actual, firstFrameMs, modelShownMs, longestBlockMs, load, idle, orbit, views: counted, pictures, failures, problems };
+ } finally {
+ await page.close();
+ }
+}
+
+if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
+ const args = process.argv.slice(2);
+ const take = (name) => { const found = []; for (let i = 0; i < args.length; i++) if (args[i] === name) found.push(args[i + 1]); return found; };
+ const valued = new Set(['--backend', '--view', '--budget']);
+ const [glb, review] = args.filter((arg, index) => !arg.startsWith('--') && !valued.has(args[index - 1]));
+ if (!glb || !review) throw new Error('Usage: node scripts/verify-viewer-draws.mjs <model.glb> <output-directory> [--backend webgpu,webgl2] [--view label:px,py,pz:tx,ty,tz] [--budget <draws>]');
+ const backends = (take('--backend')[0] ?? 'webgpu,webgl2').split(',');
+ const budget = take('--budget')[0] ? Number(take('--budget')[0]) : undefined;
+ const views = take('--view').map((spec) => {
+ const [label, position, target] = spec.split(':');
+ return { label, position: position.split(',').map(Number), target: target.split(',').map(Number) };
+ });
+ await mkdir(review, { recursive: true });
+ const built = join(review, 'harness');
+ await buildHarness(built);
+ const { origin, stop } = await serve(built, resolve(glb));
+ const browser = await puppeteer.launch({ executablePath: chromeExecutable(), pipe: true, ...sceneBrowserOptions({ args: ['--no-sandbox', '--enable-unsafe-webgpu'] }) });
+ const results = { glb: resolve(glb), browser: await browser.version(), runs: [] };
+ try {
+ for (const backend of backends) results.runs.push(await measure(browser, origin, backend, views, review));
+ } finally {
+ await browser.close();
+ await stop();
+ }
+ await writeFile(join(review, 'draws.json'), `${JSON.stringify(results, null, 2)}\n`);
+ console.log(JSON.stringify(results, null, 2));
+ const errors = [];
+ for (const run of results.runs) {
+ if (run.idle.frames > 0) errors.push(`${run.requested}: ${run.idle.frames} frames drew while nothing changed`);
+ if (run.orbit.frames === 0) errors.push(`${run.requested}: an orbit step drew nothing`);
+ if (run.failures.length || run.problems.length) errors.push(`${run.requested}: ${[...run.failures, ...run.problems].join('; ')}`);
+ if (budget !== undefined && Math.max(run.load.draws, run.orbit.draws) > budget) errors.push(`${run.requested}: ${Math.max(run.load.draws, run.orbit.draws)} draws in a frame, over the budget of ${budget}`);
+ }
+ if (errors.length) {
+ console.error(errors.join('\n'));
+ process.exitCode = 1;
+ }
+}
diff --git a/site/scripts/verify-viewer-rig.mjs b/site/scripts/verify-viewer-rig.mjs
index a6c0ea7b..6ed8b916 100644
--- a/site/scripts/verify-viewer-rig.mjs
+++ b/site/scripts/verify-viewer-rig.mjs
@@ -5,6 +5,7 @@ import { dirname, join, resolve } from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import puppeteer from 'puppeteer-core';
import { chromeExecutable } from './build-site-media.mjs';
+import { VIEWER_THREE_ALIAS } from './viewer-three-alias.mjs';
/**
* Check, in a real browser, that the site viewer's lighting reproduces the review rig.
@@ -13,7 +14,7 @@ import { chromeExecutable } from './build-site-media.mjs';
*
* The rig's calibration chart (`assets/calibration.glb`: 48 patches, two roughness values, four panel
* orientations: key, up, side, away) is rendered from the rig's four fixed cameras with the viewer's own
- * `applyReviewRig`, in a WebGL renderer built into a small page by Vite. The median of each patch's central
+ * `applyReviewRig`, in the viewer's own renderer built into a small page by Vite. The median of each patch's central
* 11x11 pixels is compared with `measurements/review-neutral-v1.json`, which the engine's render service
* measured on the same chart (WebGPU, Dawn/D3D12). Nothing is written next to the chart; the evidence goes to
* `--out`. It needs Chrome or Chromium (CHROME_PATH) and the site's installed dependencies.
@@ -36,7 +37,7 @@ export async function buildHarness(outDir) {
root: SITE,
logLevel: 'warn',
publicDir: false,
- resolve: { dedupe: ['three'] },
+ resolve: { alias: [VIEWER_THREE_ALIAS] },
build: {
outDir,
emptyOutDir: true,
diff --git a/site/scripts/viewer-backdrop.test.ts b/site/scripts/viewer-backdrop.test.ts
new file mode 100644
index 00000000..84ebd1b0
--- /dev/null
+++ b/site/scripts/viewer-backdrop.test.ts
@@ -0,0 +1,28 @@
+import { describe, expect, test } from 'bun:test';
+import { backdropClearColor } from '../../render-service/src/display-transform.mjs';
+import { REVIEW_RIG, backdropLinear, reviewNeutral, srgbEncode } from '../src/lib/review-rig';
+
+const bytesOf = (hex: string) => [1, 3, 5].map((at) => Number.parseInt(hex.slice(at, at + 2), 16));
+const toBytes = (display: readonly number[]) =>
+ display.map((c) => Math.round(srgbEncode(Math.min(1, Math.max(0, c))) * 255));
+
+describe('the viewer backdrop survives the output pass', () => {
+ test('under the rig mapping it reads back as the rig backdrop', () => {
+ const linear = backdropLinear('neutral');
+ expect(toBytes(reviewNeutral(linear))).toEqual(bytesOf(REVIEW_RIG.backdrop));
+ });
+
+ test('the rig mapping gives the clear colour the render service uses', () => {
+ const engine = backdropClearColor(REVIEW_RIG.backdrop, REVIEW_RIG.exposure, 'review-neutral');
+ backdropLinear('neutral').forEach((value, index) => expect(value).toBeCloseTo(engine[index], 10));
+ });
+
+ test('ACES at exposure 1 gives the clear colour the render service uses', () => {
+ const engine = backdropClearColor(REVIEW_RIG.backdrop, 1, 'aces');
+ backdropLinear('aces').forEach((value, index) => expect(value).toBeCloseTo(engine[index], 10));
+ });
+
+ test('Linear at exposure 1 is the backdrop decoded, with nothing else in the way', () => {
+ expect(toBytes(backdropLinear('linear'))).toEqual(bytesOf(REVIEW_RIG.backdrop));
+ });
+});
diff --git a/site/scripts/viewer-draws-harness.ts b/site/scripts/viewer-draws-harness.ts
new file mode 100644
index 00000000..b660543b
--- /dev/null
+++ b/site/scripts/viewer-draws-harness.ts
@@ -0,0 +1,16 @@
+import { mountAssetViewer } from '../src/components/AssetViewerRuntime';
+
+/**
+ * Browser side of `verify-viewer-draws.mjs`: the site's own viewer runtime on one model, with its query string
+ * choosing the backend and the saved cameras, so the counts come from what a visitor's page runs.
+ */
+const query = new URLSearchParams(location.search);
+const failures: string[] = [];
+(window as unknown as { kilnViewerFailures: string[] }).kilnViewerFailures = failures;
+mountAssetViewer(document.getElementById('viewer') as HTMLElement, {
+ name: 'model',
+ modelUrl: '/model.glb',
+ onError: (error) => failures.push(error.message),
+ forceWebGL: query.get('backend') === 'webgl2',
+ views: JSON.parse(query.get('views') ?? '[]'),
+});
diff --git a/site/scripts/viewer-draws.test.ts b/site/scripts/viewer-draws.test.ts
new file mode 100644
index 00000000..526121a2
--- /dev/null
+++ b/site/scripts/viewer-draws.test.ts
@@ -0,0 +1,137 @@
+import { describe, expect, test } from 'bun:test';
+import * as THREE from 'three';
+import {
+ SHADOW_RESOLUTION,
+ composeContactShadow,
+ rebakeDue,
+ restoreCulling,
+ viewerFrameloop,
+} from '../src/components/viewer-draws';
+
+const channel = (size: number, at: (x: number, y: number) => number) => {
+ const red = new Uint8Array(size * size * 4);
+ for (let y = 0; y < size; y++)
+ for (let x = 0; x < size; x++) red[(y * size + x) * 4] = at(x, y);
+ return red;
+};
+const alphaAt = (pixels: Uint8Array, size: number, x: number, y: number) =>
+ pixels[(y * size + x) * 4 + 3] as number;
+
+describe('the baked contact shadow', () => {
+ const options = { opacity: 0.45, blur: 2.4, colour: [0x29, 0x2d, 0x29] as const };
+
+ test('an empty ground has no shadow at all', () => {
+ const pixels = composeContactShadow(channel(32, () => 0), 32, options);
+ expect(pixels.length).toBe(32 * 32 * 4);
+ expect(Math.max(...pixels.filter((_, index) => index % 4 === 3))).toBe(0);
+ });
+
+ test('the colour is the same everywhere; only the alpha carries the shadow', () => {
+ const pixels = composeContactShadow(channel(16, () => 255), 16, options);
+ for (let i = 0; i < pixels.length; i += 4) {
+ expect([pixels[i], pixels[i + 1], pixels[i + 2]]).toEqual([0x29, 0x2d, 0x29]);
+ }
+ });
+
+ test('full coverage reads back at the opacity asked for, as the old shadow did', () => {
+ const size = 64;
+ const pixels = composeContactShadow(channel(size, () => 255), size, options);
+ expect(alphaAt(pixels, size, size / 2, size / 2)).toBeCloseTo(0.45 * 255, -0.5);
+ });
+
+ test('a lit point spreads into a soft pool centred where it was', () => {
+ const size = 128;
+ const c = size / 2;
+ const source = channel(size, (x, y) => (Math.abs(x - c) < 6 && Math.abs(y - c) < 6 ? 255 : 0));
+ const pixels = composeContactShadow(source, size, { ...options, opacity: 1 });
+ const centre = alphaAt(pixels, size, c, c);
+ expect(centre).toBeGreaterThan(0);
+ expect(alphaAt(pixels, size, c + 8, c)).toBeLessThan(centre);
+ expect(alphaAt(pixels, size, c - 8, c)).toBeCloseTo(alphaAt(pixels, size, c + 8, c), -1);
+ expect(alphaAt(pixels, size, c, c + 8)).toBeCloseTo(alphaAt(pixels, size, c, c - 8), -1);
+ expect(alphaAt(pixels, size, 2, 2)).toBe(0);
+ });
+
+ test('the blur is measured in the same fraction of the texture at every resolution', () => {
+ const spread = (size: number) => {
+ const c = size / 2;
+ const r = size / 16;
+ const pixels = composeContactShadow(
+ channel(size, (x, y) => (Math.abs(x - c) < r && Math.abs(y - c) < r ? 255 : 0)),
+ size,
+ { ...options, opacity: 1 },
+ );
+ return alphaAt(pixels, size, Math.round(c + r * 2), c);
+ };
+ expect(Math.abs(spread(256) - spread(512))).toBeLessThanOrEqual(6);
+ });
+
+ test('keeps the resolution the old shadow used', () => {
+ expect(SHADOW_RESOLUTION).toBe(512);
+ });
+});
+
+describe('drawing only when something changes', () => {
+ test('a still model waits for the camera, so an idle page draws nothing', () => {
+ expect(viewerFrameloop({ spin: false, clipPlaying: false })).toBe('demand');
+ });
+
+ test('turntable and a playing clip draw every frame', () => {
+ expect(viewerFrameloop({ spin: true, clipPlaying: false })).toBe('always');
+ expect(viewerFrameloop({ spin: false, clipPlaying: true })).toBe('always');
+ });
+
+ test('a playing clip refreshes the shadow a few times a second, not every frame', () => {
+ expect(rebakeDue(0.1, 0)).toBe(false);
+ expect(rebakeDue(0.25, 0)).toBe(true);
+ expect(rebakeDue(10, 9.9)).toBe(false);
+ });
+
+ test('a clip played again after a pause re-bakes at once, though the clock restarted at zero', () => {
+ // React Three Fiber restarts its clock whenever the frame loop changes, so the last bake can be in the clock's future.
+ expect(rebakeDue(0.02, 40)).toBe(true);
+ });
+});
+
+describe('culling that cannot make a part blink', () => {
+ const offsetBox = (x: number) => {
+ const geometry = new THREE.BoxGeometry(1, 1, 1).translate(x, 0, 0);
+ return new THREE.Mesh(geometry, new THREE.MeshBasicMaterial());
+ };
+
+ test('still parts are culled against a sphere measured from their real vertices', () => {
+ const mesh = offsetBox(500);
+ // What a loader can leave behind: a sphere that does not contain the vertices.
+ mesh.geometry.boundingSphere = new THREE.Sphere(new THREE.Vector3(), 1);
+ mesh.frustumCulled = false;
+ restoreCulling(mesh);
+ expect(mesh.frustumCulled).toBe(true);
+ expect(mesh.geometry.boundingSphere?.center.x).toBeCloseTo(500, 5);
+ });
+
+ test('a shared geometry is measured once', () => {
+ const first = offsetBox(10);
+ const second = new THREE.Mesh(first.geometry, first.material);
+ const group = new THREE.Group().add(first, second);
+ const measured = restoreCulling(group);
+ expect(measured).toBe(1);
+ expect(second.frustumCulled).toBe(true);
+ });
+
+ test('skinned and morphing parts stay drawn: their rest-pose sphere does not bound them', () => {
+ const skinned = offsetBox(0) as unknown as THREE.SkinnedMesh;
+ (skinned as unknown as { isSkinnedMesh: boolean }).isSkinnedMesh = true;
+ const morphing = offsetBox(0);
+ morphing.morphTargetInfluences = [0.5];
+ const group = new THREE.Group().add(skinned, morphing);
+ restoreCulling(group);
+ expect(skinned.frustumCulled).toBe(false);
+ expect(morphing.frustumCulled).toBe(false);
+ });
+
+ test('objects that are not meshes keep their defaults', () => {
+ const light = new THREE.DirectionalLight();
+ restoreCulling(light);
+ expect(light.frustumCulled).toBe(true);
+ });
+});
diff --git a/site/scripts/viewer-renderer.test.ts b/site/scripts/viewer-renderer.test.ts
new file mode 100644
index 00000000..482da8e5
--- /dev/null
+++ b/site/scripts/viewer-renderer.test.ts
@@ -0,0 +1,71 @@
+import { describe, expect, test } from 'bun:test';
+import * as THREE from 'three/webgpu';
+import { NodeBuilder } from 'three/webgpu';
+import { compilesOnPageThread, shareInstancedShaders } from '../src/components/viewer-renderer';
+
+const backendOf = (webgpu: boolean) =>
+ ({ backend: { isWebGPUBackend: webgpu } }) as unknown as THREE.WebGPURenderer;
+
+const withBatches = (count: number) => {
+ const group = new THREE.Group();
+ const geometry = new THREE.BoxGeometry();
+ const material = new THREE.MeshStandardNodeMaterial();
+ for (let i = 0; i < count; i++) group.add(new THREE.InstancedMesh(geometry, material, 3));
+ group.add(new THREE.Mesh(geometry, material));
+ return group;
+};
+
+describe('which models build their shaders before they are first drawn', () => {
+ test('WebGL2 always does, since it compiles on the page thread', () => {
+ expect(compilesOnPageThread(backendOf(false))).toBe(true);
+ expect(compilesOnPageThread(backendOf(false), withBatches(0))).toBe(true);
+ });
+
+ test('WebGPU does for a model with many GPU batches, whose node graphs are each built alone', () => {
+ // r186 adds an InstancedMesh's uuid to its render cache key. 176 batches held the first frame for 5.7 s.
+ expect(compilesOnPageThread(backendOf(true), withBatches(16))).toBe(true);
+ });
+
+ test('WebGPU draws a plain model or a few batches at once, as before', () => {
+ expect(compilesOnPageThread(backendOf(true))).toBe(false);
+ expect(compilesOnPageThread(backendOf(true), withBatches(0))).toBe(false);
+ expect(compilesOnPageThread(backendOf(true), withBatches(15))).toBe(false);
+ });
+});
+
+/** A renderer as three's node builder sees it: only the backend's capabilities are read. */
+const rendererWithLimit = (bytes: number) => ({
+ backend: { capabilities: { getUniformBufferLimit: () => bytes } },
+});
+
+/** What three r186's node builder reports to `nodes/accessors/Instance.js` and `Skinning.js` while it builds `object`. */
+const limitSeenByNodes = (renderer: object, object: object) =>
+ NodeBuilder.prototype.getUniformBufferLimit.call({ renderer, object } as unknown as NodeBuilder);
+
+const batch = new THREE.InstancedMesh(new THREE.BoxGeometry(), new THREE.MeshStandardNodeMaterial(), 3);
+const skinned = new THREE.SkinnedMesh(new THREE.BoxGeometry(), new THREE.MeshStandardNodeMaterial());
+
+describe('instanced parts share their shaders', () => {
+ test('a GPU batch of any size takes the instanced-attribute path', () => {
+ const renderer = rendererWithLimit(65536);
+ // Unpatched, a batch under 1,024 copies is a uniform array named after its own node, so each
+ // batch is a shader of its own: 176 batches cost 203 WebGL2 programs and 399 WebGPU modules.
+ expect(limitSeenByNodes(renderer, batch)).toBeGreaterThanOrEqual(64);
+ shareInstancedShaders(renderer as never);
+ // `createInstanceMatrixNode` uses the uniform array only when `count * 64` fits the limit.
+ expect(limitSeenByNodes(renderer, batch)).toBeLessThan(64);
+ });
+
+ test('a skinned part keeps its bones in a uniform block', () => {
+ // Skinning reads the same limit; only instanced parts are moved off the uniform path.
+ const renderer = rendererWithLimit(65536);
+ shareInstancedShaders(renderer as never);
+ expect(limitSeenByNodes(renderer, skinned)).toBe(65536);
+ });
+
+ test('another renderer on the page is left alone', () => {
+ const other = rendererWithLimit(65536);
+ shareInstancedShaders(rendererWithLimit(65536) as never);
+ expect(limitSeenByNodes(other, batch)).toBe(65536);
+ });
+});
diff --git a/site/scripts/viewer-rig-harness.ts b/site/scripts/viewer-rig-harness.ts
index 3318ad95..5dbd415d 100644
--- a/site/scripts/viewer-rig-harness.ts
+++ b/site/scripts/viewer-rig-harness.ts
@@ -1,13 +1,14 @@
-import * as THREE from 'three';
-import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';
-import { RoomEnvironment } from 'three/examples/jsm/environments/RoomEnvironment.js';
+import * as THREE from 'three/webgpu';
+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
+import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';
import { REVIEW_RIG } from '../src/lib/review-rig';
-import { applyReviewRig, usesReviewNeutral } from '../src/lib/review-rig-three';
+import { applyReviewRig } from '../src/lib/review-rig-three';
+import { viewerBackend, viewerRendererFactory } from '../src/components/viewer-renderer';
/**
* Browser side of `verify-viewer-rig.mjs`: renders the rig's calibration chart with the site viewer's own
- * lighting module (`applyReviewRig`, the same call the viewer's React component makes) in a WebGL renderer,
- * and reports the median colour of each patch's central 11x11 pixels, as the rig's own measurements do.
+ * lighting module (`applyReviewRig`, the same call the viewer's React component makes) in the viewer's own
+ * renderer, on the backend asked for, and reports the median colour of each patch's central 11x11 pixels, as the rig's own measurements do.
*/
interface ChartCamera {
@@ -27,6 +28,7 @@ interface ChartGroup {
interface ChartRequest {
/** 'rig' is the viewer's lighting now; 'previous' is the lighting it had before the rig, kept only as a measured comparison. */
lighting?: 'rig' | 'previous';
+ backend?: 'webgpu' | 'webgl2';
glbUrl: string;
width: number;
height: number;
@@ -39,7 +41,7 @@ const median = (values: number[]) => {
};
/** The viewer's lighting before it followed the rig (room environment .6, two directional lights, Neutral tone mapping, exposure 1). */
-function applyPreviousViewerLighting(renderer: THREE.WebGLRenderer, scene: THREE.Scene) {
+function applyPreviousViewerLighting(renderer: THREE.WebGPURenderer, scene: THREE.Scene) {
renderer.toneMapping = THREE.NeutralToneMapping;
renderer.toneMappingExposure = 1;
const pmrem = new THREE.PMREMGenerator(renderer);
@@ -54,9 +56,9 @@ function applyPreviousViewerLighting(renderer: THREE.WebGLRenderer, scene: THREE
scene.background = new THREE.Color('#aab1bc');
}
-async function renderChart({ glbUrl, width, height, groups, lighting = 'rig' }: ChartRequest) {
+async function renderChart({ glbUrl, width, height, groups, lighting = 'rig', backend = 'webgpu' }: ChartRequest) {
const canvas = document.createElement('canvas');
- const renderer = new THREE.WebGLRenderer({ canvas, antialias: true, alpha: false, preserveDrawingBuffer: true });
+ const renderer = await viewerRendererFactory({ forceWebGL: backend === 'webgl2' })({ canvas });
renderer.setPixelRatio(1);
renderer.setSize(width, height, false);
const scene = new THREE.Scene();
@@ -65,8 +67,6 @@ async function renderChart({ glbUrl, width, height, groups, lighting = 'rig' }:
const gltf = await new GLTFLoader().loadAsync(glbUrl);
scene.add(gltf.scene);
- const gl = renderer.getContext();
- const debug = gl.getExtension('WEBGL_debug_renderer_info');
const copy = document.createElement('canvas');
copy.width = width;
copy.height = height;
@@ -96,9 +96,9 @@ async function renderChart({ glbUrl, width, height, groups, lighting = 'rig' }:
const corner = (x: number, y: number) => [...data.subarray((y * width + x) * 4, (y * width + x) * 4 + 3)];
results.push({ name: group.name, samples, corners: [corner(0, 0), corner(width - 1, 0), corner(0, height - 1), corner(width - 1, height - 1)], png: copy.toDataURL('image/png') });
}
- const renderedBy = debug ? String(gl.getParameter(debug.UNMASKED_RENDERER_WEBGL)) : String(gl.getParameter(gl.RENDERER));
+ const renderedBy = viewerBackend(renderer);
renderer.dispose();
- return { renderedBy, three: THREE.REVISION, usesReviewNeutral, lighting, rig: JSON.parse(JSON.stringify(REVIEW_RIG)), results };
+ return { renderedBy, three: THREE.REVISION, usesReviewNeutral: true, lighting, rig: JSON.parse(JSON.stringify(REVIEW_RIG)), results };
}
(window as unknown as { kilnRigChart: typeof renderChart }).kilnRigChart = renderChart;
diff --git a/site/scripts/viewer-three-alias.mjs b/site/scripts/viewer-three-alias.mjs
new file mode 100644
index 00000000..7b59946d
--- /dev/null
+++ b/site/scripts/viewer-three-alias.mjs
@@ -0,0 +1,7 @@
+import { fileURLToPath } from 'node:url';
+
+/** Bare `three` in the site's client graph is the WebGPU build (`src/lib/three-runtime.ts`), so its classes have one identity. */
+export const VIEWER_THREE_ALIAS = {
+ find: /^three$/,
+ replacement: fileURLToPath(new URL('../src/lib/three-runtime.ts', import.meta.url)),
+};
diff --git a/site/src/components/AssetViewerRuntime.tsx b/site/src/components/AssetViewerRuntime.tsx
index 6b34c831..ed5e431a 100644
--- a/site/src/components/AssetViewerRuntime.tsx
+++ b/site/src/components/AssetViewerRuntime.tsx
@@ -1,16 +1,14 @@
import { Canvas, useFrame, useThree } from '@react-three/fiber';
-import { ContactShadows, Grid, OrbitControls, useGLTF, useProgress } from '@react-three/drei';
+import { useProgress } from '@react-three/drei/core/Progress';
import { Component, Suspense, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
import { createRoot } from 'react-dom/client';
-import * as THREE from 'three';
-import { REVIEW_RIG } from '../lib/review-rig';
+import * as THREE from 'three/webgpu';
import {
DEFAULT_TONE_MAPPING,
TONE_MAPPINGS,
type ToneMappingId,
applyReviewRig,
applyToneMapping,
- reviewToneMapping,
toneMappingChoice,
} from '../lib/review-rig-three';
import {
@@ -25,6 +23,10 @@ import {
} from './viewer-framing';
import { clearingOnError } from './viewer-retry';
import { createVehiclePaint, PAINT_SWATCHES } from './vehicle-paint';
+import { OrbitControls, clearModel, useModel } from './viewer-controls';
+import { restoreCulling, viewerFrameloop } from './viewer-draws';
+import { BakedContactShadow, GroundGrid } from './viewer-ground';
+import { compileAhead, releaseViewerRenderer, viewerRendererFactory } from './viewer-renderer';
interface OrbitLike {
target: THREE.Vector3;
@@ -87,17 +89,26 @@ function surfacePoints(root: THREE.Object3D, budget = 4000): THREE.Vector3[] {
* is generated in the browser from three's own room scene (a few milliseconds, once) rather than fetched.
*/
function ReviewLighting() {
- const gl = useThree((s) => s.gl);
+ const gl = useThree((s) => s.gl) as unknown as THREE.WebGPURenderer;
const scene = useThree((s) => s.scene);
- useEffect(() => applyReviewRig(gl, scene), [gl, scene]);
+ const invalidate = useThree((s) => s.invalidate);
+ useEffect(() => {
+ const remove = applyReviewRig(gl, scene);
+ invalidate();
+ return remove;
+ }, [gl, scene, invalidate]);
return null;
}
/** The tone mapping the visitor chose: the rig's own until they pick another (see `TONE_MAPPINGS`). */
function ToneMapping({ id }: { id: ToneMappingId }) {
- const gl = useThree((s) => s.gl);
+ const gl = useThree((s) => s.gl) as unknown as THREE.WebGPURenderer;
const scene = useThree((s) => s.scene);
- useEffect(() => applyToneMapping(gl, scene, id), [gl, scene, id]);
+ const invalidate = useThree((s) => s.invalidate);
+ useEffect(() => {
+ applyToneMapping(gl, scene, id);
+ invalidate();
+ }, [gl, scene, id, invalidate]);
return null;
}
@@ -128,18 +139,21 @@ function Model({
paintColour: string | null;
onPaintReady: (originalHex: string | undefined) => void;
}) {
- // No Draco decoder path: drei's default would fetch the decoder from a third-party host. No shipped GLB uses
- // KHR_draco_mesh_compression, and validate-static fails the build if one ever does.
- const { scene: loadedScene, animations } = useGLTF(url, false);
+ // No Draco decoder: it would have to be fetched from another host. No shipped GLB uses KHR_draco_mesh_compression,
+ // and validate-static fails the build if one ever does.
+ const { scene: loadedScene, animations } = useModel(url);
const paint = useMemo(
() => createVehiclePaint(loadedScene, paintAssetId),
[loadedScene, paintAssetId],
);
const scene = paint?.scene ?? loadedScene;
useEffect(() => onPaintReady(paint?.originalHex), [paint, onPaintReady]);
- useEffect(() => paint?.setColour(paintColour), [paint, paintColour]);
+ const invalidate = useThree((s) => s.invalidate);
+ useEffect(() => {
+ paint?.setColour(paintColour);
+ invalidate();
+ }, [paint, paintColour, invalidate]);
useEffect(() => {
- onReady();
return () => {
const geometries = new Set<THREE.BufferGeometry>();
const materials = new Set<THREE.Material>();
@@ -158,9 +172,9 @@ function Model({
for (const geometry of geometries) geometry.dispose();
for (const material of materials) material.dispose();
for (const texture of textures) texture.dispose();
- useGLTF.clear(url);
+ clearModel(url);
};
- }, [scene, url, onReady]);
+ }, [scene, url]);
const mixer = useMemo(() => new THREE.AnimationMixer(scene), [scene]);
useEffect(() => {
onClips(animations.map((clip) => ({ id: clip.uuid, name: clip.name })));
@@ -173,10 +187,11 @@ function Model({
mixer.stopAllAction();
const clip = animations[clipIndex];
if (clip) mixer.clipAction(clip).reset().play();
+ invalidate();
return () => {
mixer.stopAllAction();
};
- }, [animations, clipIndex, mixer]);
+ }, [animations, clipIndex, mixer, invalidate]);
useFrame((_, delta) => {
if (!paused) mixer.update(Math.min(delta, 0.1));
});
@@ -191,19 +206,13 @@ function Model({
// walk every vertex again.
const points = useMemo(() => surfacePoints(scene), [scene]);
- /**
- * `frustumCulled` off across the board. Several of these programs place parts
- * a long way from the origin -- the airship's mooring mast, the carrier's
- * island -- and three culls against a bounding sphere it computes per mesh, so
- * a part whose geometry was built with a large offset baked into its vertices
- * can blink out at certain angles. Fifty draw calls more is nothing here; a
- * disappearing funnel is not.
- */
+ // Several of these programs place parts a long way from the origin -- the airship's mooring mast, the carrier's
+ // island -- with the offset baked into their vertices. Measuring each sphere from those vertices keeps them in
+ // view; on a model of thousands of parts, culling is what stops every part being drawn from inside the nave.
useEffect(() => {
- scene.traverse((o) => {
- o.frustumCulled = false;
- });
- }, [scene]);
+ restoreCulling(scene);
+ invalidate();
+ }, [scene, invalidate]);
// Frame on load, on every explicit reset, and on resize. The engine's contract
// puts an asset on Y=0 facing +X, so the camera can be placed from the geometry
@@ -238,7 +247,30 @@ function Model({
controls.maxDistance = radius * 14;
controls.update();
onBounds(radius);
- }, [scene, points, camera, controls, framing, viewShowing, onBounds, width, height]);
+ invalidate();
+ }, [scene, points, camera, controls, framing, viewShowing, onBounds, width, height, invalidate]);
+
+ // The model joins the view once its shaders are built, and the view counts as ready from then (see `compileAhead`).
+ const renderer = useThree((s) => s.gl) as unknown as THREE.WebGPURenderer;
+ const root = useThree((s) => s.scene);
+ const [compiled, setCompiled] = useState<THREE.Object3D | null>(null);
+ useEffect(() => {
+ let live = true;
+ compileAhead(renderer, scene, camera, root)
+ .catch(() => undefined)
+ .then(() => {
+ if (live) setCompiled(scene);
+ });
+ return () => {
+ live = false;
+ };
+ }, [renderer, scene, camera, root]);
+ const shown = compiled === scene;
+ useEffect(() => {
+ if (!shown) return;
+ onReady();
+ invalidate();
+ }, [shown, onReady, invalidate]);
useEffect(() => {
const touched: THREE.Material[] = [];
@@ -251,14 +283,15 @@ function Model({
touched.push(mat);
}
});
+ invalidate();
// Restored on the way out because drei caches the loaded scene by URL, and a
// material left in wireframe would come back that way on the next visit.
return () => {
for (const m of touched) (m as THREE.MeshStandardMaterial).wireframe = false;
};
- }, [scene, wireframe]);
+ }, [scene, wireframe, invalidate]);
- return <primitive object={scene} />;
+ return shown ? <primitive object={scene} /> : null;
}
interface ViewerProps {
@@ -268,6 +301,8 @@ interface ViewerProps {
paintAssetId?: string;
/** Saved cameras to offer as buttons. Most models have none. */
views?: SavedView[];
+ /** Skip WebGPU, as a browser without it would: for checks of the fallback. */
+ forceWebGL?: boolean;
}
class ViewerBoundary extends Component<
@@ -295,13 +330,23 @@ function Loading() {
) : null;
}
-function ContextMonitor({ onError }: { onError: (error: Error) => void }) {
- const canvas = useThree((state) => state.gl.domElement);
+/** Reports a lost GPU, on either backend, and releases the renderer when the view closes. */
+function RendererMonitor({ onError }: { onError: (error: Error) => void }) {
+ const renderer = useThree((state) => state.gl) as unknown as THREE.WebGPURenderer;
useEffect(() => {
- const lost = () => onError(new Error('WebGL context lost'));
+ const canvas = renderer.domElement;
+ let closing = false;
+ const lost = () => {
+ if (!closing) onError(new Error('The graphics device was lost'));
+ };
canvas.addEventListener('webglcontextlost', lost);
- return () => canvas.removeEventListener('webglcontextlost', lost);
- }, [canvas, onError]);
+ renderer.onDeviceLost = lost;
+ return () => {
+ closing = true;
+ canvas.removeEventListener('webglcontextlost', lost);
+ void releaseViewerRenderer(renderer);
+ };
+ }, [renderer, onError]);
return null;
}
@@ -335,7 +380,8 @@ function KeyboardCamera({ command }: { command: CameraCommand | undefined }) {
return null;
}
-function Viewer({ name, modelUrl, onError, paintAssetId, views }: ViewerProps) {
+function Viewer({ name, modelUrl, onError, paintAssetId, views, forceWebGL }: ViewerProps) {
+ const renderer = useMemo(() => viewerRendererFactory({ forceWebGL }), [forceWebGL]);
const [wireframe, setWireframe] = useState(false);
const [grid, setGrid] = useState(true);
const [spin, setSpin] = useState(false);
@@ -366,24 +412,14 @@ function Viewer({ name, modelUrl, onError, paintAssetId, views }: ViewerProps) {
role="img"
aria-label={`3D preview of ${name}. Use the controls below to orbit, zoom or inspect.`}
dpr={[1, 1.5]}
- gl={{
- antialias: true,
- alpha: true,
- toneMapping: reviewToneMapping,
- toneMappingExposure: REVIEW_RIG.exposure,
- }}
+ frameloop={viewerFrameloop({ spin, clipPlaying: clipIndex >= 0 && !paused })}
+ gl={renderer as never}
camera={{ fov: 34, position: [6, 3, 5] }}
>
- <ContextMonitor onError={onError} />
+ <RendererMonitor onError={onError} />
<ReviewLighting />
<ToneMapping id={toneMapping} />
- <OrbitControls
- makeDefault
- autoRotate={spin}
- autoRotateSpeed={0.55}
- enableDamping
- dampingFactor={0.06}
- />
+ <OrbitControls autoRotate={spin} autoRotateSpeed={0.55} dampingFactor={0.06} />
<KeyboardCamera command={command} />
<Suspense fallback={null}>
<Model
@@ -401,23 +437,22 @@ function Viewer({ name, modelUrl, onError, paintAssetId, views }: ViewerProps) {
onPaintReady={setOriginalPaint}
/>
</Suspense>
- <ContactShadows
- position={[0, 0.001, 0]}
- scale={radius * 4}
- far={radius * 1.5}
- opacity={0.45}
- blur={2.4}
- resolution={512}
- color="#292d29"
- />
- {grid && (
- <Grid
- {...groundGrid(radius)}
- cellColor="#9ba4b0"
- sectionColor="#7b8492"
- fadeStrength={1.4}
+ <group>
+ <BakedContactShadow
+ radius={radius}
+ ready={ready}
+ playing={clipIndex >= 0 && !paused}
+ pose={clipIndex}
/>
- )}
+ {grid && (
+ <GroundGrid
+ {...groundGrid(radius)}
+ cellColor="#9ba4b0"
+ sectionColor="#7b8492"
+ fadeStrength={1.4}
+ />
+ )}
+ </group>
</Canvas>
{!ready && <Loading />}
</section>
@@ -618,12 +653,15 @@ function Viewer({ name, modelUrl, onError, paintAssetId, views }: ViewerProps) {
}
export function mountAssetViewer(element: HTMLElement, props: ViewerProps) {
- // Check before React/Three initialize a renderer, so the fallback does not leave a failed canvas.
- const probe = document.createElement('canvas');
- const context = probe.getContext('webgl2');
- if (!context) throw new Error('WebGL2 is unavailable');
- context.getExtension('WEBGL_lose_context')?.loseContext();
- const onError = clearingOnError(props.modelUrl, props.onError, (url) => useGLTF.clear(url));
+ // Check before React/Three initialize a renderer, so the page's fallback does not leave a failed canvas. A browser
+ // with WebGPU can still lack an adapter, so WebGL2 is what proves the view can draw when `navigator.gpu` is absent.
+ if (!('gpu' in navigator)) {
+ const probe = document.createElement('canvas');
+ const context = probe.getContext('webgl2');
+ if (!context) throw new Error('Neither WebGPU nor WebGL2 is available');
+ context.getExtension('WEBGL_lose_context')?.loseContext();
+ }
+ const onError = clearingOnError(props.modelUrl, props.onError, clearModel);
const root = createRoot(element);
root.render(
<ViewerBoundary onError={onError}>
diff --git a/site/src/components/viewer-controls.tsx b/site/src/components/viewer-controls.tsx
new file mode 100644
index 00000000..297b450f
--- /dev/null
+++ b/site/src/components/viewer-controls.tsx
@@ -0,0 +1,56 @@
+import { useFrame, useLoader, useThree } from '@react-three/fiber';
+import { useEffect, useMemo } from 'react';
+import type { Camera } from 'three/webgpu';
+import { OrbitControls as ThreeOrbitControls } from 'three/addons/controls/OrbitControls.js';
+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
+import { MeshoptDecoder } from 'three/addons/libs/meshopt_decoder.module.js';
+
+/**
+ * three's own orbit controls and glTF loader. drei's versions come through three-stdlib, whose index reaches classic
+ * renderer classes the WebGPU build does not have.
+ */
+
+/** Orbit controls as the canvas's default controls, drawing a frame whenever they move the camera. */
+export function OrbitControls({
+ autoRotate,
+ autoRotateSpeed,
+ dampingFactor,
+}: {
+ autoRotate: boolean;
+ autoRotateSpeed: number;
+ dampingFactor: number;
+}) {
+ const camera = useThree((state) => state.camera) as Camera;
+ const canvas = useThree((state) => state.gl.domElement);
+ const invalidate = useThree((state) => state.invalidate);
+ const set = useThree((state) => state.set);
+ const controls = useMemo(() => new ThreeOrbitControls(camera), [camera]);
+ useEffect(() => {
+ controls.connect(canvas);
+ controls.addEventListener('change', invalidate as () => void);
+ set({ controls: controls as never });
+ return () => {
+ controls.removeEventListener('change', invalidate as () => void);
+ controls.dispose();
+ set({ controls: null });
+ };
+ }, [controls, canvas, invalidate, set]);
+ useEffect(() => {
+ controls.enableDamping = true;
+ controls.dampingFactor = dampingFactor;
+ controls.autoRotate = autoRotate;
+ controls.autoRotateSpeed = autoRotateSpeed;
+ }, [controls, autoRotate, autoRotateSpeed, dampingFactor]);
+ // Before the frame's render. Damping keeps moving the camera after the pointer stops, and each move asks for a frame.
+ useFrame(() => controls.update(), -1);
+ return null;
+}
+
+const withMeshopt = (loader: GLTFLoader) => {
+ loader.setMeshoptDecoder(MeshoptDecoder);
+};
+
+/** The model at `url`, suspending while it loads; one load per URL until `clearModel`. */
+export const useModel = (url: string) => useLoader(GLTFLoader, url, withMeshopt);
+
+export const clearModel = (url: string) => useLoader.clear(GLTFLoader, url);
diff --git a/site/src/components/viewer-draws.ts b/site/src/components/viewer-draws.ts
new file mode 100644
index 00000000..c11f3980
--- /dev/null
+++ b/site/src/components/viewer-draws.ts
@@ -0,0 +1,116 @@
+import type { BufferGeometry, Object3D } from 'three';
+
+/**
+ * What keeps the 3D view's draw calls down, apart from the renderer: a contact shadow baked once rather than
+ * redrawn with the whole model every frame, no drawing while nothing changes, and culling that is safe to leave on.
+ */
+
+export const SHADOW_RESOLUTION = 512;
+
+/** The tap weights of the blur the shadow always had (drei's contact shadow), centre last. */
+const TAPS = [0.051, 0.0918, 0.12245, 0.1531, 0.1633, 0.1531, 0.12245, 0.0918, 0.051];
+
+/** One blur along one axis, clamped at the edges. `along` is the distance between neighbouring pixels on that axis. */
+function blurPass(
+ source: Float32Array,
+ target: Float32Array,
+ size: number,
+ step: number,
+ horizontal: boolean,
+) {
+ const last = size - 1;
+ for (let y = 0; y < size; y++) {
+ for (let x = 0; x < size; x++) {
+ let sum = 0;
+ for (let tap = 0; tap < 9; tap++) {
+ const offset = (tap - 4) * step;
+ const sx = horizontal ? Math.min(last, Math.max(0, x + offset)) : x;
+ const sy = horizontal ? y : Math.min(last, Math.max(0, y + offset));
+ sum += (source[sy * size + sx] as number) * (TAPS[tap] as number);
+ }
+ target[y * size + x] = sum;
+ }
+ }
+}
+
+export interface ContactShadowOptions {
+ /** Alpha at full coverage, 0 to 1. */
+ opacity: number;
+ /** drei's `blur`: 1 is a tap spacing of 1/256 of the texture. */
+ blur: number;
+ /** The shadow's sRGB bytes. */
+ colour: readonly [number, number, number];
+}
+
+/**
+ * Turn the bake's red channel (how close the model comes to the ground at each texel) into the shadow's texture:
+ * a wide blur and a narrow one on each axis, as the old shadow did on the GPU each frame, in the shadow's colour with
+ * the coverage in alpha. Whole-pixel taps keep this to a few tens of milliseconds at 512, and two sizes hide the steps.
+ */
+export function composeContactShadow(
+ bake: Uint8Array,
+ size: number,
+ { opacity, blur, colour }: ContactShadowOptions,
+): Uint8Array {
+ let front = new Float32Array(size * size);
+ let back = new Float32Array(size * size);
+ for (let i = 0; i < front.length; i++) front[i] = (bake[i * 4] as number) / 255;
+ for (const scale of [1, 0.4]) {
+ const step = Math.max(1, Math.round((blur * scale * size) / 256));
+ for (const horizontal of [true, false]) {
+ blurPass(front, back, size, step, horizontal);
+ [front, back] = [back, front];
+ }
+ }
+ const pixels = new Uint8Array(size * size * 4);
+ for (let i = 0; i < front.length; i++) {
+ pixels[i * 4] = colour[0];
+ pixels[i * 4 + 1] = colour[1];
+ pixels[i * 4 + 2] = colour[2];
+ pixels[i * 4 + 3] = Math.round((front[i] as number) * opacity * 255);
+ }
+ return pixels;
+}
+
+/** A still model draws when the camera or a control changes it; a turntable or a playing clip draws every frame. */
+export function viewerFrameloop(state: {
+ spin: boolean;
+ clipPlaying: boolean;
+}): 'always' | 'demand' {
+ return state.spin || state.clipPlaying ? 'always' : 'demand';
+}
+
+const SHADOW_REFRESH_SECONDS = 0.25;
+
+/**
+ * Whether a playing clip's shadow is due for a new bake: a few times a second is enough for a soft shadow. A last
+ * bake later than `now` means the clock restarted (React Three Fiber resets it when the frame loop changes), so the
+ * shadow is due at once rather than frozen until the clock catches up.
+ */
+export const rebakeDue = (now: number, lastBake: number) =>
+ now < lastBake || now - lastBake >= SHADOW_REFRESH_SECONDS;
+
+/**
+ * Culling on for everything whose bounding sphere can be trusted, and measured here rather than taken from the file:
+ * a part blinks out when its sphere does not contain its vertices. Skinned and morphing parts leave their rest-pose
+ * sphere as they move, so they are always drawn. Returns how many geometries were measured.
+ */
+export function restoreCulling(root: Object3D): number {
+ const measured = new Set<BufferGeometry>();
+ root.traverse((object) => {
+ const part = object as Object3D & {
+ geometry?: BufferGeometry;
+ isSkinnedMesh?: boolean;
+ isInstancedMesh?: boolean;
+ morphTargetInfluences?: number[];
+ };
+ const { geometry } = part;
+ if (!geometry) return;
+ const moving = part.isSkinnedMesh || (part.morphTargetInfluences?.length ?? 0) > 0;
+ part.frustumCulled = !moving;
+ if (moving || part.isInstancedMesh || measured.has(geometry)) return;
+ geometry.computeBoundingSphere();
+ measured.add(geometry);
+ });
+ return measured.size;
+}
diff --git a/site/src/components/viewer-ground.tsx b/site/src/components/viewer-ground.tsx
new file mode 100644
index 00000000..5a5ea3c1
--- /dev/null
+++ b/site/src/components/viewer-ground.tsx
@@ -0,0 +1,237 @@
+import { useFrame, useThree } from '@react-three/fiber';
+import { useEffect, useMemo, useRef } from 'react';
+import * as THREE from 'three/webgpu';
+import {
+ abs,
+ cameraPosition,
+ clamp,
+ color,
+ distance,
+ float,
+ fract,
+ fwidth,
+ min,
+ mix,
+ pow,
+ positionWorld,
+ vec2,
+ vec3,
+} from 'three/tsl';
+import { compilesOnPageThread, viewerBackend } from './viewer-renderer';
+import { SHADOW_RESOLUTION, composeContactShadow, rebakeDue } from './viewer-draws';
+
+const SHADOW = { opacity: 0.3, blur: 2.4, colour: [0x29, 0x2d, 0x29] as const };
+
+/**
+ * The contact shadow, drawn once. A camera under the ground plane sees how close the model comes to the ground; that
+ * picture is read back, blurred on the CPU and shown on one plane, so the shadow costs one draw a frame however large
+ * the model is. Reading it back rather than blurring on the GPU means the two backends share the code. A playing clip
+ * bakes again a few times a second.
+ */
+export function BakedContactShadow({
+ radius,
+ ready,
+ playing,
+ pose,
+}: {
+ radius: number;
+ ready: boolean;
+ playing: boolean;
+ /** Changes when the pose changes without a clip playing, so the shadow follows it. */
+ pose: number;
+}) {
+ const renderer = useThree((state) => state.gl) as unknown as THREE.WebGPURenderer;
+ const scene = useThree((state) => state.scene);
+ const invalidate = useThree((state) => state.invalidate);
+ const plane = useRef<THREE.Mesh>(null);
+ const baking = useRef(false);
+ const lastBake = useRef(-Infinity);
+
+ const texture = useMemo(() => {
+ const data = new Uint8Array(SHADOW_RESOLUTION * SHADOW_RESOLUTION * 4);
+ const made = new THREE.DataTexture(data, SHADOW_RESOLUTION, SHADOW_RESOLUTION);
+ made.colorSpace = THREE.SRGBColorSpace;
+ made.minFilter = THREE.LinearFilter;
+ made.magFilter = THREE.LinearFilter;
+ made.needsUpdate = true;
+ return made;
+ }, []);
+ const target = useMemo(
+ () => new THREE.RenderTarget(SHADOW_RESOLUTION, SHADOW_RESOLUTION, { depthBuffer: true }),
+ [],
+ );
+ const far = radius * 1.5;
+ const size = radius * 4;
+ const closeness = useMemo(() => {
+ // No depth test, as the drei shadow this replaces had: the last surface drawn over a texel sets it, which keeps
+ // the shadow light under tall models instead of as dark as whatever comes closest to the ground.
+ const material = new THREE.MeshBasicNodeMaterial({ depthTest: false, depthWrite: false });
+ material.colorNode = vec3(clamp(float(1).sub(positionWorld.y.div(far)), 0, 1));
+ material.toneMapped = false;
+ return material;
+ }, [far]);
+ useEffect(() => () => closeness.dispose(), [closeness]);
+ useEffect(
+ () => () => {
+ texture.dispose();
+ target.dispose();
+ },
+ [texture, target],
+ );
+
+ const bake = async () => {
+ if (baking.current) return;
+ baking.current = true;
+ const camera = new THREE.OrthographicCamera(-size / 2, size / 2, size / 2, -size / 2, 0, far);
+ camera.rotation.x = Math.PI / 2;
+ camera.updateMatrixWorld();
+ /** Runs `step` with the scene set up for the bake, and puts the scene back before anything else can draw. */
+ const asBaked = <T,>(step: () => T): T => {
+ const before = {
+ background: scene.background,
+ override: scene.overrideMaterial,
+ target: renderer.getRenderTarget(),
+ alpha: renderer.getClearAlpha(),
+ clear: renderer.getClearColor(new THREE.Color()),
+ };
+ const ground = plane.current?.parent;
+ const groundShown = ground?.visible;
+ if (ground) ground.visible = false;
+ scene.background = null;
+ scene.overrideMaterial = closeness;
+ renderer.setRenderTarget(target);
+ renderer.setClearColor(0x000000, 0);
+ try {
+ return step();
+ } finally {
+ scene.background = before.background;
+ scene.overrideMaterial = before.override;
+ renderer.setRenderTarget(before.target);
+ renderer.setClearColor(before.clear, before.alpha);
+ if (ground) ground.visible = groundShown ?? true;
+ }
+ };
+ try {
+ // Where the page would wait on them, the bake's own shaders are built first, as the model's are (see `compileAhead`).
+ if (compilesOnPageThread(renderer, scene))
+ await asBaked(() => renderer.compileAsync(scene, camera)).catch(() => undefined);
+ asBaked(() => renderer.render(scene, camera));
+ } catch (error) {
+ baking.current = false;
+ throw error;
+ }
+ try {
+ const read = (await renderer.readRenderTargetPixelsAsync(
+ target,
+ 0,
+ 0,
+ SHADOW_RESOLUTION,
+ SHADOW_RESOLUTION,
+ )) as Uint8Array;
+ const pixels = composeContactShadow(
+ uprightRows(read, viewerBackend(renderer)),
+ SHADOW_RESOLUTION,
+ SHADOW,
+ );
+ (texture.image.data as Uint8Array).set(pixels);
+ texture.needsUpdate = true;
+ invalidate();
+ } finally {
+ baking.current = false;
+ }
+ };
+
+ // Pausing bakes once more, so the shadow matches the pose the clip stopped on.
+ // biome-ignore lint/correctness/useExhaustiveDependencies: bake reads the size and scene these trigger on.
+ useEffect(() => {
+ if (ready) void bake();
+ }, [ready, radius, pose, playing]);
+
+ useFrame(({ clock }) => {
+ if (!playing || !ready) return;
+ const now = clock.getElapsedTime();
+ if (!rebakeDue(now, lastBake.current)) return;
+ lastBake.current = now;
+ void bake();
+ });
+
+ return (
+ <mesh ref={plane} position={[0, 0.001, 0]} rotation-x={-Math.PI / 2} scale={[size, size, 1]}>
+ <planeGeometry args={[1, 1]} />
+ <meshBasicMaterial map={texture} transparent depthWrite={false} />
+ </mesh>
+ );
+}
+
+/**
+ * Row 0 of the shadow's texture is the far (+Z) edge of the plane, which is the top of the bake's picture. WebGPU reads
+ * pictures back top row first, WebGL bottom row first.
+ */
+export function uprightRows(read: Uint8Array, backend: 'webgpu' | 'webgl2'): Uint8Array {
+ if (backend === 'webgpu') return read;
+ const rowBytes = SHADOW_RESOLUTION * 4;
+ const flipped = new Uint8Array(read.length);
+ for (let row = 0; row < SHADOW_RESOLUTION; row++) {
+ const from = row * rowBytes;
+ flipped.set(read.subarray(from, from + rowBytes), (SHADOW_RESOLUTION - 1 - row) * rowBytes);
+ }
+ return flipped;
+}
+
+const gridLines = (cell: number, thickness: number) => {
+ const position = vec2(positionWorld.x, positionWorld.z).div(cell);
+ const across = abs(fract(position.sub(0.5)).sub(0.5)).div(fwidth(position));
+ const line = min(across.x, across.y).add(1 - thickness);
+ return float(1).sub(min(line, 1));
+};
+
+/**
+ * The ground grid: thin cell lines and heavier section lines, fading with distance from the camera. A small plane
+ * carried under the camera, with the lines taken from world position so they stay still (see `groundGrid`).
+ */
+export function GroundGrid({
+ args,
+ cellSize,
+ sectionSize,
+ fadeDistance,
+ cellColor,
+ sectionColor,
+ fadeStrength,
+}: {
+ args: [number, number];
+ cellSize: number;
+ sectionSize: number;
+ fadeDistance: number;
+ cellColor: string;
+ sectionColor: string;
+ fadeStrength: number;
+}) {
+ const plane = useRef<THREE.Mesh>(null);
+ const material = useMemo(() => {
+ const made = new THREE.MeshBasicNodeMaterial({
+ transparent: true,
+ side: THREE.DoubleSide,
+ depthWrite: false,
+ });
+ const cells = gridLines(cellSize, 0.5);
+ const sections = gridLines(sectionSize, 1);
+ const away = distance(
+ vec2(cameraPosition.x, cameraPosition.z),
+ vec2(positionWorld.x, positionWorld.z),
+ );
+ const fade = pow(float(1).sub(min(away.div(fadeDistance), 1)), fadeStrength);
+ const alpha = cells.add(sections).mul(fade);
+ made.colorNode = mix(color(cellColor), color(sectionColor), min(1, sections));
+ made.opacityNode = mix(alpha.mul(0.75), alpha, sections);
+ return made;
+ }, [cellSize, sectionSize, fadeDistance, cellColor, sectionColor, fadeStrength]);
+ useEffect(() => () => material.dispose(), [material]);
+ useFrame(({ camera }) => {
+ plane.current?.position.set(camera.position.x, 0, camera.position.z);
+ });
+ return (
+ <mesh ref={plane} rotation-x={-Math.PI / 2} material={material} frustumCulled={false}>
+ <planeGeometry args={args} />
+ </mesh>
+ );
+}
diff --git a/site/src/components/viewer-renderer.ts b/site/src/components/viewer-renderer.ts
new file mode 100644
index 00000000..685454cf
--- /dev/null
+++ b/site/src/components/viewer-renderer.ts
@@ -0,0 +1,158 @@
+import * as THREE from 'three/webgpu';
+import { installReviewToneMapping } from '../lib/review-rig-three';
+
+export type ViewerBackend = 'webgpu' | 'webgl2';
+
+interface TextureManager {
+ updateTexture(texture: THREE.Texture, options?: object): void;
+ _destroyTexture(texture: THREE.Texture): void;
+}
+
+/**
+ * r186's texture manager keeps its disposal listeners after `dispose()`, and a texture shared between renderers then
+ * holds every closed viewer in memory. The scene kit found this (`scene-kit/src/renderer/texture-cleanup.ts`); the
+ * same release is needed here, where a visitor can open and close a view many times on one page.
+ */
+function trackTextures(renderer: THREE.WebGPURenderer): () => void {
+ const manager = (renderer as unknown as { _textures?: TextureManager })._textures;
+ if (!manager) return () => {};
+ const textures = new Set<THREE.Texture>();
+ const { updateTexture: update, _destroyTexture: destroy } = manager;
+ manager.updateTexture = function (texture, options) {
+ textures.add(texture);
+ return update.call(this, texture, options);
+ };
+ manager._destroyTexture = function (texture) {
+ textures.delete(texture);
+ return destroy.call(this, texture);
+ };
+ return () => {
+ for (const texture of textures) destroy.call(manager, texture);
+ textures.clear();
+ manager.updateTexture = update;
+ manager._destroyTexture = destroy;
+ };
+}
+
+const releases = new WeakMap<THREE.WebGPURenderer, () => void>();
+
+/** The viewer's renderers, whose instanced parts are built to share shaders. */
+const sharing = new WeakSet<object>();
+let builderPatched = false;
+
+/**
+ * Let every GPU batch with the same material share one shader. Below 1,024 copies, r186's
+ * `nodes/accessors/Instance.js` puts a batch's matrices in a uniform array named after that
+ * batch's own node and sized to its count, so each `InstancedMesh` builds a shader of its own.
+ * A cathedral exported with `--draws minimal` has 176 batches. On WebGL2 they cost 203 programs,
+ * and it first drew at 52 s against 9 s for the plain file. On WebGPU they cost 399 modules and
+ * held the page for 5 s. Above the limit, three reads the matrices as instanced attributes, which
+ * are named by slot. With a limit of zero every batch does that: 29 programs and a first frame at
+ * 10 s on WebGL2, and 55 modules with no task over 0.2 s on WebGPU.
+ *
+ * Skinning and `RangeNode` read the same limit, so the zero is reported only while an instanced
+ * part is being built, and a skeleton keeps its bones in a uniform block as before. Only the
+ * viewer's renderers are changed.
+ */
+export function shareInstancedShaders(renderer: THREE.WebGPURenderer): void {
+ sharing.add(renderer);
+ if (builderPatched) return;
+ builderPatched = true;
+ const prototype = THREE.NodeBuilder.prototype as unknown as {
+ getUniformBufferLimit(this: {
+ renderer: object;
+ object?: { isInstancedMesh?: boolean };
+ }): number;
+ };
+ const limit = prototype.getUniformBufferLimit;
+ prototype.getUniformBufferLimit = function () {
+ if (sharing.has(this.renderer) && this.object?.isInstancedMesh) return 0;
+ return limit.call(this);
+ };
+}
+
+/**
+ * The view's renderer: WebGPU where the browser has it, and three's own WebGL2 backend where it does not. Everything
+ * drawn is three's node materials, so both backends run the same shaders. No power preference is passed: Chromium on
+ * Windows ignores it and warns.
+ */
+export function viewerRendererFactory(options: { forceWebGL?: boolean } = {}) {
+ return async ({ canvas }: { canvas: HTMLCanvasElement | OffscreenCanvas }) => {
+ const renderer = new THREE.WebGPURenderer({
+ canvas: canvas as HTMLCanvasElement,
+ antialias: true,
+ alpha: true,
+ forceWebGL: options.forceWebGL ?? false,
+ });
+ installReviewToneMapping(renderer);
+ await renderer.init();
+ shareInstancedShaders(renderer);
+ releases.set(renderer, trackTextures(renderer));
+ (canvas as HTMLCanvasElement).dataset.viewerBackend = viewerBackend(renderer);
+ return renderer;
+ };
+}
+
+export function viewerBackend(renderer: THREE.WebGPURenderer): ViewerBackend {
+ return (renderer.backend as unknown as { isWebGPUBackend?: boolean }).isWebGPUBackend
+ ? 'webgpu'
+ : 'webgl2';
+}
+
+/**
+ * GPU batches from which WebGPU builds ahead too. Each one is a node graph of its own, about 17 ms per pass on the
+ * page's thread, and the view and its shadow bake are two passes: 16 batches hold the page for about half a second.
+ */
+const BATCHES_BUILT_AHEAD = 16;
+
+function gpuBatches(object: THREE.Object3D): number {
+ let batches = 0;
+ object.traverse((part) => {
+ if ((part as THREE.InstancedMesh).isInstancedMesh) batches += 1;
+ });
+ return batches;
+}
+
+/**
+ * Whether drawing `object` for the first time makes the page wait for its shaders. WebGL2 compiles on the page's
+ * thread: through Direct3D a skinned mech held the page for up to 2.9 s and first drew at 4.7 s. WebGPU builds
+ * pipelines in the GPU process, and compiling there first only delayed the mech's first frame, by 1-2.7 s. Its node
+ * graphs are built on the page's thread, though, and r186 builds each `InstancedMesh`'s alone: `RenderObject` adds
+ * the object's uuid to the cache key. A cathedral with 176 batches held the page for 5.7 s in its first frame.
+ */
+export const compilesOnPageThread = (renderer: THREE.WebGPURenderer, object?: THREE.Object3D) =>
+ viewerBackend(renderer) === 'webgl2' ||
+ (object !== undefined && gpuBatches(object) >= BATCHES_BUILT_AHEAD);
+
+/**
+ * Where the page would wait on shaders, build every pipeline `object` needs before it is first drawn, culled parts
+ * included. With it nothing held the page longer than about 0.9 s while the WebGL2 mech loaded, the unskinned file's
+ * own figure, and it first drew at 3.6-4.5 s. `compileAsync` reads everything it uses before its first wait, so
+ * culling is restored as soon as it returns.
+ */
+export function compileAhead(
+ renderer: THREE.WebGPURenderer,
+ object: THREE.Object3D,
+ camera: THREE.Camera,
+ scene: THREE.Scene,
+): Promise<void> {
+ if (!compilesOnPageThread(renderer, object)) return Promise.resolve();
+ const culled: THREE.Object3D[] = [];
+ object.traverse((part) => {
+ if (!part.frustumCulled) return;
+ culled.push(part);
+ part.frustumCulled = false;
+ });
+ try {
+ return renderer.compileAsync(object, camera, scene);
+ } finally {
+ for (const part of culled) part.frustumCulled = true;
+ }
+}
+
+/** Close a view's renderer and let go of what it uploaded. */
+export function releaseViewerRenderer(renderer: THREE.WebGPURenderer) {
+ releases.get(renderer)?.();
+ releases.delete(renderer);
+ return renderer.dispose();
+}
diff --git a/site/src/lib/review-rig-three.ts b/site/src/lib/review-rig-three.ts
index e24400ec..85508bc2 100644
--- a/site/src/lib/review-rig-three.ts
+++ b/site/src/lib/review-rig-three.ts
@@ -1,21 +1,51 @@
-import * as THREE from 'three';
-import { RoomEnvironment } from 'three/examples/jsm/environments/RoomEnvironment.js';
-import { REVIEW_RIG, type RigLight, installReviewNeutral } from './review-rig';
+import { Fn, If, float, max, min, mix, vec3 } from 'three/tsl';
+import * as THREE from 'three/webgpu';
+import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';
+import { REVIEW_RIG, type RigLight, backdropLinear } from './review-rig';
+
+/** The slot the rig's mapper is installed in on each renderer (see `installReviewToneMapping`). */
+export const reviewToneMapping: THREE.ToneMapping = THREE.CustomToneMapping;
/**
- * The tone mapping of the rig, or three's own Neutral mapping when the installed three no longer has the stub
- * the rig's shader replaces (see `installReviewNeutral`). Decided once, when this module first loads, before
- * any program is compiled; the patch touches only three's `CustomToneMapping` slot, which nothing else on the
- * page uses.
+ * Review Neutral as a shader node: the same construction as `reviewNeutral` and as the engine's
+ * `render-service/src/review-tone-mapping.mjs`, adapted from three.js r186 neutralToneMapping (MIT), with the rig's
+ * constants. Both of the view's backends compile it, as they do for the render service's captures.
*/
-export const reviewToneMapping: THREE.ToneMapping = installReviewNeutral(
- THREE.ShaderChunk as unknown as Record<string, string>,
-)
- ? THREE.CustomToneMapping
- : THREE.NeutralToneMapping;
+const reviewNeutralNode = Fn(([input, exposure]: [THREE.Node<'vec3'>, THREE.Node<'float'>]) => {
+ const { offset, startCompression: start, desaturation } = REVIEW_RIG.toneMapping;
+ const colour = vec3(input).mul(exposure).toVar();
+ const minimum = min(colour.r, min(colour.g, colour.b));
+ const glare = minimum
+ .lessThan(2 * offset)
+ .select(minimum.sub(minimum.mul(minimum).div(4 * offset)), float(offset));
+ colour.subAssign(glare);
+ const peak = max(colour.r, max(colour.g, colour.b));
+ // A shader return inside If needs the explicit function layout below.
+ If(peak.lessThan(start), () => {
+ return colour;
+ });
+ const d = 1 - start;
+ const newPeak = float(1).sub(float(d * d).div(peak.add(1 - 2 * start)));
+ colour.mulAssign(newPeak.div(peak));
+ const whiteMix = float(1).sub(float(1).div(peak.sub(newPeak).mul(desaturation).add(1)));
+ return mix(colour, vec3(newPeak), whiteMix);
+}).setLayout({
+ name: 'reviewNeutralToneMapping',
+ type: 'vec3',
+ inputs: [
+ { name: 'color', type: 'vec3' },
+ { name: 'exposure', type: 'float' },
+ ],
+});
-/** True when the viewer is using the rig's own mapper rather than the fallback. */
-export const usesReviewNeutral = reviewToneMapping === THREE.CustomToneMapping;
+/** Give a renderer the rig's mapper, in three's `CustomToneMapping` slot. */
+export function installReviewToneMapping(renderer: THREE.WebGPURenderer): void {
+ (
+ renderer.library as unknown as {
+ addToneMapping(node: unknown, mapping: THREE.ToneMapping): void;
+ }
+ ).addToneMapping(reviewNeutralNode, THREE.CustomToneMapping);
+}
export type ToneMappingId = 'neutral' | 'aces' | 'linear';
@@ -57,13 +87,14 @@ export function toneMappingChoice(id: string): ToneMappingChoice {
* materials already in the scene are rebuilt for it.
*/
export function applyToneMapping(
- renderer: THREE.WebGLRenderer,
+ renderer: THREE.WebGPURenderer,
scene: THREE.Scene,
id: string,
): void {
const choice = toneMappingChoice(id);
renderer.toneMapping = choice.mapping;
renderer.toneMappingExposure = choice.exposure;
+ scene.background = backdropColour(choice.id);
scene.traverse((object) => {
const material = (object as THREE.Mesh).material as
| THREE.Material
@@ -74,6 +105,12 @@ export function applyToneMapping(
});
}
+/** The background that reads back as the rig's backdrop under the mapping named `id`. */
+const backdropColour = (id: ToneMappingId) => {
+ const [r, g, b] = backdropLinear(id);
+ return new THREE.Color().setRGB(r, g, b, THREE.LinearSRGBColorSpace);
+};
+
function directional(spec: RigLight, name: string) {
const light = new THREE.DirectionalLight(spec.color, spec.intensity);
light.name = `review-rig:${name}`;
@@ -88,8 +125,8 @@ function directional(spec: RigLight, name: string) {
* its neutral backdrop. Returns a function that removes all of it again. The lights are fixed in the world, as
* the rig's are, so orbiting the camera changes the view but not the light.
*/
-export function applyReviewRig(renderer: THREE.WebGLRenderer, scene: THREE.Scene): () => void {
- const { environment, hemisphere, exposure, backdrop } = REVIEW_RIG;
+export function applyReviewRig(renderer: THREE.WebGPURenderer, scene: THREE.Scene): () => void {
+ const { environment, hemisphere, exposure } = REVIEW_RIG;
const before = {
toneMapping: renderer.toneMapping,
exposure: renderer.toneMappingExposure,
@@ -105,7 +142,7 @@ export function applyReviewRig(renderer: THREE.WebGLRenderer, scene: THREE.Scene
const target = pmrem.fromScene(room, environment.sigma);
scene.environment = target.texture;
scene.environmentIntensity = environment.intensity;
- scene.background = new THREE.Color(backdrop);
+ scene.background = backdropColour(DEFAULT_TONE_MAPPING);
const ambient = new THREE.HemisphereLight(
hemisphere.sky,
diff --git a/site/src/lib/review-rig.ts b/site/src/lib/review-rig.ts
index dc869d6d..3fe190c8 100644
--- a/site/src/lib/review-rig.ts
+++ b/site/src/lib/review-rig.ts
@@ -71,7 +71,7 @@ export type ReviewNeutralConstants = {
readonly desaturation: number;
};
-/** The rig's tone mapping of a linear colour, exactly as its render service computes it (used to check the shader). */
+/** The rig's tone mapping of a linear colour, exactly as its render service computes it. */
export function reviewNeutral(
linear: Vec3,
exposure: number = REVIEW_RIG.exposure,
@@ -104,50 +104,89 @@ export const reviewNeutralBytes = (linear: Vec3, exposure: number = REVIEW_RIG.e
Math.round(srgbEncode(Math.min(1, Math.max(0, c))) * 255),
);
-const glslNumber = (value: number) => (Number.isInteger(value) ? value.toFixed(1) : String(value));
+const srgbDecode = (e: number) =>
+ e <= 0.04045 ? e / 12.92 : ((e + 0.055) / 1.055) ** (1 / 0.41666);
-/** The GLSL of `CustomToneMapping` for three's WebGL renderer: the same construction as `reviewNeutral`, from the same constants. */
-export function reviewNeutralGlsl(
- constants: ReviewNeutralConstants = REVIEW_RIG.toneMapping,
-): string {
- const { offset, startCompression, desaturation } = constants;
- return `// ${REVIEW_RIG.id}: Review Neutral (Khronos PBR Neutral construction, rig-calibrated constants)
-vec3 CustomToneMapping( vec3 color ) {
- const float ReviewNeutralOffset = ${glslNumber(offset)};
- const float ReviewNeutralStart = ${glslNumber(startCompression)};
- const float ReviewNeutralDesaturation = ${glslNumber(desaturation)};
- color *= toneMappingExposure;
- float x = min( color.r, min( color.g, color.b ) );
- float glare = x < 2. * ReviewNeutralOffset ? x - x * x / ( 4. * ReviewNeutralOffset ) : ReviewNeutralOffset;
- color -= glare;
- float peak = max( color.r, max( color.g, color.b ) );
- if ( peak < ReviewNeutralStart ) return color;
- float d = 1. - ReviewNeutralStart;
- float newPeak = 1. - d * d / ( peak + d - ReviewNeutralStart );
- color *= newPeak / peak;
- float g = 1. - 1. / ( ReviewNeutralDesaturation * ( peak - newPeak ) + 1. );
- return mix( color, vec3( newPeak ), g );
-}`;
+// three's ACES filmic mapping, read row-major (the engine's `render-service/src/display-transform.mjs`), inverted.
+const ACES_INPUT = [0.59719, 0.35458, 0.04823, 0.076, 0.90834, 0.01566, 0.0284, 0.13383, 0.83777];
+const ACES_OUTPUT = [
+ 1.60475, -0.53108, -0.07367, -0.10208, 1.10813, -0.00605, -0.00327, -0.07276, 1.07602,
+];
+const ACES_FIT = { a: 0.0245786, b: 0.000090537, c: 0.983729, d: 0.432951, e: 0.238081 };
+
+const multiply = (m: readonly number[], v: readonly number[]): [number, number, number] =>
+ [0, 1, 2].map(
+ (row) =>
+ (m[row * 3] as number) * (v[0] as number) +
+ (m[row * 3 + 1] as number) * (v[1] as number) +
+ (m[row * 3 + 2] as number) * (v[2] as number),
+ ) as [number, number, number];
+
+function invert3(m: readonly number[]): number[] {
+ const [a, b, c, d, e, f, g, h, i] = m as [
+ number,
+ number,
+ number,
+ number,
+ number,
+ number,
+ number,
+ number,
+ number,
+ ];
+ const A = e * i - f * h;
+ const B = -(d * i - f * g);
+ const C = d * h - e * g;
+ const det = a * A + b * B + c * C;
+ return [
+ A,
+ -(b * i - c * h),
+ b * f - c * e,
+ B,
+ a * i - c * g,
+ -(a * f - c * d),
+ C,
+ -(a * h - b * g),
+ a * e - b * d,
+ ].map((v) => v / det);
}
-/** The stub three ships for its `CustomToneMapping` slot: the only text the rig's shader replaces. */
-export const CUSTOM_TONE_MAPPING_STUB = 'vec3 CustomToneMapping( vec3 color ) { return color; }';
+/** The non-negative root of the ACES fit, which is monotonic there: one quadratic per channel. */
+function acesFitInverse(t: number) {
+ const { a, b, c, d, e } = ACES_FIT;
+ const qa = 1 - c * t;
+ const qb = a - c * d * t;
+ const qc = -(b + e * t);
+ return (-qb + Math.sqrt(qb * qb - 4 * qa * qc)) / (2 * qa);
+}
+
+function reviewNeutralInverse(display: Vec3, exposure: number): [number, number, number] {
+ const { offset, startCompression: start, desaturation } = REVIEW_RIG.toneMapping;
+ const newPeak = Math.max(...display);
+ let colour: readonly number[] = display;
+ if (newPeak >= start) {
+ const d = 1 - start;
+ const peak = 2 * start - 1 + (d * d) / (1 - newPeak);
+ const whiteMix = 1 - 1 / (desaturation * (peak - newPeak) + 1);
+ colour = display.map((c) => (((c - newPeak * whiteMix) / (1 - whiteMix)) * peak) / newPeak);
+ }
+ const minimum = Math.min(...colour);
+ const originalMinimum = minimum < offset ? Math.sqrt(4 * offset * minimum) : minimum + offset;
+ return colour.map((c) => (c + originalMinimum - minimum) / exposure) as [number, number, number];
+}
/**
- * Put Review Neutral into three's tone mapping chunk, in place of the empty `CustomToneMapping` stub. Returns
- * whether the rig's mapper is installed. It refuses (and changes nothing) when the chunk is not the text this
- * was written against, so a three upgrade falls back to three's own Neutral mapping instead of a broken shader.
- * Idempotent. `chunks` is three's `ShaderChunk` object; nothing else about three is modified.
+ * The linear clear colour that comes out of the output pass as the rig's backdrop. The scene background is cleared into
+ * the same framebuffer as the model and tone mapped with it, so a plain colour would come out shifted. Compositing the
+ * backdrop afterwards would leave a fringe on every silhouette, so it stays in the pass and this answers what goes in,
+ * as the engine's `backdropClearColor` does for its captures.
*/
-export function installReviewNeutral(
- chunks: Record<string, string>,
- constants: ReviewNeutralConstants = REVIEW_RIG.toneMapping,
-): boolean {
- const chunk = chunks.tonemapping_pars_fragment;
- if (typeof chunk !== 'string') return false;
- if (chunk.includes('ReviewNeutralOffset')) return true;
- if (!chunk.includes(CUSTOM_TONE_MAPPING_STUB)) return false;
- const glsl = reviewNeutralGlsl(constants);
- chunks.tonemapping_pars_fragment = chunk.replace(CUSTOM_TONE_MAPPING_STUB, () => glsl);
- return true;
+export function backdropLinear(mapping: 'neutral' | 'aces' | 'linear'): [number, number, number] {
+ const display = [1, 3, 5].map((at) =>
+ srgbDecode(Number.parseInt(REVIEW_RIG.backdrop.slice(at, at + 2), 16) / 255),
+ ) as [number, number, number];
+ if (mapping === 'neutral') return reviewNeutralInverse(display, REVIEW_RIG.exposure);
+ if (mapping === 'linear') return display;
+ const fitted = multiply(invert3(ACES_OUTPUT), display).map(acesFitInverse);
+ return multiply(invert3(ACES_INPUT), fitted).map((c) => c * 0.6) as [number, number, number];
}
diff --git a/site/src/lib/three-runtime.ts b/site/src/lib/three-runtime.ts
new file mode 100644
index 00000000..3431ac5c
--- /dev/null
+++ b/site/src/lib/three-runtime.ts
@@ -0,0 +1,60 @@
+import { Timer } from 'three/webgpu';
+
+/**
+ * What bare `three` resolves to in the site's client code (`astro.config.mjs`): the WebGPU build, so the viewer, its
+ * loaders and React Three Fiber share one copy of three's classes. The scene kit's facade does the same for the scenes.
+ * That build has no `Clock` or `WebGLRenderer`, and React Three Fiber names both.
+ */
+export * from 'three/webgpu';
+
+export class Clock {
+ autoStart: boolean;
+ startTime = 0;
+ oldTime = 0;
+ elapsedTime = 0;
+ running = false;
+ private readonly timer = new Timer();
+
+ constructor(autoStart = true) {
+ this.autoStart = autoStart;
+ }
+
+ start(): void {
+ this.startTime = performance.now();
+ this.oldTime = this.startTime;
+ this.elapsedTime = 0;
+ this.running = true;
+ this.timer.reset();
+ }
+
+ stop(): void {
+ this.getElapsedTime();
+ this.running = false;
+ this.autoStart = false;
+ }
+
+ getDelta(): number {
+ if (this.autoStart && !this.running) {
+ this.start();
+ return 0;
+ }
+ if (!this.running) return 0;
+ this.timer.update();
+ const delta = this.timer.getDelta();
+ this.oldTime = performance.now();
+ this.elapsedTime += delta;
+ return delta;
+ }
+
+ getElapsedTime(): number {
+ this.getDelta();
+ return this.elapsedTime;
+ }
+}
+
+/** The classic renderer is not in this build. A canvas given no renderer factory fails here, by name. */
+export class WebGLRenderer {
+ constructor() {
+ throw new Error('The 3D view needs its WebGPU renderer factory (viewer-renderer.ts).');
+ }
+}