#!/usr/bin/env node /** * Capture the screenshots referenced by the Web Blender user manual. * * Usage: * DISPLAY=:1 CHROME_PATH=/usr/bin/google-chrome \ * node tools/web/manual/capture-manual.mjs --port 5184 --gpu hardware */ import fs from "node:fs"; import path from "node:path"; import { createRequire } from "node:module"; import { fileURLToPath } from "node:url"; const HERE = path.dirname(fileURLToPath(import.meta.url)); const REPO = path.resolve(HERE, "../../.."); const WEB = path.join(REPO, "web"); const requireFromWeb = createRequire(path.join(WEB, "package.json")); const { chromium } = requireFromWeb("playwright"); const OUT = path.join(WEB, "app/public/manuals/images"); const STUDIO = path.join(WEB, "app/public/tutorial/pbr/studio.blend"); const GLB = path.join(REPO, "re/猴头.glb"); const REPORT = path.join(REPO, "tests/golden/USER-MANUAL-001/capture-report.json"); const args = process.argv.slice(2); const flag = (name, fallback) => { const index = args.indexOf(`--${name}`); return index >= 0 && args[index + 1] ? args[index + 1] : fallback; }; const port = Number.parseInt(flag("port", "5184"), 10) || 5184; const baseUrl = `http://127.0.0.1:${port}`; const gpuMode = flag("gpu", process.env.GPU_MODE ?? "hardware"); const hardwareArgs = ["--no-sandbox", "--use-gl=angle", "--use-angle=gl", "--ignore-gpu-blocklist", "--enable-gpu-rasterization", "--enable-zero-copy", "--enable-unsafe-webgpu"]; const swiftshaderArgs = ["--no-sandbox", "--use-gl=swiftshader", "--enable-unsafe-swiftshader"]; async function waitForServer() { const deadline = Date.now() + 60_000; while (Date.now() < deadline) { try { const response = await fetch(baseUrl); if (response.status < 500) return; } catch { /* retry */ } await new Promise((resolve) => setTimeout(resolve, 400)); } throw new Error(`server unavailable: ${baseUrl}`); } const domClick = (locator) => locator.evaluate((element) => element.click()); async function main() { await waitForServer(); fs.mkdirSync(OUT, { recursive: true }); fs.mkdirSync(path.dirname(REPORT), { recursive: true }); const browser = await chromium.launch({ headless: false, executablePath: process.env.CHROME_PATH ?? "/usr/bin/google-chrome", args: gpuMode === "hardware" ? hardwareArgs : swiftshaderArgs }); const page = await browser.newPage({ viewport: { width: 1600, height: 900 } }); const images = []; const failures = []; const shot = async (name) => { const file = path.join(OUT, `${name}.jpg`); await page.screenshot({ path: file, type: "jpeg", quality: 82 }); images.push({ name, file: path.relative(REPO, file) }); console.log(`captured ${name}`); }; const closeMenu = async () => { await page.keyboard.press("Escape"); await page.waitForTimeout(200); }; try { await page.goto(`${baseUrl}/?ui=web`, { waitUntil: "domcontentloaded" }); await page.locator("main.blender-app").waitFor({ timeout: 120_000 }); await page.locator('[data-testid="blend-file-input"]').setInputFiles(STUDIO); await page.waitForFunction(() => /Objects 6/.test(document.querySelector('[data-testid="scene-stats"]')?.textContent ?? ""), null, { timeout: 120_000 }); await page.locator('[data-testid="blend-file-input"]').setInputFiles(GLB); await page.waitForFunction(() => /Objects 7/.test(document.querySelector('[data-testid="scene-stats"]')?.textContent ?? ""), null, { timeout: 120_000 }); await page.waitForTimeout(900); await domClick(page.locator('button[aria-label="保存项目"]')); await page.waitForFunction(() => document.querySelector("main.blender-app")?.getAttribute("data-user-action-save-status") === "SUCCEEDED", null, { timeout: 60_000 }); await shot("ch01-first-save"); await page.getByRole("button", { name: "文件", exact: true }).click(); await page.getByRole("menuitem", { name: "最近打开", exact: true }).click(); await page.waitForTimeout(400); await shot("ch03-recent"); await closeMenu(); await page.getByRole("button", { name: "文件", exact: true }).click(); await page.getByRole("menuitem", { name: "恢复", exact: true }).click(); await page.getByRole("menuitem", { name: "恢复浏览器恢复点", exact: true }).click(); await page.getByRole("dialog", { name: "恢复自动保存", exact: true }).waitFor({ timeout: 30_000 }); await shot("ch05-recovery"); await page.getByRole("dialog", { name: "恢复自动保存", exact: true }).getByRole("button", { name: "取消", exact: true }).click(); await page.waitForTimeout(300); const properties = page.locator(".properties-area"); await properties.locator(".area-type-switch .area-menu button").evaluate((element) => element.click()); await page.getByRole("menu").last().waitFor({ timeout: 10_000 }); await shot("ch06-area-menu"); await page.getByRole("menuitem", { name: "垂直分割(左右)", exact: true }).click(); await page.waitForTimeout(500); await shot("ch06-area-split"); await page.locator(".workspace-grid > .area-frame .area-type-switch .area-menu button").first().evaluate((element) => element.click()); await page.getByRole("menuitem", { name: "重置工作区布局", exact: true }).click(); await page.waitForTimeout(400); const canvas = page.locator(".viewport-area canvas.viewport-canvas").first(); await canvas.focus(); await page.getByRole("button", { name: "相机视图", exact: true }).evaluate((element) => element.click()); await page.waitForTimeout(700); await shot("ch07-camera-view"); await page.getByRole("button", { name: "相机视图", exact: true }).evaluate((element) => element.click()); await page.waitForTimeout(300); const row = page.locator(".tree-row.child, [role=treeitem]").first(); if (await row.count()) await row.evaluate((element) => element.click()); await page.waitForTimeout(400); await shot("ch08-outliner"); await properties.locator('button[title="修改器属性"]').evaluate((element) => element.click()); await page.waitForTimeout(400); await shot("ch09-properties-tabs"); await page.getByText("Physics", { exact: true }).first().scrollIntoViewIfNeeded().catch(() => undefined); await page.waitForTimeout(400); await shot("ch21-physics"); await page.getByRole("button", { name: "文件", exact: true }).click(); await page.getByRole("menuitem", { name: "导入", exact: true }).click(); await page.waitForTimeout(300); await shot("ch25-import-menu"); await closeMenu(); await page.getByRole("button", { name: "文件", exact: true }).click(); await page.getByRole("menuitem", { name: "导出", exact: true }).click(); await page.waitForTimeout(300); await shot("ch25-export-menu"); await closeMenu(); // Rendering chapters (24-26). The workspace tabs come from the native // editor workflow once a scene is open, and only those carry `aria-current`; // clicking the static fallback list would switch React state without // switching the native screen, so wait for the workflow tabs first. await page.waitForFunction( () => [...document.querySelectorAll(".workspace-tab")].some((tab) => tab.getAttribute("aria-current") !== null), null, { timeout: 60_000 }); const openRendering = async () => { await page.evaluate(() => { const tab = [...document.querySelectorAll(".workspace-tab")].find((item) => item.textContent === "Rendering"); if (tab instanceof HTMLElement) tab.click(); }); await page.waitForFunction(() => [...document.querySelectorAll(".workspace-tab")] .some((tab) => tab.getAttribute("aria-current") !== null && tab.textContent === "Rendering"), null, { timeout: 30_000 }); await page.waitForTimeout(900); }; await openRendering(); await shot("ch24-render-paths"); const pbrPanel = page.locator('section[aria-label="Web PBR 渲染"]'); await pbrPanel.scrollIntoViewIfNeeded(); await page.waitForTimeout(300); await shot("ch24-pbr-panel"); // A real PBR render, so the screenshot shows an actual frame and the OPFS // copy line rather than an empty result area. await pbrPanel.locator('select[aria-label="PBR 渲染分辨率"]').selectOption("512"); await pbrPanel.getByRole("button", { name: "渲染 PBR", exact: true }).click(); await pbrPanel.locator(".pbr-render-result img").waitFor({ timeout: 120_000 }); await page.waitForTimeout(400); await shot("ch24-opfs-render-record"); const nativeFallback = page.locator("details.native-render-fallback"); if (!await nativeFallback.evaluate((element) => element.open)) { await nativeFallback.locator("summary").click(); } await nativeFallback.locator(".native-render-panel").waitFor({ timeout: 30_000 }); await page.waitForTimeout(600); await shot("ch25-native-panel"); await nativeFallback.locator('select[aria-label="Engine"]').selectOption("BLENDER_EEVEE"); await nativeFallback.locator('select[aria-label="Format"]').selectOption("PNG"); await page.waitForTimeout(300); await shot("ch25-engine-format"); // A real EEVEE frame: the chapter tells the reader what the status line and // artifact list look like after it succeeds, so capture that state. await nativeFallback.getByRole("button", { name: "Render Frame", exact: true }).click(); await page.waitForFunction( () => /SUCCEEDED|FAILED|failed/i.test(document.querySelector("details.native-render-fallback pre[role=status]")?.textContent ?? ""), null, { timeout: 120_000 }); await page.waitForTimeout(600); await shot("ch25-render-frame"); await nativeFallback.locator('select[aria-label="Format"]').selectOption("FFMPEG"); await page.waitForTimeout(300); await shot("ch25-animation-format"); // Chapter 26 runs the same project at the default address, where the WASM // engine renders inside the page instead of the server backend. const embedded = await browser.newPage({ viewport: { width: 1600, height: 900 } }); try { await embedded.goto(`${baseUrl}/`, { waitUntil: "domcontentloaded" }); await embedded.locator("main.blender-app").waitFor({ timeout: 120_000 }); await embedded.locator('[data-testid="blend-file-input"]').setInputFiles(STUDIO); await embedded.waitForFunction(() => /Objects 6/.test(document.querySelector('[data-testid="scene-stats"]')?.textContent ?? ""), null, { timeout: 120_000 }); // In the embedded path the React workspace stays mounted but hidden behind // the native canvas, and F12 silently does nothing until the native editor // workflow is parsed: `runNativeWorkflow` returns early unless // `editorWorkflowStatus === "AVAILABLE"`. Workflow tabs carrying // `aria-current` are that ready signal (the static fallback list has none). await embedded.waitForFunction( () => [...document.querySelectorAll(".workspace-tab")].some((tab) => tab.getAttribute("aria-current") !== null), null, { timeout: 90_000 }); await embedded.evaluate(() => { const tab = [...document.querySelectorAll(".workspace-tab")].find((item) => item.textContent === "Rendering"); if (tab instanceof HTMLElement) tab.click(); }); await embedded.waitForFunction(() => [...document.querySelectorAll(".workspace-tab")] .some((tab) => tab.getAttribute("aria-current") !== null && tab.textContent === "Rendering"), null, { timeout: 30_000 }); await embedded.waitForTimeout(900); // F12 has two handlers and the wrong one fails silently: the window // listener returns early when the target is the native desktop canvas or // a form control. Blur first so it runs `renderFromMenu`. await embedded.evaluate(() => { const active = document.activeElement; if (active instanceof HTMLElement) active.blur(); }); await embedded.keyboard.press("F12"); // The React subtree holding `.native-render-panel` is unmounted while the // native canvas owns the viewport, and it remounts *with the render // finished* — the panel mounts closed, so wait for existence, not // visibility, and expand it afterwards. await embedded.waitForFunction(() => document.querySelector(".native-render-panel") !== null, null, { timeout: 90_000 }); const embeddedDetails = embedded.locator("details.native-render-fallback"); if (!await embeddedDetails.evaluate((element) => element.open)) await embeddedDetails.locator("summary").click(); await embedded.locator(".native-render-panel").scrollIntoViewIfNeeded(); await embedded.waitForTimeout(600); const embedFile = path.join(OUT, "ch26-embedded-result.jpg"); await embedded.screenshot({ path: embedFile, type: "jpeg", quality: 82 }); images.push({ name: "ch26-embedded-result", file: path.relative(REPO, embedFile) }); console.log("captured ch26-embedded-result"); // The default address keeps the native desktop screen behind a toggle; // capture it with the way back ("Web 业务工具") on screen. await embedded.locator('.workspace-topbar button:has-text("Blender 桌面"), button:has-text("Blender 桌面")').first().click(); await embedded.waitForTimeout(900); const desktopFile = path.join(OUT, "ch26-default-address.jpg"); await embedded.screenshot({ path: desktopFile, type: "jpeg", quality: 82 }); images.push({ name: "ch26-default-address", file: path.relative(REPO, desktopFile) }); console.log("captured ch26-default-address"); await embedded.getByTestId("native-web-tools-toggle").click(); await embedded.waitForTimeout(900); const toggleFile = path.join(OUT, "ch26-web-tools.jpg"); await embedded.screenshot({ path: toggleFile, type: "jpeg", quality: 82 }); images.push({ name: "ch26-web-tools", file: path.relative(REPO, toggleFile) }); console.log("captured ch26-web-tools"); } finally { await embedded.close().catch(() => undefined); } await page.getByRole("button", { name: "编辑", exact: true }).click(); await page.getByRole("menuitem", { name: "偏好设置", exact: true }).click(); await page.getByTestId("preferences-window").waitFor({ timeout: 30_000 }); await shot("ch27-preferences"); await page.getByRole("button", { name: "键位", exact: true }).click(); await page.waitForTimeout(300); await shot("ch27-keymap"); await page.getByRole("button", { name: "关闭偏好设置", exact: true }).click(); await page.getByRole("button", { name: "帮助", exact: true }).click(); await page.waitForTimeout(300); await shot("ch28-help"); await closeMenu(); } catch (error) { failures.push(error instanceof Error ? `${error.message}\n${error.stack ?? ""}` : String(error)); await page.screenshot({ path: path.join(OUT, "capture-failure.jpg"), type: "jpeg", quality: 82 }).catch(() => undefined); } finally { await browser.close().catch(() => undefined); const report = { schemaVersion: 1, status: failures.length ? "FAIL" : "PASS", generatedAt: new Date().toISOString(), gpuMode, images, failures }; fs.writeFileSync(REPORT, JSON.stringify(report, null, 2) + "\n", "utf8"); console.log(JSON.stringify({ status: report.status, images: images.length, failures: failures.length, report: REPORT }, null, 2)); if (failures.length) process.exitCode = 1; } } main().catch((error) => { console.error(error); process.exit(1); });