.json` and printed as a table. All framework
+directories enabled in `.env` and included in `dist/` are tested.
+Both L2 variants also run an independent RAF counter over each FPS sample's
+exact time window. The JSON includes `rafFps` and `rafChecks` (frame-event count,
+RAF count, elapsed time, and both rates) to cross-check the `frameStart` counter.
+The RAF observer does not move the scene or perform rendering.
+
+Average FPS is not a smoothness or presented-frame guarantee. `measurements`
+also record `meterFps` using the comparison's FPSMeter interval-smoothing formula
+(factor 10), plus `framePacing` with median/p95/p99/max callback intervals and
+counts of gaps over 25ms and 50ms. Slow frames can be visible even if average FPS
+is close to 60. Neither counter waits for GPU completion or measures display
+presentation; the comparison's FPSMeter has the same limitation.
+
+Blits constructs one native-border Element per square in a stable keyed list,
+then updates cached Elements with `set('x', ...)`, without triggering the entire
+list each frame. This deliberately measures Blits' Element API, not list
+reconciliation. This follows the documented [loop refs](https://www.lightningjs.io/v3-docs/blits/built-in/for-loop.html#referencing-elements-in-the-for-loop)
+and [border attribute](https://www.lightningjs.io/v3-docs/blits/shaders/v2-conversion-guide.html#border).
+`sceneValidation` verifies that node count and identities stay constant during
+movement, outside the timed samples.
+The generated scene and drawing area must have the same dimensions: generating
+a larger scene causes offscreen culling and misleadingly high FPS. Scene bounds
+and count replacement are covered by `node --test tests/rectangleBenchmark.test.js`.
+Each framework runs in its own browser process. A page error, renderer crash, or
+timeout is recorded as a failure and does not stop the remaining frameworks;
+each framework/count slice uses a fresh browser process, with a default timeout
+of 10 minutes (`RECTANGLE_TIMEOUT_MS`). A crash at one count does not stop the
+other counts or frameworks.
+Per-count results are saved as soon as each slice finishes. A failed count is
+recorded as 0 FPS with its error, while completed earlier counts are retained.
+The default counts stop at 16,000 because both Lightning 2 variants and both
+L3 renderer variants (`renderer`, `renderer-local`) reject counts above
+16,000 before creating elements (16-bit quad indices wrap past 16,384 slots).
+If higher counts are configured via `RECTANGLE_COUNTS`, those slices are
+reported as unsupported failures (0 FPS).
+
+Build the enabled frameworks and serve `dist/` in one terminal:
+
+```sh
+npm run build
+npx http-server -c-1 ./dist/
+```
+
+Then run the full suite in another terminal:
+
+```sh
+node index.js
+```
+
+For focused troubleshooting, `npm run rectangles` (or `node index.js
+--rectangles`) still runs only the rectangle suite and saves its raw JSON.
+
+Set `HEADLESS=true` to run Chromium headlessly. For representative performance
+results, use the same browser, viewport, display scaling and hardware across
+runs; browser refresh-rate limits can cap the reported FPS. The runner also
+accepts `RECTANGLE_FRAMEWORKS=ftl,renderer` to select a subset and
+`RECTANGLE_COUNTS=8000,16000` to select counts. `RECTANGLE_WARMUP_MS`,
+`RECTANGLE_SAMPLE_MS`, and `RECTANGLE_SAMPLES` adjust the sample timings (use
+short values for a smoke test, not for comparable performance results).
+
## Why not use js-framework-benchmark
Two reasons:
@@ -78,4 +159,3 @@ As of v0.0.2 the Lightning Benchmark implements weighted mean results for differ
| createLots | 0.56 |
| append | 0.55 |
| clear | 0.42 |
-
diff --git a/shared/rectangleBenchmark.js b/shared/rectangleBenchmark.js
new file mode 100644
index 0000000..21f7b76
--- /dev/null
+++ b/shared/rectangleBenchmark.js
@@ -0,0 +1,214 @@
+/**
+ * Shared moving-rectangle scene and FPS sampler used by each renderer adapter.
+ * CPU throttling is configured by the Playwright runner before navigation.
+ */
+export const RECTANGLE_COUNTS = [4000, 8000, 16000];
+
+export const tickFpsMeter = (meter, now) => {
+ if (meter.lastTick !== undefined) {
+ meter.frameTime += (now - meter.lastTick - meter.frameTime) / 10;
+ }
+ meter.lastTick = now;
+ return 1000 / meter.frameTime;
+};
+
+export const summarizeFrameIntervals = (intervals) => {
+ const sorted = [...intervals].sort((a, b) => a - b);
+ const percentile = (p) => sorted.length ? sorted[Math.ceil(sorted.length * p) - 1] : null;
+ return {
+ intervals: sorted.length,
+ medianMs: percentile(0.5),
+ p95Ms: percentile(0.95),
+ p99Ms: percentile(0.99),
+ maxMs: sorted.length ? sorted[sorted.length - 1] : null,
+ over25Ms: sorted.filter((ms) => ms > 25).length,
+ over50Ms: sorted.filter((ms) => ms > 50).length,
+ };
+};
+
+export const createRectangleScene = (count, width, height, seed = 0x12345678) => {
+ let state = seed >>> 0;
+ const random = () => {
+ state = (Math.imul(state, 1664525) + 1013904223) >>> 0;
+ return state / 0x100000000;
+ };
+
+ const scene = {
+ count,
+ width,
+ height,
+ x: new Float32Array(count),
+ y: new Float32Array(count),
+ size: new Float32Array(count),
+ speed: new Float32Array(count),
+ };
+
+ for (let i = 0; i < count; i++) {
+ scene.x[i] = random() * width;
+ scene.y[i] = random() * height;
+ scene.size[i] = 10 + random() * 40;
+ scene.speed[i] = 1 + random();
+ }
+ return scene;
+};
+
+export const advanceRectangleScene = (scene) => {
+ for (let i = 0; i < scene.count; i++) {
+ let x = scene.x[i] - scene.speed[i];
+ const halfExtent = scene.size[i] / 2;
+ if (x + halfExtent < 0) x = scene.width + halfExtent;
+ scene.x[i] = x;
+ }
+};
+
+const nextFrame = () => new Promise((resolve) => requestAnimationFrame(resolve));
+
+const sampleFps = (scene, drawFrame, durationMs, subscribeFrame, meter, crossCheckRaf = false) => new Promise((resolve, reject) => {
+ let frames = 0;
+ let rafFrames = 0;
+ let rafId;
+ let previousFrame;
+ let frameError;
+ const intervals = [];
+ const start = performance.now();
+ if (crossCheckRaf) {
+ const countRaf = () => {
+ rafFrames++;
+ rafId = requestAnimationFrame(countRaf);
+ };
+ rafId = requestAnimationFrame(countRaf);
+ }
+ const unsubscribe = subscribeFrame(() => {
+ if (frameError) return;
+ const now = performance.now();
+ if (previousFrame !== undefined) intervals.push(now - previousFrame);
+ previousFrame = now;
+ // Same FPSMeter.tick() interval smoothing as the comparison (smoothing=10).
+ tickFpsMeter(meter, now);
+ try {
+ advanceRectangleScene(scene);
+ drawFrame(scene);
+ frames++;
+ } catch (error) {
+ // Some engines isolate event-listener errors. Preserve the failure rather
+ // than silently reporting a successful sample with fewer updates.
+ frameError = error;
+ }
+ });
+ setTimeout(() => {
+ unsubscribe();
+ if (crossCheckRaf) cancelAnimationFrame(rafId);
+ if (frameError) {
+ reject(frameError);
+ return;
+ }
+ const elapsedMs = Math.max(1, performance.now() - start);
+ resolve({
+ fps: frames * 1000 / elapsedMs,
+ meterFps: 1000 / meter.frameTime,
+ framePacing: summarizeFrameIntervals(intervals),
+ frames,
+ elapsedMs,
+ ...(crossCheckRaf ? {
+ frames,
+ rafFrames,
+ elapsedMs,
+ rafFps: rafFrames * 1000 / elapsedMs,
+ } : {}),
+ });
+ }, durationMs);
+});
+
+/**
+ * Run all rectangle counts. `drawScene` replaces the platform's current scene
+ * and returns a callback that applies the next positions for each animation
+ * frame.
+ */
+export const runRectangleBenchmark = async ({
+ drawScene,
+ subscribeFrame,
+ crossCheckRaf = false,
+ width = 1000,
+ height = 540,
+ counts = window.__RECTANGLE_BENCHMARK_CONFIG__?.counts ?? RECTANGLE_COUNTS,
+ warmupMs = window.__RECTANGLE_BENCHMARK_CONFIG__?.warmupMs ?? 1000,
+ sampleMs = window.__RECTANGLE_BENCHMARK_CONFIG__?.sampleMs ?? 1500,
+ samples = window.__RECTANGLE_BENCHMARK_CONFIG__?.samples ?? 3,
+}) => {
+ const results = {};
+
+ for (const count of counts) {
+ console.log(`Rectangle slice started! ${count}`);
+ try {
+ const scene = createRectangleScene(count, width, height);
+ const drawFrame = await drawScene(scene);
+ const meter = { frameTime: 100, lastTick: undefined };
+ await nextFrame();
+ await nextFrame();
+ await sampleFps(scene, drawFrame, warmupMs, subscribeFrame, meter, crossCheckRaf);
+
+ const fpsSamples = [];
+ const rafChecks = [];
+ const measurements = [];
+ for (let sample = 0; sample < samples; sample++) {
+ const measurement = await sampleFps(scene, drawFrame, sampleMs, subscribeFrame, meter, crossCheckRaf);
+ measurements.push(measurement);
+ fpsSamples.push(measurement.fps);
+ if (crossCheckRaf) rafChecks.push(measurement);
+ }
+
+ results[count] = {
+ fps: fpsSamples.reduce((sum, fps) => sum + fps, 0) / fpsSamples.length,
+ samples: fpsSamples,
+ measurements,
+ meterFps: measurements[measurements.length - 1].meterFps,
+ ...(drawFrame.validateScene ? { sceneValidation: drawFrame.validateScene() } : {}),
+ ...(crossCheckRaf ? {
+ rafFps: rafChecks.reduce((sum, check) => sum + check.rafFps, 0) / rafChecks.length,
+ rafChecks,
+ } : {}),
+ };
+ console.log(`Rectangle benchmark ${count}: ${results[count].fps.toFixed(2)} FPS`);
+ if (crossCheckRaf) {
+ console.log(`L2 RAF cross-check ${count}: ${results[count].rafFps.toFixed(2)} RAF FPS`);
+ }
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ results[count] = { fps: 0, samples: [], error: message };
+ console.error(`Rectangle benchmark ${count} failed: ${message}`);
+ }
+ console.log('Rectangle slice result!', { count, result: results[count] });
+ }
+
+ console.log('Rectangles!', results);
+ return results;
+};
+
+/** Bridge the shared workload to a renderer's native rectangle API. */
+export const createRectangleAdapter = ({ createRect, destroyRect, setX, width = 1000, height = 540 }) => {
+ let rectangles = [];
+
+ return {
+ width,
+ height,
+ drawScene(scene) {
+ for (const rectangle of rectangles) {
+ if (rectangle !== undefined) destroyRect(rectangle);
+ }
+ rectangles = new Array(scene.count);
+ for (let i = 0; i < scene.count; i++) {
+ rectangles[i] = createRect({
+ x: scene.x[i],
+ y: scene.y[i],
+ size: scene.size[i],
+ });
+ }
+
+ return (frameScene) => {
+ for (let i = 0; i < rectangles.length; i++) {
+ setX(rectangles[i], frameScene.x[i]);
+ }
+ };
+ },
+ };
+};
diff --git a/shared/rectanglePlatformAdapters.js b/shared/rectanglePlatformAdapters.js
new file mode 100644
index 0000000..11eb066
--- /dev/null
+++ b/shared/rectanglePlatformAdapters.js
@@ -0,0 +1,165 @@
+import { createRectangleAdapter, runRectangleBenchmark } from './rectangleBenchmark.js';
+
+const FTL_RECT_COLOR = [0, 0, 0, 1];
+
+export const runFtlRectangleBenchmark = async ({ app, root, signals, createElement, RectShader, createShader, rectShader }) => {
+ const rectangles = [];
+ app.addActiveCheck(() => rectangles.length > 0);
+ return runRectangleBenchmark({
+ subscribeFrame: (callback) => signals.tick.subscribe(callback),
+ drawScene(scene) {
+ for (let i = rectangles.length - 1; i >= 0; i--) {
+ for (const rect of rectangles[i]) rect.destroy();
+ }
+ rectangles.length = 0;
+ for (let i = 0; i < scene.count; i++) {
+ const size = scene.size[i];
+ const rects = [];
+ rectangles.push(rects);
+ if (RectShader) {
+ const shader = createShader(RectShader);
+ shader.width = 1;
+ shader.color = rectShader.color;
+ if ('align' in shader) shader.align = 0.5;
+ const rect = createElement({
+ x: scene.x[i],
+ y: scene.y[i],
+ w: size,
+ h: size,
+ mountX: 0.5,
+ mountY: 0.5,
+ color: [1, 1, 1, 1],
+ shader,
+ });
+ rects.push(rect);
+ root.addChild(rect);
+ } else {
+ const border = createElement({
+ x: scene.x[i],
+ y: scene.y[i],
+ w: size,
+ h: size,
+ mountX: 0.5,
+ mountY: 0.5,
+ color: FTL_RECT_COLOR,
+ });
+ rects.push(border);
+ root.addChild(border);
+ const fill = createElement({
+ x: scene.x[i],
+ y: scene.y[i],
+ w: Math.max(0, size - 2),
+ h: Math.max(0, size - 2),
+ mountX: 0.5,
+ mountY: 0.5,
+ color: [1, 1, 1, 1],
+ });
+ rects.push(fill);
+ root.addChild(fill);
+ }
+ }
+
+ return (frameScene) => {
+ for (let i = 0; i < rectangles.length; i++) {
+ for (const rect of rectangles[i]) {
+ // FTL's position-only fast path (updateWorldStatePosition) is only
+ // taken via setPosition(); plain x= + dirty() stays on the general
+ // resolver by design.
+ if (typeof rect.setPosition === 'function') {
+ rect.setPosition(frameScene.x[i], frameScene.y[i]);
+ } else {
+ rect.x = frameScene.x[i];
+ rect.dirty();
+ }
+ }
+ }
+ };
+ },
+ });
+};
+
+// L3's indexed quad buffers use 16-bit indices, so a single batch wraps past
+// 16,384 geometry slots — the same limit as Lightning 2. Counts above 16,000
+// are reported as unsupported slices instead of measuring wrapped geometry.
+const L3_MAX_RECTANGLES = 16000;
+
+export const runRendererRectangleBenchmark = async (renderer, parent = renderer.root, BorderShader = null) => {
+ if (BorderShader) renderer.stage.shManager.registerShaderType('RectangleBorder', BorderShader);
+ const adapter = createRectangleAdapter({
+ createRect: ({ x, y, size }) => {
+ if (BorderShader) {
+ return renderer.createNode({
+ x,
+ y,
+ w: size,
+ h: size,
+ mountX: 0.5,
+ mountY: 0.5,
+ color: 0xffffffff,
+ parent,
+ shader: renderer.createShader('RectangleBorder', {
+ w: 1,
+ color: 0x000000ff,
+ align: 'center',
+ }),
+ });
+ }
+
+ const node = renderer.createNode({
+ x,
+ y,
+ w: size,
+ h: size,
+ mountX: 0.5,
+ mountY: 0.5,
+ color: 0x000000ff,
+ parent,
+ });
+ let fill;
+ try {
+ fill = renderer.createNode({
+ x,
+ y,
+ w: Math.max(0, size - 2),
+ h: Math.max(0, size - 2),
+ mountX: 0.5,
+ mountY: 0.5,
+ color: 0xffffffff,
+ parent,
+ });
+ } catch (error) {
+ node.destroy();
+ throw error;
+ }
+ return { node, fill };
+ },
+ destroyRect: (rect) => {
+ if (BorderShader) rect.destroy();
+ else {
+ rect.node.destroy();
+ rect.fill.destroy();
+ }
+ },
+ setX: (rect, x) => {
+ if (BorderShader) rect.x = x;
+ else {
+ rect.node.x = x;
+ rect.fill.x = x;
+ }
+ },
+ });
+ const drawScene = adapter.drawScene;
+ return runRectangleBenchmark({
+ ...adapter,
+ drawScene: (scene) => {
+ if (scene.count > L3_MAX_RECTANGLES) {
+ throw new Error(`Lightning 3 renderer supports at most ${L3_MAX_RECTANGLES.toLocaleString()} rectangles; this slice is unsupported.`);
+ }
+ return drawScene(scene);
+ },
+ subscribeFrame: (callback) => {
+ renderer.on('frameTick', callback);
+ return () => renderer.off('frameTick', callback);
+ },
+ });
+};
diff --git a/testrunner/processResults.js b/testrunner/processResults.js
index 9b423af..7624199 100644
--- a/testrunner/processResults.js
+++ b/testrunner/processResults.js
@@ -10,9 +10,10 @@
* @param {MemoryResults} memoryResults - The memory results object.
* @param {FileSizeResultsObject} fileSizeResults - The file size results object.
* @param {StartupResultsObject} [startupResults] - The startup results object.
+ * @param {Object} [rectangleResults] - Raw rectangle slices per framework/count.
* @returns {Object} - The processed and sorted results object.
*/
-export const processResults = (results, memoryResults, fileSizeResults, startupResults = {}) => {
+export const processResults = (results, memoryResults, fileSizeResults, startupResults = {}, rectangleResults = {}) => {
const processedResults = {};
const fastestTimes = {
create: null,
@@ -103,6 +104,11 @@ export const processResults = (results, memoryResults, fileSizeResults, startupR
if (startupCells[f]) {
processedResults[f].startup = startupCells[f];
}
+ // FPS and its diagnostics are reported independently, not mixed into
+ // the duration-based weighted operation score or framework ordering.
+ if (rectangleResults[f]) {
+ processedResults[f].rectangles = rectangleResults[f];
+ }
});
// sort the frameworks by avgMean
@@ -299,4 +305,4 @@ const computeColor = function (factor) {
const b = (1.0 - a) * 132 + a * 108;
return `rgb(${r.toFixed(0)}, ${g.toFixed(0)}, ${b.toFixed(0)})`;
}
-}
\ No newline at end of file
+}
diff --git a/testrunner/rectangleResults.js b/testrunner/rectangleResults.js
new file mode 100644
index 0000000..909d5cc
--- /dev/null
+++ b/testrunner/rectangleResults.js
@@ -0,0 +1,33 @@
+import { RECTANGLE_COUNTS } from '../shared/rectangleBenchmark.js';
+
+const escapeHtml = (value) => String(value).replace(/[&<>"']/g, (char) => ({
+ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''',
+})[char]);
+
+/** Render the FPS section in the shared results table, preserving slice errors. */
+export const renderRectangleSection = (results, frameworks, frameworkVersions = {}) => {
+ const counts = [...new Set(frameworks.flatMap((framework) =>
+ Object.keys(results[framework].rectangles || {}).map(Number).filter(Number.isFinite),
+ ))].sort((a, b) => a - b);
+ if (!counts.length) counts.push(...RECTANGLE_COUNTS);
+
+ const rows = counts.map((count) => {
+ const cells = frameworks.map((framework) => {
+ const slice = results[framework].rectangles?.[count];
+ if (!slice) return '| n/a | ';
+ if (slice.error) {
+ return `FAIL (0 FPS)${escapeHtml(slice.error)} | `;
+ }
+ if (!Number.isFinite(slice.fps)) return 'n/a | ';
+ // Include the complete diagnostics 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.fps.toFixed(2)} FPS${diagnostics} | `;
+ }).join('');
+ return `| ${count.toLocaleString('en-US')} moving rectangles | ${cells}
`;
+ }).join('\n');
+
+ return `| Rectangle rendering (FPS, higher is better) | ${frameworks.map((framework) =>
+ `${escapeHtml(framework)} ${escapeHtml(frameworkVersions[framework] ?? '')} | `,
+ ).join('')}
${rows}`;
+};
diff --git a/testrunner/runRectangles.js b/testrunner/runRectangles.js
new file mode 100644
index 0000000..fa1b9e1
--- /dev/null
+++ b/testrunner/runRectangles.js
@@ -0,0 +1,137 @@
+import fs from 'fs';
+import { chromium } from 'playwright';
+import { RECTANGLE_COUNTS } from '../shared/rectangleBenchmark.js';
+
+const DEFAULT_SLICE_TIMEOUT_MS = 10 * 60 * 1000;
+
+/** Run each rectangle-count slice in an isolated browser process. */
+export const runRectangleBenchmarks = async (frameworks, browserVersion) => {
+ const counts = process.env.RECTANGLE_COUNTS
+ ? process.env.RECTANGLE_COUNTS.split(',').map((count) => Number.parseInt(count, 10)).filter(Number.isFinite)
+ : RECTANGLE_COUNTS;
+ const cpuThrottlingRate = 6;
+ const warmupMs = Number.parseInt(process.env.RECTANGLE_WARMUP_MS || '1000', 10);
+ const sampleMs = Number.parseInt(process.env.RECTANGLE_SAMPLE_MS || '1500', 10);
+ const samples = Number.parseInt(process.env.RECTANGLE_SAMPLES || '3', 10);
+ const timeoutMs = Number.parseInt(process.env.RECTANGLE_TIMEOUT_MS || `${DEFAULT_SLICE_TIMEOUT_MS}`, 10);
+ const requestedFrameworks = process.env.RECTANGLE_FRAMEWORKS?.split(',').map((name) => name.trim()).filter(Boolean);
+ const baseUrl = process.env.RECTANGLE_BASE_URL || 'http://localhost:8080';
+ if (requestedFrameworks?.length) {
+ frameworks = frameworks.filter((framework) => requestedFrameworks.includes(framework));
+ }
+
+ const startedAt = new Date();
+ const filename = `rectangles_${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: '1280x720 @ 1x; rectangle area 1000x540',
+ counts,
+ warmupMs,
+ sampleMs,
+ samplesPerCount: samples,
+ timeoutMs,
+ cpuThrottlingRate,
+ measurement: 'renderer-callback FPS, not GPU completion or presentation',
+ fpsMeterSmoothing: 10,
+ results,
+ }, null, 2));
+ };
+
+ const runSlice = async (framework, count) => {
+ let browser;
+ let context;
+ let timeout;
+
+ try {
+ // Isolating every count means a renderer crash at 16k cannot discard 4k/8k,
+ // and the next count gets a clean process and graphics context.
+ browser = await chromium.launch({ headless: process.env.HEADLESS === 'true' });
+ context = await browser.newContext({
+ viewport: { width: 1280, height: 720 },
+ 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.__RECTANGLE_BENCHMARK_CONFIG__ = config;
+ }, { counts: [count], warmupMs, sampleMs, samples });
+
+ 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} ${count} rectangle slice timed out after ${timeoutMs}ms`),
+ ), timeoutMs);
+
+ page.on('console', async (message) => {
+ if (!message.text().startsWith('Rectangles!')) return;
+ try {
+ const results = await message.args()[1].jsonValue();
+ finish(resolve, results[count]);
+ } catch (error) {
+ finish(reject, error);
+ }
+ });
+ page.on('pageerror', (error) => finish(reject, error));
+ page.on('crash', () => finish(reject, new Error(`${framework} page crashed at ${count} rectangles`)));
+ browser.on('disconnected', () => finish(reject, new Error(`${framework} browser process disconnected at ${count} rectangles`)));
+
+ const url = framework === 'blits'
+ ? `${baseUrl}/${framework}/#/rectangles`
+ : `${baseUrl}/${framework}/#rectangles`;
+ page.goto(url).catch((error) => finish(reject, error));
+ });
+
+ if (!result) throw new Error(`${framework} did not return a result for ${count} rectangles`);
+ return result;
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ console.error(`Rectangle slice failed for ${framework} at ${count}: ${message}`);
+ return { fps: 0, samples: [], error: message };
+ } finally {
+ clearTimeout(timeout);
+ await context?.close().catch(() => {});
+ await browser?.close().catch(() => {});
+ }
+ };
+
+ writePartialResults();
+ for (const framework of frameworks) {
+ results[framework] = {};
+ for (const count of counts) {
+ console.log(`Running rectangle benchmark for ${framework} at ${count.toLocaleString()} rectangles`);
+ results[framework][count] = await runSlice(framework, count);
+ const slice = results[framework][count];
+ console.log(`${framework} ${count.toLocaleString()}: ${slice.error || `${slice.fps.toFixed(2)} FPS`}`);
+ if (slice.rafFps !== undefined) {
+ console.log(` RAF cross-check: ${slice.rafFps.toFixed(2)} FPS`);
+ }
+ if (slice.measurements) {
+ console.log(` FPSMeter-style: ${slice.meterFps.toFixed(2)} FPS; p95 intervals: ${slice.measurements.map((m) => m.framePacing.p95Ms?.toFixed(1) ?? '-').join(', ')}ms`);
+ }
+ writePartialResults();
+ }
+ }
+
+ console.log('Average FPS by framework and rectangle count:');
+ console.table(Object.fromEntries(Object.entries(results).map(([framework, slices]) => [
+ framework,
+ Object.fromEntries(Object.entries(slices).map(([count, result]) => [
+ count,
+ result.error ? `FAIL (${result.error})` : `${result.fps.toFixed(2)} FPS`,
+ ])),
+ ])));
+ console.log(`Rectangle results written to ./results/${filename}`);
+ return JSON.parse(fs.readFileSync(`./results/${filename}`, 'utf8'));
+};
diff --git a/testrunner/writeResults.js b/testrunner/writeResults.js
index b106ab5..513421c 100644
--- a/testrunner/writeResults.js
+++ b/testrunner/writeResults.js
@@ -17,6 +17,7 @@
import fs from 'fs';
import { getOSInfo, getSystemInfo } from "./systemInfo.js";
+import { renderRectangleSection } from './rectangleResults.js';
const indexHeader = `
@@ -286,10 +287,11 @@ export const writeResults = (results, frameworkVersions, browserVersion) => {
const hasMemory = frameworks.some(f => results[f].memory);
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);
// write the results header with only the relevant descriptions
fileStream.write(resultsHeader.replace('{{resultsDescription}}',
- `${hasOps ? opsDescription : ''}${hasStartup ? startupDescription : ''}`
+ `${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.
' : ''}`
));
// write some html
@@ -371,6 +373,10 @@ export const writeResults = (results, frameworkVersions, browserVersion) => {
);
}
+ if (hasRectangles) {
+ sections.push(renderRectangleSection(results, frameworks, frameworkVersions));
+ }
+
fileStream.write(table.replace('{{sections}}', sections.join('\n')));
// write the footer
@@ -385,4 +391,3 @@ export const writeResults = (results, frameworkVersions, browserVersion) => {
});
});
}
-
diff --git a/tests/rectangleBenchmark.test.js b/tests/rectangleBenchmark.test.js
new file mode 100644
index 0000000..0d14985
--- /dev/null
+++ b/tests/rectangleBenchmark.test.js
@@ -0,0 +1,67 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import {
+ createRectangleAdapter,
+ createRectangleScene,
+ advanceRectangleScene,
+ summarizeFrameIntervals,
+ RECTANGLE_COUNTS,
+ tickFpsMeter,
+} from '../shared/rectangleBenchmark.js';
+
+test('default loads are 4k, 8k and 16k', () => {
+ assert.deepEqual(RECTANGLE_COUNTS, [4000, 8000, 16000]);
+});
+
+test('FPSMeter smoothing matches the reference tick formula', () => {
+ const meter = { frameTime: 20, lastTick: 100 };
+ assert.equal(tickFpsMeter(meter, 140), 1000 / 22);
+ assert.equal(meter.lastTick, 140);
+ assert.equal(tickFpsMeter(meter, 160), 1000 / 21.8);
+});
+
+test('frame pacing exposes long gaps hidden by average FPS', () => {
+ const pacing = summarizeFrameIntervals([16, 17, 16, 100, 16]);
+ assert.equal(pacing.medianMs, 16);
+ assert.equal(pacing.p95Ms, 100);
+ assert.equal(pacing.maxMs, 100);
+ assert.equal(pacing.over25Ms, 1);
+ assert.equal(pacing.over50Ms, 1);
+ assert.equal(summarizeFrameIntervals([]).p95Ms, null);
+});
+
+test('adapter scene dimensions match the 1000x540 drawing area', () => {
+ const adapter = createRectangleAdapter({
+ createRect: (props) => props,
+ destroyRect: () => {},
+ setX: () => {},
+ });
+ assert.equal(adapter.width, 1000);
+ assert.equal(adapter.height, 540);
+ const scene = createRectangleScene(32000, adapter.width, adapter.height);
+ for (let i = 0; i < scene.count; i++) {
+ assert.ok(scene.x[i] >= 0 && scene.x[i] <= adapter.width);
+ assert.ok(scene.y[i] >= 0 && scene.y[i] <= adapter.height);
+ }
+});
+
+test('adapter replaces the previous slice rather than accumulating rectangles', () => {
+ const created = [];
+ const destroyed = [];
+ const adapter = createRectangleAdapter({
+ createRect: (props) => {
+ created.push(props);
+ return props;
+ },
+ destroyRect: (rect) => destroyed.push(rect),
+ setX: (rect, x) => { rect.x = x; },
+ });
+ adapter.drawScene(createRectangleScene(4000, adapter.width, adapter.height));
+ const scene = createRectangleScene(8000, adapter.width, adapter.height);
+ const drawFrame = adapter.drawScene(scene);
+ assert.equal(created.length, 12000);
+ assert.equal(destroyed.length, 4000);
+ advanceRectangleScene(scene);
+ drawFrame(scene);
+ assert.equal(created[4000].x, scene.x[0]);
+});
diff --git a/tests/rectangleResults.test.js b/tests/rectangleResults.test.js
new file mode 100644
index 0000000..24d83db
--- /dev/null
+++ b/tests/rectangleResults.test.js
@@ -0,0 +1,66 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import fs from 'node:fs/promises';
+import { processResults } from '../testrunner/processResults.js';
+import { renderRectangleSection } from '../testrunner/rectangleResults.js';
+import { writeResults } from '../testrunner/writeResults.js';
+
+test('full result processing keeps rectangle slices without changing the weighted score', () => {
+ const operations = { a: { create: '10ms' }, b: { create: '20ms' } };
+ const rectangles = {
+ a: { 8000: { fps: 50, samples: [50] }, 16000: { fps: 0, error: 'crash' } },
+ b: { 8000: { fps: 60, samples: [60] } },
+ };
+ const baseline = processResults(operations, {}, {}, {});
+ const combined = processResults(operations, {}, {}, {}, rectangles);
+ 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].rectangles, rectangles[framework]);
+ }
+});
+
+test('overview renders FPS, pacing diagnostics, escaped failures, and missing slices', () => {
+ const html = renderRectangleSection({
+ a: { rectangles: {
+ 8000: { fps: 42.125, measurements: [{ framePacing: { p95Ms: 50 } }] },
+ 64000: { fps: 0, error: ' ' },
+ } },
+ b: {},
+ }, ['a', 'b'], { a: '1.0' });
+ assert.match(html, /42\.13 FPS/);
+ assert.match(html, /8,000 moving rectangles/);
+ assert.match(html, /64,000 moving rectangles/);
+ assert.match(html, /FAIL \(0 FPS\)/);
+ assert.match(html, /p95Ms/);
+ assert.match(html, /<script>crash<\/script>/);
+ assert.match(html, /<SCRIPT>alert\(1\)<\/SCRIPT>/);
+ assert.doesNotMatch(html, /