3D engine that AI agents drive
Add the KTX2 measurement for AnisotropyBarnLamp (part of #304)
Nguyen Xuan An42acb6c1bf90
diff --git a/bench/ktx2/measure.mjs b/bench/ktx2/measure.mjsnew file mode 100644index 00000000..83c4229a--- /dev/null+++ b/bench/ktx2/measure.mjs@@ -0,0 +1,108 @@+// Measures KTX2 upload (issue #304) with Khronos's AnisotropyBarnLamp, in the PNG and the KHR_texture_basisu variant.+// gpu-lock: bash ~/.agents/tools/gpu-lock.sh node bench/ktx2/measure.mjs+// Downloads the glTF files (CC BY 4.0, Analytical Graphics, Inc. and Wayfair, LLC) into the gitignored artifacts/ktx2/, never committed.+// Per backend (the RTX GPU, then SwiftShader) it loads each variant three times and records the formats, the texture bytes the+// engine accounts for and the load time. On the GPU it also draws both variants through the Khronos framing of the reference+// suite into artifacts/ktx2/render/<variant>/, ready for score.py (see the README of bench/reference).+import { mkdir, writeFile, access } from 'node:fs/promises';+import { constants, setPriority } from 'node:os';+import { chromium } from 'playwright';+import { createServer } from 'vite';++const CHROME = process.env.CHROME_PATH ?? 'C:/Program Files/Google/Chrome/Application/chrome.exe';+const SOURCE = 'https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/AnisotropyBarnLamp';+const ASSET_DIRECTORY = 'artifacts/ktx2/AnisotropyBarnLamp';+const VARIANT_FILES = {+ png: ['glTF', ['AnisotropyBarnLamp.gltf', 'AnisotropyBarnLamp.bin', 'AnisotropyBarnLamp_anisotropy.png', 'AnisotropyBarnLamp_basecolor.png', 'AnisotropyBarnLamp_normalbump.png', 'AnisotropyBarnLamp_occlusionroughnessmetal.png']],+ ktx2: ['glTF-KTX-BasisU', ['AnisotropyBarnLamp.gltf', 'AnisotropyBarnLamp.bin', 'AnisotropyBarnLamp_anisotropy.ktx2', 'AnisotropyBarnLamp_basecolor.ktx2', 'AnisotropyBarnLamp_normalbump.ktx2', 'AnisotropyBarnLamp_occlusionroughnessmetal.ktx2']],+};+const BACKENDS = {+ gpu: ['--enable-webgl', '--ignore-gpu-blocklist', '--disable-renderer-backgrounding'],+ swiftshader: ['--enable-webgl', '--ignore-gpu-blocklist', '--use-angle=swiftshader', '--enable-unsafe-swiftshader'],+};+const LOAD_REPEATS = 3;++async function exists(path) {+ try {+ await access(path, constants.F_OK);+ return true;+ } catch {+ return false;+ }+}++async function download() {+ for (const [variant, [folder, names]] of Object.entries(VARIANT_FILES)) {+ await mkdir(`${ASSET_DIRECTORY}/${variant}`, { recursive: true });+ for (const name of names) {+ const target = `${ASSET_DIRECTORY}/${variant}/${name}`;+ if (await exists(target)) continue;+ const response = await fetch(`${SOURCE}/${folder}/${name}`);+ if (!response.ok) throw new Error(`${name}: HTTP ${response.status}`);+ await writeFile(target, Buffer.from(await response.arrayBuffer()));+ }+ }+}++function summarize(asset) {+ const byFormat = {};+ for (const texture of asset.textureFormats) byFormat[texture.format] = (byFormat[texture.format] ?? 0) + 1;+ return {+ formats: byFormat,+ textures: asset.textureFormats.map(({ format, width, height, colorSpace, bytes }) => ({ format, width, height, colorSpace, bytes })),+ totalBytes: asset.textureFormats.reduce((sum, texture) => sum + texture.bytes, 0),+ };+}++setPriority(0, constants.priority.PRIORITY_BELOW_NORMAL);+await download();+const server = await createServer({ server: { host: '127.0.0.1', port: 0, fs: { strict: false } }, logLevel: 'silent' });+await server.listen();+const serverUrl = `http://127.0.0.1:${server.httpServer.address().port}`;+const report = {};+try {+ for (const [backend, args] of Object.entries(BACKENDS)) {+ const browser = await chromium.launch({ executablePath: CHROME, headless: true, args });+ try {+ const page = await browser.newPage({ viewport: { width: 960, height: 540 } });+ page.on('pageerror', error => console.log('PAGE ERROR', error.message));+ await page.goto(`${serverUrl}/bench/reference/harness.html?set=ktx2`, { timeout: 180000 });+ await page.waitForFunction(() => window.loadBarnLampVariant, null, { timeout: 180000 });+ const result = await page.evaluate(async repeats => {+ const context = document.createElement('canvas').getContext('webgl2');+ const debug = context.getExtension('WEBGL_debug_renderer_info');+ const variants = {};+ for (const variant of ['png', 'ktx2']) {+ const seconds = [];+ let last = null;+ for (let run = 0; run < repeats; run++) {+ const start = performance.now();+ last = await window.loadBarnLampVariant(variant);+ seconds.push((performance.now() - start) / 1000);+ }+ variants[variant] = { seconds, workerConfig: last.workerConfig, textureFormats: last.asset.textureFormats };+ }+ return { renderer: context.getParameter(debug ? debug.UNMASKED_RENDERER_WEBGL : context.RENDERER), variants };+ }, LOAD_REPEATS);+ report[backend] = { renderer: result.renderer, variants: {} };+ for (const [variant, data] of Object.entries(result.variants)) {+ const { textureFormats, seconds, workerConfig } = data;+ report[backend].variants[variant] = { seconds, workerConfig, ...summarize({ textureFormats }) };+ }+ if (backend === 'gpu') {+ for (const variant of ['png', 'ktx2']) {+ const rendered = await page.evaluate(sceneId => window.renderReferenceScene(sceneId, { describe: false }), `AnisotropyBarnLamp-${variant}`);+ if (rendered.glError !== 0) throw new Error(`${variant} gave WebGL error ${rendered.glError}.`);+ await mkdir(`artifacts/ktx2/render/${variant}`, { recursive: true });+ await writeFile(`artifacts/ktx2/render/${variant}/AnisotropyBarnLamp-gpu.png`, Buffer.from(rendered.image, 'base64'));+ }+ }+ } finally {+ await browser.close();+ }+ }+} finally {+ await server.close();+}+await writeFile('artifacts/ktx2/result.json', JSON.stringify(report, null, 1));+console.log(JSON.stringify(report, (key, value) => (key === 'textures' ? undefined : value), 1));diff --git a/bench/reference/harness.js b/bench/reference/harness.jsindex d1375af5..faa49269 100644--- a/bench/reference/harness.js+++ b/bench/reference/harness.js@@ -1,6 +1,6 @@// Runs in the page: draws one reference scene, and describes it as plain data for Blender.import { Renderer67 } from '/src/renderer.js';-import { REFERENCE_SCENES, KHRONOS_SCENES, CLOTH_SCENES } from './scenes.js';+import { REFERENCE_SCENES, KHRONOS_SCENES, KTX2_SCENES, loadBarnLampVariant, CLOTH_SCENES } from './scenes.js';import { GRAND_SCENES } from './grand-scenes.js';import { LOOK_OPTIONS } from './look-options.js';import { skinnedGeometry } from '/src/path-tracer-scene.js';@@ -30,7 +30,7 @@ const WATER_REFLECTION = { off: false, ssr: 'ssr' }[new URLSearchParams(location// ?set=khronos draws the Khronos sample assets (npm run reference -- --khronos) and ?set=cloth the cloth scenes// (npm run reference -- --cloth) instead of the fixed scenes.-const SCENE_SETS = { khronos: KHRONOS_SCENES, cloth: CLOTH_SCENES, grand: GRAND_SCENES, look: LOOK_OPTIONS };+const SCENE_SETS = { khronos: KHRONOS_SCENES, ktx2: KTX2_SCENES, cloth: CLOTH_SCENES, grand: GRAND_SCENES, look: LOOK_OPTIONS };const SCENES = SCENE_SETS[new URLSearchParams(location.search).get('set')] ?? REFERENCE_SCENES;function encodeBytes(typedArray) {@@ -300,5 +300,6 @@ async function renderRecipePathTraced(recipe, options) {window.renderRecipePathTraced = renderRecipePathTraced;window.renderReferenceScene = renderReferenceScene;+window.loadBarnLampVariant = loadBarnLampVariant;window.renderReferencePathTraced = renderReferencePathTraced;window.referenceSceneIds = Object.keys(SCENES);diff --git a/bench/reference/scenes.js b/bench/reference/scenes.jsindex 56d4bcc4..580fa4fe 100644--- a/bench/reference/scenes.js+++ b/bench/reference/scenes.js@@ -2,7 +2,8 @@// Each builder returns parts, a camera and lighting. render-blender.py builds the same scene from a dump of this data.import { box, cylinder, sphere, torus } from '/src/geometry.js';import { createEnvironmentMap, parseRadianceHdr } from '/src/hdri.js';-import { parseGltf } from '/src/gltf.js';+import { parseGltf, loadGltf, ktx2WorkerConfigFor } from '/src/gltf.js';+import { KTX2Loader } from 'three/addons/loaders/KTX2Loader.js';import { createTree, scatterVegetation, selectLevels, vegetationParts } from '/src/vegetation.js';import { createNoiseHeight, createTerrain } from '/src/terrain.js';import { createAgentScene, loadAgentSceneModules } from '/src/agent-scene.js';@@ -158,11 +159,8 @@ function cameraAroundBounds({ minimum, maximum }) {return { center, radius, camera: { eye, target: center, up: [0, 1, 0], fov: KHRONOS_FIELD_OF_VIEW, near: distance / 100, far: distance * 10 } };}-async function khronosAssetScene(name) {+async function khronosSceneFromAsset(asset, file) {const lighting = await skyLighting();- const file = `artifacts/khronos/${name}/${name}.glb`;- const response = await fetch(`/${file}`);- const asset = await parseGltf(await response.arrayBuffer());const { center, radius, camera } = cameraAroundBounds(worldBounds(asset.parts));return {parts: asset.parts, glb: file, blenderWorld: lighting.blenderWorld,@@ -172,6 +170,12 @@ async function khronosAssetScene(name) {};}+async function khronosAssetScene(name) {+ const file = `artifacts/khronos/${name}/${name}.glb`;+ const response = await fetch(`/${file}`);+ return khronosSceneFromAsset(await parseGltf(await response.arrayBuffer()), file);+}+export const KHRONOS_SCENES = Object.fromEntries(KHRONOS_ASSET_NAMES.map(name => [name, () => khronosAssetScene(name)]));// Grand scenes: the scale people actually want to draw, built from the engine's terrain, vegetation and plain boxes.@@ -1061,3 +1065,36 @@ export const CLOTH_SCENES = {'drape-1s': () => clothScene({ kind: 'drape', seconds: 1 }),'drape-2s': () => clothScene({ kind: 'drape', seconds: 2 }),};++// Issue #304: the same AnisotropyBarnLamp as the suite's GLB, as the separate-file glTF with PNG textures and as the+// KHR_texture_basisu variant (bench/ktx2/measure.mjs downloads both into artifacts/ktx2/). Drawn through the Khronos+// framing, so they score against the suite's stored Cycles array. They are a set of their own and never reach baseline.json.+const KTX2_ASSET_DIRECTORY = 'artifacts/ktx2/AnisotropyBarnLamp';+const BASIS_TRANSCODER_PATH = '/node_modules/three/examples/jsm/libs/basis/';++// Loads one variant the way an app does and returns the asset with the format of the context that decoded it.+export async function loadBarnLampVariant(directoryName) {+ const url = `/${KTX2_ASSET_DIRECTORY}/${directoryName}/AnisotropyBarnLamp.gltf`;+ const decoders = {};+ let loader = null;+ let workerConfig = null;+ if (directoryName === 'ktx2') {+ loader = new KTX2Loader().setTranscoderPath(BASIS_TRANSCODER_PATH);+ workerConfig = ktx2WorkerConfigFor(document.createElement('canvas').getContext('webgl2'));+ loader.workerConfig = workerConfig;+ decoders.ktx2 = loader;+ }+ const asset = await loadGltf(url, { decoders });+ loader?.dispose();+ return { asset, workerConfig, url };+}++async function ktx2VariantScene(directoryName) {+ const { asset, url } = await loadBarnLampVariant(directoryName);+ return khronosSceneFromAsset(asset, url.slice(1));+}++export const KTX2_SCENES = {+ 'AnisotropyBarnLamp-png': () => ktx2VariantScene('png'),+ 'AnisotropyBarnLamp-ktx2': () => ktx2VariantScene('ktx2'),+};