diff --git a/frameworks/blits/src/App.js b/frameworks/blits/src/App.js index dc87d01..8c1efb7 100644 --- a/frameworks/blits/src/App.js +++ b/frameworks/blits/src/App.js @@ -20,6 +20,7 @@ import Blits from '@lightningjs/blits' import Benchmark from './pages/Benchmark.js' import Memory from './pages/Memory.js' import Rectangles from './pages/Rectangles.js' +import Images from './pages/Images.js' import symbols from '@lightningjs/blits/symbols' import { setRenderer } from './perf.js' @@ -37,6 +38,7 @@ export default Blits.Application({ // cold-startup measurement instead of the throughput sequence. { path: '/startup', component: Benchmark }, { path: '/rectangles', component: Rectangles }, + { path: '/images', component: Images }, ], hooks: { async ready() { diff --git a/frameworks/blits/src/pages/Images.js b/frameworks/blits/src/pages/Images.js new file mode 100644 index 0000000..0c94341 --- /dev/null +++ b/frameworks/blits/src/pages/Images.js @@ -0,0 +1,62 @@ +/* + * Copyright 2024 Comcast Cable Communications Management, LLC + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +import Blits from '@lightningjs/blits' +import { runImageBenchmark } from '../../../../shared/imageBenchmark.js' +import { createBlitsImageLoader, blitsImageEventReceived } from '../../../../shared/imagePlatformAdapters.js' + +export default Blits.Component('Images', { + template: ` + + + + `, + state() { + return { + images: [], + imageLoadedCount: 0, + imageErrorCount: 0, + } + }, + hooks: { + ready() { + runImageBenchmark({ + loadImages: createBlitsImageLoader(this), + }).catch((error) => console.error('Image benchmark failed:', error)) + }, + }, + methods: { + onImageLoaded() { + this.imageLoadedCount++ + blitsImageEventReceived(this) + }, + onImageError() { + this.imageErrorCount++ + blitsImageEventReceived(this) + }, + }, +}) diff --git a/frameworks/ftl-canvas-bitmap/index.html b/frameworks/ftl-canvas-bitmap/index.html index e4b12ce..8e27585 100644 --- a/frameworks/ftl-canvas-bitmap/index.html +++ b/frameworks/ftl-canvas-bitmap/index.html @@ -14,7 +14,7 @@ - + \ No newline at end of file diff --git a/frameworks/ftl-canvas-bitmap/index.js b/frameworks/ftl-canvas-bitmap/index.js index ce1e8e5..1530dc6 100644 --- a/frameworks/ftl-canvas-bitmap/index.js +++ b/frameworks/ftl-canvas-bitmap/index.js @@ -8,6 +8,7 @@ import { warmup } from '../../shared/utils/warmup.js'; import { reportStartup } from '../../shared/utils/startup.js'; import { run } from '../../shared/utils/run.js'; import { runFtlRectangleBenchmark } from '../../shared/rectanglePlatformAdapters.js'; +import { runFtlImageBenchmark } from '../../shared/imagePlatformAdapters.js'; const canvas = document.querySelector('canvas') @@ -36,7 +37,7 @@ const app = renderer({ numImageWorkers: 0, } }); -const { root, createElement, createText, signals, loadFont } = app; +const { root, createElement, createText, createImage, signals, loadFont } = app; const fontLoadedPromise = loadFont('bitmap', { family: 'ArialBMF', @@ -379,6 +380,8 @@ fontLoadedPromise.then(() => { runStartupBenchmark(); } else if (hash === 'rectangles') { runFtlRectangleBenchmark({ app, root: rootNode, signals, createElement }); + } else if (hash === 'images') { + runFtlImageBenchmark({ root, createElement, createImage }); } else { runBenchmark(); } diff --git a/frameworks/ftl-canvas/index.html b/frameworks/ftl-canvas/index.html index e4b12ce..8e27585 100644 --- a/frameworks/ftl-canvas/index.html +++ b/frameworks/ftl-canvas/index.html @@ -14,7 +14,7 @@ - + \ No newline at end of file diff --git a/frameworks/ftl-canvas/index.js b/frameworks/ftl-canvas/index.js index e9f5254..cb69761 100644 --- a/frameworks/ftl-canvas/index.js +++ b/frameworks/ftl-canvas/index.js @@ -8,6 +8,7 @@ import { warmup } from '../../shared/utils/warmup.js'; import { reportStartup } from '../../shared/utils/startup.js'; import { run } from '../../shared/utils/run.js'; import { runFtlRectangleBenchmark } from '../../shared/rectanglePlatformAdapters.js'; +import { runFtlImageBenchmark } from '../../shared/imagePlatformAdapters.js'; const canvas = document.querySelector('canvas') if (window.location.hash === '#rectangles') { @@ -34,7 +35,7 @@ const app = renderer({ maxTextureCount: 4096, } }); -const { root, createElement, createText, signals } = app; +const { root, createElement, createText, createImage, signals } = app; const colours = [ [1.0, 0.0, 0.0, 1.0], // red @@ -366,6 +367,8 @@ if (hash === 'memory') { runStartupBenchmark(); } else if (hash === 'rectangles') { runFtlRectangleBenchmark({ app, root: rootNode, signals, createElement }); +} else if (hash === 'images') { + runFtlImageBenchmark({ root, createElement, createImage }); } else { runBenchmark(); } diff --git a/frameworks/ftl-webgl-bitmap/index.html b/frameworks/ftl-webgl-bitmap/index.html index e4b12ce..8e27585 100644 --- a/frameworks/ftl-webgl-bitmap/index.html +++ b/frameworks/ftl-webgl-bitmap/index.html @@ -14,7 +14,7 @@ - + \ No newline at end of file diff --git a/frameworks/ftl-webgl-bitmap/index.js b/frameworks/ftl-webgl-bitmap/index.js index 7eb0b0a..937931f 100644 --- a/frameworks/ftl-webgl-bitmap/index.js +++ b/frameworks/ftl-webgl-bitmap/index.js @@ -10,6 +10,7 @@ import { warmup } from '../../shared/utils/warmup.js'; import { reportStartup } from '../../shared/utils/startup.js'; import { run } from '../../shared/utils/run.js'; import { runFtlRectangleBenchmark } from '../../shared/rectanglePlatformAdapters.js'; +import { runFtlImageBenchmark } from '../../shared/imagePlatformAdapters.js'; const borderShader = createShader(BorderShader); borderShader.width = 1; @@ -45,7 +46,7 @@ const app = renderer({ numImageWorkers: 0, } }); -const { root, createElement, createText, signals, loadFont } = app; +const { root, createElement, createText, createImage, signals, loadFont } = app; const fontLoadedPromise = loadFont('bitmap', { family: 'ArialBMF', @@ -388,6 +389,8 @@ fontLoadedPromise.then(() => { runStartupBenchmark(); } else if (hash === 'rectangles') { runFtlRectangleBenchmark({ app, root: rootNode, signals, createElement, RectShader: BorderShader, createShader, rectShader: borderShader }); + } else if (hash === 'images') { + runFtlImageBenchmark({ root, createElement, createImage }); } else { runBenchmark(); } diff --git a/frameworks/ftl/index.html b/frameworks/ftl/index.html index e4b12ce..8e27585 100644 --- a/frameworks/ftl/index.html +++ b/frameworks/ftl/index.html @@ -14,7 +14,7 @@ - + \ No newline at end of file diff --git a/frameworks/ftl/index.js b/frameworks/ftl/index.js index 2ab95aa..412fa89 100644 --- a/frameworks/ftl/index.js +++ b/frameworks/ftl/index.js @@ -10,6 +10,7 @@ import { warmup } from '../../shared/utils/warmup.js'; import { reportStartup } from '../../shared/utils/startup.js'; import { run } from '../../shared/utils/run.js'; import { runFtlRectangleBenchmark } from '../../shared/rectanglePlatformAdapters.js'; +import { runFtlImageBenchmark } from '../../shared/imagePlatformAdapters.js'; const outlineShader = createShader(OutlineShader); outlineShader.width = 1; @@ -47,7 +48,7 @@ const app = renderer({ numImageWorkers: 0 } }); -const { root, createElement, createText, signals, loadFont } = app; +const { root, createElement, createText, createImage, signals, loadFont } = app; const colours = [ @@ -401,6 +402,8 @@ if (hash === 'memory') { runStartupBenchmark(); } else if (hash === 'rectangles') { runFtlRectangleBenchmark({ app, root: rootNode, signals, createElement, RectShader: OutlineShader, createShader, rectShader: outlineShader }); +} else if (hash === 'images') { + runFtlImageBenchmark({ root, createElement, createImage }); } else { runBenchmark(); } diff --git a/frameworks/lightning2-core/index.js b/frameworks/lightning2-core/index.js index aed309d..6481b24 100644 --- a/frameworks/lightning2-core/index.js +++ b/frameworks/lightning2-core/index.js @@ -10,6 +10,7 @@ import { warmup } from '../../shared/utils/warmup'; import { reportStartup } from '../../shared/utils/startup.js'; import { run } from '../../shared/utils/run.js'; import { runRectangleBenchmark } from '../../shared/rectangleBenchmark.js'; +import { runLightning2ImageBenchmark } from '../../shared/imagePlatformAdapters.js'; // apply CSS styling const style = document.createElement('style'); @@ -82,6 +83,8 @@ export class App extends Lightning.Application { const hash = window.location.hash.substring(1); if (hash === 'rectangles') { this.runRectangleBenchmark(); + } else if (hash === 'images') { + this.runImageBenchmark(); } else if (hash === 'memory') { console.log('Running memory benchmark'); this.createMemoryBenchmark(); @@ -93,6 +96,10 @@ export class App extends Lightning.Application { } } + async runImageBenchmark() { + await runLightning2ImageBenchmark({ Lightning, app: this }); + } + async runRectangleBenchmark() { const items = this.tag('Items').childList; await runRectangleBenchmark({ diff --git a/frameworks/lightning2/index.js b/frameworks/lightning2/index.js index 967a240..8a82397 100644 --- a/frameworks/lightning2/index.js +++ b/frameworks/lightning2/index.js @@ -9,6 +9,7 @@ import { warmup } from '../../shared/utils/warmup.js'; import { reportStartup } from '../../shared/utils/startup.js'; import { run } from '../../shared/utils/run.js'; import { runRectangleBenchmark } from '../../shared/rectangleBenchmark.js'; +import { runLightning2ImageBenchmark } from '../../shared/imagePlatformAdapters.js'; // apply CSS styling const style = document.createElement('style'); @@ -130,6 +131,8 @@ export class App extends Lightning.Application { const hash = window.location.hash.substring(1); if (hash === 'rectangles') { this.runRectangleBenchmark(); + } else if (hash === 'images') { + this.runImageBenchmark(); } else if (hash === 'memory') { console.log('Running memory benchmark'); this.createMemoryBenchmark(); @@ -141,6 +144,10 @@ export class App extends Lightning.Application { } } + async runImageBenchmark() { + await runLightning2ImageBenchmark({ Lightning, app: this }); + } + async runRectangleBenchmark() { const items = this.tag('Items').childList; await runRectangleBenchmark({ diff --git a/frameworks/renderer-canvasfonts/index.js b/frameworks/renderer-canvasfonts/index.js index 6ee4cb7..8bfde27 100644 --- a/frameworks/renderer-canvasfonts/index.js +++ b/frameworks/renderer-canvasfonts/index.js @@ -25,6 +25,7 @@ import { waitUntilIdle } from '../../shared/utils/waitUntilIdle.js'; import { reportStartup } from '../../shared/utils/startup.js'; import { run } from '../../shared/utils/run.js'; import { runRendererRectangleBenchmark } from '../../shared/rectanglePlatformAdapters.js'; +import { runRendererImageBenchmark } from '../../shared/imagePlatformAdapters.js'; const rectangleMode = window.location.hash === '#rectangles'; const appHeight = rectangleMode ? 540 : 1080; @@ -385,6 +386,8 @@ if (hash === 'memory') { runStartupBenchmark(); } else if (hash === 'rectangles') { runRendererRectangleBenchmark(renderer, rootNode); +} else if (hash === 'images') { + runRendererImageBenchmark(renderer, rootNode); } else { runBenchmark(); } diff --git a/frameworks/renderer/index.js b/frameworks/renderer/index.js index 3f45cff..a97fcd4 100644 --- a/frameworks/renderer/index.js +++ b/frameworks/renderer/index.js @@ -26,6 +26,7 @@ import { waitUntilIdle } from '../../shared/utils/waitUntilIdle.js'; import { reportStartup } from '../../shared/utils/startup.js'; import { run } from '../../shared/utils/run.js'; import { runRendererRectangleBenchmark } from '../../shared/rectanglePlatformAdapters.js'; +import { runRendererImageBenchmark } from '../../shared/imagePlatformAdapters.js'; const rectangleMode = window.location.hash === '#rectangles'; const appHeight = rectangleMode ? 540 : 1080; @@ -407,6 +408,8 @@ if (hash === 'memory') { runStartupBenchmark(); } else if (hash === 'rectangles') { runRendererRectangleBenchmark(renderer, rootNode, Border); +} else if (hash === 'images') { + runRendererImageBenchmark(renderer, rootNode); } else { runBenchmark(); } diff --git a/index.js b/index.js index 1954c8d..ce1f2f9 100644 --- a/index.js +++ b/index.js @@ -29,6 +29,7 @@ import { processResults, processStartupResults } from "./testrunner/processResul import { writeResults } from "./testrunner/writeResults.js"; import { getJavaScriptBundleSize } from "./testrunner/totalBundlefileSize.js"; import { runRectangleBenchmarks } from "./testrunner/runRectangles.js"; +import { runImageBenchmarks } from "./testrunner/runImages.js"; /** @@ -48,6 +49,7 @@ if (args.includes('--results') || args.includes('-r')) { */ const startupOnlyFlag = args.includes('--startup-only'); const rectanglesOnlyFlag = args.includes('--rectangles'); +const imagesOnlyFlag = args.includes('--images'); /** * Checks if the './dist' directory exists. @@ -114,6 +116,8 @@ const lookupFrameworkVersion = (dir) => { */ const dirs = fs.readdirSync('./dist', { withFileTypes: true }) .filter(dirent => dirent.isDirectory()) + // skip non-framework dirs such as dist/images (benchmark image assets) + .filter(dirent => fs.existsSync(`./dist/${dirent.name}/index.html`)) .map(dirent => dirent.name); /** @@ -165,6 +169,7 @@ let fileSizeResults = null; */ let startupResults = null; const rectangleResults = {}; +const imageResults = {}; let idx = 0; /** @@ -178,6 +183,11 @@ if (rectanglesOnlyFlag) { process.exit(0); } +if (imagesOnlyFlag) { + await runImageBenchmarks(dirs, browserVersion); + process.exit(0); +} + /** * Initializes the results object. * @typedef {import('./testrunner/types/results.js').Result} Result @@ -236,6 +246,10 @@ const run = async (dir) => { console.log(`Running rectangle rendering benchmarks for ${dir}...`); const frameworkRectangles = await runRectangleBenchmarks([dir], browserVersion); Object.assign(rectangleResults, frameworkRectangles.results); + + console.log(`Running image loading benchmarks for ${dir}...`); + const frameworkImages = await runImageBenchmarks([dir], browserVersion); + Object.assign(imageResults, frameworkImages.results); } idx++; @@ -279,7 +293,7 @@ const run = async (dir) => { return; } - const processedResults = processResults(results, memoryResults, fileSizeResults, startupResults, rectangleResults); + const processedResults = processResults(results, memoryResults, fileSizeResults, startupResults, rectangleResults, imageResults); console.log('All benchmarks done!'); console.log('Processed results:'); console.log(processedResults); diff --git a/package.json b/package.json index 702e8fd..2706040 100644 --- a/package.json +++ b/package.json @@ -11,7 +11,8 @@ "setup:playwright": "npx playwright install", "start": "concurrently --kill-others --success last \"npx http-server -c-1 ./dist/\" \"node index.js\"", "start:official": "concurrently --kill-others --success last \"npx http-server -c-1 ./dist/\" \"node index.js --results\"", - "rectangles": "node index.js --rectangles" + "rectangles": "node index.js --rectangles", + "images": "node index.js --images" }, "author": "", "license": "MIT", diff --git a/readme.md b/readme.md index 4208fa6..7d17106 100644 --- a/readme.md +++ b/readme.md @@ -112,6 +112,51 @@ accepts `RECTANGLE_FRAMEWORKS=ftl,renderer` to select a subset and `RECTANGLE_SAMPLE_MS`, and `RECTANGLE_SAMPLES` adjust the sample timings (use short values for a smoke test, not for comparable performance results). +## Image loading benchmark + +The image loading benchmark is included automatically in the **full benchmark +run** (`npm start` / `npm run start:official`), right after the rectangle +benchmark, and adds an image-loading section to the same HTML results overview. +It is reported separately and does not change the duration-based weighted score. +`--startup-only` skips it. + +Each framework loads local images and the slice ends when every +texture-loaded/texture-failed event has fired. Images are served from +`dist/images/` (the runner copies `shared/images/`, taken from +`../renderer/examples/assets`, there before launching, so everything is local +with no internet image variance). Every load uses a **unique URL** (a +query-string suffix), so no framework texture cache or browser HTTP cache can +serve a warm entry. Each framework loads **1, 5, 25 and 100 images** per slice, +with **5 warmup loads** followed by 5 measured loads per count (like the other +benchmarks, **6x CPU throttling** is applied before navigation). All framework +apps/canvases are aligned to the same 1920x1080 size (the image runner uses a +1920x1080 viewport to match), and loaded images are rendered on a +non-overlapping grid across that area (each image gets its own cell, so +nothing covers anything else). FTL places every image on the same z-layer +(`zIndex: 0`) so they file into a single z-bucket and batch into one draw +call per frame. The measured +value is the wall-clock milliseconds from issuing the loads until the last +texture-loaded event. Per +framework the exit point is the framework's own load event: texture `loaded` +(Lightning 3 renderer — the node event is suppressed for 1x1 textures, so keep +assets larger than 1x1), texture `signals.loaded` (FTL), element `txLoaded` +(Lightning 2) and `@loaded` (Blits). + +Results are saved as `results/images_.json` and printed as a +table. Each framework runs in its own fresh browser process with a default +timeout of 10 minutes (`IMAGE_TIMEOUT_MS`); a failure is recorded as an error +and does not stop the remaining frameworks. + +For focused troubleshooting, `npm run images` (or `node index.js --images`) +runs only the image suite and saves its raw JSON. + +Environment knobs: `IMAGE_FRAMEWORKS=ftl,renderer-local` selects frameworks, +`IMAGE_COUNTS=1,5,25,100` selects counts, `IMAGE_WARMUPS` / `IMAGE_SAMPLES` +adjust warmup/measured runs per count (use short values for a smoke test, not +for comparable results), `IMAGE_ASSETS_DIR` overrides the local image source +directory, and `IMAGE_BASE_URL` overrides the server root (default +`http://localhost:8080`). Set `HEADLESS=true` to run Chromium headlessly. + ## Why not use js-framework-benchmark Two reasons: diff --git a/shared/imageBenchmark.js b/shared/imageBenchmark.js new file mode 100644 index 0000000..00f6fe0 --- /dev/null +++ b/shared/imageBenchmark.js @@ -0,0 +1,158 @@ +/** + * Shared image-loading benchmark. Each platform adapter provides a + * `loadImages(urls)` function that starts loading every URL and resolves + * once every texture-loaded/texture-failed event has fired. The benchmark + * measures wall-clock time from issuing the loads until the last load event. + * + * Every load uses a unique URL (query-string suffix), so no framework + * texture cache or browser HTTP cache can serve a warm entry. Images are + * served locally from `dist/images/` (copied there by the runner from + * `shared/images/`), so no internet access or image variance is involved. + * + * CPU throttling is configured by the Playwright runner before navigation. + */ +export const IMAGE_COUNTS = [1, 5, 25, 100]; +export const IMAGE_WARMUPS = 5; +export const IMAGE_SAMPLES = 5; + +/** + * App-area layout for rendered images. Every framework app runs at + * 1920x1080 outside rectangle mode, so loaded images are placed on a grid + * inside this area and never cover each other. + */ +export const IMAGE_LAYOUT = { width: 1920, height: 1080, maxImageSize: 160 }; + +const getInjectedConfig = () => { + if (typeof window === 'undefined') return {}; + return window.__IMAGE_BENCHMARK_CONFIG__ ?? {}; +}; + +/** + * Build `count` unique image URLs, cycling through `files`. `offset` makes + * every URL unique across warmup and measured runs of the whole suite. + */ +export const buildImageUrls = (files, count, offset = 0, baseUrl = '../images') => { + const urls = []; + for (let i = 0; i < count; i++) { + const file = files[(offset + i) % files.length]; + urls.push(`${baseUrl}/${file}?i=${offset + i}`); + } + return urls; +}; + +/** + * Build `count` load items: unique src per item plus a grid position/size + * inside `area` so rendered images are spread out and never overlap. + * Columns/rows are chosen to keep cells close to the area's aspect ratio. + */ +export const buildImageLayout = (files, count, offset = 0, baseUrl = '../images', area = IMAGE_LAYOUT) => { + const cols = Math.max(1, Math.ceil(Math.sqrt((count * area.width) / area.height))); + const rows = Math.max(1, Math.ceil(count / cols)); + const cellW = area.width / cols; + const cellH = area.height / rows; + const size = Math.max(1, Math.min(cellW, cellH, area.maxImageSize ?? Infinity)); + const items = []; + for (let i = 0; i < count; i++) { + const file = files[(offset + i) % files.length]; + const col = i % cols; + const row = Math.floor(i / cols); + const item = { + src: `${baseUrl}/${file}?i=${offset + i}`, + x: Math.round(col * cellW + (cellW - size) / 2), + y: Math.round(row * cellH + (cellH - size) / 2), + w: Math.round(size), + h: Math.round(size), + }; + // Renderers cull (and FTL refuses to load) out-of-bounds content, so an + // out-of-bounds item would silently never render/load. Fail loudly. + if (item.x < 0 || item.y < 0 || item.x + item.w > area.width || item.y + item.h > area.height) { + throw new Error(`image layout item out of bounds: ${JSON.stringify(item)} for area ${area.width}x${area.height}`); + } + items.push(item); + } + return items; +}; + +const defaultSettle = () => new Promise((resolve) => setTimeout(resolve, 25)); + +/** + * Run the image-loading benchmark. + * + * For each count in `counts`: `warmups` discarded loads, then `samples` + * measured loads. Each measured load times `loadImages(urls)` from call to + * the last texture-loaded event. Results are logged as `Images!` for the + * Playwright runner and returned. + * + * @param {Object} options + * @param {(items: Array<{src: string, x: number, y: number, w: number, h: number}>) => Promise<{failedLoads?: number}>} options.loadImages + * @param {number[]} [options.counts] + * @param {number} [options.warmups] + * @param {number} [options.samples] + * @param {string[]} [options.files] - Image file names served under baseUrl. + * @param {string} [options.baseUrl] - Absolute or page-relative image dir. + * @param {Object} [options.layout] - App area the grid layout spreads over. + * @param {() => Promise} [options.settle] - Pause between runs. + */ +export const runImageBenchmark = async ({ + loadImages, + counts = getInjectedConfig().counts ?? IMAGE_COUNTS, + warmups = getInjectedConfig().warmups ?? IMAGE_WARMUPS, + samples = getInjectedConfig().samples ?? IMAGE_SAMPLES, + files = getInjectedConfig().files ?? ['image.png'], + baseUrl = getInjectedConfig().baseUrl ?? '../images', + layout = getInjectedConfig().layout ?? IMAGE_LAYOUT, + settle = defaultSettle, +}) => { + const results = {}; + let urlOffset = 0; + + for (const count of counts) { + console.log(`Image slice started! ${count}`); + try { + for (let w = 0; w < warmups; w++) { + await loadImages(buildImageLayout(files, count, urlOffset, baseUrl, layout)); + urlOffset += count; + await settle(); + } + + const times = []; + let failedLoads = 0; + let error = null; + for (let s = 0; s < samples; s++) { + const items = buildImageLayout(files, count, urlOffset, baseUrl, layout); + urlOffset += count; + const start = performance.now(); + try { + const res = await loadImages(items); + failedLoads += res?.failedLoads ?? 0; + } catch (loadError) { + error = loadError instanceof Error ? loadError.message : String(loadError); + } + times.push(performance.now() - start); + await settle(); + } + + const averageMs = times.reduce((sum, ms) => sum + ms, 0) / times.length; + const minMs = Math.min(...times); + results[count] = { + count, + warmups, + samples: times.map((ms) => Number(ms.toFixed(2))), + averageMs: Number(averageMs.toFixed(2)), + minMs: Number(minMs.toFixed(2)), + spreadMs: Number((Math.max(...times) - minMs).toFixed(2)), + failedLoads, + ...(error ? { error } : {}), + }; + console.log(`Image benchmark ${count}: ${averageMs.toFixed(2)}ms avg (min ${minMs.toFixed(2)}ms)`); + } catch (sliceError) { + const message = sliceError instanceof Error ? sliceError.message : String(sliceError); + results[count] = { count, warmups, samples: [], error: message }; + console.error(`Image benchmark ${count} failed: ${message}`); + } + console.log('Image slice result!', { count, result: results[count] }); + } + + console.log('Images!', results); + return results; +}; diff --git a/shared/imagePlatformAdapters.js b/shared/imagePlatformAdapters.js new file mode 100644 index 0000000..71f2cc9 --- /dev/null +++ b/shared/imagePlatformAdapters.js @@ -0,0 +1,172 @@ +import { runImageBenchmark } from './imageBenchmark.js'; + +/** + * Platform adapters for the shared image-loading benchmark. Each adapter + * only receives its framework's own objects (no framework imports here, so + * every framework bundle can include this file) and returns a + * `loadImages(urls)` promise that resolves when every texture-loaded / + * texture-failed event has fired. + */ + +/** + * Lightning 3 renderer: one node per item at its grid position shows the + * image; the load is tracked on the texture's own `loaded` / `failed` + * events (not the node event) because CoreNode deliberately suppresses + * `loaded` for 1x1 textures. + */ +export const runRendererImageBenchmark = async (renderer, parent = renderer.root) => { + return runImageBenchmark({ + loadImages: (items) => new Promise((resolve) => { + const nodes = []; + const textures = []; + const errors = []; + let pending = items.length; + if (pending === 0) return resolve({ failedLoads: 0 }); + const finish = () => { + if (--pending > 0) return; + for (const node of nodes) node.destroy(); + for (const tex of textures) tex.destroy(); + resolve({ failedLoads: errors.length, errors }); + }; + for (const item of items) { + const tex = renderer.createTexture('ImageTexture', { src: item.src }); + textures.push(tex); + const node = renderer.createNode({ + x: item.x, + y: item.y, + w: item.w, + h: item.h, + texture: tex, + parent, + }); + nodes.push(node); + tex.once('loaded', finish); + tex.once('failed', () => { + errors.push(item.src); + finish(); + }); + renderer.stage.txManager.loadTexture(tex); + } + }), + }); +}; + +/** + * FTL: an element with an image `texture` loads it through the texture + * manager; the texture fires `signals.loaded` / `signals.failed` once the + * GPU upload completes. + */ +export const runFtlImageBenchmark = async ({ root, createElement, createImage }) => { + return runImageBenchmark({ + loadImages: (items) => new Promise((resolve) => { + const elements = []; + const unsubscribes = []; + const errors = []; + let pending = items.length; + if (pending === 0) return resolve({ failedLoads: 0 }); + const finish = () => { + if (--pending > 0) return; + for (const unsubscribe of unsubscribes) unsubscribe?.(); + for (const el of elements) el.destroy(); + resolve({ failedLoads: errors.length, errors }); + }; + for (const item of items) { + const tex = createImage({ src: item.src }); + // All images share one z-layer (zIndex 0) so FTL files them into a + // single z-bucket and batches them into one draw call per frame, + // instead of one shader switch + draw per unique zIndex. + const el = createElement({ x: item.x, y: item.y, w: item.w, h: item.h, zIndex: 0 }); + root.addChild(el); + elements.push(el); + unsubscribes.push(tex.signals.loaded.subscribe(finish)); + unsubscribes.push( + typeof tex.signals.failed?.subscribe === 'function' + ? tex.signals.failed.subscribe(() => { + errors.push(item.src); + finish(); + }) + : null, + ); + // Assign after addChild so the in-bounds element takes the refcount + // that starts the load immediately. + el.texture = tex; + // Signals do not replay: an already-ready texture (cache hit) must + // still count as loaded. + if (tex.isReady === true) finish(); + } + }), + }); +}; + +/** + * Lightning 2: an element with `src` creates an ImageTexture and emits + * `txLoaded` / `txError` on the element. + */ +export const runLightning2ImageBenchmark = async ({ Lightning, app }) => { + class ImageBlock extends Lightning.Component { + static _template() { + return { x: 0, y: 0, w: 32, h: 32, rect: true, src: '' }; + } + + _init() { + const { x, y, w, h, src } = this.data; + this.patch({ x, y, w, h, src }); + } + } + + return runImageBenchmark({ + loadImages: (items) => new Promise((resolve) => { + const childList = app.tag('Items').childList; + const errors = []; + let pending = items.length; + if (pending === 0) return resolve({ failedLoads: 0 }); + const finish = () => { + if (--pending > 0) return; + childList.clear(); + resolve({ failedLoads: errors.length, errors }); + }; + for (const item of items) { + childList.add({ type: ImageBlock, data: item }); + const el = childList.getAt(childList.length - 1); + el.on('txLoaded', finish); + el.on('txError', () => { + errors.push(item.src); + finish(); + }); + } + }), + }); +}; + +/** + * Blits: `` drives FTL textures through the + * node adapter. Used by the Blits Images page, which owns the template loop + * and resolves per run. + */ +export const createBlitsImageLoader = (component) => { + return (items) => new Promise((resolve) => { + component._imageResolve = resolve; + component._imagePending = items.length; + component.imageLoadedCount = 0; + component.imageErrorCount = 0; + component.images = items.map((item) => ({ + src: item.src, + x: item.x, + y: item.y, + w: item.w, + h: item.h, + })); + }); +}; + +/** Called from the Blits Images page `@loaded`/`@error` handlers. */ +export const blitsImageEventReceived = (component) => { + if (component._imagePending === undefined) return; + if (component.imageLoadedCount + component.imageErrorCount < component._imagePending) return; + const resolve = component._imageResolve; + const failedLoads = component.imageErrorCount; + component._imagePending = undefined; + component._imageResolve = undefined; + component.images = []; + if (resolve) resolve({ failedLoads }); +}; diff --git a/shared/images/elevator.png b/shared/images/elevator.png new file mode 100644 index 0000000..93807b7 Binary files /dev/null and b/shared/images/elevator.png differ diff --git a/shared/images/environment.png b/shared/images/environment.png new file mode 100644 index 0000000..7d23acc Binary files /dev/null and b/shared/images/environment.png differ diff --git a/shared/images/lightning.png b/shared/images/lightning.png new file mode 100644 index 0000000..2677c5c Binary files /dev/null and b/shared/images/lightning.png differ diff --git a/shared/images/premium.png b/shared/images/premium.png new file mode 100644 index 0000000..d7e6980 Binary files /dev/null and b/shared/images/premium.png differ diff --git a/shared/images/robot.png b/shared/images/robot.png new file mode 100644 index 0000000..e8befeb Binary files /dev/null and b/shared/images/robot.png differ diff --git a/shared/images/rocko.png b/shared/images/rocko.png new file mode 100644 index 0000000..c4ef743 Binary files /dev/null and b/shared/images/rocko.png differ diff --git a/shared/images/spritemap.png b/shared/images/spritemap.png new file mode 100644 index 0000000..4c39c10 Binary files /dev/null and b/shared/images/spritemap.png differ diff --git a/shared/images/testscreen.png b/shared/images/testscreen.png new file mode 100644 index 0000000..4019f1b Binary files /dev/null and b/shared/images/testscreen.png differ diff --git a/shared/images/testscreen_rotated.png b/shared/images/testscreen_rotated.png new file mode 100644 index 0000000..7c1cba9 Binary files /dev/null and b/shared/images/testscreen_rotated.png differ diff --git a/testrunner/imageResults.js b/testrunner/imageResults.js new file mode 100644 index 0000000..33fef06 --- /dev/null +++ b/testrunner/imageResults.js @@ -0,0 +1,33 @@ +import { IMAGE_COUNTS } from '../shared/imageBenchmark.js'; + +const escapeHtml = (value) => String(value).replace(/[&<>\"']/g, (char) => ({ + '&': '&', '<': '<', '>': '>', '\"': '"', "'": ''', +})[char]); + +/** Render the image-loading section in the shared results table, preserving slice errors. */ +export const renderImageSection = (results, frameworks, frameworkVersions = {}) => { + const counts = [...new Set(frameworks.flatMap((framework) => + Object.keys(results[framework].images || {}).map(Number).filter(Number.isFinite), + ))].sort((a, b) => a - b); + if (!counts.length) counts.push(...IMAGE_COUNTS); + + const rows = counts.map((count) => { + const cells = frameworks.map((framework) => { + const slice = results[framework].images?.[count]; + if (!slice) return 'n/a'; + if (slice.error) { + return `
FAIL${escapeHtml(slice.error)}
`; + } + if (!Number.isFinite(slice.averageMs)) return 'n/a'; + // Include the complete per-slice data in the HTML itself so official + // copies are self-contained and do not depend on a local raw JSON file. + const diagnostics = escapeHtml(JSON.stringify(slice, null, 2)); + return `
${slice.averageMs.toFixed(2)}ms (min ${slice.minMs.toFixed(2)}ms)
${diagnostics}
`; + }).join(''); + return `${count.toLocaleString('en-US')} image${count === 1 ? '' : 's'}${cells}`; + }).join('\n'); + + return `Image loading (ms, lower is better)${frameworks.map((framework) => + `${escapeHtml(framework)} ${escapeHtml(frameworkVersions[framework] ?? '')}`, + ).join('')}${rows}`; +}; diff --git a/testrunner/processResults.js b/testrunner/processResults.js index 7624199..31443d0 100644 --- a/testrunner/processResults.js +++ b/testrunner/processResults.js @@ -11,9 +11,10 @@ * @param {FileSizeResultsObject} fileSizeResults - The file size results object. * @param {StartupResultsObject} [startupResults] - The startup results object. * @param {Object} [rectangleResults] - Raw rectangle slices per framework/count. + * @param {Object} [imageResults] - Raw image-loading slices per framework/count. * @returns {Object} - The processed and sorted results object. */ -export const processResults = (results, memoryResults, fileSizeResults, startupResults = {}, rectangleResults = {}) => { +export const processResults = (results, memoryResults, fileSizeResults, startupResults = {}, rectangleResults = {}, imageResults = {}) => { const processedResults = {}; const fastestTimes = { create: null, @@ -109,6 +110,11 @@ export const processResults = (results, memoryResults, fileSizeResults, startupR if (rectangleResults[f]) { processedResults[f].rectangles = rectangleResults[f]; } + // Image load times are reported independently as well, not mixed into + // the duration-based weighted operation score or framework ordering. + if (imageResults[f]) { + processedResults[f].images = imageResults[f]; + } }); // sort the frameworks by avgMean diff --git a/testrunner/runImages.js b/testrunner/runImages.js new file mode 100644 index 0000000..abaebb1 --- /dev/null +++ b/testrunner/runImages.js @@ -0,0 +1,178 @@ +import fs from 'fs'; +import path from 'path'; +import { chromium } from 'playwright'; +import { IMAGE_COUNTS, IMAGE_WARMUPS, IMAGE_SAMPLES } from '../shared/imageBenchmark.js'; + +const DEFAULT_TIMEOUT_MS = 10 * 60 * 1000; +const IMAGE_EXTENSIONS = new Set(['.png', '.jpg', '.jpeg', '.webp', '.gif', '.svg']); + +/** + * Pick the local image source dir: IMAGE_ASSETS_DIR wins, then the committed + * `shared/images/` copies (taken from ../renderer/examples/assets), then the + * renderer examples dir itself. Everything is served locally from dist/. + */ +const resolveAssetSource = () => { + if (process.env.IMAGE_ASSETS_DIR) return path.resolve(process.env.IMAGE_ASSETS_DIR); + const shared = path.resolve('./shared/images'); + if (fs.existsSync(shared)) { + const hasImages = fs.readdirSync(shared).some((f) => IMAGE_EXTENSIONS.has(path.extname(f).toLowerCase())); + if (hasImages) return shared; + } + return path.resolve('../renderer/examples/assets'); +}; + +/** + * Copy the local image assets into `dist/images/` so framework pages can + * reference them as `/images/` without internet access. + * @returns {string[]} The image file names now served under dist/images. + */ +export const ensureImageAssets = (distDir = './dist') => { + const source = resolveAssetSource(); + const dest = path.resolve(distDir, 'images'); + fs.mkdirSync(dest, { recursive: true }); + const files = fs.readdirSync(source) + .filter((f) => IMAGE_EXTENSIONS.has(path.extname(f).toLowerCase())) + .sort(); + for (const file of files) { + fs.copyFileSync(path.join(source, file), path.join(dest, file)); + } + return files; +}; + +/** + * Run the image-loading benchmark for each framework. One fresh browser + * process per framework runs all counts in-page (the page performs its own + * warmups, then the measured slices, and logs `Images!` with the results). + * Results are saved incrementally to `results/images_.json`. + */ +export const runImageBenchmarks = async (frameworks, browserVersion) => { + const counts = process.env.IMAGE_COUNTS + ? process.env.IMAGE_COUNTS.split(',').map((c) => Number.parseInt(c, 10)).filter(Number.isFinite) + : IMAGE_COUNTS; + const warmups = Number.parseInt(process.env.IMAGE_WARMUPS || `${IMAGE_WARMUPS}`, 10); + const samples = Number.parseInt(process.env.IMAGE_SAMPLES || `${IMAGE_SAMPLES}`, 10); + const timeoutMs = Number.parseInt(process.env.IMAGE_TIMEOUT_MS || `${DEFAULT_TIMEOUT_MS}`, 10); + const requestedFrameworks = process.env.IMAGE_FRAMEWORKS?.split(',').map((name) => name.trim()).filter(Boolean); + const baseUrl = process.env.IMAGE_BASE_URL || 'http://localhost:8080'; + if (requestedFrameworks?.length) { + frameworks = frameworks.filter((framework) => requestedFrameworks.includes(framework)); + } + + const files = ensureImageAssets('./dist'); + const imageBaseUrl = `${baseUrl}/images`; + const cpuThrottlingRate = 6; + + const startedAt = new Date(); + const filename = `images_${startedAt.toISOString().replace(/[:.]/g, '-')}.json`; + const results = {}; + fs.mkdirSync('./results', { recursive: true }); + const writePartialResults = () => { + fs.writeFileSync(`./results/${filename}`, JSON.stringify({ + date: startedAt.toISOString(), + browser: browserVersion, + viewport: '1920x1080 @ 1x (matches the 1920x1080 app/canvas size of every framework)', + counts, + warmupsPerCount: warmups, + samplesPerCount: samples, + timeoutMs, + cpuThrottlingRate, + imageBaseUrl, + imageFiles: files, + measurement: 'ms from issuing the loads until every texture loaded/failed event fired; unique URL per image (no cache reuse), local files only', + results, + }, null, 2)); + }; + + const runFramework = async (framework) => { + let browser; + let context; + let timeout; + + try { + browser = await chromium.launch({ headless: process.env.HEADLESS === 'true' }); + context = await browser.newContext({ + // match the 1920x1080 app/canvas size every framework uses outside + // rectangle mode, so the whole image grid is in view + viewport: { width: 1920, height: 1080 }, + deviceScaleFactor: 1, + }); + const page = await context.newPage(); + const client = await context.newCDPSession(page); + await client.send('Emulation.setCPUThrottlingRate', { rate: cpuThrottlingRate }); + await page.addInitScript((config) => { + window.__IMAGE_BENCHMARK_CONFIG__ = config; + }, { counts, warmups, samples, files, baseUrl: imageBaseUrl }); + + const result = await new Promise((resolve, reject) => { + let settled = false; + const finish = (callback, value) => { + if (settled) return; + settled = true; + clearTimeout(timeout); + callback(value); + }; + timeout = setTimeout(() => finish( + reject, + new Error(`${framework} image benchmark timed out after ${timeoutMs}ms`), + ), timeoutMs); + + page.on('console', async (message) => { + const text = message.text(); + if (text.startsWith('Image slice result!')) { + try { + const payload = await message.args()[1].jsonValue(); + console.log(` ${framework} ${payload.count} images: ${payload.result.error || `${payload.result.averageMs}ms avg`}`); + } catch { /* progress log only */ } + return; + } + if (!text.startsWith('Images!')) return; + try { + const slices = await message.args()[1].jsonValue(); + finish(resolve, slices); + } catch (error) { + finish(reject, error); + } + }); + page.on('pageerror', (error) => finish(reject, error)); + page.on('crash', () => finish(reject, new Error(`${framework} page crashed during image benchmark`))); + browser.on('disconnected', () => finish(reject, new Error(`${framework} browser process disconnected during image benchmark`))); + + const url = framework === 'blits' + ? `${baseUrl}/${framework}/#/images` + : `${baseUrl}/${framework}/#images`; + page.goto(url).catch((error) => finish(reject, error)); + }); + + if (!result) throw new Error(`${framework} did not return image benchmark results`); + return result; + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + console.error(`Image benchmark failed for ${framework}: ${message}`); + return { error: message }; + } finally { + clearTimeout(timeout); + await context?.close().catch(() => {}); + await browser?.close().catch(() => {}); + } + }; + + writePartialResults(); + for (const framework of frameworks) { + console.log(`Running image loading benchmark for ${framework} (counts: ${counts.join(', ')})`); + results[framework] = await runFramework(framework); + writePartialResults(); + } + + console.log('Average image load time (ms) by framework and image count:'); + console.table(Object.fromEntries(Object.entries(results).map(([framework, slices]) => [ + framework, + slices.error + ? { error: `FAIL (${slices.error})` } + : Object.fromEntries(Object.entries(slices).map(([count, slice]) => [ + `${count} images`, + slice.error ? `FAIL (${slice.error})` : `${slice.averageMs.toFixed(2)}ms (min ${slice.minMs.toFixed(2)})`, + ])), + ]))); + console.log(`Image results written to ./results/${filename}`); + return JSON.parse(fs.readFileSync(`./results/${filename}`, 'utf8')); +}; diff --git a/testrunner/types/imageResults.js b/testrunner/types/imageResults.js new file mode 100644 index 0000000..a7b0323 --- /dev/null +++ b/testrunner/types/imageResults.js @@ -0,0 +1,19 @@ +/** + * A single image-loading slice for one image count. + * + * @typedef {Object} ImageSliceResult + * @property {number} count - Number of images loaded in this slice. + * @property {number} warmups - Discarded warmup loads run before sampling. + * @property {number[]} samples - Measured milliseconds per load (call to last texture-loaded event). + * @property {number} averageMs - Mean of `samples`. + * @property {number} minMs - Fastest sample. + * @property {number} spreadMs - Max minus min of `samples`. + * @property {number} failedLoads - Textures that fired a failed event instead of loaded. + * @property {string} [error] - Present when the whole slice failed. + * + * @typedef {Object} ImageResults + * @property {string} framework - The framework name. + * @property {Object} results - Slices keyed by image count. + */ + +export {} diff --git a/testrunner/writeResults.js b/testrunner/writeResults.js index 513421c..ef522ab 100644 --- a/testrunner/writeResults.js +++ b/testrunner/writeResults.js @@ -18,6 +18,7 @@ import fs from 'fs'; import { getOSInfo, getSystemInfo } from "./systemInfo.js"; import { renderRectangleSection } from './rectangleResults.js'; +import { renderImageSection } from './imageResults.js'; const indexHeader = ` @@ -82,6 +83,9 @@ const opsDescription = ` const startupDescription = `

Startup is measured from navigation start to the first idle after rendering 1,000 nodes (fresh browser context per run, 6x CPU slowdown applied before navigation, so JS fetch/parse is included)

`; +const imagesDescription = ` +

Image loading: milliseconds from issuing the load until every texture-loaded event fired, loading 1 / 5 / 25 / 100 unique local images per slice (5 warmups + 5 samples per count, 6x CPU slowdown). Lower is better. Reported separately from the weighted operation score; expand a cell for per-sample details.

`; + const opsSection = ` @@ -288,10 +292,11 @@ export const writeResults = (results, frameworkVersions, browserVersion) => { const hasStartup = frameworks.some(f => results[f].startup); const hasFileSize = frameworks.some(f => results[f].fileSize !== undefined); const hasRectangles = frameworks.some(f => results[f].rectangles); + const hasImages = frameworks.some(f => results[f].images); // write the results header with only the relevant descriptions fileStream.write(resultsHeader.replace('{{resultsDescription}}', - `${hasOps ? opsDescription : ''}${hasStartup ? startupDescription : ''}${hasRectangles ? '

Rectangle rendering: average callback FPS (higher is better), 6x CPU slowdown, 1000x540 drawing area. Reported separately from the weighted operation score; expand a cell for frame-pacing and failure details.

' : ''}` + `${hasOps ? opsDescription : ''}${hasStartup ? startupDescription : ''}${hasRectangles ? '

Rectangle rendering: average callback FPS (higher is better), 6x CPU slowdown, 1000x540 drawing area. Reported separately from the weighted operation score; expand a cell for frame-pacing and failure details.

' : ''}${hasImages ? imagesDescription : ''}` )); // write some html @@ -377,6 +382,10 @@ export const writeResults = (results, frameworkVersions, browserVersion) => { sections.push(renderRectangleSection(results, frameworks, frameworkVersions)); } + if (hasImages) { + sections.push(renderImageSection(results, frameworks, frameworkVersions)); + } + fileStream.write(table.replace('{{sections}}', sections.join('\n'))); // write the footer diff --git a/tests/imageBenchmark.test.js b/tests/imageBenchmark.test.js new file mode 100644 index 0000000..7c3bdb9 --- /dev/null +++ b/tests/imageBenchmark.test.js @@ -0,0 +1,161 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { + IMAGE_COUNTS, + IMAGE_WARMUPS, + IMAGE_SAMPLES, + IMAGE_LAYOUT, + buildImageUrls, + buildImageLayout, + runImageBenchmark, +} from '../shared/imageBenchmark.js'; + +test('default image counts are 1, 5, 25 and 100', () => { + assert.deepEqual(IMAGE_COUNTS, [1, 5, 25, 100]); + assert.equal(IMAGE_WARMUPS, 5); + assert.equal(IMAGE_SAMPLES, 5); +}); + +test('buildImageUrls returns the requested count and cycles files', () => { + const files = ['a.png', 'b.png']; + const urls = buildImageUrls(files, 5, 0, '/images'); + assert.equal(urls.length, 5); + assert.deepEqual(urls, [ + '/images/a.png?i=0', + '/images/b.png?i=1', + '/images/a.png?i=2', + '/images/b.png?i=3', + '/images/a.png?i=4', + ]); +}); + +test('buildImageUrls never repeats a URL across offsets', () => { + const files = ['a.png', 'b.png', 'c.png']; + const all = [...buildImageUrls(files, 4, 0), ...buildImageUrls(files, 4, 4), ...buildImageUrls(files, 4, 8)]; + assert.equal(new Set(all).size, all.length); +}); + +test('buildImageLayout spreads items over the area without overlap', () => { + for (const count of [1, 5, 25, 100]) { + const items = buildImageLayout(['a.png', 'b.png'], count, 0, '/images', IMAGE_LAYOUT); + assert.equal(items.length, count); + assert.equal(new Set(items.map((i) => i.src)).size, count); + const rects = items.map((i) => ({ x: i.x, y: i.y, w: i.w, h: i.h })); + for (const r of rects) { + assert.ok(r.x >= 0 && r.y >= 0, 'origin inside area'); + assert.ok(r.x + r.w <= IMAGE_LAYOUT.width && r.y + r.h <= IMAGE_LAYOUT.height, 'rect inside area'); + assert.ok(r.w >= 1 && r.h >= 1, 'non-degenerate size'); + } + for (let i = 0; i < rects.length; i++) { + for (let j = i + 1; j < rects.length; j++) { + const a = rects[i]; + const b = rects[j]; + const overlap = a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h; + assert.equal(overlap, false, `items ${i} and ${j} overlap`); + } + } + } +}); + +test('buildImageLayout keeps URLs unique across offsets', () => { + const all = [...buildImageLayout(['a.png'], 10, 0), ...buildImageLayout(['a.png'], 10, 10)]; + assert.equal(new Set(all.map((i) => i.src)).size, all.length); +}); + +test('buildImageLayout throws instead of placing images out of bounds (renderers cull OOB)', () => { + // rounding can push the last cell past the area edge (51+51 > 101) — + // that must fail loudly, since renderers would cull the image + assert.throws( + () => buildImageLayout(['a.png'], 2, 0, '/images', { width: 101, height: 100, maxImageSize: 160 }), + /out of bounds/, + ); + // and the default layout never goes out of bounds at any default count + for (const count of IMAGE_COUNTS) { + const items = buildImageLayout(['a.png'], count, 0, '/images', IMAGE_LAYOUT); + for (const item of items) { + assert.ok(item.x >= 0 && item.y >= 0 && item.x + item.w <= IMAGE_LAYOUT.width && item.y + item.h <= IMAGE_LAYOUT.height); + } + } +}); + +test('runImageBenchmark runs warmups + samples per count with unique laid-out items and reports timings', async () => { + const calls = []; + const logs = []; + const originalLog = console.log; + console.log = (...args) => logs.push(args); + try { + const results = await runImageBenchmark({ + loadImages: async (items) => { + calls.push(items); + return { failedLoads: 0 }; + }, + counts: [1, 3], + warmups: 5, + samples: 5, + files: ['a.png', 'b.png'], + baseUrl: '/images', + settle: () => Promise.resolve(), + }); + + // 5 warmups + 5 samples per count, each with the right number of unique items + assert.equal(calls.length, 2 * (5 + 5)); + assert.equal(calls[0].length, 1); + assert.equal(calls[10].length, 3); + const allItems = calls.flat(); + const allSrcs = allItems.map((item) => item.src); + assert.equal(new Set(allSrcs).size, allSrcs.length); + assert.ok(allSrcs.every((src) => src.startsWith('/images/') && src.includes('?i='))); + // every item carries a grid position so rendered images do not stack + for (const item of allItems) { + for (const key of ['x', 'y', 'w', 'h']) assert.ok(Number.isFinite(item[key]), key); + } + + for (const count of [1, 3]) { + const slice = results[count]; + assert.equal(slice.warmups, 5); + assert.equal(slice.samples.length, 5); + assert.ok(slice.samples.every((ms) => ms >= 0)); + assert.ok(slice.averageMs >= slice.minMs); + assert.equal(slice.failedLoads, 0); + assert.equal(slice.error, undefined); + } + assert.ok(logs.some((args) => args[0] === 'Images!')); + } finally { + console.log = originalLog; + } +}); + +test('runImageBenchmark accumulates failed loads and captures slice errors', async () => { + const originalLog = console.log; + const originalError = console.error; + console.log = () => {}; + console.error = () => {}; + try { + let calls = 0; + const results = await runImageBenchmark({ + loadImages: async (items) => { + calls++; + // count=1: call 1 is the warmup, calls 2-3 are samples. + // count=2: call 4 is the warmup, calls 5-6 are samples. + if (calls === 2) return { failedLoads: 1 }; + if (calls >= 5) throw new Error('boom'); + return { failedLoads: 0 }; + }, + counts: [1, 2], + warmups: 1, + samples: 2, + files: ['a.png'], + baseUrl: '/images', + settle: () => Promise.resolve(), + }); + + assert.equal(results[1].failedLoads, 1); + assert.equal(results[1].error, undefined); + // samples still recorded even when the load rejects + assert.equal(results[2].samples.length, 2); + assert.equal(results[2].error, 'boom'); + } finally { + console.log = originalLog; + console.error = originalError; + } +}); diff --git a/tests/imageResults.test.js b/tests/imageResults.test.js new file mode 100644 index 0000000..6baf36d --- /dev/null +++ b/tests/imageResults.test.js @@ -0,0 +1,65 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import fs from 'node:fs/promises'; +import { processResults } from '../testrunner/processResults.js'; +import { renderImageSection } from '../testrunner/imageResults.js'; +import { writeResults } from '../testrunner/writeResults.js'; + +test('full result processing keeps image slices without changing the weighted score', () => { + const operations = { a: { create: '10ms' }, b: { create: '20ms' } }; + const images = { + a: { 1: { averageMs: 5, minMs: 4 }, 100: { error: 'crash' } }, + b: { 1: { averageMs: 8, minMs: 7 } }, + }; + const baseline = processResults(operations, {}, {}, {}); + const combined = processResults(operations, {}, {}, {}, {}, images); + assert.deepEqual(Object.keys(combined), Object.keys(baseline)); + for (const framework of Object.keys(operations)) { + assert.equal(combined[framework].avgMean, baseline[framework].avgMean); + assert.deepEqual(combined[framework].images, images[framework]); + } +}); + +test('reports without image data retain their original result shape', () => { + const result = processResults({ a: { create: '10ms' } }, {}, {}, {}); + assert.equal(Object.hasOwn(result.a, 'images'), false); +}); + +test('overview renders load times, escaped failures, and missing slices', () => { + const html = renderImageSection({ + a: { images: { + 1: { count: 1, samples: [4, 5, 6], averageMs: 5, minMs: 4, spreadMs: 2, failedLoads: 0 }, + 100: { count: 100, error: '' }, + } }, + b: {}, + }, ['a', 'b'], { a: '1.0' }); + assert.match(html, /5\.00ms \(min 4\.00ms\)/); + assert.match(html, /1 image/i); + assert.match(html, /n\/a<\/td>/); +}); + +test('full HTML overview includes image loading beside the existing benchmark sections', async () => { + const browser = `image-report-test-${process.pid}-${Date.now()}`; + const results = processResults( + { a: { create: '10ms' } }, + { a: { heap: 4, create: 5 } }, + { a: 2048 }, + { a: { startup: '120ms', min: 120, runs: [120] } }, + {}, + { a: { 1: { count: 1, samples: [5], averageMs: 5, minMs: 5, spreadMs: 0, failedLoads: 0, warmups: 5 }, 100: { error: 'page crashed' } } }, + ); + const filename = await writeResults(results, { a: '1.0' }, browser); + try { + const html = await fs.readFile(`./results/${filename}`, 'utf8'); + for (const text of ['create rows', 'create 20k nodes', 'cold startup', 'bundle size', '5.00ms (min 5.00ms)', 'FAIL', 'page crashed', 'unique local images', '6x CPU slowdown']) { + assert.ok(html.includes(text), text); + } + assert.doesNotMatch(html, /\{\{\w+\}\}/); + } finally { + await fs.unlink(`./results/${filename}`); + } +});