From fa7268fee59fc72a34c8468c86532762602a502f Mon Sep 17 00:00:00 2001 From: alowpoly Date: Thu, 3 Dec 2026 09:20:52 -0300 Subject: [PATCH 01/15] chore(bench): prune 40 dead harnesses, slim bundler, and clear deep-import allowlist --- .github/scripts/check-boundaries.mjs | 10 +- bench/README.md | 29 + bench/anim-shadow-test.html | 25 - bench/animated-human-bench.mjs | 775 ----- bench/animated-human.html | 671 ----- bench/async-scene-mount-bench.mjs | 160 - bench/async-scene-mount.html | 56 - bench/atlas-background-bench.mjs | 145 - bench/atlas-background.html | 39 - bench/build.mjs | 105 +- bench/entries/asyncSceneMount.ts | 333 --- bench/entries/atlasBackground.ts | 177 -- bench/entries/htmlMount.ts | 375 --- bench/entries/parityMeshes.ts | 34 - bench/entries/shadowParityReact.tsx | 50 - bench/entries/shadowParityVue.ts | 55 - bench/entries/syncSceneAdd.ts | 162 -- bench/entries/threeParityDashboard.ts | 936 ------ bench/html-mount-bench.mjs | 152 - bench/html-mount.html | 53 - bench/mask-polygon-bench.mjs | 423 --- bench/mask-polygon.html | 558 ---- bench/nonvoxel-visual-compare.mjs | 326 --- bench/parity-quad.html | 330 --- bench/perspective-receiver-shadow.html | 291 -- bench/point-light-oracle.html | 3062 -------------------- bench/real-shadow.html | 604 ---- bench/scripts/color-delta.mjs | 40 - bench/scripts/point-light-mask-verdict.mjs | 57 - bench/scripts/shadow-mask-verdict.mjs | 57 - bench/scripts/shadow-oracle-verdict.mjs | 46 - bench/scripts/shadow-regression.mjs | 150 - bench/scripts/threejs-parity-shots.mjs | 87 - bench/shadow-diff.mjs | 91 - bench/shadow-oracle.html | 3038 ------------------- bench/shadow-parametric.html | 2913 ------------------- bench/shadow-parity.html | 222 -- bench/shadow-rubric.mjs | 117 - bench/shadow-trace.html | 130 - bench/snap-shadow.mjs | 16 - bench/sync-scene-add-bench.mjs | 152 - bench/sync-scene-add.html | 52 - bench/three-parity.html | 143 - 43 files changed, 71 insertions(+), 17176 deletions(-) create mode 100644 bench/README.md delete mode 100644 bench/anim-shadow-test.html delete mode 100644 bench/animated-human-bench.mjs delete mode 100644 bench/animated-human.html delete mode 100644 bench/async-scene-mount-bench.mjs delete mode 100644 bench/async-scene-mount.html delete mode 100644 bench/atlas-background-bench.mjs delete mode 100644 bench/atlas-background.html delete mode 100644 bench/entries/asyncSceneMount.ts delete mode 100644 bench/entries/atlasBackground.ts delete mode 100644 bench/entries/htmlMount.ts delete mode 100644 bench/entries/parityMeshes.ts delete mode 100644 bench/entries/shadowParityReact.tsx delete mode 100644 bench/entries/shadowParityVue.ts delete mode 100644 bench/entries/syncSceneAdd.ts delete mode 100644 bench/entries/threeParityDashboard.ts delete mode 100644 bench/html-mount-bench.mjs delete mode 100644 bench/html-mount.html delete mode 100644 bench/mask-polygon-bench.mjs delete mode 100644 bench/mask-polygon.html delete mode 100644 bench/nonvoxel-visual-compare.mjs delete mode 100644 bench/parity-quad.html delete mode 100644 bench/perspective-receiver-shadow.html delete mode 100644 bench/point-light-oracle.html delete mode 100644 bench/real-shadow.html delete mode 100644 bench/scripts/color-delta.mjs delete mode 100644 bench/scripts/point-light-mask-verdict.mjs delete mode 100644 bench/scripts/shadow-mask-verdict.mjs delete mode 100644 bench/scripts/shadow-oracle-verdict.mjs delete mode 100644 bench/scripts/shadow-regression.mjs delete mode 100644 bench/scripts/threejs-parity-shots.mjs delete mode 100644 bench/shadow-diff.mjs delete mode 100644 bench/shadow-oracle.html delete mode 100644 bench/shadow-parametric.html delete mode 100644 bench/shadow-parity.html delete mode 100644 bench/shadow-rubric.mjs delete mode 100644 bench/shadow-trace.html delete mode 100644 bench/snap-shadow.mjs delete mode 100644 bench/sync-scene-add-bench.mjs delete mode 100644 bench/sync-scene-add.html delete mode 100644 bench/three-parity.html diff --git a/.github/scripts/check-boundaries.mjs b/.github/scripts/check-boundaries.mjs index 4a12a329a..ab85ecda7 100644 --- a/.github/scripts/check-boundaries.mjs +++ b/.github/scripts/check-boundaries.mjs @@ -65,14 +65,10 @@ const NO_NODE_BUILTINS = new Set(["core", "polycss", "react", "vue", "fonts"]); const MORPH_NODE_PREFIX = `src${sep}prepare${sep}`; /** - * Known deep-src imports that are accepted for now. Keep this list SHORT and - * annotated; every entry is debt. + * Known deep-src imports that are accepted for now. Keep this list empty; + * every entry is debt. */ -export const DEEP_IMPORT_ALLOWLIST = new Set([ - // bench/ is not a workspace member, and the atlas emit surface it measures - // is intentionally not public API. Tracked as F1 in the architecture notes. - "bench/entries/atlasBackground.ts", -]); +export const DEEP_IMPORT_ALLOWLIST = new Set(); const SOURCE_RE = /\.(ts|tsx|mts|cts|mjs|cjs|js)$/; diff --git a/bench/README.md b/bench/README.md new file mode 100644 index 000000000..4fef51742 --- /dev/null +++ b/bench/README.md @@ -0,0 +1,29 @@ +# PolyCSS Bench & Visual Gates + +Browser harnesses, visual regression gates, IR conformance checks, and geometry benchmarks. + +## Primary commands + +- `pnpm bench:build` — bundle the 5 browser entries (`polycss`, `polycss-elements`, `polycss-render-stats`, `polycss-react`, `polycss-vue`) into `bench/.generated/`. +- `pnpm bench:gate:parity` — HEAD internal equivalence across vanilla, HTML elements, React, and Vue (`pixelmatch`, zero committed baselines). +- `pnpm bench:gate:strict -- --base-ref main` — fail-closed base-vs-candidate static triptych gate (`threshold: 0, includeAA: true`, 0 px diff, `pageerror` + `renderStats` tag-shift checks). +- `pnpm bench:gate:ci -- --base-ref main` — single-pass `strict,parity` run with shared static capture cache and `report.html` output. +- `pnpm bench:gate:oracle -- --base-ref main` — compare base and candidate dynamic lighting against base `mode=baked`. +- `pnpm bench:gate:video -- --base-ref main` — 360° frame-locked motion triptych MP4 gate. +- `pnpm check:ir` — zero-browser cross-renderer DOM/CSS IR conformance (`bench/renderer-ir-conformance.test.mjs`). +- `pnpm bench:serve` / `pnpm bench:perf` — local bench server (`:4400`) and FPS/frame-time benchmark (`bench/perf-*.html`). + +## Standalone corpus & micro-benchmarks + +Run directly with `node` (build `@layoutit/polycss-core` first when needed): + +- `bench/gltf-simplifier-corpus-bench.mjs` +- `bench/lossy-optimizer-bench.mjs` and `bench/lossy-corpus-bench.mjs` +- `bench/minecraft-movement-bench.mjs` +- `bench/nonvoxel-rotation-bench.mjs` +- `bench/seam-gap-bench.mjs` +- `bench/shadow-timing-bench.mjs` +- `bench/stl-corpus-sanity.mjs` +- `bench/vox-import-bench.mjs` + +Investigation notes live in `bench/notes/`. diff --git a/bench/anim-shadow-test.html b/bench/anim-shadow-test.html deleted file mode 100644 index 9ea4a7033..000000000 --- a/bench/anim-shadow-test.html +++ /dev/null @@ -1,25 +0,0 @@ - - -
- - diff --git a/bench/animated-human-bench.mjs b/bench/animated-human-bench.mjs deleted file mode 100644 index e63592edf..000000000 --- a/bench/animated-human-bench.mjs +++ /dev/null @@ -1,775 +0,0 @@ -#!/usr/bin/env node -/** - * Playwright benchmark for the animated human run sequence. - * - * The page drives the real vanilla animation path: - * parse GLB -> sample clip -> createPolyAnimationMixer.update(dt) -> - * PolyMeshHandle.setPolygons(..., { merge:false, stableDom:true }). - * - * Usage: - * node bench/animated-human-bench.mjs - * node bench/animated-human-bench.mjs --mode baked,dynamic --label human-run - * node bench/animated-human-bench.mjs --compare-stable-dom --trace - * node bench/animated-human-bench.mjs --profile - * node bench/animated-human-bench.mjs --mesh poly-pizza/animated-human.glb --clip run - */ -import { createServer } from "node:http"; -import { mkdirSync, writeFileSync } from "node:fs"; -import { readFile } from "node:fs/promises"; -import { dirname, extname, resolve } from "node:path"; -import { fileURLToPath } from "node:url"; -import { chromium } from "playwright"; -import { chromiumArgsWithGpuDefault } from "./chromium-defaults.mjs"; - -const __dirname = dirname(fileURLToPath(import.meta.url)); -const repoRoot = resolve(__dirname, ".."); -const benchDir = resolve(repoRoot, "bench"); -const galleryDir = resolve(repoRoot, "website/public/gallery"); - -const argv = process.argv.slice(2); -const flag = (name) => argv.indexOf(`--${name}`); -const optStr = (name, dflt = "") => { - const i = flag(name); - if (i >= 0) return argv[i + 1] ?? dflt; - const prefixed = argv.find((arg) => arg.startsWith(`--${name}=`)); - return prefixed ? prefixed.slice(name.length + 3) : dflt; -}; -const optNum = (name, dflt) => { - const raw = optStr(name); - if (raw.trim() === "") return dflt; - const value = Number(raw); - return Number.isFinite(value) ? value : dflt; -}; -const optAll = (name) => { - const values = []; - for (let i = 0; i < argv.length; i += 1) { - const arg = argv[i]; - if (arg === `--${name}` && argv[i + 1]) { - values.push(argv[i + 1]); - i += 1; - } else if (arg.startsWith(`--${name}=`)) { - values.push(arg.slice(name.length + 3)); - } - } - return values; -}; -const hasFlag = (name) => flag(name) >= 0 || argv.includes(`--${name}=true`); -const hasOpt = (name) => - flag(name) >= 0 || argv.some((arg) => arg.startsWith(`--${name}=`)); - -const MESH = optStr("mesh", "poly-pizza/animated-human.glb"); -const CLIP = optStr("clip", "run"); -const TARGET_SIZE = optNum("target-size", optNum("targetSize", 72)); -const TIME_SCALE = optNum("time-scale", optNum("timeScale", 1)); -const WARMUP_MS = optNum("warmup", 2000); -const SAMPLE_MS = optNum("sample", 5000); -const RUNS = Math.max(1, optNum("runs", 1)); -const LABEL = optStr("label"); -const JSON_PATH = optStr("json"); -const HEADED = hasFlag("headed"); -const TRACE = hasFlag("trace"); -const PROFILE = hasFlag("profile"); -const COMPARE_STABLE_TRIANGLE_DEBUG = hasFlag("compare-stable-triangle-debug"); -const COMPARE_ANIMATION_DRIVER = hasFlag("compare-animation-driver"); -const COMPARE_ANIMATION_FRAME_CACHE = hasFlag("compare-animation-frame-cache"); -const COMPARE_ANIMATED_MESH_OPTIMIZATION = hasFlag("compare-animated-mesh-optimization"); -const REQUIRE_SOLID_TRIANGLES = hasFlag("require-solid-triangles"); -const BROWSER_EXECUTABLE = optStr("browser-executable"); -const SOFTWARE_BACKEND = hasFlag("software-backend"); -const SOLID_TEXTURE_SAMPLES = !hasFlag("no-solid-texture-samples"); -const DISABLE_STRATEGIES = optStr("disable-strategies", optStr("disableStrategies")); -const STABLE_TRIANGLE_DEBUG = optStr("stable-triangle-debug", optStr("stableTriangleDebug")); -const ANIMATION_DRIVER = optStr("animation-driver", optStr("animationDriver", "js")); -const ANIMATION_FRAME_CACHE = hasFlag("animation-frame-cache") || hasFlag("animationFrameCache"); -const ANIMATION_FRAME_CACHE_FRAMES = optNum( - "animation-frame-cache-frames", - optNum("animationFrameCacheFrames", 60), -); -const KEYFRAME_SAMPLES = optNum("keyframe-samples", optNum("keyframeSamples", 24)); -const DEFAULT_STABLE_TRIANGLE_COLOR_STEPS = 8; -const DEFAULT_STABLE_TRIANGLE_COLOR_POLICY = "cadence"; -const DEFAULT_STABLE_TRIANGLE_COLOR_FREEZE_FRAMES = 0; -const DEFAULT_STABLE_TRIANGLE_COLOR_BUDGET = 0.16; -const DEFAULT_STABLE_TRIANGLE_COLOR_MAX_AGE = 8; -const DEFAULT_STABLE_TRIANGLE_COLOR_MAX_STEP = 8; -const HAS_STABLE_TRIANGLE_COLOR_STEPS = - hasOpt("stable-triangle-color-steps") || hasOpt("stableTriangleColorSteps"); -const STABLE_TRIANGLE_COLOR_STEPS = optNum( - "stable-triangle-color-steps", - optNum("stableTriangleColorSteps", DEFAULT_STABLE_TRIANGLE_COLOR_STEPS), -); -const HAS_STABLE_TRIANGLE_COLOR_POLICY = - hasOpt("stable-triangle-color-policy") || hasOpt("stableTriangleColorPolicy"); -const STABLE_TRIANGLE_COLOR_POLICY = optStr( - "stable-triangle-color-policy", - optStr("stableTriangleColorPolicy", DEFAULT_STABLE_TRIANGLE_COLOR_POLICY), -); -const HAS_STABLE_TRIANGLE_COLOR_FREEZE_FRAMES = - hasOpt("stable-triangle-color-freeze-frames") || hasOpt("stableTriangleColorFreezeFrames"); -const STABLE_TRIANGLE_COLOR_FREEZE_FRAMES = optNum( - "stable-triangle-color-freeze-frames", - optNum("stableTriangleColorFreezeFrames", 0), -); -const HAS_STABLE_TRIANGLE_COLOR_BUDGET = - hasOpt("stable-triangle-color-budget") || hasOpt("stableTriangleColorBudget"); -const STABLE_TRIANGLE_COLOR_BUDGET = optNum( - "stable-triangle-color-budget", - optNum("stableTriangleColorBudget", 0), -); -const HAS_STABLE_TRIANGLE_COLOR_MAX_AGE = - hasOpt("stable-triangle-color-max-age") || hasOpt("stableTriangleColorMaxAge"); -const STABLE_TRIANGLE_COLOR_MAX_AGE = optNum( - "stable-triangle-color-max-age", - optNum("stableTriangleColorMaxAge", 0), -); -const HAS_STABLE_TRIANGLE_COLOR_MAX_STEP = - hasOpt("stable-triangle-color-max-step") || hasOpt("stableTriangleColorMaxStep"); -const STABLE_TRIANGLE_COLOR_MAX_STEP = optNum( - "stable-triangle-color-max-step", - optNum("stableTriangleColorMaxStep", 0), -); -const HAS_STABLE_TRIANGLE_MATRIX_DECIMALS = - hasOpt("stable-triangle-matrix-decimals") || hasOpt("stableTriangleMatrixDecimals"); -const STABLE_TRIANGLE_MATRIX_DECIMALS = optNum( - "stable-triangle-matrix-decimals", - optNum("stableTriangleMatrixDecimals", 3), -); -const STABLE_TRIANGLE_COLOR_STEPS_LABEL = HAS_STABLE_TRIANGLE_COLOR_STEPS - ? String(STABLE_TRIANGLE_COLOR_STEPS) - : `auto(${DEFAULT_STABLE_TRIANGLE_COLOR_STEPS})`; -const STABLE_TRIANGLE_COLOR_POLICY_LABEL = HAS_STABLE_TRIANGLE_COLOR_POLICY - ? STABLE_TRIANGLE_COLOR_POLICY - : `auto(${DEFAULT_STABLE_TRIANGLE_COLOR_POLICY})`; -const STABLE_TRIANGLE_COLOR_FREEZE_FRAMES_LABEL = HAS_STABLE_TRIANGLE_COLOR_FREEZE_FRAMES - ? String(STABLE_TRIANGLE_COLOR_FREEZE_FRAMES) - : `auto(${DEFAULT_STABLE_TRIANGLE_COLOR_FREEZE_FRAMES})`; -const STABLE_TRIANGLE_COLOR_BUDGET_LABEL = HAS_STABLE_TRIANGLE_COLOR_BUDGET - ? String(STABLE_TRIANGLE_COLOR_BUDGET) - : `auto(${DEFAULT_STABLE_TRIANGLE_COLOR_BUDGET} adaptive)`; -const STABLE_TRIANGLE_COLOR_MAX_AGE_LABEL = HAS_STABLE_TRIANGLE_COLOR_MAX_AGE - ? String(STABLE_TRIANGLE_COLOR_MAX_AGE) - : `auto(${DEFAULT_STABLE_TRIANGLE_COLOR_MAX_AGE} adaptive)`; -const STABLE_TRIANGLE_COLOR_MAX_STEP_LABEL = HAS_STABLE_TRIANGLE_COLOR_MAX_STEP - ? String(STABLE_TRIANGLE_COLOR_MAX_STEP) - : `auto(${DEFAULT_STABLE_TRIANGLE_COLOR_MAX_STEP})`; -const STABLE_TRIANGLE_MATRIX_DECIMALS_LABEL = HAS_STABLE_TRIANGLE_MATRIX_DECIMALS - ? String(STABLE_TRIANGLE_MATRIX_DECIMALS) - : "auto(3)"; -const CHROMIUM_ARGS = chromiumArgsWithGpuDefault([ - ...optAll("chromium-arg"), - ...optAll("chromium-args").flatMap((value) => value.split(/\s+/).filter(Boolean)), -], { softwareBackend: SOFTWARE_BACKEND }); - -const MODES = optStr("mode", "baked") - .split(",") - .map((value) => value.trim()) - .filter(Boolean) - .map((value) => value === "dynamic" ? "dynamic" : "baked"); -const STABLE_DOM_VARIANTS = hasFlag("compare-stable-dom") - ? [true, false] - : [!hasFlag("no-stable-dom")]; -const STABLE_TRIANGLE_DEBUG_VARIANTS = COMPARE_STABLE_TRIANGLE_DEBUG - ? ["", "transform-only", "plan-only"] - : [STABLE_TRIANGLE_DEBUG].filter((value) => - value === "" || value === "transform-only" || value === "plan-only" - ); -const VALID_ANIMATION_DRIVERS = [ - "js", - "css-keyframes", - "js-style-cache", - "typed-om-style-cache", - "progressive-style-cache", -]; -const ANIMATION_DRIVER_VARIANTS = COMPARE_ANIMATION_DRIVER - ? ["js", "progressive-style-cache", "js-style-cache", "css-keyframes"] - : [VALID_ANIMATION_DRIVERS.includes(ANIMATION_DRIVER) - ? ANIMATION_DRIVER - : "js"]; -const ANIMATION_FRAME_CACHE_VARIANTS = COMPARE_ANIMATION_FRAME_CACHE - ? [false, true] - : [ANIMATION_FRAME_CACHE]; -const ANIMATED_MESH_OPTIMIZATION_VARIANTS = COMPARE_ANIMATED_MESH_OPTIMIZATION - ? [false, true] - : [hasFlag("animated-mesh-optimization") || hasFlag("animatedMeshOptimization")]; - -const MIME = { - ".html": "text/html; charset=utf-8", - ".js": "application/javascript; charset=utf-8", - ".mjs": "application/javascript; charset=utf-8", - ".css": "text/css; charset=utf-8", - ".json": "application/json; charset=utf-8", - ".glb": "model/gltf-binary", - ".gltf": "application/json; charset=utf-8", - ".png": "image/png", - ".jpg": "image/jpeg", - ".jpeg": "image/jpeg", - ".webp": "image/webp", -}; - -const TRACE_CATEGORIES = [ - "devtools.timeline", - "disabled-by-default-devtools.timeline", - "blink", - "blink.user_timing", - "cc", - "gpu", - "viz", - "renderer.scheduler", -].join(","); - -function startServer() { - return new Promise((resolveStart, rejectStart) => { - const server = createServer(async (req, res) => { - try { - const u = new URL(req.url, "http://localhost"); - const safe = u.pathname.replace(/\/+/g, "/"); - if (safe.includes("..")) { - res.writeHead(403); - res.end(); - return; - } - const abs = safe.startsWith("/gallery/") - ? resolve(galleryDir, safe.slice("/gallery/".length)) - : resolve(benchDir, safe === "/" ? "animated-human.html" : safe.slice(1)); - const data = await readFile(abs); - res.writeHead(200, { - "Content-Type": MIME[extname(abs).toLowerCase()] || "application/octet-stream", - "Cache-Control": "no-store", - }); - res.end(data); - } catch (error) { - res.writeHead(404); - res.end(String(error?.message ?? error)); - } - }); - server.on("error", rejectStart); - server.listen(0, "127.0.0.1", () => { - const addr = server.address(); - resolveStart({ server, port: typeof addr === "object" ? addr.port : 0 }); - }); - }); -} - -function stopServer(server) { - return new Promise((resolveStop) => server.close(resolveStop)); -} - -function quantile(values, q) { - const sorted = values.filter(Number.isFinite).sort((a, b) => a - b); - if (sorted.length === 0) return 0; - const i = (sorted.length - 1) * q; - const lo = Math.floor(i); - const hi = Math.ceil(i); - if (lo === hi) return sorted[lo]; - return sorted[lo] + (sorted[hi] - sorted[lo]) * (i - lo); -} - -function summarizeFrameTimes(samples) { - const dtsRaw = samples.map((sample) => sample.dt).filter((dt) => dt > 0); - const dts = dtsRaw.filter((dt) => dt < 2000); - const p50 = quantile(dts, 0.5); - const p95 = quantile(dts, 0.95); - const p99 = quantile(dts, 0.99); - return { - fps_p50: p50 > 0 ? +(1000 / p50).toFixed(2) : 0, - fps_p95: p95 > 0 ? +(1000 / p95).toFixed(2) : 0, - frame_time_p50_ms: +p50.toFixed(3), - frame_time_p95_ms: +p95.toFixed(3), - frame_time_p99_ms: +p99.toFixed(3), - sample_count: dts.length, - sample_count_raw: dtsRaw.length, - sample_count_filtered: dtsRaw.length - dts.length, - }; -} - -function summarizeDurations(samples, key) { - const values = samples - .map((sample) => Number(sample?.[key])) - .filter((value) => Number.isFinite(value) && value >= 0); - if (values.length === 0) { - return { p50_ms: 0, p95_ms: 0, p99_ms: 0, avg_ms: 0, max_ms: 0 }; - } - const sum = values.reduce((acc, value) => acc + value, 0); - return { - p50_ms: +quantile(values, 0.5).toFixed(3), - p95_ms: +quantile(values, 0.95).toFixed(3), - p99_ms: +quantile(values, 0.99).toFixed(3), - avg_ms: +(sum / values.length).toFixed(3), - max_ms: +Math.max(...values).toFixed(3), - }; -} - -function metricMap(metrics) { - const out = new Map(); - for (const metric of metrics?.metrics ?? []) out.set(metric.name, metric.value); - return out; -} - -function diffPerformanceMetrics(before, after) { - const a = metricMap(before); - const b = metricMap(after); - const keys = [ - "Timestamp", - "Documents", - "Frames", - "JSEventListeners", - "Nodes", - "LayoutCount", - "RecalcStyleCount", - "LayoutDuration", - "RecalcStyleDuration", - "ScriptDuration", - "TaskDuration", - "JSHeapUsedSize", - "JSHeapTotalSize", - ]; - const out = {}; - for (const key of keys) { - const beforeValue = a.get(key); - const afterValue = b.get(key); - if (beforeValue === undefined || afterValue === undefined) continue; - const value = key === "Timestamp" || key === "Documents" || key === "Frames" || - key === "JSEventListeners" || key === "Nodes" || - key === "JSHeapUsedSize" || key === "JSHeapTotalSize" - ? afterValue - : afterValue - beforeValue; - out[key] = Number(value.toFixed(key.endsWith("Duration") ? 6 : 3)); - } - return out; -} - -function summarizeTraceEvents(events) { - const byName = new Map(); - let completeEventCount = 0; - let totalDurationUs = 0; - for (const event of events) { - if (event?.ph !== "X" || typeof event.dur !== "number") continue; - completeEventCount += 1; - totalDurationUs += event.dur; - const prev = byName.get(event.name) ?? { count: 0, durationUs: 0 }; - prev.count += 1; - prev.durationUs += event.dur; - byName.set(event.name, prev); - } - - const get = (...names) => { - let count = 0; - let durationUs = 0; - for (const name of names) { - const entry = byName.get(name); - if (!entry) continue; - count += entry.count; - durationUs += entry.durationUs; - } - return { count, duration_ms: +(durationUs / 1000).toFixed(3) }; - }; - - return { - eventCount: events.length, - completeEventCount, - totalCompleteDurationMs: +(totalDurationUs / 1000).toFixed(3), - groups: { - style: get("UpdateLayoutTree", "RecalculateStyles"), - layout: get("Layout"), - prePaint: get("PrePaint"), - paint: get("Paint"), - raster: get("RasterTask", "ImageDecodeTask", "Decode Image"), - script: get("FunctionCall", "EvaluateScript", "EventDispatch", "TimerFire", "FireAnimationFrame"), - compositorMain: get( - "ProxyMain::BeginMainFrame", - "WebFrameWidgetImpl::UpdateLifecycle", - "PaintArtifactCompositor::Update", - "Layerize", - "Commit", - "ProxyImpl::ReadyToCommit", - ), - compositorImpl: get( - "LayerTreeImpl::UpdateDrawProperties", - "LayerTreeHostImpl::PrepareToDraw", - "MainFrame.Draw", - "SubmitCompositorFrame", - ), - }, - topEvents: [...byName.entries()] - .sort((a, b) => b[1].durationUs - a[1].durationUs) - .slice(0, 16) - .map(([name, entry]) => ({ - name, - count: entry.count, - duration_ms: +(entry.durationUs / 1000).toFixed(3), - })), - }; -} - -async function startTrace(cdp) { - const events = []; - cdp.on("Tracing.dataCollected", (payload) => { - if (Array.isArray(payload.value)) events.push(...payload.value); - }); - await cdp.send("Performance.enable"); - await cdp.send("Tracing.start", { - transferMode: "ReportEvents", - categories: TRACE_CATEGORIES, - }); - return events; -} - -async function stopTrace(cdp, events) { - const done = new Promise((resolveDone) => { - cdp.once("Tracing.tracingComplete", resolveDone); - }); - await cdp.send("Tracing.end"); - await done; - return summarizeTraceEvents(events); -} - -function cpuFrameLabel(callFrame) { - const fn = callFrame?.functionName || "(anonymous)"; - const url = callFrame?.url ? callFrame.url.split("/").pop() : ""; - const line = Number.isFinite(callFrame?.lineNumber) ? callFrame.lineNumber + 1 : 0; - return url ? `${fn} (${url}:${line})` : fn; -} - -function summarizeCpuProfile(profile) { - const nodeById = new Map(); - for (const node of profile?.nodes ?? []) nodeById.set(node.id, node); - const samples = profile?.samples ?? []; - const deltas = profile?.timeDeltas ?? []; - const fallbackDeltaUs = samples.length > 0 && Number.isFinite(profile?.endTime) && Number.isFinite(profile?.startTime) - ? ((profile.endTime - profile.startTime) * 1000) / samples.length - : 0; - - let totalUs = 0; - const byFrame = new Map(); - for (let i = 0; i < samples.length; i += 1) { - const node = nodeById.get(samples[i]); - if (!node) continue; - const deltaUs = Number.isFinite(deltas[i]) ? deltas[i] : fallbackDeltaUs; - totalUs += deltaUs; - const label = cpuFrameLabel(node.callFrame); - const entry = byFrame.get(label) ?? { - frame: label, - functionName: node.callFrame?.functionName || "(anonymous)", - url: node.callFrame?.url || "", - line: Number.isFinite(node.callFrame?.lineNumber) ? node.callFrame.lineNumber + 1 : null, - column: Number.isFinite(node.callFrame?.columnNumber) ? node.callFrame.columnNumber + 1 : null, - self_ms: 0, - samples: 0, - }; - entry.self_ms += deltaUs / 1000; - entry.samples += 1; - byFrame.set(label, entry); - } - - const topSelf = [...byFrame.values()] - .sort((a, b) => b.self_ms - a.self_ms) - .slice(0, 24) - .map((entry) => ({ - ...entry, - self_ms: +entry.self_ms.toFixed(3), - self_pct: totalUs > 0 ? +((entry.self_ms * 1000 / totalUs) * 100).toFixed(2) : 0, - })); - - return { - samples: samples.length, - total_ms: +(totalUs / 1000).toFixed(3), - topSelf, - }; -} - -async function startCpuProfile(cdp) { - await cdp.send("Profiler.enable"); - await cdp.send("Profiler.setSamplingInterval", { interval: 100 }); - await cdp.send("Profiler.start"); -} - -async function stopCpuProfile(cdp) { - const { profile } = await cdp.send("Profiler.stop"); - return summarizeCpuProfile(profile); -} - -function scenarioKey({ - mode, - stableDom, - stableTriangleDebug, - animationDriver, - animationFrameCache, - animatedMeshOptimization, - run, -}) { - const stable = stableDom ? "stable" : "remount"; - const debugSuffix = COMPARE_STABLE_TRIANGLE_DEBUG || stableTriangleDebug - ? `.${stableTriangleDebug || "normal"}` - : ""; - const driverSuffix = COMPARE_ANIMATION_DRIVER || animationDriver !== "js" - ? `.${animationDriver}` - : ""; - const frameCacheSuffix = animationFrameCache ? ".framecache" : ""; - const meshOptSuffix = animatedMeshOptimization ? ".meshopt" : ""; - return RUNS > 1 - ? `${mode}.${stable}${debugSuffix}${driverSuffix}${frameCacheSuffix}${meshOptSuffix}.r${run + 1}` - : `${mode}.${stable}${debugSuffix}${driverSuffix}${frameCacheSuffix}${meshOptSuffix}`; -} - -function buildUrl(port, scenario) { - const params = new URLSearchParams({ - mesh: MESH, - clip: CLIP, - mode: scenario.mode, - stableDom: scenario.stableDom ? "1" : "0", - animationDriver: scenario.animationDriver, - animationFrameCache: scenario.animationFrameCache ? "1" : "0", - animationFrameCacheFrames: String(ANIMATION_FRAME_CACHE_FRAMES), - keyframeSamples: String(KEYFRAME_SAMPLES), - animatedMeshOptimization: scenario.animatedMeshOptimization ? "1" : "0", - targetSize: String(TARGET_SIZE), - timeScale: String(TIME_SCALE), - solidTextureSamples: SOLID_TEXTURE_SAMPLES ? "1" : "0", - }); - if (DISABLE_STRATEGIES) params.set("disableStrategies", DISABLE_STRATEGIES); - if (scenario.stableTriangleDebug) params.set("stableTriangleDebug", scenario.stableTriangleDebug); - if (HAS_STABLE_TRIANGLE_COLOR_POLICY) { - params.set("stableTriangleColorPolicy", STABLE_TRIANGLE_COLOR_POLICY); - } - if (HAS_STABLE_TRIANGLE_COLOR_STEPS) { - params.set("stableTriangleColorSteps", String(STABLE_TRIANGLE_COLOR_STEPS)); - } - if (HAS_STABLE_TRIANGLE_COLOR_FREEZE_FRAMES) { - params.set("stableTriangleColorFreezeFrames", String(STABLE_TRIANGLE_COLOR_FREEZE_FRAMES)); - } - if ( - HAS_STABLE_TRIANGLE_COLOR_BUDGET || - STABLE_TRIANGLE_COLOR_POLICY === "adaptive" - ) { - params.set( - "stableTriangleColorBudget", - String(STABLE_TRIANGLE_COLOR_BUDGET || DEFAULT_STABLE_TRIANGLE_COLOR_BUDGET), - ); - } - if ( - HAS_STABLE_TRIANGLE_COLOR_MAX_AGE || - STABLE_TRIANGLE_COLOR_POLICY === "adaptive" - ) { - params.set( - "stableTriangleColorMaxAge", - String(STABLE_TRIANGLE_COLOR_MAX_AGE || DEFAULT_STABLE_TRIANGLE_COLOR_MAX_AGE), - ); - } - if (HAS_STABLE_TRIANGLE_COLOR_MAX_STEP) { - params.set("stableTriangleColorMaxStep", String(STABLE_TRIANGLE_COLOR_MAX_STEP)); - } - if (HAS_STABLE_TRIANGLE_MATRIX_DECIMALS) { - params.set("stableTriangleMatrixDecimals", String(STABLE_TRIANGLE_MATRIX_DECIMALS)); - } - return `http://127.0.0.1:${port}/animated-human.html?${params.toString()}`; -} - -async function runScenario(port, scenario) { - const launchOptions = { headless: !HEADED, args: CHROMIUM_ARGS }; - if (BROWSER_EXECUTABLE) launchOptions.executablePath = BROWSER_EXECUTABLE; - const browser = await chromium.launch(launchOptions); - try { - const ctx = await browser.newContext({ viewport: { width: 1280, height: 800 } }); - const page = await ctx.newPage(); - const url = buildUrl(port, scenario); - - await page.goto(url, { waitUntil: "load" }); - await page.waitForFunction(() => window.__perf__?.ready === true, null, { timeout: 45000 }); - await page.waitForTimeout(WARMUP_MS); - - const cdp = TRACE || PROFILE ? await ctx.newCDPSession(page) : null; - let traceEvents = null; - let metricsBefore = null; - if (cdp) { - if (PROFILE) await startCpuProfile(cdp); - if (TRACE) traceEvents = await startTrace(cdp); - metricsBefore = await cdp.send("Performance.getMetrics"); - } - - const startIndexes = await page.evaluate(() => ({ - samples: window.__perf__.samples.length, - animationSamples: window.__perf__.animationSamples.length, - })); - await page.waitForTimeout(SAMPLE_MS); - - const metricsAfter = cdp ? await cdp.send("Performance.getMetrics") : null; - const trace = cdp && TRACE ? await stopTrace(cdp, traceEvents) : null; - const cpuProfile = cdp && PROFILE ? await stopCpuProfile(cdp) : null; - const pageResult = await page.evaluate((from) => ({ - samples: window.__perf__.samples.slice(from.samples), - animationSamples: window.__perf__.animationSamples.slice(from.animationSamples), - polyCount: window.__perf__.polyCount, - renderStats: window.__perf__.renderStats, - animation: window.__perf__.animation, - }), startIndexes); - - await ctx.close(); - - return { - ...summarizeFrameTimes(pageResult.samples), - animation_update: summarizeDurations(pageResult.animationSamples, "updateMs"), - set_polygons: summarizeDurations(pageResult.animationSamples, "setPolygonsMs"), - sample_and_mixer: summarizeDurations(pageResult.animationSamples, "nonSetPolygonsMs"), - triangleFrameApplied: pageResult.animationSamples.filter((sample) => - sample?.triangleFrameApplied === true - ).length, - animation_sample_count: pageResult.animationSamples.length, - polyCount: pageResult.polyCount, - renderStats: pageResult.renderStats, - animation: pageResult.animation, - trace, - cpuProfile, - performanceMetrics: metricsBefore && metricsAfter - ? diffPerformanceMetrics(metricsBefore, metricsAfter) - : null, - }; - } finally { - await browser.close(); - } -} - -const scenarios = []; -for (const mode of MODES) { - for (const stableDom of STABLE_DOM_VARIANTS) { - for (const stableTriangleDebug of STABLE_TRIANGLE_DEBUG_VARIANTS) { - for (const animationDriver of ANIMATION_DRIVER_VARIANTS) { - for (const animationFrameCache of ANIMATION_FRAME_CACHE_VARIANTS) { - for (const animatedMeshOptimization of ANIMATED_MESH_OPTIMIZATION_VARIANTS) { - for (let run = 0; run < RUNS; run += 1) { - scenarios.push({ - mode, - stableDom, - stableTriangleDebug, - animationDriver, - animationFrameCache, - animatedMeshOptimization, - run, - }); - } - } - } - } - } - } -} - -console.log(`[animated-human] mesh=${MESH} clip=${CLIP} targetSize=${TARGET_SIZE} warmup=${WARMUP_MS}ms sample=${SAMPLE_MS}ms animatedMeshOptimization=${ANIMATED_MESH_OPTIMIZATION_VARIANTS.join(",")} animationDriver=${ANIMATION_DRIVER_VARIANTS.join(",")} animationFrameCache=${ANIMATION_FRAME_CACHE_VARIANTS.join(",")} animationFrameCacheFrames=${ANIMATION_FRAME_CACHE_FRAMES} keyframeSamples=${KEYFRAME_SAMPLES} stableTriangleDebug=${STABLE_TRIANGLE_DEBUG_VARIANTS.map((value) => value || "normal").join(",")} colorPolicy=${STABLE_TRIANGLE_COLOR_POLICY_LABEL} colorSteps=${STABLE_TRIANGLE_COLOR_STEPS_LABEL} colorFreezeFrames=${STABLE_TRIANGLE_COLOR_FREEZE_FRAMES_LABEL} colorBudget=${STABLE_TRIANGLE_COLOR_BUDGET_LABEL} colorMaxAge=${STABLE_TRIANGLE_COLOR_MAX_AGE_LABEL} colorMaxStep=${STABLE_TRIANGLE_COLOR_MAX_STEP_LABEL} matrixDecimals=${STABLE_TRIANGLE_MATRIX_DECIMALS_LABEL}`); -if (BROWSER_EXECUTABLE) console.log(`[animated-human] browser=${BROWSER_EXECUTABLE}`); -if (SOFTWARE_BACKEND) console.log("[animated-human] software backend=on"); -if (CHROMIUM_ARGS.length > 0) console.log(`[animated-human] chromium args=${CHROMIUM_ARGS.join(" ")}`); -if (TRACE) console.log("[animated-human] trace=on"); -if (PROFILE) console.log("[animated-human] profile=on"); -if (REQUIRE_SOLID_TRIANGLES) console.log("[animated-human] require solid triangle path=on"); - -const { server, port } = await startServer(); -console.log(`[animated-human] server :${port}`); - -try { - const results = {}; - for (const scenario of scenarios) { - const key = scenarioKey(scenario); - process.stdout.write(` ${key.padEnd(30)}`); - const result = await runScenario(port, scenario); - const polygonStats = result.renderStats?.polygons; - const tags = result.renderStats?.dom?.tags; - if ( - REQUIRE_SOLID_TRIANGLES && - ( - result.polyCount <= 0 || - polygonStats?.solidTriangles !== result.polyCount || - tags?.u !== result.polyCount - ) - ) { - throw new Error( - `${key} left the baked solid triangle path: ` + - `polygons solid/textured=${polygonStats?.solid ?? "?"}/${polygonStats?.textured ?? "?"}, ` + - `tags b/i/s/u/q=${tags?.b ?? "?"}/${tags?.i ?? "?"}/${tags?.s ?? "?"}/${tags?.u ?? "?"}/${tags?.q ?? "?"}`, - ); - } - results[key] = result; - const tagNote = tags ? ` tags b/i/s/u/q=${tags.b}/${tags.i}/${tags.s}/${tags.u}/${tags.q}` : ""; - const traceNote = result.trace?.groups - ? ` trace script/style/paint/comp=${result.trace.groups.script.duration_ms.toFixed(1)}/${result.trace.groups.style.duration_ms.toFixed(1)}/${result.trace.groups.paint.duration_ms.toFixed(1)}/${(result.trace.groups.compositorMain.duration_ms + result.trace.groups.compositorImpl.duration_ms).toFixed(1)}ms` - : ""; - const profileTop = result.cpuProfile?.topSelf?.[0]; - const profileNote = profileTop - ? ` profile top=${profileTop.functionName || profileTop.frame} ${profileTop.self_ms.toFixed(1)}ms` - : ""; - process.stdout.write( - `p50=${result.fps_p50.toFixed(1).padStart(5)}fps ` + - `p95=${result.fps_p95.toFixed(1).padStart(5)}fps ` + - `update p50=${result.animation_update.p50_ms.toFixed(2)}ms ` + - `setPolys p50=${result.set_polygons.p50_ms.toFixed(2)}ms ` + - `typed=${result.triangleFrameApplied}/${result.animation_sample_count} ` + - `clip=${result.animation?.clip?.name ?? "?"}${tagNote}${traceNote}${profileNote}\n`, - ); - } - - const out = { - mesh: MESH, - clip: CLIP, - targetSize: TARGET_SIZE, - timeScale: TIME_SCALE, - solidTextureSamples: SOLID_TEXTURE_SAMPLES, - compareAnimatedMeshOptimization: COMPARE_ANIMATED_MESH_OPTIMIZATION, - compareAnimationDriver: COMPARE_ANIMATION_DRIVER, - compareAnimationFrameCache: COMPARE_ANIMATION_FRAME_CACHE, - animatedMeshOptimization: ANIMATED_MESH_OPTIMIZATION_VARIANTS.length === 1 - ? ANIMATED_MESH_OPTIMIZATION_VARIANTS[0] - : "compare", - animationDriver: ANIMATION_DRIVER_VARIANTS.length === 1 ? ANIMATION_DRIVER_VARIANTS[0] : "compare", - animationFrameCache: ANIMATION_FRAME_CACHE_VARIANTS.length === 1 - ? ANIMATION_FRAME_CACHE_VARIANTS[0] - : "compare", - animationFrameCacheFrames: ANIMATION_FRAME_CACHE_FRAMES, - keyframeSamples: KEYFRAME_SAMPLES, - stableTriangleDebug: STABLE_TRIANGLE_DEBUG || null, - stableTriangleColorPolicy: HAS_STABLE_TRIANGLE_COLOR_POLICY - ? STABLE_TRIANGLE_COLOR_POLICY - : "auto", - stableTriangleColorSteps: HAS_STABLE_TRIANGLE_COLOR_STEPS - ? (STABLE_TRIANGLE_COLOR_STEPS > 1 ? STABLE_TRIANGLE_COLOR_STEPS : null) - : "auto", - defaultStableTriangleColorSteps: DEFAULT_STABLE_TRIANGLE_COLOR_STEPS, - defaultStableTriangleColorPolicy: DEFAULT_STABLE_TRIANGLE_COLOR_POLICY, - stableTriangleColorFreezeFrames: HAS_STABLE_TRIANGLE_COLOR_FREEZE_FRAMES - ? STABLE_TRIANGLE_COLOR_FREEZE_FRAMES - : "auto", - defaultStableTriangleColorFreezeFrames: DEFAULT_STABLE_TRIANGLE_COLOR_FREEZE_FRAMES, - stableTriangleColorBudget: HAS_STABLE_TRIANGLE_COLOR_BUDGET - ? (STABLE_TRIANGLE_COLOR_BUDGET > 0 ? STABLE_TRIANGLE_COLOR_BUDGET : null) - : "auto", - defaultStableTriangleColorBudget: DEFAULT_STABLE_TRIANGLE_COLOR_BUDGET, - stableTriangleColorMaxAge: HAS_STABLE_TRIANGLE_COLOR_MAX_AGE - ? (STABLE_TRIANGLE_COLOR_MAX_AGE > 0 ? STABLE_TRIANGLE_COLOR_MAX_AGE : null) - : "auto", - defaultStableTriangleColorMaxAge: DEFAULT_STABLE_TRIANGLE_COLOR_MAX_AGE, - stableTriangleColorMaxStep: HAS_STABLE_TRIANGLE_COLOR_MAX_STEP - ? (STABLE_TRIANGLE_COLOR_MAX_STEP > 0 ? STABLE_TRIANGLE_COLOR_MAX_STEP : null) - : "auto", - defaultStableTriangleColorMaxStep: DEFAULT_STABLE_TRIANGLE_COLOR_MAX_STEP, - stableTriangleMatrixDecimals: HAS_STABLE_TRIANGLE_MATRIX_DECIMALS - ? STABLE_TRIANGLE_MATRIX_DECIMALS - : "auto", - compareStableTriangleDebug: COMPARE_STABLE_TRIANGLE_DEBUG, - requireSolidTriangles: REQUIRE_SOLID_TRIANGLES, - disableStrategies: DISABLE_STRATEGIES || null, - browserExecutable: BROWSER_EXECUTABLE || null, - chromiumArgs: CHROMIUM_ARGS, - softwareBackend: SOFTWARE_BACKEND, - warmup_ms: WARMUP_MS, - sample_ms: SAMPLE_MS, - results, - }; - - const outputPath = JSON_PATH || (LABEL ? resolve(repoRoot, "bench/results", `${LABEL}.json`) : ""); - if (outputPath) { - mkdirSync(dirname(outputPath), { recursive: true }); - writeFileSync(outputPath, JSON.stringify(out, null, 2) + "\n"); - console.log(`[animated-human] wrote ${outputPath}`); - } - - console.log(JSON.stringify(out, null, 2)); -} finally { - await stopServer(server); -} diff --git a/bench/animated-human.html b/bench/animated-human.html deleted file mode 100644 index 4e05f9131..000000000 --- a/bench/animated-human.html +++ /dev/null @@ -1,671 +0,0 @@ - - - - - polycss bench - animated human - - - -
- - - - diff --git a/bench/async-scene-mount-bench.mjs b/bench/async-scene-mount-bench.mjs deleted file mode 100644 index fc4d9cadd..000000000 --- a/bench/async-scene-mount-bench.mjs +++ /dev/null @@ -1,160 +0,0 @@ -/** - * Benchmark createPolyScene's internal async setPolygonsChunked path. - * - * Usage: - * node bench/async-scene-mount-bench.mjs - * node bench/async-scene-mount-bench.mjs --count 50000 --repeats 5 --label async-scene-mount - */ -import { createServer } from "node:http"; -import { readFile, mkdir, writeFile } from "node:fs/promises"; -import { dirname, extname, resolve } from "node:path"; -import { fileURLToPath } from "node:url"; -import { chromium } from "playwright"; -import { chromiumArgsWithGpuDefault } from "./chromium-defaults.mjs"; - -const __dirname = dirname(fileURLToPath(import.meta.url)); -const repoRoot = resolve(__dirname, ".."); -const benchDir = resolve(repoRoot, "bench"); - -const argv = process.argv.slice(2); -const flag = (name) => argv.indexOf(`--${name}`); -const optStr = (name, dflt = "") => { - const i = flag(name); - return i >= 0 ? argv[i + 1] : dflt; -}; -const optNum = (name, dflt) => { - const raw = optStr(name); - return raw ? Number(raw) : dflt; -}; -const hasFlag = (name) => flag(name) >= 0; -const optAll = (name) => { - const values = []; - for (let i = 0; i < argv.length; i += 1) { - const arg = argv[i]; - if (arg === `--${name}` && argv[i + 1]) { - values.push(argv[i + 1]); - i += 1; - } else if (arg.startsWith(`--${name}=`)) { - values.push(arg.slice(name.length + 3)); - } - } - return values; -}; - -const COUNT = optNum("count", 10000); -const REPEATS = optNum("repeats", 5); -const CHUNK_SIZE = optNum("chunk-size", optNum("chunkSize", 750)); -const MODE = optStr("mode", "baked"); -const SHAPE = optStr("shape", "quad"); -const REPLACE_EXISTING = hasFlag("replace-existing") || hasFlag("replaceExisting"); -const DISABLE_STRATEGIES = [ - ...optAll("disable-strategy"), - ...optAll("disable-strategies").flatMap((value) => value.split(",")), -].map((value) => value.trim()).filter(Boolean); -const LABEL = optStr("label"); -const HEADED = hasFlag("headed"); -const BROWSER_EXECUTABLE = optStr("browser-executable"); -const STRATEGIES = [ - ...optAll("strategy"), - ...optAll("strategies").flatMap((value) => value.split(",").filter(Boolean)), -]; -const CHROMIUM_ARGS = chromiumArgsWithGpuDefault([ - ...optAll("chromium-arg"), - ...optAll("chromium-args").flatMap((value) => value.split(/\s+/).filter(Boolean)), -]); - -const MIME = { - ".html": "text/html; charset=utf-8", - ".js": "application/javascript; charset=utf-8", - ".mjs": "application/javascript; charset=utf-8", - ".css": "text/css; charset=utf-8", -}; - -function startServer() { - return new Promise((resolveStart, rejectStart) => { - const server = createServer(async (req, res) => { - try { - const url = new URL(req.url, "http://localhost"); - const safe = url.pathname.replace(/\/+/g, "/"); - if (safe.includes("..")) { - res.writeHead(403); - res.end("forbidden"); - return; - } - const abs = resolve(benchDir, safe === "/" ? "async-scene-mount.html" : safe.slice(1)); - const data = await readFile(abs); - res.writeHead(200, { - "Content-Type": MIME[extname(abs).toLowerCase()] || "application/octet-stream", - "Cache-Control": "no-store", - }); - res.end(data); - } catch (err) { - res.writeHead(404); - res.end(String(err?.message ?? err)); - } - }); - server.on("error", rejectStart); - server.listen(0, "127.0.0.1", () => { - const addr = server.address(); - resolveStart({ server, port: typeof addr === "object" ? addr.port : 0 }); - }); - }); -} - -function stopServer(server) { - return new Promise((resolveStop) => server.close(resolveStop)); -} - -function printResult(result) { - console.log(`[async-scene-mount] count=${result.options.count} repeats=${result.options.repeats} chunk=${result.options.chunkSize} mode=${result.options.mode} shape=${result.options.shape} replaceExisting=${result.options.replaceExisting} disable=${result.options.disableStrategies.join(",")}`); - console.log(JSON.stringify(result.summary, null, 2)); - for (const row of result.rows) { - console.log( - `${row.strategy.padEnd(16)} #${row.repeat} ` + - `render=${row.renderMs.toFixed(3)}ms mount=${row.mountMs.toFixed(3)}ms update=${row.updateMs.toFixed(3)}ms ` + - `mounted=${row.mounted} leaves=${row.leafCount}`, - ); - } -} - -let server; -let browser; -try { - const started = await startServer(); - server = started.server; - const url = `http://127.0.0.1:${started.port}/async-scene-mount.html`; - console.log(`[async-scene-mount] ${url}`); - if (CHROMIUM_ARGS.length > 0) console.log(`[async-scene-mount] chromium args=${CHROMIUM_ARGS.join(" ")}`); - browser = await chromium.launch({ - headless: !HEADED, - executablePath: BROWSER_EXECUTABLE || undefined, - args: CHROMIUM_ARGS, - }); - const page = await browser.newPage({ viewport: { width: 1200, height: 900 } }); - await page.goto(url, { waitUntil: "load" }); - const result = await page.evaluate( - async ({ count, repeats, chunkSize, mode, shape, replaceExisting, strategies, disableStrategies }) => - window.runPolycssAsyncSceneMountBench({ count, repeats, chunkSize, mode, shape, replaceExisting, strategies, disableStrategies }), - { - count: COUNT, - repeats: REPEATS, - chunkSize: CHUNK_SIZE, - mode: MODE === "dynamic" ? "dynamic" : "baked", - shape: SHAPE === "triangle" ? "triangle" : "quad", - replaceExisting: REPLACE_EXISTING, - strategies: STRATEGIES, - disableStrategies: DISABLE_STRATEGIES.length > 0 ? DISABLE_STRATEGIES : undefined, - }, - ); - printResult(result); - if (LABEL) { - const dir = resolve(repoRoot, "bench/results"); - await mkdir(dir, { recursive: true }); - const file = resolve(dir, `${LABEL}.json`); - await writeFile(file, JSON.stringify(result, null, 2)); - console.log(`[async-scene-mount] wrote ${file}`); - } -} finally { - if (browser) await browser.close(); - if (server) await stopServer(server); -} diff --git a/bench/async-scene-mount.html b/bench/async-scene-mount.html deleted file mode 100644 index 429cb44e6..000000000 --- a/bench/async-scene-mount.html +++ /dev/null @@ -1,56 +0,0 @@ - - - - - polycss async scene mount bench - - - -
ready
-
- - - diff --git a/bench/atlas-background-bench.mjs b/bench/atlas-background-bench.mjs deleted file mode 100644 index 9364c0e45..000000000 --- a/bench/atlas-background-bench.mjs +++ /dev/null @@ -1,145 +0,0 @@ -/** - * Benchmark atlas page reveal style application on existing leaves. - * - * Usage: - * node bench/atlas-background-bench.mjs - * node bench/atlas-background-bench.mjs --count 10000 --repeats 7 --mode baked --label atlas-bg - */ -import { createServer } from "node:http"; -import { readFile, mkdir, writeFile } from "node:fs/promises"; -import { dirname, extname, resolve } from "node:path"; -import { fileURLToPath } from "node:url"; -import { chromium } from "playwright"; -import { chromiumArgsWithGpuDefault } from "./chromium-defaults.mjs"; - -const __dirname = dirname(fileURLToPath(import.meta.url)); -const repoRoot = resolve(__dirname, ".."); -const benchDir = resolve(repoRoot, "bench"); - -const argv = process.argv.slice(2); -const flag = (name) => argv.indexOf(`--${name}`); -const optStr = (name, dflt = "") => { - const i = flag(name); - return i >= 0 ? argv[i + 1] : dflt; -}; -const optNum = (name, dflt) => { - const raw = optStr(name); - return raw ? Number(raw) : dflt; -}; -const hasFlag = (name) => flag(name) >= 0; -const optAll = (name) => { - const values = []; - for (let i = 0; i < argv.length; i += 1) { - const arg = argv[i]; - if (arg === `--${name}` && argv[i + 1]) { - values.push(argv[i + 1]); - i += 1; - } else if (arg.startsWith(`--${name}=`)) { - values.push(arg.slice(name.length + 3)); - } - } - return values; -}; - -const COUNT = optNum("count", 10000); -const REPEATS = optNum("repeats", 5); -const MODE = optStr("mode", "baked"); -const SKIP_DYNAMIC_NORMALS = hasFlag("skip-dynamic-normals") || hasFlag("skipDynamicNormals"); -const LABEL = optStr("label"); -const HEADED = hasFlag("headed"); -const BROWSER_EXECUTABLE = optStr("browser-executable"); -const CHROMIUM_ARGS = chromiumArgsWithGpuDefault([ - ...optAll("chromium-arg"), - ...optAll("chromium-args").flatMap((value) => value.split(/\s+/).filter(Boolean)), -]); - -const MIME = { - ".html": "text/html; charset=utf-8", - ".js": "application/javascript; charset=utf-8", - ".mjs": "application/javascript; charset=utf-8", - ".css": "text/css; charset=utf-8", -}; - -function startServer() { - return new Promise((resolveStart, rejectStart) => { - const server = createServer(async (req, res) => { - try { - const url = new URL(req.url, "http://localhost"); - const safe = url.pathname.replace(/\/+/g, "/"); - if (safe.includes("..")) { - res.writeHead(403); - res.end("forbidden"); - return; - } - const abs = resolve(benchDir, safe === "/" ? "atlas-background.html" : safe.slice(1)); - const data = await readFile(abs); - res.writeHead(200, { - "Content-Type": MIME[extname(abs).toLowerCase()] || "application/octet-stream", - "Cache-Control": "no-store", - }); - res.end(data); - } catch (err) { - res.writeHead(404); - res.end(String(err?.message ?? err)); - } - }); - server.on("error", rejectStart); - server.listen(0, "127.0.0.1", () => { - const addr = server.address(); - resolveStart({ server, port: typeof addr === "object" ? addr.port : 0 }); - }); - }); -} - -function stopServer(server) { - return new Promise((resolveStop) => server.close(resolveStop)); -} - -function printResult(result) { - console.log(`[atlas-background] count=${result.options.count} repeats=${result.options.repeats} mode=${result.options.mode} skipDynamicNormals=${result.options.skipDynamicNormals}`); - console.log(JSON.stringify(result.summary, null, 2)); - for (const row of result.rows) { - console.log( - `#${row.repeat} apply=${row.applyMs.toFixed(3)}ms ` + - `leaves=${row.leafCount} styleChars=${row.inlineStyleChars}`, - ); - } -} - -let server; -let browser; -try { - const started = await startServer(); - server = started.server; - const url = `http://127.0.0.1:${started.port}/atlas-background.html`; - console.log(`[atlas-background] ${url}`); - if (CHROMIUM_ARGS.length > 0) console.log(`[atlas-background] chromium args=${CHROMIUM_ARGS.join(" ")}`); - browser = await chromium.launch({ - headless: !HEADED, - executablePath: BROWSER_EXECUTABLE || undefined, - args: CHROMIUM_ARGS, - }); - const page = await browser.newPage({ viewport: { width: 1200, height: 900 } }); - await page.goto(url, { waitUntil: "load" }); - const result = await page.evaluate( - async ({ count, repeats, mode, skipDynamicNormals }) => - window.runPolycssAtlasBackgroundBench({ count, repeats, mode, skipDynamicNormals }), - { - count: COUNT, - repeats: REPEATS, - mode: MODE === "dynamic" ? "dynamic" : "baked", - skipDynamicNormals: SKIP_DYNAMIC_NORMALS, - }, - ); - printResult(result); - if (LABEL) { - const dir = resolve(repoRoot, "bench/results"); - await mkdir(dir, { recursive: true }); - const file = resolve(dir, `${LABEL}.json`); - await writeFile(file, JSON.stringify(result, null, 2)); - console.log(`[atlas-background] wrote ${file}`); - } -} finally { - if (browser) await browser.close(); - if (server) await stopServer(server); -} diff --git a/bench/atlas-background.html b/bench/atlas-background.html deleted file mode 100644 index 590e3ca9f..000000000 --- a/bench/atlas-background.html +++ /dev/null @@ -1,39 +0,0 @@ - - - - - polycss atlas background bench - - - -
- - - diff --git a/bench/build.mjs b/bench/build.mjs index 5a497a173..cc47b27c6 100644 --- a/bench/build.mjs +++ b/bench/build.mjs @@ -16,14 +16,6 @@ * bench/.generated/polycss-vue.js * ← Vue entry (bench/entries/vue.ts) bundled * with Vue 3 + @layoutit/polycss-vue - * bench/.generated/polycss-html-mount.js - * ← leaf HTML chunk mount benchmark entry - * bench/.generated/polycss-async-scene-mount.js - * ← internal async scene chunk mount benchmark entry - * bench/.generated/polycss-sync-scene-add.js - * ← synchronous scene.add renderer benchmark entry - * bench/.generated/polycss-atlas-background.js - * ← atlas page background reveal benchmark entry * * Why not reuse the published dists? The packages keep workspace-peer * imports as bare specifiers (e.g. `@layoutit/polycss-core`), which the browser @@ -40,17 +32,26 @@ import { fileURLToPath } from "node:url"; const __dirname = dirname(fileURLToPath(import.meta.url)); const repoRoot = resolve(__dirname, ".."); -const bundleDir = resolve(__dirname, ".generated"); + +const argv = process.argv.slice(2); +const optStr = (name, dflt = "") => { + const i = argv.indexOf(`--${name}`); + return i >= 0 ? (argv[i + 1] ?? dflt) : dflt; +}; + +const packagesRoot = resolve(optStr("packages-root", resolve(repoRoot, "packages"))); +const bundleDir = resolve(optStr("out-dir", resolve(__dirname, ".generated"))); +const group = optStr("group", "all"); const ALIASES = { - "@layoutit/polycss-core": resolve(repoRoot, "packages/core/src/index.ts"), - "@layoutit/polycss-core/three": resolve(repoRoot, "packages/core/src/three/index.ts"), - "@layoutit/polycss": resolve(repoRoot, "packages/polycss/src/index.ts"), - "@layoutit/polycss/elements": resolve(repoRoot, "packages/polycss/src/elements/index.ts"), - "@layoutit/polycss/three": resolve(repoRoot, "packages/polycss/src/three.ts"), - "@layoutit/polycss-react": resolve(repoRoot, "packages/react/src/index.ts"), - "@layoutit/polycss-vue": resolve(repoRoot, "packages/vue/src/index.ts"), - "three": resolve(repoRoot, "node_modules/three/build/three.module.js"), + "@layoutit/polycss-core": resolve(packagesRoot, "core/src/index.ts"), + "@layoutit/polycss-core/three": resolve(packagesRoot, "core/src/three/index.ts"), + "@layoutit/polycss": resolve(packagesRoot, "polycss/src/index.ts"), + "@layoutit/polycss/elements": resolve(packagesRoot, "polycss/src/elements/index.ts"), + "@layoutit/polycss/three": resolve(packagesRoot, "polycss/src/three.ts"), + "@layoutit/polycss-react": resolve(packagesRoot, "react/src/index.ts"), + "@layoutit/polycss-vue": resolve(packagesRoot, "vue/src/index.ts"), + "three": resolve(repoRoot, "node_modules/three/build/three.module.js"), // Pin React + ReactDOM to the workspace-root copies so the alias-resolved // @layoutit/polycss-react source AND the bench entry import the SAME instance. // Without this, esbuild treats two `react` imports starting from different @@ -70,6 +71,7 @@ const COMMON = { minify: false, // keep readable for debugging sourcemap: false, alias: ALIASES, + nodePaths: [resolve(repoRoot, "node_modules")], loader: { ".tsx": "tsx", ".ts": "ts" }, jsx: "automatic", // React 17+ classic-vs-automatic; React entry uses automatic define: { @@ -80,77 +82,48 @@ const COMMON = { const targets = [ { label: "vanilla (createPolyScene + controls + loadMesh)", - entry: resolve(repoRoot, "packages/polycss/src/index.ts"), + entry: resolve(packagesRoot, "polycss/src/index.ts"), out: resolve(bundleDir, "polycss.js"), + gate: true, }, { label: "elements (side-effect register)", - entry: resolve(repoRoot, "packages/polycss/src/elements/index.ts"), + entry: resolve(packagesRoot, "polycss/src/elements/index.ts"), out: resolve(bundleDir, "polycss-elements.js"), + gate: true, }, { label: "render stats helper", entry: resolve(__dirname, "entries/renderStats.ts"), out: resolve(bundleDir, "polycss-render-stats.js"), + gate: true, }, { label: "react entry", entry: resolve(__dirname, "entries/react.tsx"), out: resolve(bundleDir, "polycss-react.js"), + gate: true, }, { label: "vue entry", entry: resolve(__dirname, "entries/vue.ts"), out: resolve(bundleDir, "polycss-vue.js"), - }, - { - label: "shadow-parity shared meshes", - entry: resolve(__dirname, "entries/parityMeshes.ts"), - out: resolve(bundleDir, "parity-meshes.js"), - }, - { - label: "shadow-parity react mount", - entry: resolve(__dirname, "entries/shadowParityReact.tsx"), - out: resolve(bundleDir, "shadow-parity-react.js"), - }, - { - label: "shadow-parity vue mount", - entry: resolve(__dirname, "entries/shadowParityVue.ts"), - out: resolve(bundleDir, "shadow-parity-vue.js"), - }, - { - label: "HTML chunk mount bench entry", - entry: resolve(__dirname, "entries/htmlMount.ts"), - out: resolve(bundleDir, "polycss-html-mount.js"), - }, - { - label: "async scene mount bench entry", - entry: resolve(__dirname, "entries/asyncSceneMount.ts"), - out: resolve(bundleDir, "polycss-async-scene-mount.js"), - }, - { - label: "sync scene.add bench entry", - entry: resolve(__dirname, "entries/syncSceneAdd.ts"), - out: resolve(bundleDir, "polycss-sync-scene-add.js"), - }, - { - label: "atlas background bench entry", - entry: resolve(__dirname, "entries/atlasBackground.ts"), - out: resolve(bundleDir, "polycss-atlas-background.js"), - }, - { - label: "three parity dashboard", - entry: resolve(__dirname, "entries/threeParityDashboard.ts"), - out: resolve(bundleDir, "polycss-three-parity-dashboard.js"), + gate: true, }, ]; +const selected = group === "gate" ? targets.filter((t) => t.gate) : targets; +if (group !== "all" && group !== "gate") { + throw new Error(`Unknown --group "${group}" (expected "all" or "gate")`); +} + const t0 = performance.now(); await mkdir(bundleDir, { recursive: true }); -for (const t of targets) { - process.stdout.write(`[bench/build] bundling ${t.label} … `); - const start = performance.now(); - await build({ ...COMMON, entryPoints: [t.entry], outfile: t.out }); - console.log(`${(performance.now() - start).toFixed(0)}ms`); -} -console.log(`[bench/build] all bundles ready in ${(performance.now() - t0).toFixed(0)}ms`); +await Promise.all( + selected.map(async (t) => { + const start = performance.now(); + await build({ ...COMMON, entryPoints: [t.entry], outfile: t.out }); + console.log(`[bench/build] bundled ${t.label} … ${(performance.now() - start).toFixed(0)}ms`); + }), +); +console.log(`[bench/build] ${selected.length} bundles ready in ${(performance.now() - t0).toFixed(0)}ms`); diff --git a/bench/entries/asyncSceneMount.ts b/bench/entries/asyncSceneMount.ts deleted file mode 100644 index e3fde4851..000000000 --- a/bench/entries/asyncSceneMount.ts +++ /dev/null @@ -1,333 +0,0 @@ -import { - createPolyOrthographicCamera, - createPolyScene, - injectPolyBaseStyles, - renderPolygonsWithTextureAtlasAsync, - type ParseResult, - type Polygon, - type PolyMeshHandle, - type RenderedPoly, - type PolyTextureLightingMode, -} from "@layoutit/polycss"; - -type AsyncSceneMountStrategy = - | "scene-production" - | "manual-fragment" - | "manual-append"; - -const DEFAULT_STRATEGIES: AsyncSceneMountStrategy[] = [ - "scene-production", - "manual-fragment", - "manual-append", -]; - -interface ChunkedMeshHandle extends PolyMeshHandle { - setPolygonsChunked(polygons: Polygon[], options?: { - merge?: boolean; - stableDom?: boolean; - recomputeAutoCenter?: boolean; - }): Promise; -} - -interface AsyncSceneMountBenchOptions { - count?: number; - repeats?: number; - chunkSize?: number; - mode?: PolyTextureLightingMode; - shape?: "quad" | "triangle"; - replaceExisting?: boolean; - strategies?: AsyncSceneMountStrategy[]; - disableStrategies?: Array<"b" | "i" | "u">; -} - -interface AsyncSceneMountBenchRow { - strategy: AsyncSceneMountStrategy; - repeat: number; - count: number; - renderMs: number; - mountMs: number; - updateMs: number; - leafCount: number; - mounted: boolean; -} - -interface AsyncSceneMountBenchSummary { - renderMedianMs: number; - mountMedianMs: number; - updateMedianMs: number; - updateP90Ms: number; - leafCount: number; -} - -function solidGrid(count: number, shape: "quad" | "triangle"): Polygon[] { - const side = Math.ceil(Math.sqrt(count)); - const polygons: Polygon[] = []; - for (let i = 0; i < count; i += 1) { - const x = i % side; - const y = Math.floor(i / side); - const color = `#${((i * 2654435761) & 0xffffff).toString(16).padStart(6, "0")}`; - const vertices: Polygon["vertices"] = shape === "triangle" - ? [ - [x, y, 0], - [x + 0.88, y, 0], - [x, y + 0.88, 0], - ] - : [ - [x, y, 0], - [x + 0.88, y, 0], - [x + 0.88, y + 0.88, 0], - [x, y + 0.88, 0], - ]; - polygons.push({ vertices, color }); - } - return polygons; -} - -function makeParseResult(polygons: Polygon[]): ParseResult { - return { - polygons, - objectUrls: [], - warnings: [], - dispose: () => {}, - }; -} - -function nextFrame(): Promise { - return new Promise((resolve) => requestAnimationFrame(() => resolve())); -} - -function yieldToBrowser(): Promise { - return new Promise((resolve) => setTimeout(resolve, 0)); -} - -function quantile(sorted: readonly number[], q: number): number { - if (sorted.length === 0) return 0; - const pos = (sorted.length - 1) * q; - const lo = Math.floor(pos); - const hi = Math.ceil(pos); - if (lo === hi) return sorted[lo] ?? 0; - return (sorted[lo] ?? 0) + ((sorted[hi] ?? 0) - (sorted[lo] ?? 0)) * (pos - lo); -} - -function summarizeRows(rows: readonly AsyncSceneMountBenchRow[]): AsyncSceneMountBenchSummary { - const renders = rows.map((row) => row.renderMs).sort((a, b) => a - b); - const mounts = rows.map((row) => row.mountMs).sort((a, b) => a - b); - const updates = rows.map((row) => row.updateMs).sort((a, b) => a - b); - return { - renderMedianMs: Number(quantile(renders, 0.5).toFixed(3)), - mountMedianMs: Number(quantile(mounts, 0.5).toFixed(3)), - updateMedianMs: Number(quantile(updates, 0.5).toFixed(3)), - updateP90Ms: Number(quantile(updates, 0.9).toFixed(3)), - leafCount: rows[rows.length - 1]?.leafCount ?? 0, - }; -} - -function summarize(rows: readonly AsyncSceneMountBenchRow[]): Record { - const byStrategy = new Map(); - for (const row of rows) { - const group = byStrategy.get(row.strategy); - if (group) group.push(row); - else byStrategy.set(row.strategy, [row]); - } - const out = {} as Record; - for (const [strategy, group] of byStrategy) out[strategy] = summarizeRows(group); - return out; -} - -function mountedLeafCount(target: HTMLElement): number { - return target.querySelectorAll(".polycss-mesh > b, .polycss-mesh > i, .polycss-mesh > s, .polycss-mesh > u").length; -} - -function createWrapper(target: HTMLElement, mode: PolyTextureLightingMode): HTMLElement { - injectPolyBaseStyles(document); - target.replaceChildren(); - const cameraEl = document.createElement("div"); - cameraEl.className = "polycss-camera"; - cameraEl.style.perspective = "1000000px"; - const sceneEl = document.createElement("div"); - sceneEl.className = "polycss-scene"; - sceneEl.dataset.polycssLighting = mode; - const wrapper = document.createElement("div"); - wrapper.className = "polycss-mesh"; - sceneEl.appendChild(wrapper); - cameraEl.appendChild(sceneEl); - target.appendChild(cameraEl); - return wrapper; -} - -async function mountFragmentChunks( - wrapper: HTMLElement, - rendered: readonly RenderedPoly[], - chunkSize: number, -): Promise { - let fragment = document.createDocumentFragment(); - for (let i = 0; i < rendered.length; i += 1) { - fragment.appendChild(rendered[i]!.element); - if ((i + 1) % chunkSize === 0) { - wrapper.appendChild(fragment); - fragment = document.createDocumentFragment(); - await yieldToBrowser(); - } - } - if (fragment.childNodes.length > 0) wrapper.appendChild(fragment); -} - -async function mountAppendBatches( - wrapper: HTMLElement, - rendered: readonly RenderedPoly[], - chunkSize: number, -): Promise { - let batch: HTMLElement[] = []; - for (let i = 0; i < rendered.length; i += 1) { - batch.push(rendered[i]!.element); - if ((i + 1) % chunkSize === 0) { - wrapper.append(...batch); - batch = []; - await yieldToBrowser(); - } - } - if (batch.length > 0) wrapper.append(...batch); -} - -async function runSceneProduction( - target: HTMLElement, - polygons: Polygon[], - repeat: number, - mode: PolyTextureLightingMode, - replaceExisting: boolean, - disableStrategies: Array<"b" | "i" | "u">, -): Promise { - target.replaceChildren(); - const scene = createPolyScene(target, { - camera: createPolyOrthographicCamera({ rotX: 65, rotY: 45, zoom: 1 }), - textureLighting: mode, - strategies: { disable: disableStrategies }, - }); - const handle = scene.add(makeParseResult(replaceExisting ? polygons : []), { - merge: false, - excludeFromAutoCenter: true, - }) as ChunkedMeshHandle; - await nextFrame(); - - performance.mark("polycss-async-scene-update-start"); - console.timeStamp("polycss-async-scene-update-start"); - const t0 = performance.now(); - await handle.setPolygonsChunked(polygons, { - merge: false, - stableDom: false, - recomputeAutoCenter: false, - }); - const t1 = performance.now(); - console.timeStamp("polycss-async-scene-update-end"); - performance.mark("polycss-async-scene-update-end"); - - const leafCount = mountedLeafCount(target); - const row: AsyncSceneMountBenchRow = { - strategy: "scene-production", - repeat, - count: polygons.length, - renderMs: 0, - mountMs: 0, - updateMs: Number((t1 - t0).toFixed(3)), - leafCount, - mounted: leafCount === polygons.length, - }; - - scene.destroy(); - target.replaceChildren(); - await nextFrame(); - return row; -} - -async function runManualStrategy( - target: HTMLElement, - polygons: Polygon[], - repeat: number, - mode: PolyTextureLightingMode, - chunkSize: number, - strategy: "manual-fragment" | "manual-append", - disableStrategies: Array<"b" | "i" | "u">, -): Promise { - const wrapper = createWrapper(target, mode); - let cancelled = false; - - performance.mark(`polycss-${strategy}-render-start`); - console.timeStamp(`polycss-${strategy}-render-start`); - const t0 = performance.now(); - const result = await renderPolygonsWithTextureAtlasAsync(polygons, { - doc: document, - textureLighting: mode, - strategies: { disable: disableStrategies }, - }, () => cancelled); - const t1 = performance.now(); - console.timeStamp(`polycss-${strategy}-render-end`); - performance.mark(`polycss-${strategy}-render-end`); - - performance.mark(`polycss-${strategy}-mount-start`); - console.timeStamp(`polycss-${strategy}-mount-start`); - if (strategy === "manual-fragment") await mountFragmentChunks(wrapper, result.rendered, chunkSize); - else await mountAppendBatches(wrapper, result.rendered, chunkSize); - const t2 = performance.now(); - console.timeStamp(`polycss-${strategy}-mount-end`); - performance.mark(`polycss-${strategy}-mount-end`); - - const leafCount = mountedLeafCount(target); - const row: AsyncSceneMountBenchRow = { - strategy, - repeat, - count: polygons.length, - renderMs: Number((t1 - t0).toFixed(3)), - mountMs: Number((t2 - t1).toFixed(3)), - updateMs: Number((t2 - t0).toFixed(3)), - leafCount, - mounted: leafCount === polygons.length, - }; - - cancelled = true; - result.dispose(); - target.replaceChildren(); - await nextFrame(); - return row; -} - -export async function runPolycssAsyncSceneMountBench(input: AsyncSceneMountBenchOptions = {}): Promise<{ - options: Required> & { strategies: AsyncSceneMountStrategy[] }; - rows: AsyncSceneMountBenchRow[]; - summary: Record; -}> { - const options = { - count: Math.max(1, Math.floor(input.count ?? 10000)), - repeats: Math.max(1, Math.floor(input.repeats ?? 5)), - chunkSize: Math.max(1, Math.floor(input.chunkSize ?? 750)), - mode: input.mode ?? "baked", - shape: input.shape ?? "quad", - replaceExisting: input.replaceExisting ?? false, - disableStrategies: input.disableStrategies ?? ["i", "u"], - strategies: input.strategies?.length ? input.strategies : DEFAULT_STRATEGIES, - }; - const target = document.getElementById("bench-target") ?? document.body.appendChild(document.createElement("div")); - target.id = "bench-target"; - const polygons = solidGrid(options.count, options.shape); - const rows: AsyncSceneMountBenchRow[] = []; - - for (let repeat = 0; repeat < options.repeats; repeat += 1) { - const strategies = repeat % 2 === 0 ? options.strategies : [...options.strategies].reverse(); - for (const strategy of strategies) { - if (strategy === "scene-production") { - rows.push(await runSceneProduction(target, polygons, repeat, options.mode, options.replaceExisting, options.disableStrategies)); - } else { - rows.push(await runManualStrategy(target, polygons, repeat, options.mode, options.chunkSize, strategy, options.disableStrategies)); - } - } - } - - return { - options, - rows, - summary: summarize(rows), - }; -} - -(window as unknown as { - runPolycssAsyncSceneMountBench: typeof runPolycssAsyncSceneMountBench; -}).runPolycssAsyncSceneMountBench = runPolycssAsyncSceneMountBench; diff --git a/bench/entries/atlasBackground.ts b/bench/entries/atlasBackground.ts deleted file mode 100644 index 46be90c94..000000000 --- a/bench/entries/atlasBackground.ts +++ /dev/null @@ -1,177 +0,0 @@ -import type { - PackedTextureAtlasEntry, - Polygon, - PolyTextureLightingMode, - TextureAtlasPage, -} from "@layoutit/polycss-core"; -import { - applyAtlasBackground, - createAtlasElement, -} from "../../packages/polycss/src/render/atlas/emit"; - -interface AtlasBackgroundBenchOptions { - count?: number; - repeats?: number; - mode?: PolyTextureLightingMode; - skipDynamicNormals?: boolean; -} - -interface AtlasBackgroundBenchRow { - repeat: number; - count: number; - applyMs: number; - leafCount: number; - inlineStyleChars: number; -} - -interface AtlasBackgroundBenchSummary { - applyMedianMs: number; - applyP90Ms: number; - leafCount: number; - inlineStyleChars: number; -} - -const DATA_URL = - "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADElEQVR42mP8z8BQDwAFgwJ/l3S1WQAAAABJRU5ErkJggg=="; - -function nextFrame(): Promise { - return new Promise((resolve) => requestAnimationFrame(() => resolve())); -} - -function quantile(sorted: readonly number[], q: number): number { - if (sorted.length === 0) return 0; - const pos = (sorted.length - 1) * q; - const lo = Math.floor(pos); - const hi = Math.ceil(pos); - if (lo === hi) return sorted[lo] ?? 0; - return (sorted[lo] ?? 0) + ((sorted[hi] ?? 0) - (sorted[lo] ?? 0)) * (pos - lo); -} - -function summarize(rows: readonly AtlasBackgroundBenchRow[]): AtlasBackgroundBenchSummary { - const applies = rows.map((row) => row.applyMs).sort((a, b) => a - b); - const last = rows[rows.length - 1]; - return { - applyMedianMs: Number(quantile(applies, 0.5).toFixed(3)), - applyP90Ms: Number(quantile(applies, 0.9).toFixed(3)), - leafCount: last?.leafCount ?? 0, - inlineStyleChars: last?.inlineStyleChars ?? 0, - }; -} - -function makeEntry(index: number): PackedTextureAtlasEntry { - const side = Math.ceil(Math.sqrt(index + 1)); - const x = (index % side) * 16; - const y = Math.floor(index / side) * 16; - const polygon: Polygon = { - vertices: [ - [x, y, 0], - [x + 1, y, 0], - [x + 1, y + 1, 0], - [x, y + 1, 0], - ], - color: "#66cc88", - }; - return { - index, - polygon, - texture: null, - x: (index % 64) * 16, - y: Math.floor(index / 64) * 16, - w: 16, - h: 16, - canvasW: 16, - canvasH: 16, - atlasMatrix: `1,0,0,0,0,1,0,0,0,0,1,0,${x},${y},0,1`, - normal: [0, 0, 1], - } as unknown as PackedTextureAtlasEntry; -} - -function makePage(entries: readonly PackedTextureAtlasEntry[]): TextureAtlasPage { - return { - width: 1024, - height: 1024, - entries, - url: DATA_URL, - } as unknown as TextureAtlasPage; -} - -function inlineStyleChars(root: ParentNode): number { - let total = 0; - for (const el of root.querySelectorAll("s")) { - total += el.getAttribute("style")?.length ?? 0; - } - return total; -} - -async function runOne( - target: HTMLElement, - entries: readonly PackedTextureAtlasEntry[], - repeat: number, - mode: PolyTextureLightingMode, - skipDynamicNormals: boolean, -): Promise { - target.replaceChildren(); - const wrapper = document.createElement("div"); - wrapper.className = "polycss-mesh"; - const fragment = document.createDocumentFragment(); - const elements: HTMLElement[] = []; - for (const entry of entries) { - const el = createAtlasElement(entry, mode, document, skipDynamicNormals); - elements.push(el); - fragment.appendChild(el); - } - wrapper.appendChild(fragment); - target.appendChild(wrapper); - await nextFrame(); - - const page = makePage(entries); - performance.mark("polycss-atlas-background-start"); - console.timeStamp("polycss-atlas-background-start"); - const t0 = performance.now(); - for (let i = 0; i < entries.length; i += 1) { - applyAtlasBackground(elements[i]!, page, mode, entries[i]!, !skipDynamicNormals); - } - const t1 = performance.now(); - console.timeStamp("polycss-atlas-background-end"); - performance.mark("polycss-atlas-background-end"); - - const row: AtlasBackgroundBenchRow = { - repeat, - count: entries.length, - applyMs: Number((t1 - t0).toFixed(3)), - leafCount: target.querySelectorAll("s").length, - inlineStyleChars: inlineStyleChars(target), - }; - target.replaceChildren(); - await nextFrame(); - return row; -} - -export async function runPolycssAtlasBackgroundBench(input: AtlasBackgroundBenchOptions = {}): Promise<{ - options: Required; - rows: AtlasBackgroundBenchRow[]; - summary: AtlasBackgroundBenchSummary; -}> { - const options = { - count: Math.max(1, Math.floor(input.count ?? 10000)), - repeats: Math.max(1, Math.floor(input.repeats ?? 5)), - mode: input.mode ?? "baked", - skipDynamicNormals: input.skipDynamicNormals ?? false, - }; - const target = document.getElementById("bench-target") ?? document.body.appendChild(document.createElement("div")); - target.id = "bench-target"; - const entries = Array.from({ length: options.count }, (_unused, index) => makeEntry(index)); - const rows: AtlasBackgroundBenchRow[] = []; - for (let repeat = 0; repeat < options.repeats; repeat += 1) { - rows.push(await runOne(target, entries, repeat, options.mode, options.skipDynamicNormals)); - } - return { - options, - rows, - summary: summarize(rows), - }; -} - -(window as unknown as { - runPolycssAtlasBackgroundBench: typeof runPolycssAtlasBackgroundBench; -}).runPolycssAtlasBackgroundBench = runPolycssAtlasBackgroundBench; diff --git a/bench/entries/htmlMount.ts b/bench/entries/htmlMount.ts deleted file mode 100644 index eae725b9c..000000000 --- a/bench/entries/htmlMount.ts +++ /dev/null @@ -1,375 +0,0 @@ -import type { Polygon, PolyTextureLightingMode } from "@layoutit/polycss-core"; -import type { RenderedPoly } from "@layoutit/polycss"; -import { renderPolygonsWithTextureAtlas } from "@layoutit/polycss"; - -type MountStrategy = - | "fragment-append" - | "fragment-replace" - | "detached-wrapper" - | "append-batches" - | "fragment-chunks-yield" - | "contextual-fragment" - | "insert-adjacent-html" - | "append-html-unsafe" - | "stream-append-html-unsafe" - | "stream-html-unsafe" - | "direct-inner-html" - | "reuse-style-update"; - -const STRATEGIES: MountStrategy[] = [ - "fragment-append", - "fragment-replace", - "detached-wrapper", - "append-batches", - "fragment-chunks-yield", - "contextual-fragment", - "insert-adjacent-html", - "append-html-unsafe", - "stream-append-html-unsafe", - "stream-html-unsafe", - "direct-inner-html", - "reuse-style-update", -]; - -interface HtmlMountBenchOptions { - count?: number; - repeats?: number; - chunkSize?: number; - mode?: PolyTextureLightingMode; - strategies?: MountStrategy[]; -} - -interface HtmlMountBenchRow { - strategy: MountStrategy; - repeat: number; - count: number; - rendered: number; - supported: boolean; - mounted: boolean; - renderMs: number; - prepareMs: number; - mountMs: number; - totalMs: number; - leafCount: number; -} - -interface StrategySummary { - supported: boolean; - mounted: boolean; - prepareMedianMs: number; - mountMedianMs: number; - totalMedianMs: number; - leafCount: number; -} - -type HtmlInsertionTarget = HTMLElement & { - appendHTMLUnsafe?: (html: string, options?: unknown) => void; - streamAppendHTMLUnsafe?: (options?: unknown) => WritableStream; - streamHTMLUnsafe?: (options?: unknown) => WritableStream; -}; - -function solidGrid(count: number): Polygon[] { - const side = Math.ceil(Math.sqrt(count)); - const polygons: Polygon[] = []; - for (let i = 0; i < count; i += 1) { - const x = i % side; - const y = Math.floor(i / side); - const color = `#${((i * 2654435761) & 0xffffff).toString(16).padStart(6, "0")}`; - polygons.push({ - vertices: [ - [x, y, 0], - [x + 0.88, y, 0], - [x + 0.88, y + 0.88, 0], - [x, y + 0.88, 0], - ], - color, - }); - } - return polygons; -} - -function resetTarget(target: HTMLElement): void { - target.replaceChildren(); -} - -function yieldToBrowser(): Promise { - const scheduler = (globalThis as unknown as { - scheduler?: { yield?: () => Promise }; - }).scheduler; - return scheduler?.yield - ? scheduler.yield() - : new Promise((resolve) => setTimeout(resolve, 0)); -} - -function mountFragment(target: HTMLElement, rendered: readonly RenderedPoly[]): void { - const fragment = document.createDocumentFragment(); - for (const item of rendered) fragment.appendChild(item.element); - target.appendChild(fragment); -} - -function replaceWithFragment(target: HTMLElement, rendered: readonly RenderedPoly[]): void { - const fragment = document.createDocumentFragment(); - for (const item of rendered) fragment.appendChild(item.element); - target.replaceChildren(fragment); -} - -function mountDetachedWrapper(target: HTMLElement, rendered: readonly RenderedPoly[]): void { - const wrapper = document.createElement("div"); - wrapper.className = "polycss-mesh"; - const fragment = document.createDocumentFragment(); - for (const item of rendered) fragment.appendChild(item.element); - wrapper.appendChild(fragment); - target.replaceChildren(wrapper); -} - -function mountAppendBatches(target: HTMLElement, rendered: readonly RenderedPoly[], chunkSize: number): void { - for (let start = 0; start < rendered.length; start += chunkSize) { - const nodes = rendered.slice(start, start + chunkSize).map((item) => item.element); - target.append(...nodes); - } -} - -async function mountFragmentChunksYield( - target: HTMLElement, - rendered: readonly RenderedPoly[], - chunkSize: number, -): Promise { - for (let start = 0; start < rendered.length; start += chunkSize) { - const fragment = document.createDocumentFragment(); - const end = Math.min(rendered.length, start + chunkSize); - for (let i = start; i < end; i += 1) fragment.appendChild(rendered[i]!.element); - target.appendChild(fragment); - await yieldToBrowser(); - } -} - -function htmlFromRendered(rendered: readonly RenderedPoly[], chunkSize: number): string[] { - const chunks: string[] = []; - for (let start = 0; start < rendered.length; start += chunkSize) { - let html = ""; - const end = Math.min(rendered.length, start + chunkSize); - for (let i = start; i < end; i += 1) html += rendered[i]!.element.outerHTML; - chunks.push(html); - } - return chunks; -} - -function directHtmlForGrid(count: number, chunkSize: number): string[] { - const side = Math.ceil(Math.sqrt(count)); - const chunks: string[] = []; - let html = ""; - for (let i = 0; i < count; i += 1) { - const x = i % side; - const y = Math.floor(i / side); - const color = `#${((i * 2654435761) & 0xffffff).toString(16).padStart(6, "0")}`; - const tx = Number((y * 50).toFixed(3)); - const ty = Number((x * 50).toFixed(3)); - html += ``; - if ((i + 1) % chunkSize === 0) { - chunks.push(html); - html = ""; - } - } - if (html) chunks.push(html); - return chunks; -} - -function mountContextualFragment(target: HTMLElement, htmlChunks: readonly string[]): void { - const range = document.createRange(); - range.selectNode(target); - for (const html of htmlChunks) { - target.appendChild(range.createContextualFragment(html)); - } - range.detach(); -} - -function mountInsertAdjacentHtml(target: HTMLElement, htmlChunks: readonly string[]): void { - for (const html of htmlChunks) target.insertAdjacentHTML("beforeend", html); -} - -function mountAppendHtmlUnsafe(target: HtmlInsertionTarget, htmlChunks: readonly string[]): boolean { - if (typeof target.appendHTMLUnsafe !== "function") return false; - for (const html of htmlChunks) target.appendHTMLUnsafe(html); - return true; -} - -async function mountHtmlStream( - target: HtmlInsertionTarget, - htmlChunks: readonly string[], - method: "streamAppendHTMLUnsafe" | "streamHTMLUnsafe", -): Promise { - const stream = target[method]?.(); - if (!stream) return false; - const writer = stream.getWriter(); - try { - for (const html of htmlChunks) await writer.write(html); - await writer.close(); - return true; - } catch { - try { await writer.abort(); } catch { /* ignore */ } - return false; - } -} - -function mutateMountedTransforms(rendered: readonly RenderedPoly[]): void { - for (let i = 0; i < rendered.length; i += 1) { - const element = rendered[i]!.element; - element.style.transform = `${element.style.transform} translateZ(0px)`; - } -} - -function quantile(sorted: readonly number[], q: number): number { - if (sorted.length === 0) return 0; - const pos = (sorted.length - 1) * q; - const lo = Math.floor(pos); - const hi = Math.ceil(pos); - if (lo === hi) return sorted[lo] ?? 0; - return (sorted[lo] ?? 0) + ((sorted[hi] ?? 0) - (sorted[lo] ?? 0)) * (pos - lo); -} - -function summarize(rows: HtmlMountBenchRow[]): Record { - const byStrategy = new Map(); - for (const row of rows) { - const group = byStrategy.get(row.strategy); - if (group) group.push(row); - else byStrategy.set(row.strategy, [row]); - } - const out = {} as Record; - for (const [strategy, group] of byStrategy) { - const prepare = group.map((row) => row.prepareMs).sort((a, b) => a - b); - const mount = group.map((row) => row.mountMs).sort((a, b) => a - b); - const total = group.map((row) => row.totalMs).sort((a, b) => a - b); - out[strategy] = { - supported: group.some((row) => row.supported), - mounted: group.every((row) => row.mounted), - prepareMedianMs: Number(quantile(prepare, 0.5).toFixed(3)), - mountMedianMs: Number(quantile(mount, 0.5).toFixed(3)), - totalMedianMs: Number(quantile(total, 0.5).toFixed(3)), - leafCount: group[group.length - 1]?.leafCount ?? 0, - }; - } - return out; -} - -function strategySupported(target: HtmlInsertionTarget, strategy: MountStrategy): boolean { - if (strategy === "append-html-unsafe") return typeof target.appendHTMLUnsafe === "function"; - if (strategy === "stream-append-html-unsafe") return typeof target.streamAppendHTMLUnsafe === "function"; - if (strategy === "stream-html-unsafe") return typeof target.streamHTMLUnsafe === "function"; - return true; -} - -async function runOne( - target: HTMLElement, - polygons: Polygon[], - strategy: MountStrategy, - repeat: number, - options: Required> & { strategies: MountStrategy[] }, -): Promise { - resetTarget(target); - const insertionTarget = target as HtmlInsertionTarget; - const supported = strategySupported(insertionTarget, strategy); - const t0 = performance.now(); - const result = strategy === "direct-inner-html" - ? { rendered: [] as RenderedPoly[], dispose: () => {} } - : renderPolygonsWithTextureAtlas(polygons, { - doc: document, - textureLighting: options.mode, - strategies: { disable: ["i", "u"] }, - }); - const t1 = performance.now(); - - let htmlChunks: string[] = []; - if ( - strategy === "contextual-fragment" || - strategy === "insert-adjacent-html" || - strategy === "append-html-unsafe" || - strategy === "stream-append-html-unsafe" || - strategy === "stream-html-unsafe" - ) { - htmlChunks = htmlFromRendered(result.rendered, options.chunkSize); - } else if (strategy === "direct-inner-html") { - htmlChunks = directHtmlForGrid(options.count, options.chunkSize); - } else if (strategy === "reuse-style-update") { - mountFragment(target, result.rendered); - await new Promise((resolve) => requestAnimationFrame(() => resolve(undefined))); - } - const t2 = performance.now(); - - let mounted = supported; - if (supported) { - if (strategy === "fragment-append") mountFragment(target, result.rendered); - else if (strategy === "fragment-replace") replaceWithFragment(target, result.rendered); - else if (strategy === "detached-wrapper") mountDetachedWrapper(target, result.rendered); - else if (strategy === "append-batches") mountAppendBatches(target, result.rendered, options.chunkSize); - else if (strategy === "fragment-chunks-yield") await mountFragmentChunksYield(target, result.rendered, options.chunkSize); - else if (strategy === "contextual-fragment") mountContextualFragment(target, htmlChunks); - else if (strategy === "insert-adjacent-html") mountInsertAdjacentHtml(target, htmlChunks); - else if (strategy === "append-html-unsafe") mounted = mountAppendHtmlUnsafe(insertionTarget, htmlChunks); - else if (strategy === "stream-append-html-unsafe") mounted = await mountHtmlStream(insertionTarget, htmlChunks, "streamAppendHTMLUnsafe"); - else if (strategy === "stream-html-unsafe") mounted = await mountHtmlStream(insertionTarget, htmlChunks, "streamHTMLUnsafe"); - else if (strategy === "direct-inner-html") { - target.innerHTML = htmlChunks.join(""); - } else if (strategy === "reuse-style-update") { - mutateMountedTransforms(result.rendered); - } - } - const t3 = performance.now(); - - const row: HtmlMountBenchRow = { - strategy, - repeat, - count: polygons.length, - rendered: strategy === "direct-inner-html" ? polygons.length : result.rendered.length, - supported, - mounted, - renderMs: Number((t1 - t0).toFixed(3)), - prepareMs: Number((t2 - t1).toFixed(3)), - mountMs: Number((t3 - t2).toFixed(3)), - totalMs: Number((t3 - t0).toFixed(3)), - leafCount: target.querySelectorAll("b,i,s,u").length, - }; - result.dispose(); - resetTarget(target); - await new Promise((resolve) => requestAnimationFrame(() => resolve(undefined))); - return row; -} - -export async function runPolycssHtmlMountBench(input: HtmlMountBenchOptions = {}): Promise<{ - supported: boolean; - options: Required> & { strategies: MountStrategy[] }; - rows: HtmlMountBenchRow[]; - summary: Record; -}> { - const options = { - count: Math.max(1, Math.floor(input.count ?? 10000)), - repeats: Math.max(1, Math.floor(input.repeats ?? 5)), - chunkSize: Math.max(1, Math.floor(input.chunkSize ?? 750)), - mode: input.mode ?? "baked", - strategies: input.strategies?.length ? input.strategies : STRATEGIES, - }; - const target = document.getElementById("bench-target") ?? document.body.appendChild(document.createElement("div")); - target.id = "bench-target"; - const polygons = solidGrid(options.count); - const rows: HtmlMountBenchRow[] = []; - const htmlTarget = target as HtmlInsertionTarget; - const supported = typeof htmlTarget.appendHTMLUnsafe === "function" || - typeof htmlTarget.streamAppendHTMLUnsafe === "function" || - typeof htmlTarget.streamHTMLUnsafe === "function"; - - for (let repeat = 0; repeat < options.repeats; repeat += 1) { - for (const strategy of options.strategies) { - rows.push(await runOne(target, polygons, strategy, repeat, options)); - } - } - - return { - supported, - options, - rows, - summary: summarize(rows), - }; -} - -(window as unknown as { - runPolycssHtmlMountBench: typeof runPolycssHtmlMountBench; -}).runPolycssHtmlMountBench = runPolycssHtmlMountBench; diff --git a/bench/entries/parityMeshes.ts b/bench/entries/parityMeshes.ts deleted file mode 100644 index 15958c518..000000000 --- a/bench/entries/parityMeshes.ts +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Bench entry — shared scene geometry for shadow-parity.html, so every pane - * (vanilla / React / Vue) renders byte-identical polygons. Bundled into - * bench/.generated/parity-meshes.js. - */ -import { boxPolygons, spherePolygons } from "@layoutit/polycss-core"; -import type { Polygon } from "@layoutit/polycss-core"; - -/** Round caster — its many-vertex silhouette makes the parametric `definition` - * knob visually obvious. */ -export function spherePolys(radius = 8, subdivisions = 2, color = "#dc2626"): Polygon[] { - return spherePolygons({ radius, subdivisions }).map((p) => ({ ...p, color })); -} - -/** Unit-2 cube centered at the origin (sit it on the floor with position z=1). */ -export function cubePolygons(color = "#dc2626"): Polygon[] { - return boxPolygons({ size: 2 }).map((p) => ({ ...p, color })); -} - -/** Flat square floor on z=0. */ -export function floorPolygons(size = 20, color = "#cbd5e1"): Polygon[] { - const h = size / 2; - return [ - { - vertices: [ - [-h, -h, 0], - [h, -h, 0], - [h, h, 0], - [-h, h, 0], - ], - color, - }, - ]; -} diff --git a/bench/entries/shadowParityReact.tsx b/bench/entries/shadowParityReact.tsx deleted file mode 100644 index 649c201a7..000000000 --- a/bench/entries/shadowParityReact.tsx +++ /dev/null @@ -1,50 +0,0 @@ -/** - * Bench entry — React shadow-parity mount. Bundled by bench/build.mjs into - * bench/.generated/shadow-parity-react.js and used by bench/shadow-parity.html. - * - * Exposes a tiny imperative `mount(host, params)` that renders the SAME scene - * the vanilla / Vue / three panes render, so the parity page can compare all - * renderers pixel-for-pixel. Driven via the public component API (no iframe / - * postMessage). - */ -import { createElement as h } from "react"; -import { createRoot } from "react-dom/client"; -import { PolyCamera, PolyScene, PolyMesh } from "@layoutit/polycss-react"; - -export interface ParityParams { - cubePolys: unknown[]; - floorPolys: unknown[]; - cubeCenter: [number, number, number]; - directionalLight?: unknown; - pointLights?: unknown[]; - ambientLight?: unknown; - textureLighting: "baked" | "dynamic"; - shadow: { color?: string; opacity?: number; lift?: number }; - cam: { rotX: number; rotY: number; zoom: number }; -} - -export function mount(host: HTMLElement, initial: ParityParams) { - const root = createRoot(host); - const render = (p: ParityParams): void => { - root.render( - h( - PolyCamera as never, - { rotX: p.cam.rotX, rotY: p.cam.rotY, zoom: p.cam.zoom } as never, - h( - PolyScene as never, - { - directionalLight: p.directionalLight, - pointLights: p.pointLights, - ambientLight: p.ambientLight, - textureLighting: p.textureLighting, - shadow: p.shadow, - } as never, - h(PolyMesh as never, { key: "floor", polygons: p.floorPolys, receiveShadow: true } as never), - h(PolyMesh as never, { key: "cube", polygons: p.cubePolys, position: p.cubeCenter, castShadow: true } as never), - ), - ), - ); - }; - render(initial); - return { update: render, dispose: () => root.unmount() }; -} diff --git a/bench/entries/shadowParityVue.ts b/bench/entries/shadowParityVue.ts deleted file mode 100644 index 2e5885cfa..000000000 --- a/bench/entries/shadowParityVue.ts +++ /dev/null @@ -1,55 +0,0 @@ -/** - * Bench entry — Vue shadow-parity mount. Bundled by bench/build.mjs into - * bench/.generated/shadow-parity-vue.js and used by bench/shadow-parity.html. - * - * Mirror of shadowParityReact.tsx: a tiny imperative `mount(host, params)` - * that renders the same scene as the other panes via the public component API. - */ -import { createApp, h, reactive } from "vue"; -import { PolyCamera, PolyScene, PolyMesh } from "@layoutit/polycss-vue"; - -export interface ParityParams { - cubePolys: unknown[]; - floorPolys: unknown[]; - cubeCenter: [number, number, number]; - directionalLight?: unknown; - pointLights?: unknown[]; - ambientLight?: unknown; - textureLighting: "baked" | "dynamic"; - shadow: { color?: string; opacity?: number; lift?: number }; - cam: { rotX: number; rotY: number; zoom: number }; -} - -export function mount(host: HTMLElement, initial: ParityParams) { - const st = reactive<{ p: ParityParams }>({ p: initial }); - const app = createApp({ - render() { - const p = st.p; - return h( - PolyCamera as never, - { rotX: p.cam.rotX, rotY: p.cam.rotY, zoom: p.cam.zoom }, - { - default: () => - h( - PolyScene as never, - { - directionalLight: p.directionalLight, - pointLights: p.pointLights, - ambientLight: p.ambientLight, - textureLighting: p.textureLighting, - shadow: p.shadow, - }, - { - default: () => [ - h(PolyMesh as never, { polygons: p.floorPolys, receiveShadow: true }), - h(PolyMesh as never, { polygons: p.cubePolys, position: p.cubeCenter, castShadow: true }), - ], - }, - ), - }, - ); - }, - }); - app.mount(host); - return { update: (np: ParityParams) => { st.p = np; }, dispose: () => app.unmount() }; -} diff --git a/bench/entries/syncSceneAdd.ts b/bench/entries/syncSceneAdd.ts deleted file mode 100644 index e3934791b..000000000 --- a/bench/entries/syncSceneAdd.ts +++ /dev/null @@ -1,162 +0,0 @@ -import { - createPolyOrthographicCamera, - createPolyScene, - type ParseResult, - type Polygon, - type PolyTextureLightingMode, -} from "@layoutit/polycss"; - -interface SyncSceneAddBenchOptions { - count?: number; - repeats?: number; - mode?: PolyTextureLightingMode; - palette?: "same" | "unique"; - shape?: "quad" | "triangle"; - disableStrategies?: Array<"b" | "i" | "u">; -} - -interface SyncSceneAddBenchRow { - repeat: number; - count: number; - addMs: number; - leafCount: number; - mounted: boolean; -} - -interface SyncSceneAddBenchSummary { - addMedianMs: number; - addP90Ms: number; - leafCount: number; -} - -function solidGrid(count: number, palette: "same" | "unique", shape: "quad" | "triangle"): Polygon[] { - const side = Math.ceil(Math.sqrt(count)); - const polygons: Polygon[] = []; - for (let i = 0; i < count; i += 1) { - const x = i % side; - const y = Math.floor(i / side); - const color = palette === "same" - ? "#66cc88" - : `#${((i * 2654435761) & 0xffffff).toString(16).padStart(6, "0")}`; - const vertices: Polygon["vertices"] = shape === "triangle" - ? [ - [x, y, 0], - [x + 0.88, y, 0], - [x, y + 0.88, 0], - ] - : [ - [x, y, 0], - [x + 0.88, y, 0], - [x + 0.88, y + 0.88, 0], - [x, y + 0.88, 0], - ]; - polygons.push({ vertices, color }); - } - return polygons; -} - -function makeParseResult(polygons: Polygon[]): ParseResult { - return { - polygons, - objectUrls: [], - warnings: [], - dispose: () => {}, - }; -} - -function nextFrame(): Promise { - return new Promise((resolve) => requestAnimationFrame(() => resolve())); -} - -function quantile(sorted: readonly number[], q: number): number { - if (sorted.length === 0) return 0; - const pos = (sorted.length - 1) * q; - const lo = Math.floor(pos); - const hi = Math.ceil(pos); - if (lo === hi) return sorted[lo] ?? 0; - return (sorted[lo] ?? 0) + ((sorted[hi] ?? 0) - (sorted[lo] ?? 0)) * (pos - lo); -} - -function summarize(rows: readonly SyncSceneAddBenchRow[]): SyncSceneAddBenchSummary { - const adds = rows.map((row) => row.addMs).sort((a, b) => a - b); - return { - addMedianMs: Number(quantile(adds, 0.5).toFixed(3)), - addP90Ms: Number(quantile(adds, 0.9).toFixed(3)), - leafCount: rows[rows.length - 1]?.leafCount ?? 0, - }; -} - -async function runOne( - target: HTMLElement, - polygons: Polygon[], - repeat: number, - mode: PolyTextureLightingMode, - disableStrategies: Array<"b" | "i" | "u">, -): Promise { - target.replaceChildren(); - const scene = createPolyScene(target, { - camera: createPolyOrthographicCamera({ rotX: 65, rotY: 45, zoom: 1 }), - textureLighting: mode, - strategies: { disable: disableStrategies }, - }); - await nextFrame(); - - performance.mark("polycss-sync-scene-add-start"); - console.timeStamp("polycss-sync-scene-add-start"); - const t0 = performance.now(); - const handle = scene.add(makeParseResult(polygons), { - merge: false, - excludeFromAutoCenter: true, - }); - const t1 = performance.now(); - console.timeStamp("polycss-sync-scene-add-end"); - performance.mark("polycss-sync-scene-add-end"); - - const leafCount = target.querySelectorAll(".polycss-mesh > b, .polycss-mesh > i, .polycss-mesh > s, .polycss-mesh > u").length; - const row: SyncSceneAddBenchRow = { - repeat, - count: polygons.length, - addMs: Number((t1 - t0).toFixed(3)), - leafCount, - mounted: leafCount === polygons.length, - }; - - handle.dispose(); - scene.destroy(); - target.replaceChildren(); - await nextFrame(); - return row; -} - -export async function runPolycssSyncSceneAddBench(input: SyncSceneAddBenchOptions = {}): Promise<{ - options: Required; - rows: SyncSceneAddBenchRow[]; - summary: SyncSceneAddBenchSummary; -}> { - const options = { - count: Math.max(1, Math.floor(input.count ?? 10000)), - repeats: Math.max(1, Math.floor(input.repeats ?? 5)), - mode: input.mode ?? "baked", - palette: input.palette ?? "same", - shape: input.shape ?? "quad", - disableStrategies: input.disableStrategies ?? ["i", "u"], - }; - const target = document.getElementById("bench-target") ?? document.body.appendChild(document.createElement("div")); - target.id = "bench-target"; - const polygons = solidGrid(options.count, options.palette, options.shape); - const rows: SyncSceneAddBenchRow[] = []; - - for (let repeat = 0; repeat < options.repeats; repeat += 1) { - rows.push(await runOne(target, polygons, repeat, options.mode, options.disableStrategies)); - } - - return { - options, - rows, - summary: summarize(rows), - }; -} - -(window as unknown as { - runPolycssSyncSceneAddBench: typeof runPolycssSyncSceneAddBench; -}).runPolycssSyncSceneAddBench = runPolycssSyncSceneAddBench; diff --git a/bench/entries/threeParityDashboard.ts b/bench/entries/threeParityDashboard.ts deleted file mode 100644 index 7ee0e6b4c..000000000 --- a/bench/entries/threeParityDashboard.ts +++ /dev/null @@ -1,936 +0,0 @@ -import * as THREE from "three"; -import { - boxPolygons, - createPolyOrthographicCamera, - createPolyPerspectiveCamera, - createPolyScene, - dodecahedronPolygons, - icosahedronPolygons, - loadMesh, -} from "@layoutit/polycss"; -import type { - ParseResult, - Polygon, - Vec3, -} from "@layoutit/polycss"; -import { - AmbientLight, - DirectionalLight, - OrthographicCamera as PolyThreeOrthographicCamera, - PerspectiveCamera as PolyThreePerspectiveCamera, - Vector3, - createPolyOrthographicCameraFromThree, - createPolyPerspectiveCameraFromThree, - mountPolyThreeScene, - polyToThreePoint, - threeToPolyPoint, -} from "@layoutit/polycss/three"; - -type CameraMode = "perspective" | "orthographic" | "fpv"; -type ObjectKey = "cube" | "icosahedron" | "dodecahedron" | "cactus" | "box" | "car"; -type SceneKey = "single" | "lineup" | "occlusion"; -type ViewKey = "iso" | "front" | "side" | "top"; -type LightingMode = "baked" | "dynamic"; -type ThreePolygon = Omit & { vertices: Vec3[] }; -type BBox2 = { x: number; y: number; width: number; height: number; count: number }; - -const state = { - object: "cube" as ObjectKey, - scene: "single" as SceneKey, - camera: "perspective" as CameraMode, - view: "iso" as ViewKey, - fov: 42, - orthoSize: 7, - zoom: 1, - lighting: "baked" as LightingMode, - yaw: 35, - pitch: 24, -}; - -const objectCache = new Map>(); -let renderToken = 0; -let renderer: THREE.WebGLRenderer | null = null; -let polyScenes: Array<{ destroy(): void }> = []; -let activeCodeTab: "three" | "adapter" | "native" = "three"; -let lastCode = { three: "", adapter: "", native: "" }; - -const els = { - object: byId("object"), - scene: byId("scene"), - camera: byId("camera"), - view: byId("view"), - lighting: byId("lighting"), - fov: byId("fov"), - orthoSize: byId("ortho-size"), - zoom: byId("zoom"), - fovValue: byId("fov-value"), - sizeValue: byId("size-value"), - zoomValue: byId("zoom-value"), - reset: byId("reset"), - threeSurface: byId("three-surface"), - adapterHost: byId("adapter-host"), - nativeHost: byId("native-host"), - metricThree: byId("metric-three"), - metricAdapter: byId("metric-adapter"), - metricNative: byId("metric-native"), - metricDelta: byId("metric-delta"), - code: byId("code"), -}; - -const objectLabels: Record = { - cube: "colored cube", - icosahedron: "icosahedron", - dodecahedron: "dodecahedron", - cactus: "gallery cactus", - box: "gallery box", - car: "gallery car", -}; - -function byId(id: string): T { - const el = document.getElementById(id); - if (!el) throw new Error(`Missing #${id}`); - return el as T; -} - -function parseResult(polygons: Polygon[]): ParseResult { - return { polygons, objectUrls: [], warnings: [], dispose() {} }; -} - -function polyPolygonsToThree(polygons: Polygon[]): ThreePolygon[] { - return polygons.map((polygon) => ({ - ...polygon, - vertices: polygon.vertices.map((vertex) => polyToThreePoint(vertex).toArray() as Vec3), - textureTriangles: undefined, - uvs: undefined, - texture: undefined, - material: undefined, - })); -} - -function threePolygonsToPoly(polygons: ThreePolygon[]): Polygon[] { - return polygons.map((polygon) => ({ - ...polygon, - vertices: polygon.vertices.map((vertex) => threeToPolyPoint(vertex as Vec3)), - textureTriangles: undefined, - uvs: undefined, - texture: undefined, - material: undefined, - })); -} - -function normalizeThreePolygons(polygons: ThreePolygon[], targetSize = 2.4): ThreePolygon[] { - const bounds = bounds3(polygons); - const span = [ - bounds.max[0] - bounds.min[0], - bounds.max[1] - bounds.min[1], - bounds.max[2] - bounds.min[2], - ]; - const maxSpan = Math.max(span[0], span[1], span[2], 0.0001); - const scale = targetSize / maxSpan; - const centerX = (bounds.min[0] + bounds.max[0]) / 2; - const centerZ = (bounds.min[2] + bounds.max[2]) / 2; - const minY = bounds.min[1]; - - return polygons.map((polygon) => ({ - ...polygon, - vertices: polygon.vertices.map((vertex) => [ - (vertex[0] - centerX) * scale, - (vertex[1] - minY) * scale, - (vertex[2] - centerZ) * scale, - ]), - })); -} - -function bounds3(polygons: Pick[]) { - const min: Vec3 = [Infinity, Infinity, Infinity]; - const max: Vec3 = [-Infinity, -Infinity, -Infinity]; - for (const polygon of polygons) { - for (const vertex of polygon.vertices) { - min[0] = Math.min(min[0], vertex[0]); - min[1] = Math.min(min[1], vertex[1]); - min[2] = Math.min(min[2], vertex[2]); - max[0] = Math.max(max[0], vertex[0]); - max[1] = Math.max(max[1], vertex[1]); - max[2] = Math.max(max[2], vertex[2]); - } - } - return { min, max }; -} - -function transformThreePolygons( - polygons: ThreePolygon[], - transform: { position?: Vec3; scale?: number; rotationY?: number }, -): ThreePolygon[] { - const matrix = new THREE.Matrix4(); - matrix.compose( - new THREE.Vector3(...(transform.position ?? [0, 0, 0])), - new THREE.Quaternion().setFromEuler(new THREE.Euler(0, transform.rotationY ?? 0, 0)), - new THREE.Vector3(transform.scale ?? 1, transform.scale ?? 1, transform.scale ?? 1), - ); - return polygons.map((polygon) => ({ - ...polygon, - vertices: polygon.vertices.map((vertex) => { - const v = new THREE.Vector3(vertex[0], vertex[1], vertex[2]).applyMatrix4(matrix); - return [v.x, v.y, v.z] as Vec3; - }), - })); -} - -function floorPolygon(): ThreePolygon { - return { - color: "#d8dee8", - vertices: [ - [-4.2, 0, -4.2], - [-4.2, 0, 4.2], - [4.2, 0, 4.2], - [4.2, 0, -4.2], - ], - }; -} - -async function objectPolygons(key: ObjectKey): Promise { - if (!objectCache.has(key)) { - objectCache.set(key, loadObjectPolygons(key)); - } - return objectCache.get(key)!; -} - -async function loadObjectPolygons(key: ObjectKey): Promise { - if (key === "cube") { - return normalizeThreePolygons(polyPolygonsToThree(boxPolygons({ - size: 2, - faces: { - right: { color: "#ef4444" }, - left: { color: "#b91c1c" }, - front: { color: "#f59e0b" }, - back: { color: "#2563eb" }, - top: { color: "#f8fafc" }, - bottom: { color: "#64748b" }, - }, - })), 2.15); - } - if (key === "icosahedron") { - return normalizeThreePolygons(polyPolygonsToThree(icosahedronPolygons({ size: 1, color: "#38bdf8" })), 2.25); - } - if (key === "dodecahedron") { - return normalizeThreePolygons(polyPolygonsToThree(dodecahedronPolygons({ size: 1, color: "#f97316" })), 2.25); - } - - const url = { - cactus: "/gallery/glb/poly-pizza/cactus-a.glb", - box: "/gallery/glb/urban/Box.glb", - car: "/gallery/glb/urban/Car.glb", - }[key]; - const result = await loadMesh(url, { - meshResolution: "lossless", - gltfOptions: { center: true }, - solidTextureSamples: true, - }); - return normalizeThreePolygons(polyPolygonsToThree(result.polygons), key === "car" ? 3.0 : 2.45); -} - -async function scenePolygons(): Promise { - const base = await objectPolygons(state.object); - const floor = floorPolygon(); - if (state.scene === "lineup") { - return [ - floor, - ...transformThreePolygons(base, { position: [-2.25, 0, 0.2], scale: 0.72, rotationY: -0.45 }), - ...transformThreePolygons(base, { position: [0, 0, 0], scale: 0.86, rotationY: 0.1 }), - ...transformThreePolygons(base, { position: [2.25, 0, -0.15], scale: 0.72, rotationY: 0.55 }), - ]; - } - if (state.scene === "occlusion") { - return [ - floor, - ...transformThreePolygons(base, { position: [-0.72, 0, 0.78], scale: 0.95, rotationY: 0.5 }), - ...transformThreePolygons(base, { position: [0.82, 0, -0.42], scale: 0.95, rotationY: -0.35 }), - ]; - } - return [floor, ...base]; -} - -function panelSize(el: HTMLElement) { - const rect = el.getBoundingClientRect(); - return { - width: Math.max(300, Math.round(rect.width)), - height: Math.max(260, Math.round(rect.height)), - }; -} - -function cameraPosition(mode: CameraMode): { position: THREE.Vector3; target: THREE.Vector3 } { - if (mode === "fpv") { - return { - position: new THREE.Vector3(-0.4, 1.35, 5.1 / state.zoom), - target: new THREE.Vector3(0, 1.05, 0), - }; - } - const target = new THREE.Vector3(0, 1.05, 0); - const radius = 7.2 / state.zoom; - const yaw = state.yaw * Math.PI / 180; - const pitch = state.pitch * Math.PI / 180; - return { - position: new THREE.Vector3( - Math.sin(yaw) * Math.cos(pitch) * radius, - target.y + Math.sin(pitch) * radius, - Math.cos(yaw) * Math.cos(pitch) * radius, - ), - target, - }; -} - -function applyPresetView() { - const view = state.view; - if (view === "iso") { - state.yaw = 35; - state.pitch = 24; - } else if (view === "front") { - state.yaw = 0; - state.pitch = 0; - } else if (view === "side") { - state.yaw = 90; - state.pitch = 0; - } else { - state.yaw = 0; - state.pitch = 82; - } -} - -function makeThreeCamera(size: { width: number; height: number }) { - const mode = state.camera; - const { position, target } = cameraPosition(mode); - const aspect = size.width / size.height; - const camera = mode === "orthographic" - ? new THREE.OrthographicCamera( - -state.orthoSize * aspect / 2, - state.orthoSize * aspect / 2, - state.orthoSize / 2, - -state.orthoSize / 2, - 0.01, - 200, - ) - : new THREE.PerspectiveCamera(state.fov, aspect, 0.01, 200); - camera.position.copy(position); - camera.lookAt(target); - camera.updateProjectionMatrix(); - camera.updateMatrixWorld(); - return camera; -} - -function makeCompatCamera(size: { width: number; height: number }) { - const mode = state.camera; - const { position, target } = cameraPosition(mode); - const aspect = size.width / size.height; - if (mode === "orthographic") { - const camera = new PolyThreeOrthographicCamera( - -state.orthoSize * aspect / 2, - state.orthoSize * aspect / 2, - state.orthoSize / 2, - -state.orthoSize / 2, - 0.01, - 200, - ); - camera.position.set(position.x, position.y, position.z); - camera.lookAt(new Vector3(target.x, target.y, target.z)); - return camera; - } - const camera = new PolyThreePerspectiveCamera(state.fov, aspect, 0.01, 200); - camera.position.set(position.x, position.y, position.z); - camera.lookAt(new Vector3(target.x, target.y, target.z)); - return camera; -} - -function makeLights() { - const ambient = new AmbientLight("#ffffff", 0.48); - const directional = new DirectionalLight("#ffffff", 0.82); - directional.position.set(3.4, 5.2, 4.1); - directional.target.position.set(0, 0.8, 0); - return { ambient, directional }; -} - -function renderThree(polygons: ThreePolygon[], camera: THREE.Camera, size: { width: number; height: number }) { - renderer?.dispose(); - els.threeSurface.textContent = ""; - const canvas = document.createElement("canvas"); - els.threeSurface.appendChild(canvas); - try { - renderer = new THREE.WebGLRenderer({ canvas, antialias: true, alpha: false }); - renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2)); - renderer.setSize(size.width, size.height, false); - renderer.setClearColor(0xf8fafc, 1); - - const scene = new THREE.Scene(); - scene.add(new THREE.AmbientLight("#ffffff", 0.48)); - const light = new THREE.DirectionalLight("#ffffff", 0.82); - light.position.set(3.4, 5.2, 4.1); - light.target.position.set(0, 0.8, 0); - scene.add(light); - scene.add(light.target); - - scene.add(meshFromPolygons(polygons)); - renderer.render(scene, camera); - } catch (err) { - renderer = null; - renderThreeCanvasFallback(canvas, polygons, camera, size); - console.warn("Three.js WebGL unavailable; dashboard used a 2D projected fallback for this panel.", err); - } -} - -function meshFromPolygons(polygons: ThreePolygon[]) { - const positions: number[] = []; - const colors: number[] = []; - for (const polygon of polygons) { - if (polygon.vertices.length < 3) continue; - const color = new THREE.Color(polygon.color ?? "#cbd5e1"); - for (let i = 1; i < polygon.vertices.length - 1; i++) { - for (const vertex of [polygon.vertices[0], polygon.vertices[i], polygon.vertices[i + 1]]) { - positions.push(vertex[0], vertex[1], vertex[2]); - colors.push(color.r, color.g, color.b); - } - } - } - const geometry = new THREE.BufferGeometry(); - geometry.setAttribute("position", new THREE.Float32BufferAttribute(positions, 3)); - geometry.setAttribute("color", new THREE.Float32BufferAttribute(colors, 3)); - geometry.computeVertexNormals(); - return new THREE.Mesh( - geometry, - new THREE.MeshLambertMaterial({ vertexColors: true, side: THREE.FrontSide }), - ); -} - -function renderThreeCanvasFallback( - canvas: HTMLCanvasElement, - polygons: ThreePolygon[], - camera: THREE.Camera, - size: { width: number; height: number }, -) { - const dpr = Math.min(window.devicePixelRatio || 1, 2); - canvas.width = Math.round(size.width * dpr); - canvas.height = Math.round(size.height * dpr); - canvas.style.width = "100%"; - canvas.style.height = "100%"; - const ctx = canvas.getContext("2d"); - if (!ctx) return; - ctx.scale(dpr, dpr); - ctx.fillStyle = "#f8fafc"; - ctx.fillRect(0, 0, size.width, size.height); - - const light = new THREE.Vector3(3.4, 5.2, 4.1).sub(new THREE.Vector3(0, 0.8, 0)).normalize(); - const drawables = polygons - .filter((polygon) => polygon.vertices.length >= 3) - .map((polygon) => { - const pts = polygon.vertices.map((vertex) => { - const world = new THREE.Vector3(vertex[0], vertex[1], vertex[2]); - const ndc = world.clone().project(camera); - const view = world.clone().applyMatrix4(camera.matrixWorldInverse); - return { - x: (ndc.x * 0.5 + 0.5) * size.width, - y: (-ndc.y * 0.5 + 0.5) * size.height, - z: view.z, - }; - }); - return { - polygon, - pts, - z: pts.reduce((sum, pt) => sum + pt.z, 0) / pts.length, - }; - }) - .sort((a, b) => a.z - b.z); - - for (const item of drawables) { - const normal = polygonNormal(item.polygon.vertices); - const direct = 0.82 * Math.max(0, normal.dot(light)); - const color = lambertSrgbColor(item.polygon.color ?? "#cbd5e1", direct, 0.48); - ctx.beginPath(); - ctx.moveTo(item.pts[0].x, item.pts[0].y); - for (let i = 1; i < item.pts.length; i++) ctx.lineTo(item.pts[i].x, item.pts[i].y); - ctx.closePath(); - ctx.fillStyle = `#${color.getHexString()}`; - ctx.fill(); - } - - ctx.fillStyle = "rgba(82, 96, 114, 0.82)"; - ctx.font = "11px ui-monospace, SFMono-Regular, Menlo, monospace"; - ctx.fillText("2D fallback: WebGL unavailable in this browser", 12, size.height - 14); -} - -function lambertSrgbColor(baseHex: string, direct: number, ambient: number) { - const base = new THREE.Color(baseHex); - const lit = new THREE.Color( - base.r * (direct + ambient) / Math.PI, - base.g * (direct + ambient) / Math.PI, - base.b * (direct + ambient) / Math.PI, - ); - return lit; -} - -function polygonNormal(vertices: Vec3[]) { - if (vertices.length < 3) return new THREE.Vector3(0, 1, 0); - const a = new THREE.Vector3(...vertices[0]); - const b = new THREE.Vector3(...vertices[1]); - const c = new THREE.Vector3(...vertices[2]); - return b.sub(a).cross(c.sub(a)).normalize(); -} - -function renderAdapter(host: HTMLElement, polygons: Polygon[], camera: ReturnType, size: { height: number }) { - const { ambient, directional } = makeLights(); - const scene = mountPolyThreeScene(host, { - camera, - cameraOptions: { viewportHeight: size.height }, - polygons, - autoCenter: false, - directionalLight: directional.toPolyDirectionalLight(), - ambientLight: ambient.toPolyAmbientLight(), - textureLighting: state.lighting, - textureQuality: 1, - }); - polyScenes.push(scene); -} - -function renderNative(host: HTMLElement, polygons: Polygon[], camera: ReturnType, size: { height: number }) { - const { ambient, directional } = makeLights(); - const nativeCamera = camera instanceof PolyThreePerspectiveCamera - ? createPolyPerspectiveCameraFromThree(camera, { viewportHeight: size.height }) - : createPolyOrthographicCameraFromThree(camera, { viewportHeight: size.height }); - const scene = createPolyScene(host, { - camera: nativeCamera, - autoCenter: false, - directionalLight: directional.toPolyDirectionalLight(), - ambientLight: ambient.toPolyAmbientLight(), - textureLighting: state.lighting, - textureQuality: 1, - }); - scene.add(parseResult(polygons), { merge: false, meshResolution: "lossless" }); - polyScenes.push(scene); -} - -function clearPolyScenes() { - for (const scene of polyScenes) scene.destroy(); - polyScenes = []; - els.adapterHost.textContent = ""; - els.nativeHost.textContent = ""; -} - -async function render() { - const token = ++renderToken; - setLoading(true); - updateLabels(); - try { - const polygons = await scenePolygons(); - if (token !== renderToken) return; - - clearPolyScenes(); - const size = panelSize(els.threeSurface); - const threeCamera = makeThreeCamera(size); - const compatCamera = makeCompatCamera(size); - const polyPolygons = threePolygonsToPoly(polygons); - - renderThree(polygons, threeCamera, size); - renderAdapter(els.adapterHost, polyPolygons, compatCamera, size); - renderNative(els.nativeHost, polyPolygons, compatCamera, size); - updateCode(); - - requestAnimationFrame(() => { - const threeBox = projectedBBox(polygons, threeCamera, size); - const adapterBox = domBBox(els.adapterHost); - const nativeBox = domBBox(els.nativeHost); - updateMetrics(threeBox, adapterBox, nativeBox); - setLoading(false); - (window as unknown as { __polyThreeParityReady?: boolean; __polyThreeParitySnapshot?: unknown }).__polyThreeParityReady = true; - (window as unknown as { __polyThreeParitySnapshot?: unknown }).__polyThreeParitySnapshot = { - state: { ...state }, - threeBox, - adapterBox, - nativeBox, - }; - }); - } catch (err) { - setLoading(false); - const message = err instanceof Error ? err.message : String(err); - els.metricDelta.textContent = `error: ${message}`; - throw err; - } -} - -function projectedBBox(polygons: ThreePolygon[], camera: THREE.Camera, size: { width: number; height: number }): BBox2 { - let minX = Infinity; - let minY = Infinity; - let maxX = -Infinity; - let maxY = -Infinity; - let count = 0; - for (const polygon of polygons) { - for (const vertex of polygon.vertices) { - const v = new THREE.Vector3(vertex[0], vertex[1], vertex[2]).project(camera); - if (!Number.isFinite(v.x) || !Number.isFinite(v.y) || !Number.isFinite(v.z)) continue; - const x = (v.x * 0.5 + 0.5) * size.width; - const y = (-v.y * 0.5 + 0.5) * size.height; - minX = Math.min(minX, x); - minY = Math.min(minY, y); - maxX = Math.max(maxX, x); - maxY = Math.max(maxY, y); - count++; - } - } - return bboxOrEmpty(minX, minY, maxX, maxY, count); -} - -function domBBox(host: HTMLElement): BBox2 { - const root = host.getBoundingClientRect(); - let minX = Infinity; - let minY = Infinity; - let maxX = -Infinity; - let maxY = -Infinity; - let count = 0; - for (const el of host.querySelectorAll(".polycss-mesh *")) { - const rect = el.getBoundingClientRect(); - if (rect.width < 0.5 || rect.height < 0.5) continue; - minX = Math.min(minX, rect.left - root.left); - minY = Math.min(minY, rect.top - root.top); - maxX = Math.max(maxX, rect.right - root.left); - maxY = Math.max(maxY, rect.bottom - root.top); - count++; - } - return bboxOrEmpty(minX, minY, maxX, maxY, count); -} - -function bboxOrEmpty(minX: number, minY: number, maxX: number, maxY: number, count: number): BBox2 { - if (!count) return { x: 0, y: 0, width: 0, height: 0, count: 0 }; - return { - x: minX, - y: minY, - width: Math.max(0, maxX - minX), - height: Math.max(0, maxY - minY), - count, - }; -} - -function updateMetrics(three: BBox2, adapter: BBox2, native: BBox2) { - els.metricThree.textContent = fmtBox(three); - els.metricAdapter.textContent = fmtBox(adapter); - els.metricNative.textContent = fmtBox(native); - els.metricDelta.textContent = [ - `PolyCSS lighting: ${state.lighting}`, - `adapter vs three: ${fmtDelta(three, adapter)}`, - `native vs three: ${fmtDelta(three, native)}`, - `native vs adapter:${fmtDelta(adapter, native)}`, - ].join("\n"); -} - -function fmtBox(box: BBox2): string { - return `x ${box.x.toFixed(1)} -y ${box.y.toFixed(1)} -w ${box.width.toFixed(1)} -h ${box.height.toFixed(1)} -leaves/verts ${box.count}`; -} - -function fmtDelta(a: BBox2, b: BBox2): string { - const acx = a.x + a.width / 2; - const acy = a.y + a.height / 2; - const bcx = b.x + b.width / 2; - const bcy = b.y + b.height / 2; - return `center ${Math.hypot(acx - bcx, acy - bcy).toFixed(1)}px, size ${Math.hypot(a.width - b.width, a.height - b.height).toFixed(1)}px`; -} - -function setLoading(active: boolean) { - for (const surface of [els.threeSurface, els.adapterHost.parentElement, els.nativeHost.parentElement]) { - if (!surface) continue; - const existing = surface.querySelector(".loading"); - if (!active) { - existing?.remove(); - continue; - } - if (!existing) { - const loading = document.createElement("div"); - loading.className = "loading"; - loading.textContent = "rendering"; - surface.appendChild(loading); - } - } -} - -function updateLabels() { - els.fovValue.textContent = `${state.fov}deg`; - els.sizeValue.textContent = state.orthoSize.toFixed(2); - els.zoomValue.textContent = `${state.zoom.toFixed(2)}x`; -} - -function codeNumber(value: number): string { - return Number(value.toFixed(4)).toString(); -} - -function codeVector(v: THREE.Vector3): string { - return `${codeNumber(v.x)}, ${codeNumber(v.y)}, ${codeNumber(v.z)}`; -} - -function codeSize() { - const size = panelSize(els.threeSurface); - return { ...size, aspect: size.width / size.height }; -} - -function threeCameraCode(size = codeSize()): string { - const { position, target } = cameraPosition(state.camera); - if (state.camera === "orthographic") { - return `const camera = new THREE.OrthographicCamera( - ${codeNumber(-state.orthoSize * size.aspect / 2)}, - ${codeNumber(state.orthoSize * size.aspect / 2)}, - ${codeNumber(state.orthoSize / 2)}, - ${codeNumber(-state.orthoSize / 2)}, - 0.01, - 200, -); -camera.position.set(${codeVector(position)}); -camera.lookAt(${codeVector(target)}); -camera.updateProjectionMatrix(); -camera.updateMatrixWorld();`; - } - return `const camera = new THREE.PerspectiveCamera(${state.fov}, ${codeNumber(size.aspect)}, 0.01, 200); -camera.position.set(${codeVector(position)}); -camera.lookAt(${codeVector(target)}); -camera.updateProjectionMatrix(); -camera.updateMatrixWorld();`; -} - -function compatCameraCode(variableName: string, size = codeSize()): string { - const { position, target } = cameraPosition(state.camera); - if (state.camera === "orthographic") { - return `const ${variableName} = new OrthographicCamera( - ${codeNumber(-state.orthoSize * size.aspect / 2)}, - ${codeNumber(state.orthoSize * size.aspect / 2)}, - ${codeNumber(state.orthoSize / 2)}, - ${codeNumber(-state.orthoSize / 2)}, - 0.01, - 200, -); -${variableName}.position.set(${codeVector(position)}); -${variableName}.lookAt(${codeVector(target)});`; - } - return `const ${variableName} = new PerspectiveCamera(${state.fov}, ${codeNumber(size.aspect)}, 0.01, 200); -${variableName}.position.set(${codeVector(position)}); -${variableName}.lookAt(${codeVector(target)});`; -} - -function lightsCode(prefix: "THREE" | "poly") { - if (prefix === "THREE") { - return `scene.add(new THREE.AmbientLight("#ffffff", 0.48)); -const directional = new THREE.DirectionalLight("#ffffff", 0.82); -directional.position.set(3.4, 5.2, 4.1); -directional.target.position.set(0, 0.8, 0); -scene.add(directional); -scene.add(directional.target);`; - } - return `const ambient = new AmbientLight("#ffffff", 0.48); -const directional = new DirectionalLight("#ffffff", 0.82); -directional.position.set(3.4, 5.2, 4.1); -directional.target.position.set(0, 0.8, 0);`; -} - -function currentInputComment() { - return `// Input geometry: ${objectLabels[state.object]}, ${state.scene} scene, authored in Three/Y-up coordinates. -// The bench loader produces this from primitives or gallery GLBs, then applies the same floor/lineup/occlusion transforms. -const threePolygons = await loadSelectedScenePolygons();`; -} - -function updateCode() { - const size = codeSize(); - lastCode = { - three: `import * as THREE from "three"; - -const host = document.querySelector("#three")!; -const size = { width: ${size.width}, height: ${size.height} }; -${currentInputComment()} - -const canvas = document.createElement("canvas"); -host.appendChild(canvas); -const renderer = new THREE.WebGLRenderer({ canvas, antialias: true, alpha: false }); -renderer.setSize(size.width, size.height, false); -renderer.setClearColor(0xf8fafc, 1); - -${threeCameraCode(size)} - -const scene = new THREE.Scene(); -${lightsCode("THREE")} -scene.add(meshFromPolygons(threePolygons)); -renderer.render(scene, camera); - -function meshFromPolygons(polygons) { - const positions = []; - const colors = []; - for (const polygon of polygons) { - const color = new THREE.Color(polygon.color ?? "#cbd5e1"); - for (let i = 1; i < polygon.vertices.length - 1; i++) { - for (const vertex of [polygon.vertices[0], polygon.vertices[i], polygon.vertices[i + 1]]) { - positions.push(vertex[0], vertex[1], vertex[2]); - colors.push(color.r, color.g, color.b); - } - } - } - const geometry = new THREE.BufferGeometry(); - geometry.setAttribute("position", new THREE.Float32BufferAttribute(positions, 3)); - geometry.setAttribute("color", new THREE.Float32BufferAttribute(colors, 3)); - geometry.computeVertexNormals(); - return new THREE.Mesh( - geometry, - new THREE.MeshLambertMaterial({ vertexColors: true, side: THREE.FrontSide }), - ); -}`, - adapter: `import { - AmbientLight, - DirectionalLight, - ${state.camera === "orthographic" ? "OrthographicCamera" : "PerspectiveCamera"}, - mountPolyThreeScene, - threeToPolyPoint, -} from "@layoutit/polycss/three"; - -const host = document.querySelector("#poly-three")!; -${currentInputComment()} - -const polyPolygons = threePolygons.map((polygon) => ({ - color: polygon.color, - vertices: polygon.vertices.map((vertex) => threeToPolyPoint(vertex)), -})); - -${compatCameraCode("camera", size)} -${lightsCode("poly")} - -mountPolyThreeScene(host, { - camera, - cameraOptions: { viewportHeight: ${size.height} }, - polygons: polyPolygons, - autoCenter: false, - directionalLight: directional.toPolyDirectionalLight(), - ambientLight: ambient.toPolyAmbientLight(), - textureLighting: "${state.lighting}", - textureQuality: 1, -});`, - native: `import { createPolyScene } from "@layoutit/polycss"; -import { - AmbientLight, - DirectionalLight, - ${state.camera === "orthographic" ? "OrthographicCamera, createPolyOrthographicCameraFromThree" : "PerspectiveCamera, createPolyPerspectiveCameraFromThree"}, - threeToPolyPoint, -} from "@layoutit/polycss/three"; - -const host = document.querySelector("#poly-native")!; -${currentInputComment()} - -const polyPolygons = threePolygons.map((polygon) => ({ - color: polygon.color, - vertices: polygon.vertices.map((vertex) => threeToPolyPoint(vertex)), -})); - -${compatCameraCode("threeLikeCamera", size)} -${lightsCode("poly")} - -const camera = ${state.camera === "orthographic" ? "createPolyOrthographicCameraFromThree" : "createPolyPerspectiveCameraFromThree"}(threeLikeCamera, { - viewportHeight: ${size.height}, -}); - -const scene = createPolyScene(host, { - camera, - autoCenter: false, - directionalLight: directional.toPolyDirectionalLight(), - ambientLight: ambient.toPolyAmbientLight(), - textureLighting: "${state.lighting}", - textureQuality: 1, -}); - -scene.add({ polygons: polyPolygons, objectUrls: [], warnings: [], dispose() {} }, { - merge: false, - meshResolution: "lossless", -});`, - }; - els.code.textContent = lastCode[activeCodeTab]; -} - -function bindControls() { - els.object.value = state.object; - els.scene.value = state.scene; - els.camera.value = state.camera; - els.view.value = state.view; - els.lighting.value = state.lighting; - els.fov.value = String(state.fov); - els.orthoSize.value = String(state.orthoSize); - els.zoom.value = String(state.zoom); - - els.object.addEventListener("change", () => { - state.object = els.object.value as ObjectKey; - render(); - }); - els.scene.addEventListener("change", () => { - state.scene = els.scene.value as SceneKey; - render(); - }); - els.camera.addEventListener("change", () => { - state.camera = els.camera.value as CameraMode; - render(); - }); - els.view.addEventListener("change", () => { - state.view = els.view.value as ViewKey; - applyPresetView(); - render(); - }); - els.lighting.addEventListener("change", () => { - state.lighting = els.lighting.value as LightingMode; - render(); - }); - els.fov.addEventListener("input", () => { - state.fov = Number(els.fov.value); - render(); - }); - els.orthoSize.addEventListener("input", () => { - state.orthoSize = Number(els.orthoSize.value); - render(); - }); - els.zoom.addEventListener("input", () => { - state.zoom = Number(els.zoom.value); - render(); - }); - els.reset.addEventListener("click", () => { - state.zoom = 1; - state.view = "iso"; - els.zoom.value = "1"; - els.view.value = "iso"; - applyPresetView(); - render(); - }); - - for (const button of document.querySelectorAll(".tabs button")) { - button.addEventListener("click", () => { - activeCodeTab = button.dataset.tab as typeof activeCodeTab; - for (const b of document.querySelectorAll(".tabs button")) b.classList.remove("active"); - button.classList.add("active"); - els.code.textContent = lastCode[activeCodeTab]; - }); - } - - let dragging = false; - let lastX = 0; - let lastY = 0; - for (const surface of document.querySelectorAll(".surface")) { - surface.addEventListener("pointerdown", (event) => { - dragging = true; - lastX = event.clientX; - lastY = event.clientY; - surface.setPointerCapture(event.pointerId); - }); - surface.addEventListener("pointermove", (event) => { - if (!dragging || state.camera === "fpv") return; - state.yaw += (event.clientX - lastX) * 0.35; - state.pitch = Math.max(-82, Math.min(82, state.pitch - (event.clientY - lastY) * 0.25)); - lastX = event.clientX; - lastY = event.clientY; - render(); - }); - surface.addEventListener("pointerup", () => { - dragging = false; - }); - } - - window.addEventListener("resize", () => render()); -} - -bindControls(); -applyPresetView(); -render(); diff --git a/bench/html-mount-bench.mjs b/bench/html-mount-bench.mjs deleted file mode 100644 index e2dccbbe0..000000000 --- a/bench/html-mount-bench.mjs +++ /dev/null @@ -1,152 +0,0 @@ -/** - * Benchmark the experimental trusted HTML chunk mount helper against the - * existing DocumentFragment mount path. - * - * Usage: - * node bench/html-mount-bench.mjs - * node bench/html-mount-bench.mjs --count 20000 --repeats 7 --label html-mount - * node bench/html-mount-bench.mjs --no-experimental - */ -import { createServer } from "node:http"; -import { readFile, mkdir, writeFile } from "node:fs/promises"; -import { dirname, extname, resolve } from "node:path"; -import { fileURLToPath } from "node:url"; -import { chromium } from "playwright"; -import { chromiumArgsWithGpuDefault } from "./chromium-defaults.mjs"; - -const __dirname = dirname(fileURLToPath(import.meta.url)); -const repoRoot = resolve(__dirname, ".."); -const benchDir = resolve(repoRoot, "bench"); - -const argv = process.argv.slice(2); -const flag = (name) => argv.indexOf(`--${name}`); -const optStr = (name, dflt = "") => { - const i = flag(name); - return i >= 0 ? argv[i + 1] : dflt; -}; -const optNum = (name, dflt) => { - const raw = optStr(name); - return raw ? Number(raw) : dflt; -}; -const hasFlag = (name) => flag(name) >= 0; -const optAll = (name) => { - const values = []; - for (let i = 0; i < argv.length; i += 1) { - const arg = argv[i]; - if (arg === `--${name}` && argv[i + 1]) { - values.push(argv[i + 1]); - i += 1; - } else if (arg.startsWith(`--${name}=`)) { - values.push(arg.slice(name.length + 3)); - } - } - return values; -}; - -const COUNT = optNum("count", 10000); -const REPEATS = optNum("repeats", 5); -const CHUNK_SIZE = optNum("chunk-size", optNum("chunkSize", 750)); -const MODE = optStr("mode", "baked"); -const LABEL = optStr("label"); -const HEADED = hasFlag("headed"); -const NO_EXPERIMENTAL = hasFlag("no-experimental"); -const YIELD_BETWEEN_CHUNKS = hasFlag("yield"); -const BROWSER_EXECUTABLE = optStr("browser-executable"); -const CHROMIUM_ARGS = chromiumArgsWithGpuDefault([ - ...(NO_EXPERIMENTAL ? [] : ["--enable-experimental-web-platform-features"]), - ...optAll("chromium-arg"), - ...optAll("chromium-args").flatMap((value) => value.split(/\s+/).filter(Boolean)), -]); - -const MIME = { - ".html": "text/html; charset=utf-8", - ".js": "application/javascript; charset=utf-8", - ".mjs": "application/javascript; charset=utf-8", - ".css": "text/css; charset=utf-8", -}; - -function startServer() { - return new Promise((resolveStart, rejectStart) => { - const server = createServer(async (req, res) => { - try { - const url = new URL(req.url, "http://localhost"); - const safe = url.pathname.replace(/\/+/g, "/"); - if (safe.includes("..")) { - res.writeHead(403); - res.end("forbidden"); - return; - } - const abs = resolve(benchDir, safe === "/" ? "html-mount.html" : safe.slice(1)); - const data = await readFile(abs); - res.writeHead(200, { - "Content-Type": MIME[extname(abs).toLowerCase()] || "application/octet-stream", - "Cache-Control": "no-store", - }); - res.end(data); - } catch (err) { - res.writeHead(404); - res.end(String(err?.message ?? err)); - } - }); - server.on("error", rejectStart); - server.listen(0, "127.0.0.1", () => { - const addr = server.address(); - resolveStart({ server, port: typeof addr === "object" ? addr.port : 0 }); - }); - }); -} - -function stopServer(server) { - return new Promise((resolveStop) => server.close(resolveStop)); -} - -function printResult(result) { - console.log(`[html-mount] supported=${result.supported} count=${result.options.count} repeats=${result.options.repeats} chunk=${result.options.chunkSize}`); - console.log(JSON.stringify(result.summary, null, 2)); - for (const row of result.rows) { - console.log( - `${row.strategy.padEnd(8)} #${row.repeat} ` + - `render=${row.renderMs.toFixed(3)}ms mount=${row.mountMs.toFixed(3)}ms ` + - `total=${row.totalMs.toFixed(3)}ms mounted=${row.mounted} leaves=${row.leafCount}`, - ); - } -} - -let server; -let browser; -try { - const started = await startServer(); - server = started.server; - const url = `http://127.0.0.1:${started.port}/html-mount.html`; - console.log(`[html-mount] ${url}`); - if (CHROMIUM_ARGS.length > 0) console.log(`[html-mount] chromium args=${CHROMIUM_ARGS.join(" ")}`); - browser = await chromium.launch({ - headless: !HEADED, - executablePath: BROWSER_EXECUTABLE || undefined, - args: CHROMIUM_ARGS, - }); - const page = await browser.newPage({ viewport: { width: 1200, height: 900 } }); - await page.goto(url, { waitUntil: "load" }); - const result = await page.evaluate( - async ({ count, repeats, chunkSize, mode, yieldBetweenChunks }) => - window.runPolycssHtmlMountBench({ count, repeats, chunkSize, mode, yieldBetweenChunks }), - { - count: COUNT, - repeats: REPEATS, - chunkSize: CHUNK_SIZE, - mode: MODE === "dynamic" ? "dynamic" : "baked", - yieldBetweenChunks: YIELD_BETWEEN_CHUNKS, - }, - ); - printResult(result); - if (LABEL) { - const dir = resolve(repoRoot, "bench/results"); - await mkdir(dir, { recursive: true }); - const file = resolve(dir, `${LABEL}.json`); - await writeFile(file, JSON.stringify(result, null, 2)); - console.log(`[html-mount] wrote ${file}`); - } -} finally { - if (browser) await browser.close(); - if (server) await stopServer(server); -} diff --git a/bench/html-mount.html b/bench/html-mount.html deleted file mode 100644 index c1ce8954b..000000000 --- a/bench/html-mount.html +++ /dev/null @@ -1,53 +0,0 @@ - - - - - polycss HTML chunk mount bench - - - -
ready
-
- - - diff --git a/bench/mask-polygon-bench.mjs b/bench/mask-polygon-bench.mjs deleted file mode 100644 index 278af37a2..000000000 --- a/bench/mask-polygon-bench.mjs +++ /dev/null @@ -1,423 +0,0 @@ -#!/usr/bin/env node -/** - * Synthetic browser bench for solid non-rect polygon primitives: - * - * node bench/mask-polygon-bench.mjs - * node bench/mask-polygon-bench.mjs --counts 1000,3000 --variants border16,solid64,mask16,atlas64 --label mask-poly - * node bench/mask-polygon-bench.mjs --variants border16,border16:ellipse0,border16:inset50,border16:xywh0 - * node bench/mask-polygon-bench.mjs --variants border16,solid64,clip16,svgpoly16,svgpath16 - * node bench/mask-polygon-bench.mjs --variants border16,borderclass16,bordervar16,bordercontainpaint16,bordernowill16 - */ -import { createServer } from "node:http"; -import { readFile, mkdir, writeFile } from "node:fs/promises"; -import { dirname, extname, resolve } from "node:path"; -import { fileURLToPath } from "node:url"; -import { chromium } from "playwright"; -import { chromiumArgsWithGpuDefault } from "./chromium-defaults.mjs"; - -const __dirname = dirname(fileURLToPath(import.meta.url)); -const repoRoot = resolve(__dirname, ".."); -const benchDir = resolve(repoRoot, "bench"); - -const argv = process.argv.slice(2); -const flag = (name) => argv.indexOf(`--${name}`); -const hasFlag = (name) => flag(name) >= 0 || argv.includes(`--${name}=true`); -const optStr = (name, dflt = "") => { - const exact = flag(name); - if (exact >= 0) return argv[exact + 1] ?? dflt; - const prefixed = argv.find((arg) => arg.startsWith(`--${name}=`)); - return prefixed ? prefixed.slice(name.length + 3) : dflt; -}; -const optNum = (name, dflt) => { - const raw = optStr(name, String(dflt)); - const value = Number(raw); - return Number.isFinite(value) ? value : dflt; -}; -const optAll = (name) => { - const values = []; - for (let i = 0; i < argv.length; i += 1) { - const arg = argv[i]; - if (arg === `--${name}` && argv[i + 1]) { - values.push(argv[i + 1]); - i += 1; - } else if (arg.startsWith(`--${name}=`)) { - values.push(arg.slice(name.length + 3)); - } - } - return values; -}; - -const COUNTS = parseNumberList(optStr("counts", "1000,3000,6000")); -const VARIANTS = parseVariants(optStr("variants", "border16,mask16,mask64,atlas64")); -const REPEATS = Math.max(1, Math.round(optNum("repeats", 2))); -const WARMUP_MS = Math.max(0, optNum("warmup", 1200)); -const SAMPLE_MS = Math.max(250, optNum("sample", 2500)); -const SHAPE = optStr("shape", "hex"); -const MOTION = optStr("motion", "orbit"); -const TARGET = optNum("target", 64); -const LABEL = optStr("label"); -const JSON_PATH = optStr("json"); -const HEADED = hasFlag("headed"); -const BROWSER_EXECUTABLE = optStr("browser-executable"); -const BORDER_SHAPE_FLAG = "--enable-blink-features=CSSBorderShape"; -const CHROMIUM_ARGS = chromiumArgsWithGpuDefault([ - ...(!hasFlag("no-border-shape-flag") ? [BORDER_SHAPE_FLAG] : []), - ...optAll("chromium-arg"), - ...optAll("chromium-args").flatMap((value) => value.split(/\s+/).filter(Boolean)), -]); - -const MIME = { - ".html": "text/html; charset=utf-8", - ".js": "application/javascript; charset=utf-8", - ".mjs": "application/javascript; charset=utf-8", - ".css": "text/css; charset=utf-8", - ".png": "image/png", -}; - -function parseNumberList(value) { - return String(value) - .split(",") - .map((part) => Number(part.trim())) - .filter((n) => Number.isFinite(n) && n > 0) - .map((n) => Math.round(n)); -} - -function parseVariants(value) { - return String(value) - .split(",") - .map((part) => part.trim()) - .filter(Boolean) - .map((id) => { - const [baseId, borderInnerRaw] = id.split(":"); - const samePathMatch = /^border(class|var|containpaint|containstrict|containlayout|nowill|isolate|solidstyle)(\d+)?$/i.exec(baseId); - if (samePathMatch) { - const mode = samePathMatch[1].toLowerCase(); - const primitive = Number(samePathMatch[2] ?? 16); - return { - id: `${baseId}${borderInnerRaw ? `:${borderInnerRaw.toLowerCase()}` : ""}`, - strategy: "border", - borderFunction: "polygon", - borderInner: borderInnerRaw?.toLowerCase(), - borderShapeSource: mode === "class" ? "class" : mode === "var" ? "var" : "inline", - leafContain: mode === "containpaint" - ? "paint" - : mode === "containstrict" - ? "strict" - : mode === "containlayout" - ? "layout" - : undefined, - leafWillChange: mode === "nowill" ? "auto" : undefined, - leafIsolation: mode === "isolate" ? "isolate" : undefined, - borderStyle: mode === "solidstyle" ? "solid" : undefined, - primitive, - }; - } - const borderMatch = /^border(?:(polygonplain|polygon|path|shape|circle|ellipse|xywh|inset|rect))?(\d+)?$/i.exec(baseId); - if (borderMatch) { - const borderFunction = (borderMatch[1] ?? "polygon").toLowerCase(); - const primitive = Number(borderMatch[2] ?? 16); - const borderInner = borderInnerRaw?.toLowerCase(); - const baseVariantId = borderFunction === "polygon" ? `border${primitive}` : `border${borderFunction}${primitive}`; - return { - id: borderInner ? `${baseVariantId}:${borderInner}` : baseVariantId, - strategy: "border", - borderFunction, - borderInner, - primitive, - }; - } - const clipMatch = /^clip(\d+)?$/i.exec(id); - if (clipMatch) { - const primitive = Number(clipMatch[1] ?? 16); - return { id: `clip${primitive}`, strategy: "clip", primitive }; - } - const svgMatch = /^svg(?:(poly|polygon|path))?(\d+)?$/i.exec(id); - if (svgMatch) { - const svgMode = (svgMatch[1] ?? "poly").toLowerCase() === "path" ? "path" : "polygon"; - const primitive = Number(svgMatch[2] ?? 16); - return { - id: `svg${svgMode === "path" ? "path" : "poly"}${primitive}`, - strategy: "svg", - svgMode, - primitive, - }; - } - const solidMatch = /^solid(\d+)?$/i.exec(id); - if (solidMatch) { - const primitive = Number(solidMatch[1] ?? 64); - return { id: `solid${primitive}`, strategy: "solid", primitive }; - } - const match = /^(mask|atlas)(\d+)?$/i.exec(id); - if (!match) { - throw new Error( - `Unknown variant "${id}". Use border16, borderclass16, bordervar16, bordercontainpaint16, borderpolygonplain16, borderpath16, bordershape16, solid64, clip16, svgpoly16, svgpath16, mask16, mask64, atlas64, etc.`, - ); - } - const strategy = match[1].toLowerCase(); - const primitive = Number(match[2] ?? (strategy === "atlas" ? 64 : 16)); - return { id: `${strategy}${primitive}`, strategy, primitive }; - }); -} - -function startServer() { - return new Promise((resolveStart, rejectStart) => { - const server = createServer(async (req, res) => { - try { - const url = new URL(req.url, "http://localhost"); - const safe = url.pathname.replace(/\/+/g, "/"); - if (safe.includes("..")) { - res.writeHead(403); - res.end("forbidden"); - return; - } - const abs = resolve(benchDir, safe === "/" ? "mask-polygon.html" : safe.slice(1)); - const data = await readFile(abs); - res.writeHead(200, { - "Content-Type": MIME[extname(abs).toLowerCase()] || "application/octet-stream", - "Cache-Control": "no-store", - }); - res.end(data); - } catch (err) { - res.writeHead(404); - res.end(String(err?.message ?? err)); - } - }); - server.on("error", rejectStart); - server.listen(0, "127.0.0.1", () => { - const addr = server.address(); - resolveStart({ server, port: typeof addr === "object" ? addr.port : 0 }); - }); - }); -} - -function stopServer(server) { - return new Promise((resolveStop) => server.close(resolveStop)); -} - -function quantile(values, q) { - const sorted = values.filter(Number.isFinite).sort((a, b) => a - b); - if (sorted.length === 0) return 0; - const index = (sorted.length - 1) * q; - const lo = Math.floor(index); - const hi = Math.ceil(index); - if (lo === hi) return sorted[lo]; - return sorted[lo] + (sorted[hi] - sorted[lo]) * (index - lo); -} - -function median(values) { - return quantile(values, 0.5); -} - -function summarizeSamples(samples) { - const dts = samples - .map((sample) => Number(sample?.dt)) - .filter((dt) => Number.isFinite(dt) && dt > 0 && dt < 1000); - const p50 = quantile(dts, 0.5); - const p95 = quantile(dts, 0.95); - const p99 = quantile(dts, 0.99); - return { - sampleCount: dts.length, - fpsP50: p50 > 0 ? 1000 / p50 : 0, - frameTimeP50Ms: p50, - frameTimeP95Ms: p95, - frameTimeP99Ms: p99, - over20Ms: dts.filter((dt) => dt > 20).length, - over33Ms: dts.filter((dt) => dt > 33.333).length, - }; -} - -function supported(row) { - if (row.strategy === "border") { - const functionSupported = row.support.borderFunctions?.[row.borderFunction ?? "polygon"] ?? row.support.borderShapeFunction ?? row.support.borderShape; - const innerSupported = row.borderInner ? row.support.borderInners?.[row.borderInner] : true; - return functionSupported && innerSupported; - } - if (row.strategy === "mask") return row.support.maskComposite || row.support.webkitMaskComposite; - if (row.strategy === "clip") return row.support.clipPathPolygon; - return true; -} - -function runUrl(baseUrl, variant, count) { - const url = new URL("/mask-polygon.html", baseUrl); - url.searchParams.set("strategy", variant.strategy); - url.searchParams.set("primitive", String(variant.primitive)); - if (variant.borderFunction) url.searchParams.set("borderFunction", variant.borderFunction); - if (variant.borderInner) url.searchParams.set("borderInner", variant.borderInner); - if (variant.borderShapeSource) url.searchParams.set("borderShapeSource", variant.borderShapeSource); - if (variant.leafContain) url.searchParams.set("leafContain", variant.leafContain); - if (variant.leafWillChange) url.searchParams.set("leafWillChange", variant.leafWillChange); - if (variant.leafIsolation) url.searchParams.set("leafIsolation", variant.leafIsolation); - if (variant.borderStyle) url.searchParams.set("borderStyle", variant.borderStyle); - if (variant.svgMode) url.searchParams.set("svgMode", variant.svgMode); - url.searchParams.set("count", String(count)); - url.searchParams.set("shape", SHAPE); - url.searchParams.set("motion", MOTION); - url.searchParams.set("target", String(TARGET)); - return url.href; -} - -async function runOne(browser, baseUrl, variant, count, repeat) { - const page = await browser.newPage({ viewport: { width: 1280, height: 820 } }); - try { - const url = runUrl(baseUrl, variant, count); - await page.goto(url, { waitUntil: "load" }); - await page.waitForFunction(() => window.__maskPolyBench?.ready === true, null, { timeout: 30000 }); - const result = await page.evaluate( - (options) => window.runMaskPolygonBench(options), - { warmupMs: WARMUP_MS, sampleMs: SAMPLE_MS }, - ); - const frames = summarizeSamples(result.samples); - return { - repeat, - variant: variant.id, - strategy: variant.strategy, - borderFunction: variant.borderFunction, - borderInner: variant.borderInner, - borderShapeSource: variant.borderShapeSource, - leafContain: variant.leafContain, - leafWillChange: variant.leafWillChange, - leafIsolation: variant.leafIsolation, - borderStyle: variant.borderStyle, - svgMode: variant.svgMode, - primitive: variant.primitive, - count, - shape: SHAPE, - motion: MOTION, - target: TARGET, - support: result.support, - supported: supported({ - strategy: variant.strategy, - borderFunction: variant.borderFunction, - borderInner: variant.borderInner, - borderShapeSource: variant.borderShapeSource, - leafContain: variant.leafContain, - leafWillChange: variant.leafWillChange, - leafIsolation: variant.leafIsolation, - borderStyle: variant.borderStyle, - svgMode: variant.svgMode, - support: result.support, - }), - mountMs: result.mountMs, - styleBytes: result.styleBytes, - ...frames, - url, - }; - } finally { - await page.close(); - } -} - -function aggregate(rows) { - const groups = new Map(); - for (const row of rows) { - const key = `${row.count}:${row.variant}`; - const list = groups.get(key) ?? []; - list.push(row); - groups.set(key, list); - } - return [...groups.values()].map((list) => { - const first = list[0]; - return { - count: first.count, - variant: first.variant, - strategy: first.strategy, - borderFunction: first.borderFunction, - borderInner: first.borderInner, - borderShapeSource: first.borderShapeSource, - leafContain: first.leafContain, - leafWillChange: first.leafWillChange, - leafIsolation: first.leafIsolation, - borderStyle: first.borderStyle, - svgMode: first.svgMode, - primitive: first.primitive, - supported: list.every((row) => row.supported), - fpsP50: median(list.map((row) => row.fpsP50)), - frameTimeP50Ms: median(list.map((row) => row.frameTimeP50Ms)), - frameTimeP95Ms: median(list.map((row) => row.frameTimeP95Ms)), - frameTimeP99Ms: median(list.map((row) => row.frameTimeP99Ms)), - mountMs: median(list.map((row) => row.mountMs)), - styleBytes: median(list.map((row) => row.styleBytes)), - samples: list.reduce((sum, row) => sum + row.sampleCount, 0), - }; - }).sort((a, b) => a.count - b.count || a.variant.localeCompare(b.variant)); -} - -function fmt(value, digits = 1) { - return Number.isFinite(value) ? value.toFixed(digits) : "n/a"; -} - -function printRows(rows, aggregates) { - console.log(`[mask-polygon] counts=${COUNTS.join(",")} variants=${VARIANTS.map((v) => v.id).join(",")} repeats=${REPEATS} warmup=${WARMUP_MS}ms sample=${SAMPLE_MS}ms`); - if (CHROMIUM_ARGS.length > 0) console.log(`[mask-polygon] chromium args=${CHROMIUM_ARGS.join(" ")}`); - for (const row of rows) { - console.log( - `#${row.repeat} count=${String(row.count).padStart(5)} ${row.variant.padEnd(8)} ` + - `supported=${row.supported ? "yes" : "no "} fps50=${fmt(row.fpsP50).padStart(5)} ` + - `p95=${fmt(row.frameTimeP95Ms).padStart(5)}ms p99=${fmt(row.frameTimeP99Ms).padStart(5)}ms ` + - `mount=${fmt(row.mountMs, 2).padStart(7)}ms style=${Math.round(row.styleBytes / 1024)}KiB`, - ); - } - console.log("[mask-polygon] aggregate medians"); - for (const row of aggregates) { - console.log( - `count=${String(row.count).padStart(5)} ${row.variant.padEnd(8)} ` + - `supported=${row.supported ? "yes" : "no "} fps50=${fmt(row.fpsP50).padStart(5)} ` + - `p50=${fmt(row.frameTimeP50Ms).padStart(5)}ms p95=${fmt(row.frameTimeP95Ms).padStart(5)}ms ` + - `p99=${fmt(row.frameTimeP99Ms).padStart(5)}ms mount=${fmt(row.mountMs, 2).padStart(7)}ms ` + - `style=${Math.round(row.styleBytes / 1024)}KiB`, - ); - } -} - -let server; -let browser; -try { - if (COUNTS.length === 0) throw new Error("No counts selected."); - if (VARIANTS.length === 0) throw new Error("No variants selected."); - - const started = await startServer(); - server = started.server; - const baseUrl = `http://127.0.0.1:${started.port}`; - browser = await chromium.launch({ - headless: !HEADED, - executablePath: BROWSER_EXECUTABLE || undefined, - args: CHROMIUM_ARGS, - }); - - const rows = []; - for (const count of COUNTS) { - for (const variant of VARIANTS) { - for (let repeat = 1; repeat <= REPEATS; repeat += 1) { - rows.push(await runOne(browser, baseUrl, variant, count, repeat)); - } - } - } - const aggregates = aggregate(rows); - const result = { - kind: "mask-polygon-bench", - options: { - counts: COUNTS, - variants: VARIANTS, - repeats: REPEATS, - warmupMs: WARMUP_MS, - sampleMs: SAMPLE_MS, - shape: SHAPE, - motion: MOTION, - target: TARGET, - chromiumArgs: CHROMIUM_ARGS, - }, - rows, - aggregates, - }; - printRows(rows, aggregates); - - const outputPath = JSON_PATH || (LABEL ? resolve(repoRoot, "bench/results", `${LABEL}.json`) : ""); - if (outputPath) { - await mkdir(dirname(resolve(outputPath)), { recursive: true }); - await writeFile(resolve(outputPath), `${JSON.stringify(result, null, 2)}\n`); - console.log(`[mask-polygon] wrote ${resolve(outputPath)}`); - } -} finally { - if (browser) await browser.close(); - if (server) await stopServer(server); -} diff --git a/bench/mask-polygon.html b/bench/mask-polygon.html deleted file mode 100644 index 3d1afd339..000000000 --- a/bench/mask-polygon.html +++ /dev/null @@ -1,558 +0,0 @@ - - - - - - PolyCSS mask polygon bench - - - -
-
- - - diff --git a/bench/nonvoxel-visual-compare.mjs b/bench/nonvoxel-visual-compare.mjs deleted file mode 100644 index 7d858b466..000000000 --- a/bench/nonvoxel-visual-compare.mjs +++ /dev/null @@ -1,326 +0,0 @@ -#!/usr/bin/env node -/** - * Visual parity check for non-voxel bench variants. - * - * This compares nonvoxel-vanilla.html variants against the baked baseline at - * a static camera pose. It is intentionally bench-only: the goal is to reject - * performance leads that alter projection before they reach product code. - */ -import { createServer } from "node:http"; -import { mkdirSync, writeFileSync } from "node:fs"; -import { readFile } from "node:fs/promises"; -import { dirname, extname, resolve } from "node:path"; -import { fileURLToPath } from "node:url"; -import { chromium } from "playwright"; -import { getNonVoxelVariantParams, knownNonVoxelVariantIds } from "./nonvoxel-variants.mjs"; - -const __dirname = dirname(fileURLToPath(import.meta.url)); -const repoRoot = resolve(__dirname, ".."); -const benchDir = resolve(repoRoot, "bench"); -const galleryDir = resolve(repoRoot, "website/public/gallery"); -const resultsDir = resolve(benchDir, "results"); - -const argv = process.argv.slice(2); -const flag = (name) => argv.indexOf(`--${name}`); -const optStr = (name, dflt = "") => { - const i = flag(name); - if (i >= 0) return argv[i + 1] ?? dflt; - const prefixed = argv.find((arg) => arg.startsWith(`--${name}=`)); - return prefixed ? prefixed.slice(name.length + 3) : dflt; -}; -const optNum = (name, dflt) => { - const raw = optStr(name); - if (raw.trim() === "") return dflt; - const value = Number(raw); - return Number.isFinite(value) ? value : dflt; -}; -const optAll = (name) => { - const values = []; - for (let i = 0; i < argv.length; i += 1) { - const arg = argv[i]; - if (arg === `--${name}` && argv[i + 1]) { - values.push(argv[i + 1]); - i += 1; - } else if (arg.startsWith(`--${name}=`)) { - values.push(arg.slice(name.length + 3)); - } - } - return values; -}; -const hasFlag = (name) => flag(name) >= 0 || argv.includes(`--${name}=true`); - -const MODE = optStr("mode", "baked"); -const MOTION = optStr("motion", "none"); -const THRESHOLD = optNum("threshold", 0.01); -const WIDTH = optNum("width", 1280); -const HEIGHT = optNum("height", 800); -const SETTLE_MS = optNum("settle", 250); -const JSON_PATH = optStr("json"); -const SCREENSHOT_DIR = optStr("screenshots"); -const HEADED = hasFlag("headed"); -const BROWSER_EXECUTABLE = optStr("browser-executable"); -const CHROMIUM_ARGS = [ - ...optAll("chromium-arg"), - ...optAll("chromium-args").flatMap((value) => value.split(/\s+/).filter(Boolean)), -]; - -const MODELS = [ - { id: "chicken", mesh: "chicken" }, - { id: "rock1", mesh: "rock1" }, - { id: "saucer", mesh: "saucer" }, - { id: "teapot", mesh: "teapot" }, - { id: "ducky", mesh: "ducky" }, - { id: "violin", mesh: "glb:Violin.glb", params: { zoom: "0.35", targetSize: "60" } }, - { id: "elephant", mesh: "glb:Elephant.glb", params: { zoom: "0.35", targetSize: "60" } }, - { id: "policecar", mesh: "glb:Policecar.glb", params: { zoom: "0.35", targetSize: "60" } }, -]; - -const MIME = { - ".html": "text/html; charset=utf-8", - ".js": "application/javascript; charset=utf-8", - ".mjs": "application/javascript; charset=utf-8", - ".css": "text/css; charset=utf-8", - ".json": "application/json; charset=utf-8", - ".obj": "text/plain; charset=utf-8", - ".mtl": "text/plain; charset=utf-8", - ".png": "image/png", - ".jpg": "image/jpeg", - ".jpeg": "image/jpeg", - ".gltf": "application/json; charset=utf-8", - ".glb": "model/gltf-binary", - ".vox": "application/octet-stream", -}; - -function splitList(value) { - return value - .split(",") - .map((item) => item.trim()) - .filter(Boolean); -} - -function selectedModels() { - const requested = splitList(optStr("models")); - if (requested.length === 0) return MODELS; - const byId = new Map(MODELS.map((model) => [model.id, model])); - return requested.map((id) => { - const known = byId.get(id); - if (known) return known; - if (id.startsWith("glb:") || id.startsWith("obj:")) { - return { id: id.replace(/[^a-z0-9]+/gi, "-").replace(/^-|-$/g, ""), mesh: id }; - } - throw new Error(`Unknown model "${id}". Known: ${MODELS.map((model) => model.id).join(", ")}`); - }); -} - -function selectedVariants() { - const requested = splitList(optStr("variants", "scene-split-target,scene-transform-perspective")); - return requested.map((id) => { - const params = getNonVoxelVariantParams(id); - if (!params) throw new Error(`Unknown variant "${id}". Known: ${knownNonVoxelVariantIds().join(", ")}`); - if (id === "baseline") throw new Error("Baseline is implicit; do not include it in --variants."); - return { id, params }; - }); -} - -function startServer() { - return new Promise((resolveStart, rejectStart) => { - const server = createServer(async (req, res) => { - try { - const u = new URL(req.url, "http://localhost"); - const safe = u.pathname.replace(/\/+/g, "/"); - if (safe.includes("..")) { - res.writeHead(403); - res.end(); - return; - } - const abs = safe.startsWith("/gallery/") - ? resolve(galleryDir, safe.slice("/gallery/".length)) - : resolve(benchDir, safe === "/" ? "nonvoxel-vanilla.html" : safe.slice(1)); - const data = await readFile(abs); - res.writeHead(200, { - "Content-Type": MIME[extname(abs).toLowerCase()] || "application/octet-stream", - "Cache-Control": "no-store", - }); - res.end(data); - } catch (error) { - res.writeHead(404); - res.end(String(error?.message ?? error)); - } - }); - server.on("error", rejectStart); - server.listen(0, "127.0.0.1", () => { - const addr = server.address(); - resolveStart({ server, port: typeof addr === "object" ? addr.port : 0 }); - }); - }); -} - -function stopServer(server) { - return new Promise((resolveStop) => server.close(resolveStop)); -} - -function queryString(model, params = {}) { - const search = new URLSearchParams({ - mesh: model.mesh, - mode: MODE, - motion: MOTION, - ...model.params, - ...params, - }); - return search.toString(); -} - -async function waitForReady(page) { - await page.waitForFunction(() => window.__perf__?.ready === true, null, { timeout: 30000 }); - await page.waitForFunction(() => document.querySelectorAll(".polycss-scene b,.polycss-scene i,.polycss-scene s,.polycss-scene u").length > 0, null, { timeout: 30000 }); - await page.addStyleTag({ content: "#fps{display:none!important}" }); - await page.waitForTimeout(SETTLE_MS); -} - -async function screenshotVariant(page, port, model, variant) { - const url = `http://127.0.0.1:${port}/nonvoxel-vanilla.html?${queryString(model, variant.params)}`; - await page.goto(url, { waitUntil: "load" }); - await waitForReady(page); - return { - buffer: await page.screenshot({ fullPage: false }), - url, - renderStats: await page.evaluate(() => window.__perf__?.renderStats ?? null), - sceneTransform: await page.evaluate(() => { - const scene = document.querySelector(".polycss-scene"); - const camera = document.querySelector(".polycss-camera"); - const host = document.getElementById("host"); - return { - scene: scene instanceof HTMLElement ? scene.style.transform : "", - scenePerspective: scene instanceof HTMLElement ? scene.style.perspective : "", - cameraPerspective: camera instanceof HTMLElement ? camera.style.perspective : "", - hostPerspective: host instanceof HTMLElement ? host.style.perspective : "", - shell: document.querySelector(".polycss-scene > div") instanceof HTMLElement - ? document.querySelector(".polycss-scene > div").style.transform - : "", - }; - }), - }; -} - -async function compareBuffers(page, baseline, candidate) { - return await page.evaluate(async ({ baselineB64, candidateB64 }) => { - async function loadImageData(b64) { - const img = new Image(); - img.src = `data:image/png;base64,${b64}`; - await img.decode(); - const canvas = document.createElement("canvas"); - canvas.width = img.naturalWidth; - canvas.height = img.naturalHeight; - const ctx = canvas.getContext("2d"); - ctx.drawImage(img, 0, 0); - return ctx.getImageData(0, 0, canvas.width, canvas.height); - } - - const [a, b] = await Promise.all([loadImageData(baselineB64), loadImageData(candidateB64)]); - if (a.width !== b.width || a.height !== b.height) { - return { ok: false, reason: "size", baselineSize: [a.width, a.height], candidateSize: [b.width, b.height] }; - } - - let sum = 0; - let max = 0; - let changedPixels = 0; - const pixelCount = a.width * a.height; - for (let i = 0; i < a.data.length; i += 4) { - const dr = Math.abs(a.data[i] - b.data[i]); - const dg = Math.abs(a.data[i + 1] - b.data[i + 1]); - const db = Math.abs(a.data[i + 2] - b.data[i + 2]); - const pixel = Math.max(dr, dg, db); - if (pixel > 0) changedPixels += 1; - max = Math.max(max, pixel); - sum += dr + dg + db; - } - - return { - ok: true, - meanDelta: (sum / (pixelCount * 3)) / 255, - maxDelta: max / 255, - changedPixelRatio: changedPixels / pixelCount, - }; - }, { - baselineB64: baseline.toString("base64"), - candidateB64: candidate.toString("base64"), - }); -} - -function screenshotPath(modelId, variantId) { - return resolve(SCREENSHOT_DIR, `${modelId}-${MODE}-${variantId}.png`); -} - -async function main() { - const models = selectedModels(); - const variants = selectedVariants(); - const { server, port } = await startServer(); - let browser; - try { - browser = await chromium.launch({ - headless: !HEADED, - ...(BROWSER_EXECUTABLE ? { executablePath: BROWSER_EXECUTABLE } : {}), - args: CHROMIUM_ARGS, - }); - const context = await browser.newContext({ viewport: { width: WIDTH, height: HEIGHT } }); - const page = await context.newPage(); - if (SCREENSHOT_DIR) mkdirSync(SCREENSHOT_DIR, { recursive: true }); - - const results = []; - for (const model of models) { - const baseline = await screenshotVariant(page, port, model, { id: "baseline", params: {} }); - if (SCREENSHOT_DIR) writeFileSync(screenshotPath(model.id, "baseline"), baseline.buffer); - for (const variant of variants) { - const candidate = await screenshotVariant(page, port, model, variant); - if (SCREENSHOT_DIR) writeFileSync(screenshotPath(model.id, variant.id), candidate.buffer); - const comparison = await compareBuffers(page, baseline.buffer, candidate.buffer); - const meanDelta = comparison.ok ? comparison.meanDelta : Infinity; - const pass = comparison.ok && meanDelta <= THRESHOLD; - results.push({ - model: model.id, - mesh: model.mesh, - variant: variant.id, - pass, - threshold: THRESHOLD, - ...comparison, - meanDelta: Number.isFinite(meanDelta) ? +meanDelta.toFixed(6) : meanDelta, - maxDelta: comparison.ok ? +comparison.maxDelta.toFixed(6) : null, - changedPixelRatio: comparison.ok ? +comparison.changedPixelRatio.toFixed(6) : null, - renderStats: candidate.renderStats, - transforms: { - baseline: baseline.sceneTransform, - candidate: candidate.sceneTransform, - }, - url: candidate.url, - }); - } - } - - const report = { - generatedAt: new Date().toISOString(), - mode: MODE, - motion: MOTION, - viewport: { width: WIDTH, height: HEIGHT }, - threshold: THRESHOLD, - pass: results.every((result) => result.pass), - results, - }; - - if (JSON_PATH) { - mkdirSync(dirname(resolve(JSON_PATH)), { recursive: true }); - writeFileSync(resolve(JSON_PATH), `${JSON.stringify(report, null, 2)}\n`); - } - - console.log(JSON.stringify(report, null, 2)); - await context.close(); - process.exitCode = report.pass ? 0 : 1; - } finally { - if (browser) await browser.close(); - await stopServer(server); - } -} - -main().catch((error) => { - console.error(error); - process.exit(1); -}); diff --git a/bench/parity-quad.html b/bench/parity-quad.html deleted file mode 100644 index c8d3b324e..000000000 --- a/bench/parity-quad.html +++ /dev/null @@ -1,330 +0,0 @@ - - - - - polycss parity quad — vanilla / React / Vue / HTML - - - - - - - -
- - - - diff --git a/bench/perspective-receiver-shadow.html b/bench/perspective-receiver-shadow.html deleted file mode 100644 index 0eac46c77..000000000 --- a/bench/perspective-receiver-shadow.html +++ /dev/null @@ -1,291 +0,0 @@ - - - - - perspective receiver-shadow repro - - - -
-

PolyCSS — perspective receiver-shadow repro

-
Floor mesh w/ receiveShadow:true under a perspective camera. The cast shadow is visible at rotX=0 and gets cut as you tilt up. Toggle off receiveShadow or switch to ortho to compare.
-
-
-
-
-
Configuration
- - - -
Rotation
-
40
-
0
-
50
- -
Light
-
0.40
-
0.70
-
0.50
- -
Shadow
-
2000
-
0.40
- -
Live state
-
…
- -
- Default reproduces the gallery bug: perspective camera + floor as receiver. The SVG intrinsic size matches the floor's polygon bbox (~17500 CSS-px square here); under perspective + steep rotX the layer projects to a huge tilted trapezoid that overruns the viewport's overflow:hidden ancestors. - Switch to ortho or to the legacy ground-shadow path and the shadow stays put at every angle. -
-
- - - - diff --git a/bench/point-light-oracle.html b/bench/point-light-oracle.html deleted file mode 100644 index 9a26ac623..000000000 --- a/bench/point-light-oracle.html +++ /dev/null @@ -1,3062 +0,0 @@ - - - - - point-light oracle — polycss vs three.js (point + directional lights) - - - -

PolyCSS

-

Three.js

-

Diff (PolyCSS − Three.js)

-

Misclassified polys

-
- - - - - - diff --git a/bench/real-shadow.html b/bench/real-shadow.html deleted file mode 100644 index e138b24ef..000000000 --- a/bench/real-shadow.html +++ /dev/null @@ -1,604 +0,0 @@ - - - - - polycss real-mesh shadow — plane + apple + electric pole - - - -
-
- - - 60° - - - 56° - - - - - - -
-
- - - - diff --git a/bench/scripts/color-delta.mjs b/bench/scripts/color-delta.mjs deleted file mode 100644 index 45bdac9ff..000000000 --- a/bench/scripts/color-delta.mjs +++ /dev/null @@ -1,40 +0,0 @@ -#!/usr/bin/env node -/** - * Shadow COLOR calibration — PolyCSS vs three.js. - * - * Renders both engines in NORMAL mode (real materials), aligns them at host - * resolution, and reports the per-channel color delta (PolyCSS − three.js) - * split into SHADOW pixels vs LIT floor, plus a signed-delta heatmap. - * - * Usage: node bench/scripts/color-delta.mjs "" [outPrefix] - * Server must be running (default :4322). - */ -import { chromium } from "playwright"; -import { writeFileSync } from "node:fs"; - -const url = process.argv[2]; -if (!url) { console.error("usage: color-delta.mjs [outPrefix]"); process.exit(2); } -const prefix = process.argv[3] ?? "/tmp/color-delta"; - -const browser = await chromium.launch({ args: ["--use-angle=metal", "--enable-gpu-rasterization"] }); -const ctx = await browser.newContext({ viewport: { width: 1500, height: 950 }, deviceScaleFactor: 2 }); -const page = await ctx.newPage(); -page.on("pageerror", (e) => console.error("[pageerror]", e.message)); -await page.goto(url, { waitUntil: "networkidle", timeout: 30000 }); -await page.waitForTimeout(6500); -await page.evaluate(() => window.oracleSetHelpersHidden(true)); -await page.waitForTimeout(400); - -const shot = await (await page.$("#poly-host")).screenshot(); -const json = await page.evaluate( - (d) => window.oracleColorDelta(d), - "data:image/png;base64," + shot.toString("base64"), -); - -await (await page.$(".stage.polycss")).screenshot({ path: `${prefix}-poly.png` }); -await (await page.$(".stage.three")).screenshot({ path: `${prefix}-three.png` }); -await (await page.$(".stage.diff")).screenshot({ path: `${prefix}-heat.png` }); -writeFileSync(`${prefix}.json`, JSON.stringify(json, null, 2)); -console.log(JSON.stringify(json, null, 2)); -console.error(`wrote ${prefix}-poly.png ${prefix}-three.png ${prefix}-heat.png ${prefix}.json`); -await browser.close(); diff --git a/bench/scripts/point-light-mask-verdict.mjs b/bench/scripts/point-light-mask-verdict.mjs deleted file mode 100644 index 10b76ec0e..000000000 --- a/bench/scripts/point-light-mask-verdict.mjs +++ /dev/null @@ -1,57 +0,0 @@ -#!/usr/bin/env node -/** - * Shadow-MASK parity verdict — the better oracle. - * - * Instead of a luma diff with a tolerance knob, this drives both engines - * into "shadows only" mode (PolyCSS hides meshes → shadow SVGs only; - * three.js → ShadowMaterial), reduces each REAL render to a binary - * "in shadow?" mask, and compares shadow SHAPE: missing (three shadowed, - * PolyCSS lit = a hole), extra (PolyCSS shadowed, three lit). three.js - * stays the reference; only the comparison method changes. - * - * Writes illustration PNGs (diff classification + the on-render green - * occluder outlines) next to the JSON verdict. - * - * Usage: - * node bench/scripts/shadow-mask-verdict.mjs "" [outPrefix] - * - * Server must be running on :4400. - */ -import { chromium } from 'playwright'; -import { writeFileSync } from 'node:fs'; - -const url = process.argv[2]; -if (!url) { console.error('usage: shadow-mask-verdict.mjs [outPrefix]'); process.exit(2); } -const prefix = process.argv[3] ?? '/tmp/shadow-mask'; - -const browser = await chromium.launch({ args: ['--use-angle=metal', '--enable-gpu-rasterization'] }); -const ctx = await browser.newContext({ viewport: { width: 1500, height: 950 }, deviceScaleFactor: 2 }); -const page = await ctx.newPage(); -page.on('pageerror', e => console.error('[pageerror]', e.message)); -await page.goto(url, { waitUntil: 'networkidle', timeout: 30000 }); -await page.waitForTimeout(6500); - -await page.evaluate(() => window.oracleSetHelpersHidden(true)); -// Shadows-only mode for clean binary masks on both engines. -await page.evaluate(() => window.oracleSetShadowsOnly(true)); -await page.waitForTimeout(800); // SVG recolor + three ShadowMaterial render - -const shot = await (await page.$('#poly-host')).screenshot(); -const json = await page.evaluate( - d => window.oracleMaskCompare(d), - 'data:image/png;base64,' + shot.toString('base64'), -); - -// Illustration 1: the diff classification (red=missing, blue=extra). -await (await page.$('.stage.diff')).screenshot({ path: `${prefix}-diff.png` }); -// Illustration 2: back to normal render so the green occluder outlines show. -await page.evaluate(() => window.oracleSetShadowsOnly(false)); -await page.evaluate(() => window.oracleSetHelpersHidden(true)); -await page.waitForTimeout(400); -await (await page.$('.stage.polycss')).screenshot({ path: `${prefix}-render.png` }); -await (await page.$('.stage.three')).screenshot({ path: `${prefix}-three.png` }); - -writeFileSync(`${prefix}.json`, JSON.stringify(json, null, 2)); -console.log(JSON.stringify(json, null, 2)); -console.error(`wrote ${prefix}-diff.png ${prefix}-render.png ${prefix}-three.png ${prefix}.json`); -await browser.close(); diff --git a/bench/scripts/shadow-mask-verdict.mjs b/bench/scripts/shadow-mask-verdict.mjs deleted file mode 100644 index 10b76ec0e..000000000 --- a/bench/scripts/shadow-mask-verdict.mjs +++ /dev/null @@ -1,57 +0,0 @@ -#!/usr/bin/env node -/** - * Shadow-MASK parity verdict — the better oracle. - * - * Instead of a luma diff with a tolerance knob, this drives both engines - * into "shadows only" mode (PolyCSS hides meshes → shadow SVGs only; - * three.js → ShadowMaterial), reduces each REAL render to a binary - * "in shadow?" mask, and compares shadow SHAPE: missing (three shadowed, - * PolyCSS lit = a hole), extra (PolyCSS shadowed, three lit). three.js - * stays the reference; only the comparison method changes. - * - * Writes illustration PNGs (diff classification + the on-render green - * occluder outlines) next to the JSON verdict. - * - * Usage: - * node bench/scripts/shadow-mask-verdict.mjs "" [outPrefix] - * - * Server must be running on :4400. - */ -import { chromium } from 'playwright'; -import { writeFileSync } from 'node:fs'; - -const url = process.argv[2]; -if (!url) { console.error('usage: shadow-mask-verdict.mjs [outPrefix]'); process.exit(2); } -const prefix = process.argv[3] ?? '/tmp/shadow-mask'; - -const browser = await chromium.launch({ args: ['--use-angle=metal', '--enable-gpu-rasterization'] }); -const ctx = await browser.newContext({ viewport: { width: 1500, height: 950 }, deviceScaleFactor: 2 }); -const page = await ctx.newPage(); -page.on('pageerror', e => console.error('[pageerror]', e.message)); -await page.goto(url, { waitUntil: 'networkidle', timeout: 30000 }); -await page.waitForTimeout(6500); - -await page.evaluate(() => window.oracleSetHelpersHidden(true)); -// Shadows-only mode for clean binary masks on both engines. -await page.evaluate(() => window.oracleSetShadowsOnly(true)); -await page.waitForTimeout(800); // SVG recolor + three ShadowMaterial render - -const shot = await (await page.$('#poly-host')).screenshot(); -const json = await page.evaluate( - d => window.oracleMaskCompare(d), - 'data:image/png;base64,' + shot.toString('base64'), -); - -// Illustration 1: the diff classification (red=missing, blue=extra). -await (await page.$('.stage.diff')).screenshot({ path: `${prefix}-diff.png` }); -// Illustration 2: back to normal render so the green occluder outlines show. -await page.evaluate(() => window.oracleSetShadowsOnly(false)); -await page.evaluate(() => window.oracleSetHelpersHidden(true)); -await page.waitForTimeout(400); -await (await page.$('.stage.polycss')).screenshot({ path: `${prefix}-render.png` }); -await (await page.$('.stage.three')).screenshot({ path: `${prefix}-three.png` }); - -writeFileSync(`${prefix}.json`, JSON.stringify(json, null, 2)); -console.log(JSON.stringify(json, null, 2)); -console.error(`wrote ${prefix}-diff.png ${prefix}-render.png ${prefix}-three.png ${prefix}.json`); -await browser.close(); diff --git a/bench/scripts/shadow-oracle-verdict.mjs b/bench/scripts/shadow-oracle-verdict.mjs deleted file mode 100644 index cbfae6630..000000000 --- a/bench/scripts/shadow-oracle-verdict.mjs +++ /dev/null @@ -1,46 +0,0 @@ -#!/usr/bin/env node -/** - * Headless shadow-oracle verdict. - * - * Drives bench/shadow-oracle.html with a deterministic URL, screenshots - * #poly-host with the REAL compositor (Playwright — captures the - * 3D-`matrix3d`-transformed receiver-shadow SVGs that html-to-image drops), - * hands it to the in-page oracle, and prints the JSON verdict: every polygon - * (across ALL meshes — caster model + floor receiver) whose rendered - * shading/shadow disagrees with three.js beyond the luma tolerance. - * - * Usage: - * node bench/scripts/shadow-oracle-verdict.mjs "" [outFile.json] - * - * Server must be running on :4400 (node bench/perf-serve.mjs). - */ -import { chromium } from 'playwright'; -import { writeFileSync } from 'node:fs'; - -const url = process.argv[2]; -if (!url) { console.error('usage: shadow-oracle-verdict.mjs [out.json]'); process.exit(2); } -const outFile = process.argv[3]; - -const browser = await chromium.launch({ args: ['--use-angle=metal', '--enable-gpu-rasterization'] }); -const ctx = await browser.newContext({ viewport: { width: 1500, height: 950 }, deviceScaleFactor: 1 }); -const page = await ctx.newPage(); -page.on('pageerror', e => console.error('[pageerror]', e.message)); -await page.goto(url, { waitUntil: 'networkidle', timeout: 30000 }); -// Settle: atlas blobs + shadow SVGs + three draw. -await page.waitForTimeout(6500); - -// Hide the light helper, let it present, screenshot the real PolyCSS render. -await page.evaluate(() => window.oracleSetHelpersHidden(true)); -await page.waitForTimeout(200); -const host = await page.$('#poly-host'); -const shot = await host.screenshot(); -const dataUrl = 'data:image/png;base64,' + shot.toString('base64'); - -const json = await page.evaluate(d => window.oracleCompareWithImage(d), dataUrl); -await page.evaluate(() => window.oracleSetHelpersHidden(false)); - -if (!json) { console.error('oracle returned null'); process.exit(1); } -const out = JSON.stringify(json, null, 2); -if (outFile) { writeFileSync(outFile, out); console.error('wrote', outFile); } -console.log(out); -await browser.close(); diff --git a/bench/scripts/shadow-regression.mjs b/bench/scripts/shadow-regression.mjs deleted file mode 100644 index 9cb68890f..000000000 --- a/bench/scripts/shadow-regression.mjs +++ /dev/null @@ -1,150 +0,0 @@ -#!/usr/bin/env node -/** - * Shadow-regression fixture for the perf research loop. - * - * For each (scene, light-azimuth) pair, load perf-vanilla.html at a - * deterministic URL, settle 6s, and capture both a screenshot and a - * stats JSON (paths/SVGs/path-d-chars). The output goes under - * bench/results/shadow-regression/