diff --git a/docs/product-readiness.md b/docs/product-readiness.md index 0165e88..e84d56c 100644 --- a/docs/product-readiness.md +++ b/docs/product-readiness.md @@ -146,6 +146,9 @@ The product acceptance gate must pass with zero failures. It checks: resources. - Runtime body-state apply/skip diagnostics, proving unchanged fixed shelf and inventory states are not repeatedly applied to the scene graph. +- WebGL readback policy, proving the renderer does not keep + `preserveDrawingBuffer` enabled during normal runtime and only renders for + explicit screenshot or pixel-readback requests. - Backend compose-cache diagnostics, proving repeated identical physical scene compose requests reuse the active runtime manifest instead of rebuilding the simulator. @@ -193,6 +196,9 @@ Release checks write these artifacts: - `product-readiness-visual-only-boundary.jpg`: screenshot captured after adding a local uploaded OBJ asset to the physical preset. This negative-path evidence must show visual-only builder props and a failed in-page acceptance verdict. +- `product-readiness-debug-capture.png`: PNG captured through the product debug + capture path. This verifies screenshot export still works with + `preserveDrawingBuffer` disabled in the normal renderer. - `product-readiness-evidence.json`: compact handoff manifest with the report hash, git branch/commit/dirty state/remotes, screenshot/export paths, byte sizes, capture strategy, builder/share/config-import status, canvas metadata, @@ -209,7 +215,7 @@ evidence to a code state: Representative product gate baseline for the current thresholds: -- Result: `44 passed / 0 warned / 0 failed` +- Result: `46 passed / 0 warned / 0 failed` - Frontend mode: `preview` for release handoff through `npm run product:release-check`. - Fail on warning: `true` for release handoff. @@ -220,7 +226,7 @@ Representative product gate baseline for the current thresholds: - Real backend compose/editing: `38 passed / 0 warned / 0 failed` - Physical compose: `/compose` returned `objectCount=636`, `bodyCount=573`, and `4/4` product-gate primitive bodies in inline manifest, fetched manifest, - and live state. The latest clean gate measured `282ms` on the cold compose + and live state. The latest representative gate measured `271ms` on the cold compose path. - Repeated physical compose cache: a second identical `/compose` request returns `cached=true` with the same compose key; the current real-backend verification @@ -277,6 +283,10 @@ Representative product gate baseline for the current thresholds: - Desktop screenshot: `test-results/product-readiness/product-readiness-desktop.jpg` (`strategy=canvas`; exact bytes and sha256 are in the evidence manifest) +- Debug PNG capture: + `test-results/product-readiness/product-readiness-debug-capture.png` + (`strategy=debug-capture`; latest representative gate recorded `194 KiB` + `image/png`) - Mobile screenshot: `test-results/product-readiness/product-readiness-mobile.jpg` (`strategy=canvas`; exact bytes and sha256 are in the evidence manifest) @@ -360,6 +370,10 @@ Scene evidence: - Stable-frame render gate: repeated state frames that do not change any body transform or run metadata are counted as `unchanged frames` and do not dirty the WebGL renderer. +- WebGL readback gate: normal runtime rendering leaves + `preserveDrawingBuffer=false`, avoiding the persistent framebuffer retention + cost. Pixel sampling and exported PNG screenshots call an explicit readback + render, and positive pixel evidence is cached until the next scene reload. - Manual root matrices: every manifest object root disables automatic matrix recomputation after construction. Runtime state, drag, and robot-offset changes explicitly update only the roots that actually move. @@ -367,17 +381,18 @@ Scene evidence: Bundle evidence: - JavaScript chunks: `4` -- App entry chunk: `188.12 kB raw / 49.07 KiB gzip` +- App entry chunk: `188.98 kB raw / 49.26 KiB gzip` - Largest JavaScript gzip chunk: `141.04 KiB / 170.00 KiB` -- Total JavaScript gzip: `212.83 KiB / 230.00 KiB` +- Total JavaScript gzip: `213.00 KiB / 230.00 KiB` - Large-scene performance mode: `large-scene`, target `45 fps`, actual idle render rate `0.7 fps`, DPR cap observed at `1.00` in release - gate, shadows `off`, hover picking throttled to `32ms`, `27` empty frames + gate, `preserveDrawingBuffer=false`, `1` explicit readback render, shadows + `off`, hover picking throttled to `32ms`, `28` empty frames skipped, `1839` static visual nodes frozen, `7` primitive geometry shapes cached, `51` mesh source assets retained, `576/51` mesh cache hit/miss in the primary large scene, `636` cached object bounds, `627` fast pick-proxy bounds from `51` cached source bounds, real hover proof `hoverProxy 1/fallback - 0`, with `0` camera-fit traversals, `1/636` scene root batch insertion, `351` + 0`, with `0` camera-fit traversals, `1/636` scene root batch insertion, `336` partial render frames suppressed during the primary load, `26` browser event-loop yields during scene construction, active state payload `34/602` with `3` reduced frames, @@ -393,6 +408,10 @@ Bundle evidence: `state payload 34/602` with at least one reduced state frame, proving fixed shelf/inventory bodies are not repeatedly shipped in the high-frequency polling path. +- WebGL readback gate: `browser-large-scene-performance-mode` now checks + `buffer=false` and `readback=1`, and `browser-debug-capture-png` checks the + exported PNG path (`194 KiB image/png`) so debug screenshot export remains + covered after removing the persistent drawing buffer. - Body-state cache gate: `browser-body-state-cache` waits for the paused scene to use a reduced active payload and still skip unchanged active poses. The current run passed with `state apply 4/skip 63` and `statePayload=34/602`. @@ -414,23 +433,23 @@ Bundle evidence: Control evidence: -- Cold compose endpoint: `272ms`, `4/4` composed object bodies synced. +- Cold compose endpoint: `271ms`, `4/4` composed object bodies synced. - Repeated compose cache: `68ms`, `cached=true`, same compose key. - Active state endpoint: full `/state` returned `602` bodies; active - `/state?bodies=active` returned `34` bodies in `63ms`, filtered `568` fixed + `/state?bodies=active` returned `34` bodies in `59ms`, filtered `568` fixed bodies, and retained `4/4` composed dynamic bodies. -- Scene Builder UI compose: representative run `3309ms` end to end with real +- Scene Builder UI compose: representative run `4379ms` end to end with real backend diagnostics. -- Share-link restore: representative full browser restore `6157ms`. -- Config import restore: representative full browser restore `6669ms`. +- Share-link restore: representative full browser restore `6225ms`. +- Config import restore: representative full browser restore `6794ms`. - Composed object body edit: `57ms`. - Fixed inventory edit rejection: `57ms`. - Dynamic composed object drop: `0.48012m`. - Static shelf anchor stability: `max drift 0.00000m` after a 2500 ms resume window. -- Resume backend state: `58ms paused=false` -- Resume visible UI state: `60ms` -- Pause backend state: `53ms paused=true` +- Resume backend state: `54ms paused=false` +- Resume visible UI state: `56ms` +- Pause backend state: `49ms paused=true` - Pause visible UI state: `39ms` - Desktop acceptance wait: `1243ms` total, product telemetry `0ms` - Mobile acceptance wait: `277ms` total, product telemetry `0ms` @@ -441,9 +460,9 @@ Control evidence: `acceptanceLatency=0 ms / 11-0-0`, `binding=635/636; 4/568`, `builderPhysics=已添加物体 4: 后端动态 4 / 仅视觉 0`, - `renderPerformance=large-scene; target 45 fps; actual 0.7 fps; dpr 1.00; shadows off; skipped 27; hover 32ms; frozen 1839; manual roots 636 updates 67; primitive geometries 7; mesh cache 51 sources 576/51 hit/miss retained 51g/17m; bounds cache 636 fast 627 source 51 hoverProxy 1/fallback 0 camera traversals 0; scene batches 1/636 suppressed 351 yields 26; state payload 34/602 reduced 3; ui cache physics 31/3 builder 34/1; pick proxies 636; state apply 0/skip 67; unchanged frames 1; released 0g/0m/0t`. + `renderPerformance=large-scene; target 45 fps; actual 0.7 fps; dpr 1.00; buffer preserved false; readback renders 1; shadows off; skipped 28; hover 32ms; frozen 1839; manual roots 636 updates 67; primitive geometries 7; mesh cache 51 sources 576/51 hit/miss retained 51g/17m; bounds cache 636 fast 627 source 51 hoverProxy 1/fallback 0 camera traversals 0; scene batches 1/636 suppressed 336 yields 26; state payload 34/602 reduced 3; ui cache physics 31/3 builder 34/1; pick proxies 636; state apply 0/skip 67; unchanged frames 2; released 0g/0m/0t`. - Evidence screenshot artifacts: - `builder page; share page; import page; visual-only boundary canvas; desktop canvas; mobile canvas` + `builder page; share page; import page; visual-only boundary canvas; desktop canvas; debug PNG; mobile canvas` - Evidence export artifacts: `config 1 KiB v1; package 10 KiB motrixsim-web.acceptance-package.v1; report 10 KiB; rendered screenshot recorded` diff --git a/scripts/product-readiness-gate.mjs b/scripts/product-readiness-gate.mjs index 2d1c16d..d6556fd 100644 --- a/scripts/product-readiness-gate.mjs +++ b/scripts/product-readiness-gate.mjs @@ -374,6 +374,7 @@ async function collectEvidenceArtifacts(browserEvidence) { const configImportCapture = browserEvidence?.screenshots?.configImportRestore; const visualOnlyBoundaryCapture = browserEvidence?.screenshots?.visualOnlyBoundary; const desktopCapture = browserEvidence?.screenshots?.desktop; + const debugCapture = browserEvidence?.screenshots?.debugCapture; const mobileCapture = browserEvidence?.screenshots?.mobile; const builderConfigExport = browserEvidence?.exports?.builderConfig; const packageExport = browserEvidence?.exports?.package; @@ -423,12 +424,24 @@ async function collectEvidenceArtifacts(browserEvidence) { strategy: captureStrategy(mobileCapture), canvas: browserEvidence?.mobile?.canvas, }; + const debugPng = debugCapture + ? { + ...(await describeArtifact(debugCapture.path)), + strategy: captureStrategy(debugCapture), + mime: debugCapture.mime, + } + : undefined; const validDesktop = desktop.bytes >= thresholds.minEvidenceImageBytes && desktop.sha256.length === 64 && desktop.strategy === "canvas"; const validMobile = mobile.bytes >= thresholds.minEvidenceImageBytes && mobile.sha256.length === 64 && ["canvas", "preview", "page"].includes(mobile.strategy); + const validDebugPng = Boolean(debugPng) + && debugPng.bytes >= thresholds.minEvidenceImageBytes + && debugPng.sha256.length === 64 + && debugPng.strategy === "debug-capture" + && debugPng.mime === "image/png"; const validBuilderCompose = Boolean(builderCompose) && builderCompose.bytes >= thresholds.minEvidenceImageBytes && builderCompose.sha256.length === 64 @@ -533,8 +546,8 @@ async function collectEvidenceArtifacts(browserEvidence) { && acceptanceReport.render?.containsPhysicsTiers === true; check( "evidence-screenshot-artifacts", - validDesktop && validMobile && validBuilderCompose && validShareRestore && validConfigImportRestore && validVisualOnlyBoundary, - `builder ${Math.round((builderCompose?.bytes ?? 0) / 1024)} KiB ${builderCompose?.strategy ?? "-"}; share ${Math.round((shareRestore?.bytes ?? 0) / 1024)} KiB ${shareRestore?.strategy ?? "-"}; import ${Math.round((configImportRestore?.bytes ?? 0) / 1024)} KiB ${configImportRestore?.strategy ?? "-"}; boundary ${Math.round((visualOnlyBoundary?.bytes ?? 0) / 1024)} KiB ${visualOnlyBoundary?.strategy ?? "-"}; desktop ${Math.round(desktop.bytes / 1024)} KiB ${desktop.strategy}; mobile ${Math.round(mobile.bytes / 1024)} KiB ${mobile.strategy}`, + validDesktop && validMobile && validDebugPng && validBuilderCompose && validShareRestore && validConfigImportRestore && validVisualOnlyBoundary, + `builder ${Math.round((builderCompose?.bytes ?? 0) / 1024)} KiB ${builderCompose?.strategy ?? "-"}; share ${Math.round((shareRestore?.bytes ?? 0) / 1024)} KiB ${shareRestore?.strategy ?? "-"}; import ${Math.round((configImportRestore?.bytes ?? 0) / 1024)} KiB ${configImportRestore?.strategy ?? "-"}; boundary ${Math.round((visualOnlyBoundary?.bytes ?? 0) / 1024)} KiB ${visualOnlyBoundary?.strategy ?? "-"}; desktop ${Math.round(desktop.bytes / 1024)} KiB ${desktop.strategy}; debug ${Math.round((debugPng?.bytes ?? 0) / 1024)} KiB ${debugPng?.strategy ?? "-"}; mobile ${Math.round(mobile.bytes / 1024)} KiB ${mobile.strategy}`, ); check( "evidence-export-artifacts", @@ -548,6 +561,7 @@ async function collectEvidenceArtifacts(browserEvidence) { configImportRestore, visualOnlyBoundary, desktop, + debugPng, mobile, }, exports: { @@ -623,9 +637,11 @@ async function readBrowserStats(page) { targetRenderFps: numberData("targetRenderFps"), actualRenderFps: numberData("actualRenderFps"), renderPixelRatio: numberData("renderPixelRatio"), + preserveDrawingBufferEnabled: data.preserveDrawingBufferEnabled === "true", shadowsEnabled: data.shadowsEnabled === "true", renderSkipCount: numberData("renderSkipCount"), lastRenderDurationMs: numberData("lastRenderDurationMs"), + readbackRenderCount: numberData("readbackRenderCount"), hoverPickIntervalMs: numberData("hoverPickIntervalMs"), frozenStaticObjectCount: numberData("frozenStaticObjectCount"), manualMatrixRootCount: numberData("manualMatrixRootCount"), @@ -773,17 +789,28 @@ async function waitForMobileScene(page) { } async function captureCanvasScreenshot(page, filePath, pageError, options = {}) { - const dataUrl = await page.evaluate(() => { - const canvas = document.querySelector("canvas"); - return canvas instanceof HTMLCanvasElement ? canvas.toDataURL("image/jpeg", 0.9) : undefined; - }); - if (dataUrl?.startsWith("data:image/")) { - await writeFile(filePath, Buffer.from(dataUrl.split(",", 2)[1] ?? "", "base64")); + try { + await page.locator("canvas").screenshot({ path: filePath, timeout: 15000 }); return options.fallback ? { ok: true, path: filePath, fallback: "canvas", pageError } : { ok: true, path: filePath, strategy: "canvas", pageError }; + } catch { + return undefined; + } +} + +async function captureDebugPng(page, filePath) { + try { + const dataUrl = await page.evaluate(() => window.__motrixPreviewDebug?.capturePng?.()); + if (!dataUrl?.startsWith("data:image/png;base64,")) { + return { ok: false, path: filePath, mime: "", bytes: 0, error: "debug capture did not return a PNG data URL" }; + } + const bytes = Buffer.from(dataUrl.split(",", 2)[1] ?? "", "base64"); + await writeFile(filePath, bytes); + return { ok: true, path: filePath, strategy: "debug-capture", mime: "image/png", bytes: bytes.length }; + } catch (error) { + return { ok: false, path: filePath, mime: "", bytes: 0, error: error.message }; } - return undefined; } async function capturePreviewScreenshot(page, filePath, pageError, options = {}) { @@ -1514,6 +1541,7 @@ async function verifyBrowser() { const pauseControl = await controlThroughUi(desktop, "#viewport-pause", true); const desktopAcceptance = await runAcceptanceReview(desktop); const desktopStats = await readBrowserStats(desktop); + const debugCapture = await captureDebugPng(desktop, path.join(outDir, "product-readiness-debug-capture.png")); const desktopScreenshot = await safeScreenshot("browser-desktop-screenshot", desktop, path.join(outDir, "product-readiness-desktop.jpg"), { preferCanvas: true }); const acceptanceExports = await exportAcceptanceArtifacts(desktop); await closeContext(desktopContext, "desktop-context"); @@ -1589,6 +1617,8 @@ async function verifyBrowser() { renderPerformance.largeSceneMode === true && renderPerformance.targetRenderFps === 45 && (renderPerformance.renderPixelRatio ?? Number.POSITIVE_INFINITY) <= 1.25 + && renderPerformance.preserveDrawingBufferEnabled === false + && (renderPerformance.readbackRenderCount ?? 0) > 0 && renderPerformance.shadowsEnabled === false && renderPerformance.hoverPickIntervalMs === 32 && (renderPerformance.renderSkipCount ?? 0) > 0 @@ -1613,7 +1643,12 @@ async function verifyBrowser() { && (renderPerformance.pickProxyCount ?? 0) >= objectCount && (renderPerformance.skippedBodyStateCount ?? 0) > 0 && desktopStats.diagnostics.renderPerformance.includes("large-scene"), - `mode=${renderPerformance.largeSceneMode} fps=${renderPerformance.targetRenderFps ?? "-"} dpr=${renderPerformance.renderPixelRatio ?? "-"} shadows=${renderPerformance.shadowsEnabled} hover=${renderPerformance.hoverPickIntervalMs ?? "-"} skipped=${renderPerformance.renderSkipCount ?? "-"} frozen=${renderPerformance.frozenStaticObjectCount ?? "-"} manualRoots=${renderPerformance.manualMatrixRootCount ?? "-"} manualUpdates=${renderPerformance.manualMatrixUpdateCount ?? "-"} primitiveGeometries=${renderPerformance.primitiveGeometryCount ?? "-"} meshCache=${renderPerformance.meshCacheSourceCount ?? "-"} hit=${renderPerformance.meshCacheHitCount ?? "-"} miss=${renderPerformance.meshCacheMissCount ?? "-"} retained=${renderPerformance.retainedMeshGeometryCount ?? "-"}g/${renderPerformance.retainedMeshMaterialCount ?? "-"}m bounds=${renderPerformance.sceneObjectBoundsCount ?? "-"} fast=${renderPerformance.fastPickProxyBoundsCount ?? "-"} source=${renderPerformance.meshSourceBoundsCount ?? "-"} hoverProxy=${renderPerformance.hoverProxyBoundsHitCount ?? "-"}/fallback=${renderPerformance.hoverRootBoundsFallbackCount ?? "-"} cameraTraversals=${renderPerformance.cameraFitTraversalCount ?? "-"} sceneBatches=${renderPerformance.sceneRootBatchCount ?? "-"}/${renderPerformance.batchedSceneRootCount ?? "-"} suppressed=${renderPerformance.sceneLoadSuppressedRenderCount ?? "-"} yields=${renderPerformance.sceneBuildYieldCount ?? "-"} statePayload=${renderPerformance.statePayloadBodyCount ?? "-"}/${renderPerformance.mergedBodyStateCount ?? "-"} reduced=${renderPerformance.reducedStateFrameCount ?? "-"} uiCache=physics ${renderPerformance.objectPhysicsProfileCacheHitCount ?? "-"}/${renderPerformance.objectPhysicsProfileCacheMissCount ?? "-"} builder ${renderPerformance.builderPhysicsProfileCacheHitCount ?? "-"}/${renderPerformance.builderPhysicsProfileCacheMissCount ?? "-"} pickProxies=${renderPerformance.pickProxyCount ?? "-"} stateApply=${renderPerformance.appliedBodyStateCount ?? "-"}/skip=${renderPerformance.skippedBodyStateCount ?? "-"} unchanged=${renderPerformance.unchangedFrameCount ?? "-"} released=${renderPerformance.releasedGeometryCount ?? "-"}g/${renderPerformance.releasedMaterialCount ?? "-"}m/${renderPerformance.releasedTextureCount ?? "-"}t; ${desktopStats.diagnostics.renderPerformance}`, + `mode=${renderPerformance.largeSceneMode} fps=${renderPerformance.targetRenderFps ?? "-"} dpr=${renderPerformance.renderPixelRatio ?? "-"} buffer=${renderPerformance.preserveDrawingBufferEnabled} readback=${renderPerformance.readbackRenderCount ?? "-"} shadows=${renderPerformance.shadowsEnabled} hover=${renderPerformance.hoverPickIntervalMs ?? "-"} skipped=${renderPerformance.renderSkipCount ?? "-"} frozen=${renderPerformance.frozenStaticObjectCount ?? "-"} manualRoots=${renderPerformance.manualMatrixRootCount ?? "-"} manualUpdates=${renderPerformance.manualMatrixUpdateCount ?? "-"} primitiveGeometries=${renderPerformance.primitiveGeometryCount ?? "-"} meshCache=${renderPerformance.meshCacheSourceCount ?? "-"} hit=${renderPerformance.meshCacheHitCount ?? "-"} miss=${renderPerformance.meshCacheMissCount ?? "-"} retained=${renderPerformance.retainedMeshGeometryCount ?? "-"}g/${renderPerformance.retainedMeshMaterialCount ?? "-"}m bounds=${renderPerformance.sceneObjectBoundsCount ?? "-"} fast=${renderPerformance.fastPickProxyBoundsCount ?? "-"} source=${renderPerformance.meshSourceBoundsCount ?? "-"} hoverProxy=${renderPerformance.hoverProxyBoundsHitCount ?? "-"}/fallback=${renderPerformance.hoverRootBoundsFallbackCount ?? "-"} cameraTraversals=${renderPerformance.cameraFitTraversalCount ?? "-"} sceneBatches=${renderPerformance.sceneRootBatchCount ?? "-"}/${renderPerformance.batchedSceneRootCount ?? "-"} suppressed=${renderPerformance.sceneLoadSuppressedRenderCount ?? "-"} yields=${renderPerformance.sceneBuildYieldCount ?? "-"} statePayload=${renderPerformance.statePayloadBodyCount ?? "-"}/${renderPerformance.mergedBodyStateCount ?? "-"} reduced=${renderPerformance.reducedStateFrameCount ?? "-"} uiCache=physics ${renderPerformance.objectPhysicsProfileCacheHitCount ?? "-"}/${renderPerformance.objectPhysicsProfileCacheMissCount ?? "-"} builder ${renderPerformance.builderPhysicsProfileCacheHitCount ?? "-"}/${renderPerformance.builderPhysicsProfileCacheMissCount ?? "-"} pickProxies=${renderPerformance.pickProxyCount ?? "-"} stateApply=${renderPerformance.appliedBodyStateCount ?? "-"}/skip=${renderPerformance.skippedBodyStateCount ?? "-"} unchanged=${renderPerformance.unchangedFrameCount ?? "-"} released=${renderPerformance.releasedGeometryCount ?? "-"}g/${renderPerformance.releasedMaterialCount ?? "-"}m/${renderPerformance.releasedTextureCount ?? "-"}t; ${desktopStats.diagnostics.renderPerformance}`, + ); + check( + "browser-debug-capture-png", + debugCapture.ok && debugCapture.bytes >= thresholds.minEvidenceImageBytes, + `${Math.round((debugCapture.bytes ?? 0) / 1024)} KiB ${debugCapture.mime || "-"} ${debugCapture.error ?? ""}`.trim(), ); check( "browser-hover-proxy-bounds", @@ -1700,6 +1735,7 @@ async function verifyBrowser() { configImportRestore: configImportRestore.screenshot, visualOnlyBoundary: visualOnlyBoundary.screenshot, desktop: desktopScreenshot, + debugCapture, mobile: mobileScreenshot, }, }; diff --git a/src/main.ts b/src/main.ts index e66a997..baab3a3 100644 --- a/src/main.ts +++ b/src/main.ts @@ -164,9 +164,11 @@ interface RuntimeDiagnostics { targetRenderFps: number; actualRenderFps: number; renderPixelRatio: number; + preserveDrawingBufferEnabled: boolean; shadowsEnabled: boolean; renderSkipCount: number; lastRenderDurationMs: number; + readbackRenderCount: number; hoverPickIntervalMs: number; frozenStaticObjectCount: number; manualMatrixRootCount: number; @@ -2486,9 +2488,11 @@ function currentRuntimeDiagnostics( targetRenderFps: stats.targetRenderFps, actualRenderFps: stats.actualRenderFps, renderPixelRatio: stats.renderPixelRatio, + preserveDrawingBufferEnabled: stats.preserveDrawingBufferEnabled, shadowsEnabled: stats.shadowsEnabled, renderSkipCount: stats.renderSkipCount, lastRenderDurationMs: stats.lastRenderDurationMs, + readbackRenderCount: stats.readbackRenderCount, hoverPickIntervalMs: stats.hoverPickIntervalMs, frozenStaticObjectCount: stats.frozenStaticObjectCount, manualMatrixRootCount: stats.manualMatrixRootCount, @@ -2581,7 +2585,7 @@ function currentDiagnosticsReport(): string { function renderPerformanceLabel(stats: RuntimeDiagnostics["stats"]): string { const mode = stats.largeSceneMode ? "large-scene" : "standard"; const shadows = stats.shadowsEnabled ? "shadows on" : "shadows off"; - return `${mode}; target ${stats.targetRenderFps} fps; actual ${stats.actualRenderFps.toFixed(1)} fps; dpr ${stats.renderPixelRatio.toFixed(2)}; ${shadows}; skipped ${stats.renderSkipCount}; hover ${stats.hoverPickIntervalMs}ms; frozen ${stats.frozenStaticObjectCount}; manual roots ${stats.manualMatrixRootCount} updates ${stats.manualMatrixUpdateCount}; primitive geometries ${stats.primitiveGeometryCount}; mesh cache ${stats.meshCacheSourceCount} sources ${stats.meshCacheHitCount}/${stats.meshCacheMissCount} hit/miss retained ${stats.retainedMeshGeometryCount}g/${stats.retainedMeshMaterialCount}m; bounds cache ${stats.sceneObjectBoundsCount} fast ${stats.fastPickProxyBoundsCount} source ${stats.meshSourceBoundsCount} hoverProxy ${stats.hoverProxyBoundsHitCount}/fallback ${stats.hoverRootBoundsFallbackCount} camera traversals ${stats.cameraFitTraversalCount}; scene batches ${stats.sceneRootBatchCount}/${stats.batchedSceneRootCount} suppressed ${stats.sceneLoadSuppressedRenderCount} yields ${stats.sceneBuildYieldCount}; state payload ${stats.statePayloadBodyCount}/${stats.mergedBodyStateCount} reduced ${stats.reducedStateFrameCount}; ui cache physics ${stats.objectPhysicsProfileCacheHitCount}/${stats.objectPhysicsProfileCacheMissCount} builder ${stats.builderPhysicsProfileCacheHitCount}/${stats.builderPhysicsProfileCacheMissCount}; pick proxies ${stats.pickProxyCount}; state apply ${stats.appliedBodyStateCount}/skip ${stats.skippedBodyStateCount}; unchanged frames ${stats.unchangedFrameCount}; released ${stats.releasedGeometryCount}g/${stats.releasedMaterialCount}m/${stats.releasedTextureCount}t`; + return `${mode}; target ${stats.targetRenderFps} fps; actual ${stats.actualRenderFps.toFixed(1)} fps; dpr ${stats.renderPixelRatio.toFixed(2)}; buffer preserved ${stats.preserveDrawingBufferEnabled}; readback renders ${stats.readbackRenderCount}; ${shadows}; skipped ${stats.renderSkipCount}; hover ${stats.hoverPickIntervalMs}ms; frozen ${stats.frozenStaticObjectCount}; manual roots ${stats.manualMatrixRootCount} updates ${stats.manualMatrixUpdateCount}; primitive geometries ${stats.primitiveGeometryCount}; mesh cache ${stats.meshCacheSourceCount} sources ${stats.meshCacheHitCount}/${stats.meshCacheMissCount} hit/miss retained ${stats.retainedMeshGeometryCount}g/${stats.retainedMeshMaterialCount}m; bounds cache ${stats.sceneObjectBoundsCount} fast ${stats.fastPickProxyBoundsCount} source ${stats.meshSourceBoundsCount} hoverProxy ${stats.hoverProxyBoundsHitCount}/fallback ${stats.hoverRootBoundsFallbackCount} camera traversals ${stats.cameraFitTraversalCount}; scene batches ${stats.sceneRootBatchCount}/${stats.batchedSceneRootCount} suppressed ${stats.sceneLoadSuppressedRenderCount} yields ${stats.sceneBuildYieldCount}; state payload ${stats.statePayloadBodyCount}/${stats.mergedBodyStateCount} reduced ${stats.reducedStateFrameCount}; ui cache physics ${stats.objectPhysicsProfileCacheHitCount}/${stats.objectPhysicsProfileCacheMissCount} builder ${stats.builderPhysicsProfileCacheHitCount}/${stats.builderPhysicsProfileCacheMissCount}; pick proxies ${stats.pickProxyCount}; state apply ${stats.appliedBodyStateCount}/skip ${stats.skippedBodyStateCount}; unchanged frames ${stats.unchangedFrameCount}; released ${stats.releasedGeometryCount}g/${stats.releasedMaterialCount}m/${stats.releasedTextureCount}t`; } function renderDiagnosticsPanel(diagnostics = currentRuntimeDiagnostics()): void { @@ -2599,9 +2603,11 @@ function renderDiagnosticsPanel(diagnostics = currentRuntimeDiagnostics()): void data.targetRenderFps = String(diagnostics.stats.targetRenderFps); data.actualRenderFps = diagnostics.stats.actualRenderFps.toFixed(1); data.renderPixelRatio = diagnostics.stats.renderPixelRatio.toFixed(2); + data.preserveDrawingBufferEnabled = String(diagnostics.stats.preserveDrawingBufferEnabled); data.shadowsEnabled = String(diagnostics.stats.shadowsEnabled); data.renderSkipCount = String(diagnostics.stats.renderSkipCount); data.lastRenderDurationMs = diagnostics.stats.lastRenderDurationMs.toFixed(2); + data.readbackRenderCount = String(diagnostics.stats.readbackRenderCount); data.hoverPickIntervalMs = String(diagnostics.stats.hoverPickIntervalMs); data.frozenStaticObjectCount = String(diagnostics.stats.frozenStaticObjectCount); data.manualMatrixRootCount = String(diagnostics.stats.manualMatrixRootCount); diff --git a/src/preview/UniversalPreviewer.ts b/src/preview/UniversalPreviewer.ts index 016d694..a3fee24 100644 --- a/src/preview/UniversalPreviewer.ts +++ b/src/preview/UniversalPreviewer.ts @@ -140,6 +140,7 @@ export class UniversalPreviewer { private frameCount = 0; private renderSkipCount = 0; private lastRenderDurationMs = 0; + private readbackRenderCount = 0; private renderWindowStartedAt = 0; private renderWindowFrameCount = 0; private measuredRenderFps = 0; @@ -201,7 +202,7 @@ export class UniversalPreviewer { antialias: true, alpha: false, powerPreference: "high-performance", - preserveDrawingBuffer: true, + preserveDrawingBuffer: false, }); this.renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2)); this.renderer.outputColorSpace = THREE.SRGBColorSpace; @@ -402,9 +403,11 @@ export class UniversalPreviewer { targetRenderFps: this.targetRenderIntervalMs > 0 ? Math.round(1000 / this.targetRenderIntervalMs) : 60, actualRenderFps: this.measuredRenderFps, renderPixelRatio: this.renderer.getPixelRatio(), + preserveDrawingBufferEnabled: this.renderer.getContext().getContextAttributes()?.preserveDrawingBuffer === true, shadowsEnabled: this.renderer.shadowMap.enabled, renderSkipCount: this.renderSkipCount, lastRenderDurationMs: this.lastRenderDurationMs, + readbackRenderCount: this.readbackRenderCount, hoverPickIntervalMs: this.hoverPickIntervalMs, frozenStaticObjectCount: this.frozenStaticObjectCount, manualMatrixRootCount: this.manualMatrixRootCount, @@ -453,11 +456,12 @@ export class UniversalPreviewer { } capturePng(): string { - this.renderer.render(this.scene, this.camera); + this.renderForReadback(); return this.renderer.domElement.toDataURL("image/png"); } sampleCanvasPixels(): number { + this.renderForReadback(); const gl = this.renderer.getContext(); const canvas = this.renderer.domElement; const width = canvas.width; @@ -490,6 +494,9 @@ export class UniversalPreviewer { } private cachedCanvasPixelSamples(): number { + if (this.lastPixelSamples > 0) { + return this.lastPixelSamples; + } const now = performance.now(); if (now - this.lastPixelSampleAt < 2000) { return this.lastPixelSamples; @@ -567,6 +574,16 @@ export class UniversalPreviewer { this.updateRenderFps(performance.now()); }; + private renderForReadback(): void { + const renderStartedAt = performance.now(); + this.renderer.render(this.scene, this.camera); + const now = performance.now(); + this.lastRenderDurationMs = now - renderStartedAt; + this.lastRenderAt = now; + this.renderDirty = false; + this.readbackRenderCount += 1; + } + private updateSpinningObjects(elapsed: number): boolean { if (this.spinningObjects.length === 0) { return false; @@ -944,6 +961,7 @@ export class UniversalPreviewer { this.unchangedFrameCount = 0; this.renderSkipCount = 0; this.lastRenderDurationMs = 0; + this.readbackRenderCount = 0; this.measuredRenderFps = 0; this.frozenStaticObjectCount = 0; this.manualMatrixRootCount = 0; @@ -963,6 +981,8 @@ export class UniversalPreviewer { this.sceneRootBatchCount = 0; this.renderWindowFrameCount = 0; this.renderWindowStartedAt = performance.now(); + this.lastPixelSampleAt = 0; + this.lastPixelSamples = 0; this.markRenderDirty(); } diff --git a/src/types.ts b/src/types.ts index 534b8b2..663fb0d 100644 --- a/src/types.ts +++ b/src/types.ts @@ -198,9 +198,11 @@ export interface RendererStats { targetRenderFps: number; actualRenderFps: number; renderPixelRatio: number; + preserveDrawingBufferEnabled: boolean; shadowsEnabled: boolean; renderSkipCount: number; lastRenderDurationMs: number; + readbackRenderCount: number; hoverPickIntervalMs: number; frozenStaticObjectCount: number; manualMatrixRootCount: number;