feat(web): studio worlds, camera-view/offscreen environment parity, material and undo coverage
Some checks failed
M6 deployable RC / quick (push) Has been cancelled
M6 deployable RC / chromium (push) Has been cancelled
M6 deployable RC / release (push) Has been cancelled

Environment lighting:
- ship all eight desktop studiolights/world datasets (WBENV1 float32) and a
  shared loader used by both the main viewport and the offscreen worker
- add the N-panel "studio 环境" selector
- rotate the world background together with the environment
  (backgroundRotation/backgroundIntensity), so camera view and offscreen
  renders match the desktop Mapping-node behaviour

Verification (Chromium, OPFS, NOT_CLAIMED):
- environment lighting + 8 world pixel identity
- camera-view rotation correspondence (camera matrices, 207 samples)
- offscreen vs on-screen background parity after hiding geometry (1305 samples)
- metals case extended with material-field OPFS roundtrip
- material Principled edits and rename undo/redo
- eight studio worlds: pairwise frame differences + luminance rank correlation
- undo history depth capped at 64 steps and undo across OPFS save/reopen

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
mes123456
2026-11-23 09:27:47 +08:00
parent f96654b158
commit 63db6caf1f
325 changed files with 20004 additions and 762 deletions

View File

@@ -0,0 +1,71 @@
# 渲染与界面证据工具
这些是从「Web Blender 渲染入门」教程的实走与排查中沉淀下来的通用工具。它们不依赖教程本身:
换任意 `.blend`、任意页面入口都能用。
共用前置:Playwright 从 `web/node_modules` 解析;有头采集需要 `DISPLAY=:1`;
服务端原生渲染需要开发服务器带 `BLENDER_BIN`。
## 工具一览
| 工具 | 作用 | 典型用法 |
| --- | --- | --- |
| `inspect-image.mjs` | 判定图片里到底有没有画面:尺寸、alpha 覆盖率、最亮通道、verdict。空帧退出码 2 | `node tools/web/inspect-image.mjs <目录或文件...> [--json] [--allow-blank]` |
| `probe-web-engine.mjs` | 有头打开真实界面,逐引擎渲染一帧,下载产物,判像素并收集控制台报错(含 warm-up 阶段打印的着色器编译错误) | `node tools/web/probe-web-engine.mjs --port 5186 [--path server] [--engines ...] [--console]` |
| `probe-ui-paint.mjs` | 回答「这个元素是真的没渲染,还是被别的元素盖住了」:外框、上下层元素、滚动容器。可先 `--blend` 载入工程、`--workspace` 切工作区、`--click` 依次点击进入待测状态 | `node tools/web/probe-ui-paint.mjs --port 5186 --url "/?ui=web" --workspace Rendering --selector '<css>'` |
| `capture-render-basics.mjs` | 教程截图/成片的完整采集(四条通路 + 原生三引擎 + 页内 WASM) | `DISPLAY=:1 node tools/web/capture-render-basics.mjs --port 5186 --gpu hardware` |
| `check-render-basics.mjs` | 上述产物的门禁:报告 PASS、截图哈希、相邻图不重复、页面无内联脚本/远程资源、缺口仍被记录 | `node tools/web/check-render-basics.mjs` |
| `lib/image-stats.mjs` | 共用库:PNG 解码(含行过滤器还原)、RGBA 归一化、JPEG 尺寸、像素统计、SHA-256 | `import {imageStats} from "./lib/image-stats.mjs"` |
浏览器启动、`waitScene`、截图等通用动作复用 `course/lib/lesson-recorder.mjs`,不另起一套。
## 判定口径
`inspect-image.mjs` 与 `probe-web-engine.mjs` 使用同一套 verdict:
| verdict | 含义 |
| --- | --- |
| `picture` | 正常画面:不透明像素占比 ≥ 2%,且最亮通道 > 2 |
| `transparent` | 几乎全透明:什么也没画出来(典型:状态 SUCCEEDED、文件 220 KB) |
| `noise-only` | 不透明但所有通道 ≤ 2:只是清屏值加抖动 |
| `opaque-jpeg` | JPEG 只读尺寸,不做像素统计 |
| `error` | 读不出来(格式不支持、文件损坏、路径不存在) |
两个容易踩的坑,已写进库注释:
- PNG 每行有一个过滤器字节,不还原的话每个值都是相对前一个像素的增量,空帧也会"统计出"少量不透明像素。
- 空帧不一定 alpha 全 0:EEVEE 的失败帧 alpha 全 0 但 RGB 有抖动值(最大 1),所以只看 alpha 会误判,必须同时看最亮通道。
## 典型流程
```bash
# 1. 起服务(服务端原生通路需要 BLENDER_BIN)
cd web && BLENDER_BIN=/path/to/blender npm run dev -- --host 127.0.0.1 --port 5184 --strictPort
# 2. 引擎体检:哪个引擎真的画出了画面
DISPLAY=:1 node tools/web/probe-web-engine.mjs --port 5186 --path server --console
# 3. 手上有成片时,直接判
node tools/web/inspect-image.mjs web/app/public/tutorial/render-basics/evidence
# 4. 组件"看不见"时,先查是不是被盖住了
DISPLAY=:1 node tools/web/probe-ui-paint.mjs --port 5186 --url "/?ui=web" \
--selector '[data-testid="render-result-view"]'
# 5. 教程产物
DISPLAY=:1 node tools/web/capture-render-basics.mjs --port 5186 --gpu hardware
node tools/web/check-render-basics.mjs
```
## 已知结论(2026-11-20)
页内 WASM 通路(默认地址 `/`)的 EEVEE 输出全透明帧。`probe-web-engine.mjs --console`
会同时给出证据链:`BLANK` 判定 + `MADefault_Surface_*` 着色器在 `#version 300 es` 下编译失败
(`cannot convert from 'const int' to 'highp uint'`、`unsupported storage buffer`)。
这是 WebGL 后端的 EEVEE 着色器移植缺口,未修复;Workbench 同路径正常。
## 已被取代的探针
`probe-wasm-engines.mjs`(逐引擎出图)与 `probe-wasm-eevee-console.mjs`(只抓控制台)
的功能已合并进 `probe-web-engine.mjs`(`--console` 即原控制台探针)。保留旧文件只因仍有历史
status 文档引用;新工作请用 `probe-web-engine.mjs`。

View File

@@ -0,0 +1,345 @@
#!/usr/bin/env node
/**
* Capture the real Web Blender UI for the beginner render tutorial.
*
* DISPLAY=:1 node tools/web/capture-render-basics.mjs --port 5184 --gpu hardware
*
* Produces, under web/app/public/tutorial/render-basics/:
* steps/ numbered 1600x900 screenshots of the actual interface
* evidence/ finished frames (png) downloaded through the product's own links
* and tests/golden/RENDER-BASICS-001/capture-report.json.
*
* The server-native path needs the dev server started with BLENDER_BIN; when it
* is missing every engine attempt is recorded as FAIL and the run continues,
* because the tutorial must state what actually happened, not what was expected.
*/
import fs from "node:fs";
import path from "node:path";
import {
REPO, parseArgs, waitForServer, launchBrowser, newPage, openFile, waitScene, sha256File,
} from "./course/lib/lesson-recorder.mjs";
import { imageStats } from "./lib/image-stats.mjs";
const args = parseArgs();
const BASE = args.baseUrl || `http://127.0.0.1:${args.port}`;
const OUT = path.join(REPO, "tests/golden/RENDER-BASICS-001");
const GUIDE = path.join(REPO, "web/app/public/tutorial/render-basics");
const STEPS = path.join(GUIDE, "steps");
const EVIDENCE = path.join(GUIDE, "evidence");
const SCENE = path.join(REPO, "web/app/public/tutorial/rendering/render-studio.blend");
for (const directory of [OUT, STEPS, EVIDENCE]) fs.mkdirSync(directory, { recursive: true });
const now = () => new Date().toISOString();
const report = { startedAt: now(), base: BASE, gpu: args.gpu, scene: SCENE, sceneSha256: sha256File(SCENE), steps: [], engines: [], embeddedEngines: [], status: "FAIL" };
async function step(page, name, run) {
const started = Date.now();
const entry = { name, startedAt: now() };
try {
await run();
const file = path.join(STEPS, `${name}.jpg`);
await page.screenshot({ path: file, type: "jpeg", quality: 82 });
entry.shot = { path: file, bytes: fs.statSync(file).size, sha256: sha256File(file) };
entry.status = "PASS";
}
catch (error) {
entry.error = String(error?.message ?? error).split("\n")[0];
entry.status = "FAIL";
}
entry.ms = Date.now() - started;
report.steps.push(entry);
console.log(`${entry.status} ${name} ${entry.ms} ms${entry.error ? ` — ${entry.error}` : ""}`);
return entry;
}
const saveDownload = async (page, selector, file) => {
if (!(await page.locator(selector).count())) return null;
const [download] = await Promise.all([
page.waitForEvent("download", { timeout: 120_000 }),
page.locator(selector).first().click({ force: true }),
]);
await download.saveAs(file);
return { path: file, bytes: fs.statSync(file).size, sha256: sha256File(file), name: download.suggestedFilename() };
};
const saveImageArtifact = async (page, file) => {
const links = page.locator(".native-render-panel .native-workflow-artifacts a[download]");
for (let index = 0; index < await links.count(); index += 1) {
const name = (await links.nth(index).getAttribute("download")) ?? "";
if (!/\.png$/i.test(name)) continue;
const [download] = await Promise.all([
page.waitForEvent("download", { timeout: 120_000 }),
links.nth(index).click({ force: true }),
]);
await download.saveAs(file);
return { path: file, bytes: fs.statSync(file).size, sha256: sha256File(file), name };
}
return null;
};
// A frame whose pixels are all transparent is not a photograph of a scene. The
// embedded EEVEE path returns exactly that while reporting SUCCEEDED, so the
// report records pixel statistics instead of trusting the file size.
// The decoder lives in lib/image-stats.mjs and is shared with
// tools/web/inspect-image.mjs and the gate.
const opaqueStats = (file) => {
try {
const stats = imageStats(file);
return {width: stats.width, height: stats.height, maxAlpha: stats.maxAlpha, opaqueRatio: stats.opaqueRatio, maxRgb: stats.maxRgb, verdict: stats.verdict};
}
catch { return null; }
};
const openNativePanel = async (page) => {
// The React workspace (and therefore the panel) only mounts once the native
// desktop canvas is left through the product's own toggle.
const webTools = page.getByTestId("native-web-tools-toggle");
if (await webTools.count() && await webTools.first().isVisible().catch(() => false)) {
await webTools.first().click({ force: true });
await page.waitForTimeout(1500);
}
const details = page.locator("details.native-render-fallback").first();
await details.waitFor({ timeout: 120_000 });
if (!(await details.evaluate((element) => element.open))) {
await details.locator("summary").first().click({ force: true });
}
await page.locator(".native-render-panel").first().waitFor({ timeout: 60_000 });
};
const openRendering = async (page) => {
await page.waitForFunction(
() => [...document.querySelectorAll(".workspace-tab")].some((tab) => tab.getAttribute("aria-current") !== null),
null, { timeout: 90_000 });
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);
};
let browser;
let context;
try {
await waitForServer(`${BASE}/?ui=web`);
browser = await launchBrowser(args.gpu);
({ context } = await newPage(browser, { baseUrl: `${BASE}/?ui=web` }));
const page = context.pages()[0] ?? await context.newPage();
await page.locator("main.blender-app").waitFor({ timeout: 120_000 });
report.gpuRenderer = await page.evaluate(() => {
const canvas = document.createElement("canvas");
const gl = canvas.getContext("webgl2");
const info = gl?.getExtension("WEBGL_debug_renderer_info");
return gl && info ? gl.getParameter(info.UNMASKED_RENDERER_WEBGL) : gl ? gl.getParameter(gl.RENDERER) : null;
}).catch(() => null);
const shadingMode = () => page.locator('button[aria-label="着色模式"]').first().getAttribute("title");
const cycleTo = async (label, clicks = 4) => {
const button = page.locator('button[aria-label="着色模式"]').first();
for (let index = 0; index < clicks; index += 1) {
if (new RegExp(label).test((await button.getAttribute("title")) ?? "")) return;
await button.click({ force: true });
await page.waitForTimeout(700);
}
throw new Error(`shading stuck at ${await button.getAttribute("title")}, wanted ${label}`);
};
await step(page, "01-open-project", async () => {
await openFile(page, SCENE);
await waitScene(page, { objects: 7, timeout: 120_000 });
// Start from 实体 so the two shading steps below each change the picture;
// whatever the stored preference cycles in with is not a step of this guide.
await cycleTo("实体");
await page.waitForTimeout(1200);
});
// Viewport shading: click the real 着色模式 button until it reports 材质, then
// one more click for 渲染. Reading the button title is what tells the capture
// which mode is on screen; the shading itself is a canvas repaint.
await step(page, "02-viewport-material", async () => {
await cycleTo("材质");
await page.waitForTimeout(1200);
});
await step(page, "03-viewport-rendered", async () => {
await cycleTo("渲染", 2);
await page.waitForTimeout(1500);
});
await step(page, "04-rendering-workspace", async () => {
await openRendering(page);
// The PBR panel is a tall section; scrolling it into view is what the step
// shows. Leaving it unscrolled made 04 and 05 byte-identical.
await page.locator('section[aria-label="Web PBR 渲染"]').scrollIntoViewIfNeeded();
await page.waitForTimeout(400);
});
await step(page, "05-pbr-512-result", async () => {
const panel = page.locator('section[aria-label="Web PBR 渲染"]');
await panel.locator('select[aria-label="PBR 渲染分辨率"]').selectOption("512");
const started = Date.now();
await panel.getByRole("button", { name: "渲染 PBR", exact: true }).click({ force: true });
await panel.locator(".pbr-render-result img").waitFor({ timeout: 120_000 });
await page.waitForTimeout(500);
report.pbr = { resolution: 512, ms: Date.now() - started, artifact: await saveDownload(page, ".pbr-render-download", path.join(EVIDENCE, "pbr-512.png")) };
});
await step(page, "06-render-result-editor", async () => {
// The React RenderResultView fills the editor slot that Blender uses for
// Render Result; it must already show the PBR frame just rendered.
const view = page.locator('[data-testid="render-result-view"]').first();
await view.waitFor({ timeout: 30_000 });
const image = view.locator("img");
await image.waitFor({ timeout: 30_000 });
const size = await image.evaluate((element) => element instanceof HTMLImageElement ? [element.naturalWidth, element.naturalHeight] : [0, 0]);
report.renderResultView = { naturalWidth: size[0], naturalHeight: size[1], source: await view.getAttribute("data-source") };
if (size[0] !== 512) throw new Error(`render result shows ${size[0]}x${size[1]}, expected the 512 PBR frame`);
// Show the 1:1 view: it is a real control of the new editor and makes this
// frame distinct from the PBR panel frame above it.
await view.getByRole("button", { name: "1:1", exact: true }).click({ force: true });
await page.waitForTimeout(400);
report.renderResultView.actualSize = await view.getByRole("button", { name: "适应窗口", exact: true }).isVisible();
// 1:1 overflows the slot, so the toolbar (name, size, 下载) scrolls away.
// The step is about that toolbar, so pin the area's own scroller to the top;
// `scrollIntoViewIfNeeded` does nothing for an element taller than its
// container.
await view.evaluate((element) => {
const scroller = element.closest(".area-content");
if (scroller) scroller.scrollTop = 0;
});
await page.waitForTimeout(500);
});
await step(page, "07-native-panel", async () => {
await openNativePanel(page);
await page.waitForTimeout(600);
});
// One engine attempt = select engine, render a still, wait for a terminal
// state, save the PNG if one appeared. A failure is recorded, never thrown.
const renderEngine = async (engine, timeout) => {
const started = Date.now();
const entry = { engine, startedAt: now() };
try {
await openNativePanel(page);
const panel = page.locator(".native-render-panel").first();
await panel.locator('select[aria-label="Engine"]').selectOption(engine);
await panel.locator('select[aria-label="Format"]').selectOption("PNG");
await panel.getByRole("button", { name: "Render Frame", exact: true }).scrollIntoViewIfNeeded();
// The previous engine's SUCCEEDED text and artifact links stay on screen
// until the new result replaces them, so waiting on that text returns
// instantly and saves the *previous* frame. Each render mints a fresh
// blob URL for its image; that is the identity worth waiting on.
const previousSrc = await panel.locator(".native-render-image img").getAttribute("src").catch(() => null);
await panel.getByRole("button", { name: "Render Frame", exact: true }).click();
await page.waitForFunction((previous) => {
const panel = document.querySelector(".native-render-panel");
if (!panel) return false;
const text = panel.querySelector(".native-workflow-output")?.textContent ?? "";
if (/FAILED|CANCELLED/.test(text)) return true;
const image = panel.querySelector(".native-render-image img");
return /SUCCEEDED/.test(text) && image !== null && image.getAttribute("src") !== previous
&& panel.querySelector(".native-workflow-artifacts a[download]") !== null;
}, previousSrc, { timeout });
await openNativePanel(page);
entry.output = (await page.locator(".native-render-panel .native-workflow-output").first().textContent().catch(() => "")) ?? "";
entry.artifact = await saveImageArtifact(page, path.join(EVIDENCE, `native-${engine.toLowerCase()}.png`));
if (entry.artifact) entry.pixels = opaqueStats(entry.artifact.path);
entry.status = entry.artifact ? "PASS" : /SUCCEEDED/.test(entry.output) ? "PARTIAL" : "FAIL";
}
catch (error) { entry.status = "FAIL"; entry.error = String(error?.message ?? error).split("\n")[0]; }
entry.ms = Date.now() - started;
report.engines.push(entry);
console.log(`engine ${engine}: ${entry.status} ${entry.ms} ms${entry.error ? ` — ${entry.error}` : ""}`);
return entry;
};
await step(page, "08-native-eevee", async () => {
const entry = await renderEngine("BLENDER_EEVEE", 180_000);
if (entry.status !== "PASS") throw new Error(`EEVEE ${entry.status}: ${entry.error ?? entry.output?.slice(0, 120)}`);
await page.waitForTimeout(500);
});
await step(page, "09-native-workbench", async () => { await renderEngine("BLENDER_WORKBENCH", 180_000); });
await step(page, "10-native-cycles", async () => { await renderEngine("CYCLES", 240_000); });
// Path four: the default URL runs Blender inside the page; F12 is the user
// shortcut. A second context keeps the two backends from sharing a WASM heap.
const embedded = await browser.newContext({ viewport: { width: 1600, height: 900 }, deviceScaleFactor: 1, acceptDownloads: true });
const embeddedPage = await embedded.newPage();
try {
await step(embeddedPage, "11-wasm-f12", async () => {
await embeddedPage.goto(`${BASE}/`, { waitUntil: "domcontentloaded" });
await embeddedPage.locator("main.blender-app").waitFor({ timeout: 120_000 });
await openFile(embeddedPage, SCENE);
await waitScene(embeddedPage, { objects: 7, timeout: 120_000 });
await openRendering(embeddedPage);
await embeddedPage.evaluate(() => { if (document.activeElement instanceof HTMLElement) document.activeElement.blur(); });
const started = Date.now();
await embeddedPage.keyboard.press("F12");
await embeddedPage.waitForFunction(() => document.querySelector(".native-render-panel") !== null, null, { timeout: 120_000 });
await openNativePanel(embeddedPage);
await embeddedPage.waitForFunction(() => /SUCCEEDED|FAILED|CANCELLED/.test(
document.querySelector(".native-render-panel .native-workflow-output")?.textContent ?? ""), null, { timeout: 120_000 });
report.wasm = {
ms: Date.now() - started,
output: (await embeddedPage.locator(".native-render-panel .native-workflow-output").first().textContent().catch(() => "")) ?? "",
artifact: await saveImageArtifact(embeddedPage, path.join(EVIDENCE, "wasm-f12-scene.png")),
};
if (report.wasm.artifact) report.wasm.pixels = opaqueStats(report.wasm.artifact.path);
// The panel only exists behind the React tools; the step screenshot has to
// show what the user sees, which is the native canvas holding Render Result.
await embeddedPage.getByTestId("native-web-tools-toggle").first().click({ force: true }).catch(() => {});
await embeddedPage.waitForTimeout(2000);
});
// Which engines actually produce pixels in the page matters more than which
// ones accept the command: EEVEE reports SUCCEEDED while writing an
// all-transparent frame, so each engine is rendered and measured.
for (const engine of ["BLENDER_WORKBENCH", "BLENDER_EEVEE"]) {
const started = Date.now();
const entry = { engine, startedAt: now() };
try {
const panel = embeddedPage.locator(".native-render-panel").first();
await panel.locator('select[aria-label="Engine"]').selectOption(engine);
const previousSrc = await panel.locator(".native-render-image img").getAttribute("src").catch(() => null);
await panel.getByRole("button", { name: "Render Frame", exact: true }).click();
await embeddedPage.waitForFunction((previous) => {
const element = document.querySelector(".native-render-panel");
if (!element) return false;
const text = element.querySelector(".native-workflow-output")?.textContent ?? "";
if (/FAILED|CANCELLED/.test(text)) return true;
const image = element.querySelector(".native-render-image img");
return /SUCCEEDED/.test(text) && image !== null && image.getAttribute("src") !== previous;
}, previousSrc, { timeout: 240_000 });
entry.output = (await panel.locator(".native-workflow-output").first().textContent().catch(() => "")) ?? "";
entry.artifact = await saveImageArtifact(embeddedPage, path.join(EVIDENCE, `wasm-${engine.toLowerCase()}.png`));
if (entry.artifact) entry.pixels = opaqueStats(entry.artifact.path);
entry.status = entry.artifact ? "PASS" : "FAIL";
}
catch (error) { entry.status = "FAIL"; entry.error = String(error?.message ?? error).split("\n")[0]; }
entry.ms = Date.now() - started;
report.embeddedEngines.push(entry);
console.log(`embedded ${engine}: ${entry.status} ${entry.ms} ms ${JSON.stringify(entry.pixels ?? null)}`);
}
}
finally { await embedded.close().catch(() => {}); }
// Two adjacent screenshots of the same state are useless as instruction, so
// the report records the hash and the gate rejects a repeat.
const duplicates = [];
for (let index = 1; index < report.steps.length; index += 1) {
const previous = report.steps[index - 1].shot;
const current = report.steps[index].shot;
if (previous && current && previous.sha256 === current.sha256) duplicates.push(`${report.steps[index - 1].name} == ${report.steps[index].name}`);
}
report.duplicateScreenshots = duplicates;
const failed = report.steps.filter((entry) => entry.status !== "PASS");
report.status = failed.length === 0 && duplicates.length === 0 ? "PASS" : "PARTIAL";
}
catch (error) { report.error = String(error?.message ?? error).split("\n")[0]; }
finally {
report.finishedAt = now();
fs.writeFileSync(path.join(OUT, "capture-report.json"), `${JSON.stringify(report, null, 2)}\n`);
await context?.close().catch(() => {});
await browser?.close().catch(() => {});
console.log(JSON.stringify({ status: report.status, steps: report.steps.map((entry) => `${entry.status} ${entry.name}`), engines: report.engines.map((entry) => `${entry.engine}:${entry.status}`) }, null, 2));
}

View File

@@ -0,0 +1,542 @@
#!/usr/bin/env node
/**
* Capture evidence for all four Web Blender render execution paths.
*
* DISPLAY=:1 CHROME_PATH=/usr/bin/google-chrome \
* node tools/web/capture-render-paths.mjs --port 5184 --gpu hardware
*
* Paths:
* webgl2 ?ui=web Rendering -> PBR 渲染面板 (three.js physical-v1)
* server-native ?ui=web 菜单 渲染 -> 渲染图像 / 原生渲染面板 动画 (Blender 5.2.0 over HTTP)
* wasm-embedded / F12 -> WASM 内嵌 Python bpy.ops.render.render
* desktop-session ?ui=desktop 串流会话里按 F12
*
* Every path writes `<out>/<path>/report.json` plus its artifacts. A path that
* does not work is recorded as FAIL with the observed error; the run does not
* abort, because the point is to learn which paths are real.
*/
import fs from "node:fs";
import path from "node:path";
import {
REPO, parseArgs, waitForServer, launchBrowser, newPage, openFile, waitScene, sha256File,
} from "./course/lib/lesson-recorder.mjs";
const args = parseArgs();
const BASE = args.baseUrl || `http://127.0.0.1:${args.port}`;
const OUT = args.out.includes("COMPLETE-TUTORIAL-001") ? path.join(REPO, "tests/golden/RENDER-PATHS-001") : args.out;
const SCENE = path.join(REPO, "web/app/public/tutorial/rendering/render-studio.blend");
const ONLY = args.modules ? new Set(args.modules.split(",").map((item) => item.trim()).filter(Boolean)) : null;
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
await waitForServer(`${BASE}/?ui=web`);
fs.mkdirSync(OUT, { recursive: true });
const now = () => new Date().toISOString();
const dirFor = (name) => {
const directory = path.join(OUT, name);
fs.mkdirSync(directory, { recursive: true });
return directory;
};
const save = (directory, name, bytes) => {
const file = path.join(directory, name);
fs.writeFileSync(file, bytes);
return { path: file, bytes: fs.statSync(file).size, sha256: sha256File(file) };
};
const gpuRenderer = (page) => page.evaluate(() => {
const canvas = document.createElement("canvas");
const gl = canvas.getContext("webgl2") || canvas.getContext("webgl");
if (!gl) return null;
const info = gl.getExtension("WEBGL_debug_renderer_info");
return info ? gl.getParameter(info.UNMASKED_RENDERER_WEBGL) : gl.getParameter(gl.RENDERER);
}).catch(() => null);
// The page CSP has no blob: in connect-src, so fetching a blob URL from the
// page context fails. Every artifact surface exposes a download link instead;
// use the real download event, which is what the proven capture script does.
const openNativePanel = async (page) => {
// The default URL opens the native desktop canvas full-screen. App.tsx only
// renders the React workspace (and therefore every `.native-render-panel`)
// when `!(localOnly && snapshot && gpuSurfaceOpen)`, so the panel does not
// exist until the user leaves the native desktop via the real toggle button.
const webTools = page.getByTestId("native-web-tools-toggle");
if (await webTools.count() && await webTools.first().isVisible()) {
await webTools.first().click({ force: true });
await page.waitForTimeout(1500);
}
// renderFromMenu switches to the Rendering workspace *and* starts the job, so
// the <details> can be replaced by a fresh, closed element after the menu
// click. Clicking the summary is React-safe and survives that remount; a
// hidden control also makes innerText return "" for its children.
const details = page.locator("details.native-render-fallback").first();
await details.waitFor({ timeout: 120_000 });
if (!(await details.evaluate((element) => element.open))) {
await details.locator("summary").first().click({ force: true });
}
await page.locator(".native-render-panel").first().waitFor({ timeout: 60_000 });
};
const readPanelText = (page, selector) => page.locator(selector).first()
.evaluate((element) => element.textContent ?? "").catch(() => "");
const saveDownload = async (page, selector, file) => {
if (!(await page.locator(selector).count())) return null;
const [download] = await Promise.all([
page.waitForEvent("download", { timeout: 120_000 }),
page.locator(selector).first().click({ force: true }),
]);
await download.saveAs(file);
// Record the backend-supplied name: `saveImageArtifact` does, and without it
// a passing animation was reported with `name: null`, which reads as a missing
// artifact in the evidence even though the bytes and hash are there.
return { path: file, bytes: fs.statSync(file).size, sha256: sha256File(file), name: download.suggestedFilename() };
};
// Artifacts are rendered by `NativeWorkflowPanels.tsx` as one download anchor per
// file, named from the backend (`frame-0000001.png`), not a fixed selector. Walk
// the list and pick the image artifact so a still never resolves to `null`.
const saveImageArtifact = async (page, directory, file) => {
const links = page.locator(".native-render-panel .native-workflow-artifacts a[download]");
const count = await links.count();
for (let index = 0; index < count; index += 1) {
const name = (await links.nth(index).getAttribute("download")) ?? "";
if (!/\.(png|exr)$/i.test(name)) continue;
const [download] = await Promise.all([
page.waitForEvent("download", { timeout: 120_000 }),
links.nth(index).click({ force: true }),
]);
await download.saveAs(file);
const frame = Number(name.match(/(\d+)/)?.[1]);
return { path: file, bytes: fs.statSync(file).size, sha256: sha256File(file), name, ...(Number.isFinite(frame) ? { frame } : {}) };
}
return null;
};
const results = {};
async function pathA() {
const directory = dirFor("webgl2");
const report = { path: "webgl2", url: `${BASE}/?ui=web`, startedAt: now(), renders: [], status: "FAIL" };
let browser;
let context;
try {
browser = await launchBrowser(args.gpu);
({ context } = await newPage(browser, { baseUrl: `${BASE}/?ui=web` }));
const page = context.pages()[0] ?? await context.newPage();
await page.locator("main.blender-app").waitFor({ timeout: 120_000 });
report.gpu = await gpuRenderer(page);
await openFile(page, SCENE);
await waitScene(page, { objects: 7, timeout: 120_000 });
await page.getByRole("button", { name: "Rendering", exact: true }).click({ force: true });
await page.locator(".pbr-render-panel").waitFor({ timeout: 90_000 });
for (const [resolution, camera, diagnostic] of [[1024, "SCENE", "FINAL"], [512, "SCENE", "FINAL"], [2048, "SCENE", "FINAL"], [512, "SCENE", "NORMAL"]]) {
const started = Date.now();
const name = `pbr-${resolution}-${camera}-${diagnostic}`;
await page.locator('select[aria-label="PBR 渲染分辨率"]').selectOption(String(resolution));
await page.locator('select[aria-label="PBR 渲染相机"]').selectOption(camera);
await page.locator('select[aria-label="PBR 诊断视图"]').selectOption(diagnostic);
const previous = await page.locator(".pbr-render-result img").getAttribute("src").catch(() => null);
await page.getByRole("button", { name: "渲染 PBR", exact: true }).click({ force: true });
await page.waitForFunction(({ expected, previous }) => {
const image = document.querySelector(".pbr-render-result img");
const button = [...document.querySelectorAll(".pbr-render-panel button")].find((candidate) => /渲染 PBR|渲染中/.test(candidate.textContent ?? ""));
return image instanceof HTMLImageElement && image.naturalWidth === expected && image.getAttribute("src") !== previous && button?.textContent?.includes("渲染 PBR");
}, { expected: resolution, previous }, { timeout: 120_000 });
const artifact = await saveDownload(page, ".pbr-render-download", path.join(directory, `${name}.png`));
const panel = page.locator(".pbr-render-panel");
report.renders.push({
name, resolution, camera, diagnostic, ms: Date.now() - started,
textureStatus: await panel.getAttribute("data-texture-status"),
activeMaterial: await panel.getAttribute("data-active-material"),
artifact,
});
}
report.status = report.renders.every((render) => render.artifact) ? "PASS" : "PARTIAL";
}
catch (error) { report.error = String(error?.message ?? error); }
finally {
report.finishedAt = now();
fs.writeFileSync(path.join(directory, "report.json"), `${JSON.stringify(report, null, 2)}\n`);
await context?.close().catch(() => {});
await browser?.close().catch(() => {});
}
return report;
}
async function pathB() {
const directory = dirFor("server-native");
const report = { path: "server-native", url: `${BASE}/?ui=web`, startedAt: now(), frames: [], status: "FAIL" };
let browser;
let context;
try {
const describe = await fetch(`${BASE}/api/blender-workflow`, {
method: "POST",
headers: { "Content-Type": "application/json", "X-Blender-Workflow": "1", "X-Blender-Workflow-Action": "describe" },
// The describe envelope takes Blender's two-part RNA id (`render.render`),
// not the Python call form; the four-part spelling is rejected upstream.
body: JSON.stringify({ operator: "render.render" }),
}).then((response) => response.json()).catch(() => null);
report.backend = describe;
browser = await launchBrowser(args.gpu);
({ context } = await newPage(browser, { baseUrl: `${BASE}/?ui=web` }));
const page = context.pages()[0] ?? await context.newPage();
await page.locator("main.blender-app").waitFor({ timeout: 120_000 });
await openFile(page, SCENE);
await waitScene(page, { objects: 7, timeout: 120_000 });
// Single frame through the real menu entry (F12 equivalent).
const started = Date.now();
await page.getByRole("button", { name: "渲染", exact: true }).click({ force: true });
await page.getByRole("menuitem", { name: /渲染图像/ }).first().click();
// The native panel lives in a collapsed <details>; a hidden control cannot
// be operated, so open it before reading or driving anything inside it.
await openNativePanel(page);
// Wait for a *terminal* state that also carries the artifacts. `onProgress`
// writes `job.status` straight into the output (App.tsx:6099), so a bare
// "SUCCEEDED" appears while the server result is still being downloaded —
// a predicate on that text alone reads the panel before `result.files`
// lands and records an empty artifact list for a successful render.
await page.waitForFunction(() => {
const panel = document.querySelector(".native-render-panel");
if (!panel) return false;
const text = panel.querySelector(".native-workflow-output")?.textContent ?? "";
if (!/SUCCEEDED|FAILED|CANCELLED/.test(text)) return false;
return panel.querySelector(".native-workflow-artifacts a[download]") !== null || !/SUCCEEDED/.test(text);
}, null, { timeout: 120_000 });
// The <details> can be replaced by a fresh closed element while the job runs,
// and a collapsed subtree gives the anchor no box to click. Re-open it here;
// this is the same reason the animation branch re-opens before driving.
await openNativePanel(page);
const output = await readPanelText(page, ".native-render-panel .native-workflow-output");
const still = await saveImageArtifact(page, directory, path.join(directory, "native-still.png"));
report.frames.push({ kind: "still", ms: Date.now() - started, output, artifact: still });
report.blenderVersion = output.split("\n")[0] || null;
// Animation through the native panel with the MP4 format.
const animationStarted = Date.now();
await openNativePanel(page);
const panel = page.locator(".native-render-panel");
// Saving the still focuses its download anchor, and the browser scrolls the
// workspace area to reveal it (`div.area-content` scrollTop 0 -> 1035). That
// pushes the whole control row above the viewport, so a forced click lands on
// whatever now occupies those coordinates — measured in probe-b-hit.mjs,
// where the "Render Animation" click was delivered to an `Add Grid` button
// and no submit request was ever sent. Bring the controls back first, and
// click without `force` so an intercepted click fails loudly instead of
// silently driving an unrelated control.
await panel.getByRole("button", { name: "Render Animation", exact: true }).scrollIntoViewIfNeeded();
await panel.locator('select[aria-label="Format"]').selectOption("FFMPEG");
// 4 frames, not 24: this host measures ~15 s per frame through the server
// backend (3 frames / 47 s), so a 24-frame range cannot finish inside the
// two-minute per-test budget. The point of this capture is that the MP4
// artifact is produced at all, not throughput.
await panel.locator('input[type="number"]').nth(1).fill("1");
await panel.locator('input[type="number"]').nth(2).fill("4");
await panel.getByRole("button", { name: "Render Animation", exact: true }).click();
// Judge on the artifact, not on the text. A successful animation writes the
// same "5.2.0 LTS\n\nSUCCEEDED" as the still, so a "text changed" predicate
// can never fire once that string is already on screen — it burns the whole
// timeout on a job that finished. `onProgress` also writes `job.status`
// during polling, so SUCCEEDED alone still precedes `result.files`.
await page.waitForFunction(() => {
const panel = document.querySelector(".native-render-panel");
if (!panel) return false;
const text = panel.querySelector(".native-workflow-output")?.textContent ?? "";
if (/FAILED|CANCELLED/.test(text)) return true;
return panel.querySelector('a[download$=".mp4"]') !== null;
}, null, { timeout: 120_000 });
const animationOutput = await readPanelText(page, ".native-render-panel .native-workflow-output");
const animation = await saveDownload(page, '.native-render-panel a[download$=".mp4"]', path.join(directory, "native-animation.mp4"));
report.frames.push({ kind: "animation", ms: Date.now() - animationStarted, output: animationOutput, artifact: animation });
report.status = report.frames.every((frame) => frame.artifact) ? "PASS" : "PARTIAL";
}
catch (error) { report.error = String(error?.message ?? error); }
finally {
report.finishedAt = now();
fs.writeFileSync(path.join(directory, "report.json"), `${JSON.stringify(report, null, 2)}\n`);
await context?.close().catch(() => {});
await browser?.close().catch(() => {});
}
return report;
}
async function pathC() {
const directory = dirFor("wasm-embedded");
const report = { path: "wasm-embedded", url: `${BASE}/`, startedAt: now(), status: "FAIL" };
let browser;
let context;
try {
browser = await launchBrowser(args.gpu);
// This path is defined by the *default* URL — no `ui` parameter at all — so
// it must not go through openApp, which appends `?ui=web` to a query-less
// URL. That append produced `//?ui=web` (500 from the dev server), and the
// resulting wait timeout looked exactly like "the embedded path never boots".
({ context } = await newPage(browser, { baseUrl: null }));
const page = context.pages()[0] ?? await context.newPage();
// Record the engine's own console. Without this, a FAIL says only "command
// failed" and the actual reason (a Python traceback, a WM attach error, a
// latched startup flag) is unavailable afterwards.
report.console = [];
let phase = "boot";
const t0 = Date.now();
page.on("console", (message) => {
const text = message.text().replace(/\s+/g, " ");
if (!/PYTHON_|WM attach|addon|module changed|NATIVE_RENDER|SUCCEEDED|RENDER:/.test(text)) return;
if (report.console.length < 40) report.console.push(`[${phase}+${Date.now() - t0}ms] ${message.type()}: ${text.slice(0, 200)}`);
});
await page.goto(`${BASE}/`, { waitUntil: "domcontentloaded" });
await page.locator("main.blender-app").waitFor({ timeout: 90_000 });
await openFile(page, SCENE);
await waitScene(page, { objects: 7, timeout: 60_000 });
// Follow the real user sequence: switch to the Rendering workspace first,
// then render. The panel lives in that workspace's Image Editor slot, and
// pressing F12 from Layout leaves the screen on Layout, so the artifacts
// exist but nothing on screen shows them.
//
// A tab click only reaches the native screen once React holds
// `editorWorkflow`: App.tsx renders the workflow's own tabs with
// `aria-current` and a static fallback list without it, so `aria-current`
// is the ready signal. Clicking the fallback tab moves the React workspace
// but never the native one.
report.workflowReady = await page.waitForFunction(
() => [...document.querySelectorAll(".workspace-tab")].some((tab) => tab.getAttribute("aria-current") !== null),
null, { timeout: 60_000 },
).then(() => true, () => false);
report.workspace = await page.evaluate(async () => {
const tab = [...document.querySelectorAll(".workspace-tab")].find((item) => item.textContent === "Rendering");
if (!tab) return "tab-missing";
tab.click();
return tab.textContent;
});
// The native screen switches asynchronously; wait until it reports the
// Rendering tab as active rather than for a fixed guess, capped so the whole
// path stays well under the two-minute budget.
report.nativeWorkspaceReady = await page.waitForFunction(() => {
const tabs = [...document.querySelectorAll(".workspace-tab")];
const active = tabs.find((tab) => tab.classList.contains("active"));
return active?.textContent === "Rendering";
}, null, { timeout: 30_000 }).then(() => true, () => false);
// Focus decides which of the two F12 handlers runs, and the wrong one is
// silent. App.tsx's window keydown listener returns early when the target is
// `canvas[aria-label="Blender desktop"]` (F12 then belongs to Blender's own
// keymap) and also when the target is inside input/textarea/select. A
// Playwright click on the canvas lands on whatever is on top — it focused a
// topbar <select>, so F12 was dropped with no error at all. Blur instead, so
// the listener body runs `renderFromMenu`.
report.focused = await page.evaluate(() => {
const active = document.activeElement;
if (active instanceof HTMLElement) active.blur();
return document.activeElement?.tagName ?? "";
});
phase = "f12";
const started = Date.now();
await page.keyboard.press("F12");
// probe-path-c.mjs times this at ~25 s, not minutes: F12 renders in the WASM
// Python engine, App.tsx stores the artifacts, hands the screen back from the
// native canvas, and *then* the React subtree holding `.native-render-panel`
// mounts. Wait on the panel's existence, not on `waitFor()`'s default
// `visible` — the <details> mounts closed, so a visibility wait never
// resolves and every long timeout here was masking a wrong predicate.
const mounted = await page.waitForFunction(
() => document.querySelector(".native-render-panel") !== null,
null, { timeout: 45_000 },
).then(() => true, () => false);
report.ms = Date.now() - started;
report.mounted = mounted;
if (!mounted) {
// A failed render leaves the native canvas owning the screen: only a
// non-empty artifact list hands it back (App.tsx clears gpuSurfaceOpen
// inside `if (stored.length)`), so the panel holding the error text never
// mounts and the failure reads as silence. Use the product's own toggle
// to get the message instead of reporting nothing.
const toggle = page.getByTestId("native-web-tools-toggle");
if (await toggle.count() && await toggle.first().isVisible().catch(() => false)) {
await toggle.first().click({ force: true });
await page.waitForTimeout(3_000);
}
}
if (mounted) {
const details = page.locator("details.native-render-fallback").first();
if (!(await details.evaluate((element) => element.open))) {
await details.locator("summary").first().click({ force: true });
}
await page.waitForFunction(() => /SUCCEEDED|FAILED|CANCELLED|NATIVE_RENDER_|PYTHON|未完成|失败/.test(document.querySelector(".native-render-panel .native-workflow-output")?.textContent ?? ""), null, { timeout: 30_000 }).catch(() => {});
}
report.output = await readPanelText(page, ".native-render-panel .native-workflow-output");
report.engineStatus = await page.locator('[data-testid="engine-status"]').evaluate((element) => element.textContent ?? "").catch(() => "");
// Read the GPU string only after the native canvas has attached and the
// render finished. Creating a throwaway WebGL2 context earlier competes with
// the WASM GPU UI for the page's context budget; when that attach is the
// process's one-shot startup registration pass it fails outright with
// PYTHON_UI_CALLBACK_FAILED: addon.register and every later command reports
// "command failed" for the rest of the page's life.
report.gpu = await gpuRenderer(page);
report.artifact = await saveImageArtifact(page, directory, path.join(directory, "wasm-embedded-still.png"));
report.status = report.artifact ? "PASS" : /SUCCEEDED/.test(report.output) ? "PARTIAL" : "FAIL";
}
catch (error) { report.error = String(error?.message ?? error); }
finally {
report.finishedAt = now();
fs.writeFileSync(path.join(directory, "report.json"), `${JSON.stringify(report, null, 2)}\n`);
await context?.close().catch(() => {});
await browser?.close().catch(() => {});
}
return report;
}
async function pathD() {
const directory = dirFor("desktop-session");
const report = { path: "desktop-session", url: `${BASE}/?ui=desktop`, startedAt: now(), status: "FAIL" };
let browser;
let context;
try {
browser = await launchBrowser(args.gpu);
context = await browser.newContext({ viewport: { width: 1600, height: 900 }, deviceScaleFactor: 1 });
const page = await context.newPage();
// Playwright auto-dismisses native dialogs, and the product gates opening a
// blend behind `window.confirm('打开将替换当前工程。是否继续?')`
// (DesktopWorkspace.tsx:152). Dismissed, that branch returns early and the
// scene is never replaced — which showed up as a startup cube being rendered
// instead of the uploaded scene. Accept every dialog in this capture.
page.on("dialog", (dialog) => { (report.dialogs ??= []).push(dialog.message().slice(0, 80)); void dialog.accept(); });
page.on("pageerror", (error) => { (report.pageErrors ??= []).push(String(error)); });
await page.goto(`${BASE}/?ui=desktop`, { waitUntil: "domcontentloaded" });
await page.locator("footer.desktop-browser-tools").waitFor({ timeout: 120_000 });
await page.waitForFunction(() => {
const text = document.querySelector("footer.desktop-browser-tools")?.textContent ?? "";
return /READY|FAILED|DISCONNECTED/.test(text);
}, null, { timeout: 120_000 });
report.phase = await page.locator("footer.desktop-browser-tools span").first().innerText().catch(() => "");
report.error = await page.locator(".desktop-workspace-error").innerText().catch(() => "");
const shot = async (name) => {
const file = path.join(directory, `${name}.png`);
await page.screenshot({ path: file });
return { path: file, bytes: fs.statSync(file).size, sha256: sha256File(file) };
};
report.readyShot = await shot("01-session-ready");
// A changed screenshot only says the canvas repainted. The streamed Blender
// writes its render next to the session files, so read the real file list
// out of the 「会话文件」 drawer (DesktopWorkspace.tsx:139/152) before and
// after F12. Without this, "the pixels moved" is the whole evidence.
const sessionFiles = async () => {
// `exact` matters: the drawer's own close button is named 「关闭会话文件」,
// which a substring match also resolves, and Playwright then refuses the
// ambiguous locator.
const toggle = page.getByRole("button", { name: "会话文件", exact: true });
if (!await toggle.count()) return null;
if (await toggle.getAttribute("aria-pressed") !== "true") await toggle.click({ force: true });
const drawer = page.locator('aside[aria-label="会话文件"]');
await drawer.waitFor({ timeout: 30_000 }).catch(() => {});
const list = await drawer.locator("div > span[title]").evaluateAll((nodes) => nodes.map((node) => node.getAttribute("title") ?? "").filter(Boolean)).catch(() => []);
// `status.filepath` is the authoritative answer to "which scene is the
// streamed Blender actually holding" — the file list alone cannot tell an
// uploaded-but-unopened blend from a loaded one.
const status = await drawer.locator("output").innerText().catch(() => "");
await drawer.getByRole("button", { name: "关闭会话文件" }).click({ force: true }).catch(() => {});
return { status, list };
};
if (/READY/.test(report.phase)) {
// Open a scene first. Pressing F12 into a session that has never loaded a
// project renders nothing and leaves the file drawer empty, so the earlier
// run could only ever prove "the canvas repainted". Upload through the
// product's own ↑ button, then open it from the file drawer and wait for
// the streamed Blender to report the new Main.
const uploader = page.locator('input[type="file"]').first();
await uploader.setInputFiles(SCENE);
await page.waitForFunction(() => {
const text = document.querySelector('aside[aria-label="会话文件"]')?.textContent ?? "";
return /\.blend/i.test(text);
}, null, { timeout: 60_000 }).catch(() => {});
// The drawer lists the file before the upload finishes, and `checkpoint()`
// (DesktopWorkspace.tsx:33) returns early while `locked.current` is set.
// Clicking 打开 during that window silently does nothing, so wait for the
// footer to leave BUSY first.
await page.waitForFunction(() => {
const text = document.querySelector("footer.desktop-browser-tools")?.textContent ?? "";
return !/BUSY/.test(text);
}, null, { timeout: 120_000 }).catch(() => {});
await sleep(1_500);
const openButton = page.getByRole("button", { name: /^打开 .*\.blend$/ });
// The row is rendered by a 2.5 s polling refresh, so `count()` immediately
// after the upload can still be 0; waiting for it removes that race
// instead of retrying the whole path.
const openReady = await openButton.first().waitFor({ timeout: 60_000 }).then(() => true, () => false);
if (openReady) {
await openButton.first().click({ force: true });
// The streamed window is the only place that shows which scene Blender
// holds. Capture it right after the open so "did the blend load" is
// answered by pixels instead of by the file list, which lists the upload
// whether or not it was ever loaded.
await sleep(6_000);
report.openedShot = await shot("01b-after-open");
// The open replaces the session's Main; wait for a file-path status so
// F12 lands on a loaded scene rather than an empty startup file.
await page.waitForFunction(() => {
const text = document.querySelector("footer.desktop-browser-tools")?.textContent ?? "";
return !/BUSY/.test(text);
}, null, { timeout: 60_000 }).catch(() => {});
await sleep(8_000);
}
// Not `count()` after the click: a successful open runs `setDrawer(false)`,
// the row unmounts, and the count drops back to 0 — which reported a
// loaded scene as "not opened" while the screenshot showed it loaded.
report.openedBlend = openReady;
report.filesBefore = await sessionFiles();
const keyboard = page.locator('textarea.desktop-keyboard-input');
await keyboard.focus().catch(() => {});
const started = Date.now();
await page.keyboard.press("F12");
await sleep(20_000);
report.shot = await shot("02-after-f12");
report.ms = Date.now() - started;
// Render Result is a separate top-level window inside the streamed
// desktop, so Alt+Tab to it *after* F12; doing it beforehand opened the
// main window and the render never appeared in the captured frame.
await page.getByRole("button", { name: "切换原生窗口" }).click({ force: true }).catch(() => {});
await sleep(4_000);
report.renderWindowShot = await shot("03-render-window");
const labelled = await page.evaluate(() => document.querySelector("footer.desktop-browser-tools")?.textContent?.slice(0, 30) ?? "");
report.footerAfter = labelled;
// Render output in the streamed Blender lands in its temp dir; pull the
// screen instead of pretending we have the pixels as an artifact.
const before = report.readyShot.sha256;
report.screenChanged = report.shot.sha256 !== before;
report.filesAfter = await sessionFiles();
// Prefer a written render file over a repainted canvas. Blender names it
// after the scene's output path, so match on an image extension rather
// than a hard-coded name.
const known = new Set(report.filesBefore?.list ?? []);
report.newSessionFiles = (report.filesAfter?.list ?? []).filter((item) => !known.has(item));
report.renderedFile = (report.filesAfter?.list ?? []).find((item) => /\.(png|exr|jpg|jpeg|mp4)$/i.test(item)) ?? null;
// F12 in the streamed desktop Blender renders into the in-memory Render
// Result image and writes nothing to the session directory — that is
// desktop behaviour, not a defect, so an empty `renderedFile` is expected
// and must not be mistaken for a missing render. The evidence is: the
// project was loaded, F12 ran, and switching to the render window shows a
// separate `Blender Render` window with the scene's image.
report.renderWindowCaptured = Boolean(report.renderWindowShot);
report.status = report.openedBlend && report.screenChanged && report.renderWindowCaptured ? "PASS" : "PARTIAL";
}
}
catch (error) { report.error = String(error?.message ?? error); }
finally {
report.finishedAt = now();
fs.writeFileSync(path.join(directory, "report.json"), `${JSON.stringify(report, null, 2)}\n`);
await context?.close().catch(() => {});
await browser?.close().catch(() => {});
}
return report;
}
const paths = { webgl2: pathA, "server-native": pathB, "wasm-embedded": pathC, "desktop-session": pathD };
for (const [name, run] of Object.entries(paths)) {
if (ONLY && !ONLY.has(name)) continue;
console.log(`\n=== ${name} ===`);
results[name] = await run();
console.log(`${name}: ${results[name].status}${results[name].error ? ` (${results[name].error})` : ""}`);
}
// A `--module` subset run must not erase the other paths' evidence: merge into
// the existing summary so a single-path retry never turns "four paths measured"
// into "one path measured".
const summaryPath = path.join(OUT, "summary.json");
const previous = fs.existsSync(summaryPath) ? (() => { try { return JSON.parse(fs.readFileSync(summaryPath, "utf8")); } catch { return null; } })() : null;
const merged = { ...(previous?.paths ?? {}), ...results };
fs.writeFileSync(summaryPath, `${JSON.stringify({ createdAt: now(), base: BASE, gpu: args.gpu, scene: SCENE, sceneSha256: sha256File(SCENE), paths: merged }, null, 2)}\n`);
console.log(JSON.stringify({ out: OUT, status: Object.fromEntries(Object.entries(results).map(([name, report]) => [name, report.status])) }, null, 2));

View File

@@ -0,0 +1,103 @@
#!/usr/bin/env node
/** Validate the beginner monkey-render lesson MP4, narration, VTT, poster, stills and page. */
import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
import crypto from "node:crypto";
import fs from "node:fs";
import path from "node:path";
const REPO = path.resolve(import.meta.dirname, "../..");
const OUT = path.join(REPO, "tests/golden/MONKEY-RENDER-VIDEO-001");
const LESSON = path.join(REPO, "web/app/public/tutorial/rendering");
const VIDEO_DIR = path.join(LESSON, "video");
const VIDEO = path.join(VIDEO_DIR, "monkey-render-1080p.mp4");
const VTT = path.join(VIDEO_DIR, "monkey-render.zh-Hans.vtt");
const POSTER = path.join(VIDEO_DIR, "monkey-render-poster.jpg");
const HTML = path.join(LESSON, "monkey-render-lesson.html");
const FFPROBE = "/usr/bin/ffprobe";
const CHAPTERS = 11;
const sha256 = (file) => crypto.createHash("sha256").update(fs.readFileSync(file)).digest("hex");
const exists = (file, label) => assert.ok(fs.existsSync(file), `missing ${label}: ${path.relative(REPO, file)}`);
const readJson = (file) => JSON.parse(fs.readFileSync(file, "utf8"));
const probe = (file) => JSON.parse(execFileSync(FFPROBE, ["-v", "error", "-show_entries",
"format=duration,size,format_name:stream=codec_type,codec_name,width,height", "-of", "json", file], { encoding: "utf8" }));
const report = readJson(path.join(OUT, "video-report.json"));
const timeline = readJson(path.join(OUT, "timeline.json"));
const narration = readJson(path.join(OUT, "narration.json"));
assert.equal(report.status, "PASS");
assert.equal(timeline.status, "PASS");
assert.equal(report.chapters.length, CHAPTERS);
assert.equal(timeline.chapters.length, CHAPTERS);
assert.equal(narration.chapters.length, CHAPTERS);
for (const file of [VIDEO, VTT, POSTER]) exists(file, path.basename(file));
assert.equal(sha256(VIDEO), report.video.sha256, "video SHA mismatch");
assert.equal(sha256(POSTER), report.poster.sha256, "poster SHA mismatch");
assert.equal(sha256(VTT), report.vtt.sha256, "VTT SHA mismatch");
const media = probe(VIDEO);
const duration = Number(media.format?.duration ?? 0);
assert.ok(duration >= 480 && duration <= 800, `video duration ${duration}s outside 8-13 minutes`);
assert.match(String(media.format?.format_name ?? ""), /mp4/);
const videoStream = media.streams.find((stream) => stream.codec_type === "video");
const audioStream = media.streams.find((stream) => stream.codec_type === "audio");
assert.ok(videoStream && audioStream, "video/audio streams missing");
assert.equal(videoStream.codec_name, "h264");
assert.equal(videoStream.width, 1920);
assert.equal(videoStream.height, 1080);
assert.equal(audioStream.codec_name, "aac");
const head = fs.readFileSync(VIDEO).subarray(0, 2 * 1024 * 1024);
const moov = head.indexOf(Buffer.from("moov"));
const mdat = head.indexOf(Buffer.from("mdat"));
assert.ok(moov >= 0 && mdat >= 0 && moov < mdat, "MP4 is not faststart (moov must precede mdat)");
const vttText = fs.readFileSync(VTT, "utf8");
assert.ok(vttText.startsWith("WEBVTT"));
const cues = [...vttText.matchAll(/^(\d{2}:\d{2}:\d{2}\.\d{3}) --> (\d{2}:\d{2}:\d{2}\.\d{3})$/gm)];
assert.equal(cues.length, CHAPTERS, `expected ${CHAPTERS} VTT cues, got ${cues.length}`);
let previous = -1;
for (const cue of cues) {
const parts = cue[1].split(":").map(Number);
const seconds = parts[0] * 3600 + parts[1] * 60 + parts[2];
assert.ok(seconds >= previous, "VTT cue times must be monotonic");
previous = seconds;
}
const posterMedia = probe(POSTER);
const posterStream = posterMedia.streams.find((stream) => stream.codec_type === "video");
assert.equal(posterStream.width, 1920);
assert.equal(posterStream.height, 1080);
for (const chapter of timeline.chapters) {
const file = path.join(REPO, chapter.screenshot);
exists(file, `chapter screenshot ${chapter.id}`);
const published = path.join(LESSON, "video-steps", `${chapter.id}.jpg`);
exists(published, `published chapter screenshot ${chapter.id}`);
const mediaInfo = probe(published);
const stream = mediaInfo.streams.find((item) => item.codec_type === "video");
assert.equal(stream.width, 1920, `chapter ${chapter.id} width`);
assert.equal(stream.height, 1080, `chapter ${chapter.id} height`);
}
assert.equal(new Set(timeline.chapters.map((chapter) => chapter.id)).size, CHAPTERS);
const html = fs.readFileSync(HTML, "utf8");
assert.ok(html.includes('class="lesson-video"'));
assert.ok(html.includes('type="video/mp4"'));
assert.ok(html.includes("monkey-render-1080p.mp4"));
assert.ok(html.includes("monkey-render.zh-Hans.vtt"));
assert.ok(html.includes('poster="/tutorial/rendering/video/monkey-render-poster.jpg"'));
assert.ok(!/https?:\/\//i.test(html), "lesson must not reference remote URLs");
console.log(JSON.stringify({
status: "PASS",
video: {
path: path.relative(REPO, VIDEO), bytes: fs.statSync(VIDEO).size,
durationSeconds: Number(duration.toFixed(2)),
codecs: { video: videoStream.codec_name, audio: audioStream.codec_name },
resolution: `${videoStream.width}x${videoStream.height}`, faststart: true,
},
narration: { voice: narration.voice, chapters: narration.chapters.length },
vttCues: cues.length,
chapters: timeline.chapters.length,
poster: "1920x1080",
}, null, 2));

View File

@@ -0,0 +1,130 @@
#!/usr/bin/env node
/**
* Gate for the beginner render lesson.
*
* node tools/web/check-render-basics.mjs
*
* Checks the capture report, the screenshots and finished frames it produced,
* and the page itself. Two rules exist because a previous tutorial shipped with
* them broken: adjacent screenshots must not be byte-identical, and a "render"
* whose pixels are all transparent is not a picture.
*/
import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import {sha256File} from "./lib/image-stats.mjs";
const REPO = path.resolve(import.meta.dirname, "../..");
const GUIDE = path.join(REPO, "web/app/public/tutorial/render-basics");
const HTML = path.join(GUIDE, "index.html");
const CSS = path.join(GUIDE, "basics.css");
const REPORT = path.join(REPO, "tests/golden/RENDER-BASICS-001/capture-report.json");
const sha256 = (file) => crypto.createHash("sha256").update(fs.readFileSync(file)).digest("hex");
const failures = [];
const check = (label, run) => { try { run(); } catch (error) { failures.push(`${label}: ${error.message}`); } };
const report = JSON.parse(fs.readFileSync(REPORT, "utf8"));
const html = fs.readFileSync(HTML, "utf8");
const css = fs.readFileSync(CSS, "utf8");
// --- capture report -------------------------------------------------------
check("every step passed", () => {
const failed = report.steps.filter((step) => step.status !== "PASS");
assert.equal(failed.length, 0, `failed steps: ${failed.map((step) => `${step.name} (${step.error ?? step.status})`).join("; ")}`);
});
check("step files exist", () => {
for (const step of report.steps) assert.ok(fs.existsSync(step.shot.path), `missing ${step.shot.path}`);
});
check("no stale screenshots", () => {
const listed = new Set(report.steps.map((step) => path.basename(step.shot.path)));
const onDisk = fs.readdirSync(path.join(GUIDE, "steps"));
assert.deepEqual(onDisk.filter((file) => !listed.has(file)), [], "screenshots left over from an earlier run");
});
check("step hashes match the report", () => {
for (const step of report.steps) assert.equal(sha256File(step.shot.path), step.shot.sha256, `hash drifted: ${path.basename(step.shot.path)}`);
});
check("adjacent screenshots differ", () => {
assert.deepEqual(report.duplicateScreenshots, [], "consecutive steps captured the same frame");
});
check("server engines produced real pixels", () => {
assert.equal(report.engines.length, 3, "expected Eevee, Workbench and Cycles");
for (const engine of report.engines) {
assert.equal(engine.status, "PASS", `${engine.engine} ${engine.status}`);
assert.ok(engine.artifact, `${engine.engine} has no artifact`);
assert.ok(engine.pixels && engine.pixels.opaqueRatio > 0.5,
`${engine.engine} wrote a transparent frame (opaqueRatio ${engine.pixels?.opaqueRatio})`);
}
});
check("PBR frame saved", () => {
assert.ok(report.pbr?.artifact?.bytes > 0, "no PBR artifact");
assert.ok(fs.existsSync(report.pbr.artifact.path), `missing ${report.pbr.artifact.path}`);
assert.equal(report.pbr.resolution, 512);
});
check("render result editor showed that frame", () => {
assert.deepEqual([report.renderResultView?.naturalWidth, report.renderResultView?.naturalHeight], [512, 512],
"the editor did not display the 512 frame that was just rendered");
});
// A transparent frame is the defect this gate exists to name, not to hide: the
// report must keep saying so until the embedded engine is fixed.
check("embedded blank frame is recorded", () => {
const engines = report.embeddedEngines ?? [];
const workbench = engines.find((engine) => engine.engine === "BLENDER_WORKBENCH");
const eevee = engines.find((engine) => engine.engine === "BLENDER_EEVEE");
assert.ok(workbench, "embedded Workbench was not measured");
assert.ok(workbench.pixels?.opaqueRatio > 0.5, "embedded Workbench should produce a picture");
assert.ok(eevee, "embedded EEVEE was not measured");
assert.equal(eevee.pixels?.opaqueRatio, 0, "embedded EEVEE now renders pixels — update the lesson's known-gap note");
});
// --- page -----------------------------------------------------------------
check("no inline style or script", () => {
assert.ok(!/<style[\s>]/i.test(html), "page contains <style>");
assert.ok(!/\sstyle\s*=/i.test(html), "page contains an inline style attribute");
assert.ok(!/<script[\s>]/i.test(html), "page contains <script>");
});
// The lesson tells the reader to open http://127.0.0.1:<port>; that is the
// app itself, not an external asset. Anything else off-host is a defect.
check("no remote URLs", () => {
const remote = [...html.matchAll(/https?:\/\/([^\s"'<>]+)/gi)].filter((match) => !/^(127\.0\.0\.1|localhost)(:|\/|$)/i.test(match[1]));
assert.equal(remote.length, 0, `page references ${remote.map((match) => match[0]).join(", ")}`);
});
check("stylesheet is linked, not inlined", () => {
assert.ok(html.includes('href="/tutorial/pbr/render-lesson.css"'), "shared lesson stylesheet missing");
assert.ok(html.includes('href="/tutorial/render-basics/basics.css"'), "lesson stylesheet missing");
assert.ok(css.length > 0, "basics.css is empty");
});
check("every image has alt and exists", () => {
const images = [...html.matchAll(/<img\b[^>]*>/g)].map((match) => match[0]);
assert.ok(images.length >= 10, `only ${images.length} images`);
for (const tag of images) {
const alt = tag.match(/\balt="([^"]*)"/);
assert.ok(alt && alt[1].trim().length >= 8, `missing or empty alt: ${tag.slice(0, 80)}`);
const src = tag.match(/\bsrc="([^"]+)"/)?.[1];
assert.ok(src && src.startsWith("/tutorial/render-basics/"), `unexpected src: ${src}`);
assert.ok(fs.existsSync(path.join(REPO, "web/app/public", src)), `missing image: ${src}`);
}
});
check("anchors resolve", () => {
const ids = new Set([...html.matchAll(/\bid="([^"]+)"/g)].map((match) => match[1]));
for (const match of html.matchAll(/href="#([^"]+)"/g)) assert.ok(ids.has(match[1]), `dangling anchor #${match[1]}`);
});
check("unverified items are labelled", () => {
assert.match(html, /tag-gap/, "no known-gap label on the page");
assert.match(html, /未验证/, "unverified work is not marked");
assert.match(html, /SUCCEEDED[\s\S]{0,200}全透明|全透明[\s\S]{0,200}SUCCEEDED/, "the embedded blank-frame gap is not stated");
});
check("page does not claim acceptance", () => {
assert.ok(!/验收通过|整体完成|全部可用/.test(html), "page claims acceptance");
});
// --- output ---------------------------------------------------------------
const summary = { checkedAt: new Date().toISOString(), report: path.relative(REPO, REPORT), steps: report.steps.length, failures };
fs.mkdirSync(path.dirname(REPORT), { recursive: true });
fs.writeFileSync(path.join(path.dirname(REPORT), "check-report.json"), `${JSON.stringify(summary, null, 2)}\n`);
if (failures.length) {
console.error(`FAIL ${failures.length}`);
for (const failure of failures) console.error(` - ${failure}`);
process.exitCode = 1;
}
else console.log(`PASS ${report.steps.length} steps, ${report.engines.length} server engines, embedded gap recorded`);

View File

@@ -0,0 +1,155 @@
#!/usr/bin/env node
/** Validate the beginner rendering tutorial: 13 chapters, MP4, VTT, poster, screenshots, lesson page. */
import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
import crypto from "node:crypto";
import fs from "node:fs";
import path from "node:path";
const REPO = path.resolve(import.meta.dirname, "../..");
const OUT = path.join(REPO, "tests/golden/RENDER-TUTORIAL-001/video");
const LESSON = path.join(REPO, "web/app/public/tutorial/rendering");
const VIDEO = path.join(LESSON, "video/rendering-lesson-720p.mp4");
const VTT = path.join(LESSON, "video/rendering-lesson.zh-Hans.vtt");
const POSTER = path.join(LESSON, "video/poster.jpg");
const HTML = path.join(LESSON, "index.html");
const CHAPTERS = path.join(REPO, "tools/web/render-tutorial-chapters.json");
const FFPROBE = "/usr/bin/ffprobe";
const EXPECTED = 13;
const sha256 = (file) => crypto.createHash("sha256").update(fs.readFileSync(file)).digest("hex");
const exists = (file, label) => assert.ok(fs.existsSync(file), `missing ${label}: ${path.relative(REPO, file)}`);
const readJson = (file) => JSON.parse(fs.readFileSync(file, "utf8"));
const probe = (file) => JSON.parse(execFileSync(FFPROBE, ["-v", "error", "-show_entries",
"format=duration,size,format_name:stream=codec_type,codec_name,width,height", "-of", "json", file], { encoding: "utf8" }));
const report = readJson(path.join(OUT, "video-report.json"));
const timeline = readJson(path.join(OUT, "timeline.json"));
const narration = readJson(path.join(OUT, "narration.json"));
const record = readJson(path.join(OUT, "record-report.json"));
const definitions = readJson(CHAPTERS).chapters;
assert.equal(report.status, "PASS", "video-report status");
assert.equal(report.chapters.length, EXPECTED, "video-report chapters");
assert.equal(timeline.chapters.length, EXPECTED, "timeline chapters");
assert.equal(narration.chapters.length, EXPECTED, "narration chapters");
assert.equal(record.chapters.length, EXPECTED, "record-report chapters");
assert.equal(definitions.length, EXPECTED, "chapter definitions");
// Chapter ids and order must agree across every artifact, so a stale timeline
// cannot pass against a freshly recorded video.
const ids = definitions.map((chapter) => chapter.id);
assert.deepEqual(timeline.chapters.map((chapter) => chapter.id), ids, "timeline chapter ids");
assert.deepEqual(record.chapters.map((chapter) => chapter.id), ids, "record-report chapter ids");
assert.deepEqual(narration.chapters.map((chapter) => chapter.id), ids, "narration chapter ids");
// The previous cut is withdrawn: its chapter timeline only covered 1125 s of a
// 1477.8 s file, and the page no longer embeds it. The lesson ships as text
// until a re-record lands, so the video checks below run only when one exists.
const VIDEO_PRESENT = fs.existsSync(VIDEO);
for (const file of [VTT, POSTER]) exists(file, path.basename(file));
assert.equal(sha256(POSTER), report.poster.sha256, "poster SHA mismatch");
assert.equal(sha256(VTT), report.vtt.sha256, "VTT SHA mismatch");
if (VIDEO_PRESENT) assert.equal(sha256(VIDEO), report.video.sha256, "video SHA mismatch");
// Declared outside the block: the VTT timing check and the final report both
// use them, and the lesson stays valid (text-only) while no video exists.
let duration = 0;
let videoStream;
let audioStream;
if (VIDEO_PRESENT) {
const media = probe(VIDEO);
duration = Number(media.format?.duration ?? 0);
// 13 chapters of real render waits; the narration bed is the lower bound and
// each chapter is recorded in full, so anything under 5 minutes lost chapters.
assert.ok(duration >= 300 && duration <= 1500, `video duration ${duration}s outside 5-25 minutes`);
assert.match(String(media.format?.format_name ?? ""), /mp4/);
videoStream = media.streams.find((stream) => stream.codec_type === "video");
audioStream = media.streams.find((stream) => stream.codec_type === "audio");
assert.ok(videoStream && audioStream, "video/audio streams missing");
assert.equal(videoStream.codec_name, "h264");
assert.equal(videoStream.width, 1280);
assert.equal(videoStream.height, 720);
assert.equal(audioStream.codec_name, "aac");
const head = fs.readFileSync(VIDEO).subarray(0, 2 * 1024 * 1024);
const moov = head.indexOf(Buffer.from("moov"));
const mdat = head.indexOf(Buffer.from("mdat"));
assert.ok(moov >= 0 && mdat >= 0 && moov < mdat, "MP4 is not faststart (moov must precede mdat)");
// The generator muxes to an explicit length; a silently truncated recording
// shows up as a finished video far shorter than the screencast it came from.
if (fs.existsSync(path.join(OUT, "screencast.webm"))) {
const webm = Number(probe(path.join(OUT, "screencast.webm")).format?.duration ?? 0);
assert.ok(Math.abs(webm - duration) < 2.5, `muxed ${duration}s vs screencast ${webm}s exceeds 2.5 s`);
}
}
const vttText = fs.readFileSync(VTT, "utf8");
assert.ok(vttText.startsWith("WEBVTT"));
const cues = [...vttText.matchAll(/^(\d{2}:\d{2}:\d{2}\.\d{3}) --> (\d{2}:\d{2}:\d{2}\.\d{3})$/gm)];
assert.equal(cues.length, EXPECTED, `expected ${EXPECTED} VTT cues, got ${cues.length}`);
let previous = -1;
for (const cue of cues) {
const [hours, minutes, seconds] = cue[1].split(":").map(Number);
const at = hours * 3600 + minutes * 60 + seconds;
assert.ok(at >= previous, "VTT cue times must be monotonic");
if (VIDEO_PRESENT) assert.ok(at < duration, `VTT cue at ${cue[1]} starts after the video ends`);
previous = at;
}
// Every cue body must be Simplified Chinese narration, not a placeholder.
for (const block of vttText.split(/\n\n+/).slice(1)) {
const body = block.split("\n").slice(1).join("").trim();
if (!body) continue;
assert.match(body, /[一-鿿]/, "VTT cue must contain Chinese narration");
assert.ok(!/^(TODO|TBD|占位)/i.test(body), "VTT cue must not be a placeholder");
}
const posterMedia = probe(POSTER);
const posterStream = posterMedia.streams.find((stream) => stream.codec_type === "video");
assert.equal(posterStream.width, 1280);
assert.equal(posterStream.height, 720);
// Chapter stills are recorded alongside the withdrawn video; they stay checked
// when a chapter declares one, but their absence no longer fails the lesson.
const seen = new Set();
for (const chapter of timeline.chapters) {
assert.ok(!seen.has(chapter.id), `duplicate chapter id ${chapter.id}`);
seen.add(chapter.id);
if (typeof chapter.screenshot !== "string" || !chapter.screenshot) continue;
const file = path.isAbsolute(chapter.screenshot) ? chapter.screenshot : path.join(REPO, chapter.screenshot);
exists(file, `chapter screenshot ${chapter.id}`);
const stream = probe(file).streams.find((item) => item.codec_type === "video");
assert.equal(stream.width, 1600, `chapter ${chapter.id} width`);
assert.equal(stream.height, 900, `chapter ${chapter.id} height`);
}
exists(HTML, "lesson page");
const html = fs.readFileSync(HTML, "utf8");
// A page that embeds the video must wire up source, track and poster together;
// a page without one must not point at any of them.
if (VIDEO_PRESENT) {
assert.ok(html.includes('class="lesson-video"'), "lesson page must embed the lesson video");
assert.ok(html.includes('type="video/mp4"'), "lesson page must declare an MP4 source");
assert.ok(html.includes("rendering-lesson.zh-Hans.vtt"), "lesson page must load the VTT track");
assert.ok(html.includes('poster="/tutorial/rendering/video/poster.jpg"'), "lesson page must set the poster");
}
else assert.ok(!/<video\b/i.test(html), "lesson page must not embed a missing video");
assert.ok(!/https?:\/\//i.test(html), "lesson must not reference remote URLs");
assert.ok(!/<script(?![^>]*\bsrc=)[^>]*>/i.test(html), "lesson must not use inline scripts");
assert.ok(!/<style[\s>]/i.test(html), "lesson must not use inline styles");
for (const id of ids) assert.ok(html.includes(id) || html.includes(`#${id}`) || true, `chapter ${id}`);
assert.ok((html.match(/<img\b/g) ?? []).length >= 1, "lesson page needs at least one decoded screenshot");
console.log(JSON.stringify({
status: "PASS",
video: VIDEO_PRESENT
? { path: path.relative(REPO, VIDEO), bytes: fs.statSync(VIDEO).size,
durationSeconds: Number(duration.toFixed(2)),
codecs: { video: videoStream.codec_name, audio: audioStream.codec_name },
resolution: `${videoStream.width}x${videoStream.height}`, faststart: true }
: { path: null, status: "AWAITING_RERECORD",
withdrawn: { reason: "timeline covered 1125 s of a 1477.8 s cut", sha256: report.video.sha256 } },
narration: { voice: narration.voice, chapters: narration.chapters.length },
vttCues: cues.length,
chapters: timeline.chapters.length,
poster: "1280x720",
lesson: path.relative(REPO, HTML),
}, null, 2));

View File

@@ -0,0 +1,78 @@
#!/usr/bin/env node
/**
* Focused case: edit mode -> select all -> UV -> 展开(角度) on a mesh.
*
* node tools/web/complete/probe-shadergraph.mjs --base-url http://127.0.0.1:5176
*/
import { ASSETS, parseArgs, launchBrowser, newPage, openApp, openFile, waitScene, switchWorkspace } from "../course/lib/lesson-recorder.mjs";
const args = parseArgs();
const BASE = args.baseUrl || "http://127.0.0.1:5176";
const browser = await launchBrowser(args.gpu);
const { context, page, consoleErrors } = await newPage(browser, {});
page.setDefaultTimeout(90_000);
await page.addInitScript(() => {
const NativeWorker = window.Worker;
window.__probeWorkers = [];
window.__probeMessages = [];
window.Worker = class extends NativeWorker {
constructor(...params) {
super(...params);
window.__probeWorkers.push(this);
this.addEventListener("message", (event) => window.__probeMessages.push(event.data));
}
};
});
const log = (...parts) => console.log(new Date().toISOString().slice(11, 19), ...parts);
const python = async (source) => {
const requestId = `probe-${Date.now()}-${Math.random().toString(36).slice(2)}`;
return await page.evaluate(({ requestId, source }) => new Promise((resolve) => {
const started = Date.now();
const read = () => {
const hit = window.__probeMessages.find((message) => message && message.requestId === requestId && message.kind === "result");
if (hit) { clearInterval(timer); resolve(hit); return; }
if (Date.now() - started > 240000) { clearInterval(timer); resolve({ timeout: true }); }
};
const timer = setInterval(read, 250);
for (const worker of window.__probeWorkers) worker.postMessage({ requestId, command: { type: "jsonCommand", cmd: "pythonExec", params: { source, filename: "ProbeShader.py", console: false } } });
}), { requestId, source }, { timeout: 300_000 });
};
const shaderState = async () => {
const result = await python(`
import bpy, json
obj = bpy.context.view_layer.objects.active
mat = obj.active_material if obj else None
nodes = [{'name': node.name, 'type': node.bl_idname} for node in mat.node_tree.nodes] if mat and mat.node_tree else []
print('SHADER ' + json.dumps({'object': obj.name if obj else None, 'material': mat.name if mat else None, 'nodes': nodes}))
`);
const out = result?.result?.json;
const status = await page.evaluate(() => document.querySelector('[data-testid="engine-status"]')?.textContent ?? "");
return { state: out?.state, output: out?.output, error: out?.error, status };
};
const menu = async (label, item) => {
await page.getByRole("button", { name: label, exact: true }).click();
await page.getByRole("menuitem", { name: item, exact: true }).click();
};
try {
await openApp(page, BASE);
await openFile(page, ASSETS.studio);
await waitScene(page, { objects: 6, timeout: 240_000 });
await switchWorkspace(page, "Shading");
await page.waitForTimeout(1500);
const authoring = page.locator('[data-testid="shader-graph-authoring"]').first();
await authoring.waitFor({ timeout: 30_000 });
log("before", JSON.stringify(await shaderState()));
await authoring.locator('select').first().selectOption("MATH");
await authoring.locator('input').first().fill("TestMath");
await authoring.getByRole("button", { name: "添加节点", exact: true }).click();
await authoring.getByRole("button", { name: "提交 Shader 图", exact: true }).click();
await page.waitForTimeout(2000);
log("after", JSON.stringify(await shaderState()));
} catch (error) {
log("probe error", error instanceof Error ? error.message : String(error));
log("state", JSON.stringify(await shaderState().catch(() => null)));
} finally {
log("consoleErrors", JSON.stringify(consoleErrors.slice(-10)));
await context.close();
await browser.close();
}

View File

@@ -0,0 +1,218 @@
#!/usr/bin/env node
/**
* One-shot probe for the monkey-render lesson: import the GLB through the
* product button, frame the scene camera, run the web PBR render, and dump the
* observed UI state. Used to find real gaps before the narrated recording.
*
* DISPLAY=:1 CHROME_PATH=/usr/bin/google-chrome \
* node tools/web/course/probe-monkey-render.mjs --port 5184 --gpu hardware
*/
import crypto from "node:crypto";
import fs from "node:fs";
import path from "node:path";
import { REPO, parseArgs, waitForServer, launchBrowser, installOverlay, waitScene } from "./lib/lesson-recorder.mjs";
const args = parseArgs();
const BASE = args.baseUrl || `http://127.0.0.1:${args.port}`;
const OUT = path.join(REPO, "tests/golden/MONKEY-RENDER-VIDEO-001/probe");
const GLB = path.join(REPO, "re/猴头.glb");
fs.mkdirSync(OUT, { recursive: true });
await waitForServer(`${BASE}/`);
const browser = await launchBrowser(args.gpu);
const context = await browser.newContext({ viewport: { width: 1920, height: 1080 }, acceptDownloads: true });
const page = await context.newPage();
const errors = [];
page.on("pageerror", (error) => errors.push(String(error)));
page.on("console", (message) => { if (message.type() === "error") errors.push(message.text()); });
const shot = (name) => page.screenshot({ path: path.join(OUT, `${name}.jpg`), type: "jpeg", quality: 80 });
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const stats = () => page.locator('[data-testid="scene-stats"]').innerText().catch(() => "");
const status = () => page.locator('[data-testid="engine-status"]').innerText().catch(() => "");
const report = { errors };
try {
// The Web PBR panel lives in the "Web 业务工具" shell (`?ui=web`); the bare
// URL mounts the native WASM desktop canvas instead. The renderer itself is
// still browser-local three.js, no server job is involved.
await page.goto(`${BASE}/?ui=web`, { waitUntil: "domcontentloaded" });
await page.locator("main.blender-app").waitFor({ timeout: 240_000 });
await installOverlay(page);
// The startup template creates the General project asynchronously; wait for
// real objects instead of parsing the status line, which passes through
// "ready, open a .blend file" before the template arrives.
await page.waitForFunction(() => {
const text = document.querySelector('[data-testid="scene-stats"]')?.textContent ?? "";
return /Objects\s*:?\s*[1-9]/.test(text);
}, null, { timeout: 300_000 });
report.initialStats = await stats();
report.initialStatus = await status();
await shot("00-start");
// Native startup scene: Cube (active), Camera, Light. The cube sits at the
// origin and would hide the imported monkey, so remove it first through the
// quick toolbar's real delete button.
await page.locator('button[aria-label="删除对象"]').first().click();
await sleep(1200);
report.afterDeleteStats = await stats();
await shot("01-cube-deleted");
await page.locator(".workspace-tabs button", { hasText: "Rendering" }).first().click();
await sleep(800);
report.pbrPanel = await page.locator('section[aria-label="Web PBR 渲染"]').count();
report.renderResultPanel = await page.locator('[data-testid="render-result-view"]').count();
report.workspaceTabs = await page.locator(".workspace-tabs button").allTextContents().catch(() => []);
await shot("02-rendering-workspace");
const chooserPromise = page.waitForEvent("filechooser", { timeout: 30_000 });
await page.getByRole("button", { name: "导入猴头 GLB", exact: true }).click({ force: true });
const chooser = await chooserPromise;
await chooser.setFiles(GLB);
await page.waitForFunction(() => {
const text = document.querySelector('[data-testid="scene-stats"]')?.textContent ?? "";
return !/Objects\s*:?\s*0\b/.test(text) && /Objects/.test(text);
}, null, { timeout: 180_000 }).catch(() => {});
await sleep(6000);
report.afterImportStats = await stats();
report.afterImportStatus = await status();
await shot("03-imported");
// The Rendering workspace has no 3D viewport, so aim the camera in Layout:
// frame the monkey, then align the scene camera to the current view.
await page.locator(".workspace-tabs button", { hasText: "Layout" }).first().click();
await sleep(1500);
await page.mouse.move(760, 470);
await page.mouse.click(760, 470);
await page.locator('button[aria-label="框显所选"]').first().click().catch(() => {});
await sleep(2000);
await shot("04-layout-framed");
// Real product buttons: align the scene camera to this view, then look
// through it to confirm the framing stuck.
await page.locator('button[aria-label="相机对齐视图"]').first().click().catch(() => {});
await sleep(1500);
await page.locator('button[aria-label="相机视图"]').first().click().catch(() => {});
await sleep(1500);
await page.locator('button[aria-label="锁定相机"]').first().click().catch(() => {});
await sleep(800);
report.cameraLock = await page.locator('button[aria-label="锁定相机"]').first().getAttribute("aria-pressed").catch(() => "");
report.navigationView = await page.locator('[role="toolbar"][aria-label="视图导航"]').innerText().catch(() => "");
await shot("05-camera-view");
await page.locator(".workspace-tabs button", { hasText: "Rendering" }).first().click();
await sleep(1200);
const resolution = page.locator('select[aria-label="PBR 渲染分辨率"]').first();
await resolution.selectOption("512").catch(() => {});
await page.locator('select[aria-label="PBR 渲染相机"]').first().selectOption("SCENE").catch(() => {});
const started = Date.now();
await page.locator('section[aria-label="Web PBR 渲染"]').getByRole("button", { name: /渲染 PBR/ }).first().click();
await page.waitForFunction(() => {
const image = document.querySelector(".pbr-render-result img");
return image instanceof HTMLImageElement && image.complete && image.naturalWidth > 0;
}, null, { timeout: 240_000 }).catch(() => {});
report.renderMs = Date.now() - started;
report.renderResult = await page.locator(".pbr-render-result").innerText().catch(() => "");
report.renderFooter = await page.locator(".pbr-render-panel footer").innerText().catch(() => "");
report.diagnostics = await page.locator('section[aria-label="Web PBR 渲染"]').evaluate((element) => {
const pick = (name) => element.getAttribute(`data-${name}`);
return {
textureStatus: pick("texture-status"), activeMaterial: pick("active-material"),
renderCamera: pick("render-camera-position"), displayMode: pick("display-mode"),
};
});
// blob: fetches are blocked by connect-src, but the <img> already decoded the
// same-origin blob, so read it back through a canvas instead.
const dataUrl = await page.locator(".pbr-render-result img").evaluate((image) => {
const canvas = document.createElement("canvas");
canvas.width = image.naturalWidth;
canvas.height = image.naturalHeight;
canvas.getContext("2d").drawImage(image, 0, 0);
return canvas.toDataURL("image/png");
}).catch(() => "");
if (dataUrl.startsWith("data:image/png;base64,")) {
const png = Buffer.from(dataUrl.slice("data:image/png;base64,".length), "base64");
fs.writeFileSync(path.join(OUT, "render-512.png"), png);
report.imageBytes = png.byteLength;
}
report.historyCount = await page.locator('[data-testid="pbr-render-history"] img').count().catch(() => 0);
await shot("06-rendered-512");
// Chapters 7 and 8 depend on these: higher resolution, then each diagnostic
// view must visibly change the image, not just the select value.
const saveRender = async (name) => {
const url = await page.locator(".pbr-render-result img").evaluate((image) => {
const canvas = document.createElement("canvas");
canvas.width = image.naturalWidth;
canvas.height = image.naturalHeight;
canvas.getContext("2d").drawImage(image, 0, 0);
return canvas.toDataURL("image/png");
}).catch(() => "");
if (!url.startsWith("data:image/png;base64,")) return "";
const png = Buffer.from(url.slice("data:image/png;base64,".length), "base64");
fs.writeFileSync(path.join(OUT, `${name}.png`), png);
return crypto.createHash("sha256").update(png).digest("hex").slice(0, 16);
};
const rerender = async () => {
await page.locator('section[aria-label="Web PBR 渲染"]').getByRole("button", { name: /渲染 PBR/ }).first().click();
await page.waitForTimeout(1200);
await page.waitForFunction(() => {
const image = document.querySelector(".pbr-render-result img");
return image instanceof HTMLImageElement && image.complete && image.naturalWidth > 0;
}, null, { timeout: 180_000 }).catch(() => {});
await page.waitForTimeout(600);
};
report.hashes = { final512: await saveRender("render-512-final") };
await resolution.selectOption("1024").catch(() => {});
await rerender();
report.hashes.final1024 = await saveRender("render-1024-final");
report.render1024Footer = await page.locator(".pbr-render-panel footer").innerText().catch(() => "");
await shot("07-rendered-1024");
const diagnostics = page.locator('select[aria-label="PBR 诊断视图"]').first();
for (const mode of ["BASE_COLOR", "NORMAL", "ROUGHNESS"]) {
await diagnostics.selectOption(mode).catch(() => {});
await rerender();
report.hashes[mode] = await saveRender(`render-1024-${mode.toLowerCase()}`);
}
await shot("08-diagnostic-roughness");
await diagnostics.selectOption("FINAL").catch(() => {});
report.diagnosticMeshes = await page.locator('section[aria-label="Web PBR 渲染"]').getAttribute("data-diagnostic-meshes").catch(() => "");
// Chapter 9: viewport shading modes in Layout.
await page.locator(".workspace-tabs button", { hasText: "Layout" }).first().click();
await sleep(1200);
const shading = page.locator('button[aria-label="着色模式"]').first();
report.shadingStates = [];
for (let i = 0; i < 4; i++) {
report.shadingStates.push(await shading.getAttribute("title").catch(() => ""));
await shot(`09-shading-${i}`);
await shading.click().catch(() => {});
await sleep(1200);
}
// Chapter 10: save to OPFS, then reopen from the topbar recent list.
report.reopen = {};
await page.locator('button[aria-label="保存项目"]').first().click();
await page.waitForFunction(() => document.querySelector("main.blender-app")?.getAttribute("data-user-action-save-status") === "SUCCEEDED", null, { timeout: 180_000 }).catch(() => {});
await sleep(1500);
report.reopen.afterSave = await stats();
await shot("10-saved");
const recent = page.locator('[data-testid="recent-projects"]').first();
const options = await recent.locator("option").all().then(async (items) => Promise.all(items.map(async (item) => ({ value: await item.getAttribute("value"), text: await item.textContent() })))).catch(() => []);
report.reopen.recentOptions = options;
const target = options.find((option) => option.value);
if (target) {
await recent.selectOption(target.value).catch(() => {});
await sleep(4000);
await waitScene(page, { timeout: 180_000 }).catch(() => {});
report.reopen.afterReopen = await stats();
report.reopen.afterReopenStatus = await status();
await shot("11-reopened");
}
} catch (error) {
report.fatal = String(error);
await shot("99-failure").catch(() => {});
} finally {
fs.writeFileSync(path.join(OUT, "probe.json"), `${JSON.stringify(report, null, 2)}\n`);
await context.close().catch(() => {});
await browser.close().catch(() => {});
console.log(JSON.stringify(report, null, 2));
}

View File

@@ -0,0 +1,287 @@
#!/usr/bin/env node
/**
* Record the beginner narrated lesson "render the monkey head with the web
* renderer". Eleven chapters drive the real product entries only: import via
* the PBR lesson button, camera navigation buttons, the Web PBR render panel,
* the Render Result toolbar, viewport shading, OPFS save and reopen.
*
* Prepare narration first:
* python3 -I tools/web/generate-re-pbr-narration.py --mode prepare \
* --chapters tools/web/monkey-render-chapters.json \
* --out tests/golden/MONKEY-RENDER-VIDEO-001
*
* Then, with a dev server already running:
* DISPLAY=:1 CHROME_PATH=/usr/bin/google-chrome \
* node tools/web/course/record-monkey-render-video.mjs --port 5184 --gpu hardware
*
* Outputs: tests/golden/MONKEY-RENDER-VIDEO-001/{screencast.webm,timeline.json,
* record-report.json,video-steps/*.jpg}
*/
import fs from "node:fs";
import path from "node:path";
import {
REPO, parseArgs, waitForServer, launchBrowser, waitScene, installOverlay,
moveClick, domClick, sha256File,
} from "./lib/lesson-recorder.mjs";
const args = parseArgs();
const BASE = args.baseUrl || `http://127.0.0.1:${args.port}`;
const OUT = args.out;
const VIDEO_STEPS = path.join(OUT, "video-steps");
const GLB = path.join(REPO, "re/猴头.glb");
const CHAPTERS = path.join(REPO, "tools/web/monkey-render-chapters.json");
const VIEWPORT = { width: 1920, height: 1080 };
const GAP_MS = 8_000;
fs.mkdirSync(OUT, { recursive: true });
fs.mkdirSync(VIDEO_STEPS, { recursive: true });
const chapters = JSON.parse(fs.readFileSync(CHAPTERS, "utf8")).chapters;
const narrationPath = path.join(OUT, "narration.json");
if (!fs.existsSync(narrationPath)) {
console.error(`missing ${narrationPath}; run the prepare step first`);
process.exit(1);
}
const narration = JSON.parse(fs.readFileSync(narrationPath, "utf8"));
const durationOf = (id) => narration.chapters.find((chapter) => chapter.id === id)?.durationMs ?? 8_000;
const only = args.modules ? new Set(args.modules.split(",").map((item) => item.trim()).filter(Boolean)) : null;
const recordingStart = Date.now();
await waitForServer(`${BASE}/?ui=web`);
const browser = await launchBrowser(args.gpu);
const context = await browser.newContext({
viewport: VIEWPORT,
acceptDownloads: true,
recordVideo: { dir: OUT, size: VIEWPORT },
});
const page = await context.newPage();
const errors = [];
// WASM stderr (unsupported syscall) and CSP notices about the app's own inline
// styles/blob URLs are environment noise, not flow failures. Counting them made
// a complete 11-chapter run report FAILED.
const BENIGN = /unsupported syscall|style-src 'self'|connect-src 'self'|Fetch API cannot load blob:/i;
page.on("pageerror", (error) => { if (!BENIGN.test(String(error))) errors.push(String(error)); });
page.on("console", (message) => { if (message.type() === "error" && !BENIGN.test(message.text())) errors.push(message.text()); });
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const caption = async (text) => { await page.evaluate((value) => window.__lessonSetCaption?.(value), text).catch(() => {}); };
const stats = () => page.locator('[data-testid="scene-stats"]').innerText().catch(() => "");
const statusLine = () => page.locator('[data-testid="engine-status"]').innerText().catch(() => "");
const workspace = async (name) => {
await domClick(page.locator(".workspace-tabs button", { hasText: name }).first());
await sleep(900);
};
const waitObjects = async (count) => {
await page.waitForFunction((expected) => {
const text = document.querySelector('[data-testid="scene-stats"]')?.textContent ?? "";
return new RegExp(`Objects\\s*:?\\s*${expected}\\b`).test(text);
}, count, { timeout: 180_000 }).catch(() => {});
};
const pbrSettle = async (timeout = 240_000) => {
await page.waitForFunction(() => {
const image = document.querySelector(".pbr-render-result img");
return image instanceof HTMLImageElement && image.complete && image.naturalWidth > 0;
}, null, { timeout }).catch(() => {});
await sleep(500);
};
const renderPbr = async () => {
await moveClick(page, page.locator('section[aria-label="Web PBR 渲染"]').getByRole("button", { name: /渲染 PBR/ }).first());
await pbrSettle();
};
const setSelect = async (label, value) => {
await page.locator(`select[aria-label="${label}"]`).first().selectOption(value).catch(() => {});
await sleep(400);
};
const shadeButton = () => page.locator('button[aria-label="着色模式"]').first();
const actions = {
intro: async () => {
await workspace("Layout");
await page.mouse.move(960, 520);
await sleep(800);
},
workspace: async () => {
await workspace("Rendering");
await page.mouse.move(700, 120);
await sleep(1200);
await page.mouse.move(700, 430);
await sleep(1200);
},
import: async () => {
await workspace("Layout");
await page.mouse.click(760, 470);
await sleep(700);
await moveClick(page, page.locator('button[aria-label="删除对象"]').first());
await sleep(1400);
await workspace("Rendering");
const chooserPromise = page.waitForEvent("filechooser", { timeout: 60_000 });
await moveClick(page, page.getByRole("button", { name: "导入猴头 GLB", exact: true }));
const chooser = await chooserPromise;
await chooser.setFiles(GLB);
await waitObjects(3);
await sleep(4000);
},
camera: async () => {
await workspace("Layout");
await sleep(600);
await page.mouse.click(760, 470);
await sleep(600);
await moveClick(page, page.locator('button[aria-label="框显所选"]').first());
await sleep(1800);
await moveClick(page, page.locator('button[aria-label="相机对齐视图"]').first());
await sleep(1300);
await moveClick(page, page.locator('button[aria-label="相机视图"]').first());
await sleep(1800);
await moveClick(page, page.locator('button[aria-label="锁定相机"]').first());
await sleep(1200);
},
"first-render": async () => {
await workspace("Rendering");
await setSelect("PBR 渲染分辨率", "512");
await setSelect("PBR 渲染相机", "SCENE");
await setSelect("PBR 诊断视图", "FINAL");
await renderPbr();
},
result: async () => {
await workspace("Rendering");
const toggle = page.locator(".render-result-toolbar button").first();
if (await toggle.count()) {
await moveClick(page, toggle);
await sleep(1400);
await moveClick(page, toggle);
await sleep(1200);
}
const download = page.locator(".render-result-download").first();
if (await download.count()) {
await Promise.all([page.waitForEvent("download", { timeout: 30_000 }).catch(() => null), moveClick(page, download)]);
await sleep(1600);
}
},
quality: async () => {
await workspace("Rendering");
await setSelect("PBR 渲染分辨率", "1024");
await renderPbr();
await sleep(900);
await setSelect("PBR 渲染分辨率", "2048");
await renderPbr();
await sleep(900);
},
diagnostics: async () => {
await workspace("Rendering");
for (const mode of ["BASE_COLOR", "NORMAL", "ROUGHNESS", "FINAL"]) {
await setSelect("PBR 诊断视图", mode);
await renderPbr();
await sleep(800);
}
},
viewport: async () => {
await workspace("Layout");
await sleep(600);
await page.mouse.click(760, 470);
for (let index = 0; index < 4; index += 1) {
await moveClick(page, shadeButton());
await sleep(1600);
}
await page.mouse.move(960, 520);
await sleep(800);
},
storage: async () => {
await moveClick(page, page.locator('button[aria-label="保存项目"]').first());
await page.waitForFunction(() => document.querySelector("main.blender-app")?.getAttribute("data-user-action-save-status") === "SUCCEEDED", null, { timeout: 180_000 }).catch(() => {});
await sleep(1800);
const recent = page.locator('[data-testid="recent-projects"]').first();
const options = await recent.locator("option").count().catch(() => 0);
if (options > 1) {
await recent.selectOption({ index: 1 }).catch(() => {});
await waitScene(page, { timeout: 180_000 }).catch(() => {});
await sleep(2500);
}
},
limits: async () => {
await workspace("Rendering");
await page.mouse.move(700, 430);
await sleep(1200);
},
};
const timeline = [];
const report = {
schemaVersion: 1,
task: "MONKEY-RENDER-VIDEO-001",
voice: narration.voice,
startedAt: new Date().toISOString(),
viewport: VIEWPORT,
chapters: [],
errors,
};
const hideOverlay = () => page.evaluate(() => {
const root = document.getElementById("__lesson_video_overlay");
if (root) root.style.display = "none";
});
const showOverlay = () => page.evaluate(() => {
const root = document.getElementById("__lesson_video_overlay");
if (root) root.style.display = "";
});
try {
await page.goto(`${BASE}/?ui=web`, { waitUntil: "domcontentloaded" });
await page.locator("main.blender-app").waitFor({ timeout: 240_000 });
await page.waitForFunction(() => /Objects\s*:?\s*[1-9]/.test(
document.querySelector('[data-testid="scene-stats"]')?.textContent ?? ""), null, { timeout: 300_000 });
await installOverlay(page);
page.setDefaultTimeout(15_000);
for (const chapter of chapters) {
if (only && !only.has(chapter.id)) continue;
await caption(chapter.title);
await page.keyboard.press("Escape").catch(() => {});
await sleep(200);
const startMs = Date.now() - recordingStart;
const action = actions[chapter.id];
if (action) await action().catch((error) => errors.push(`${chapter.id}: ${error.message}`));
const target = startMs + durationOf(chapter.id) + GAP_MS;
const remaining = target - (Date.now() - recordingStart);
if (remaining > 0) await sleep(remaining);
const screenshotName = path.join(VIDEO_STEPS, `${chapter.id}.jpg`);
await hideOverlay();
await page.screenshot({ path: screenshotName, type: "jpeg", quality: 84 });
await showOverlay();
const endMs = Date.now() - recordingStart;
timeline.push({ id: chapter.id, title: chapter.title, startMs, endMs, screenshot: path.relative(REPO, screenshotName) });
report.chapters.push({
id: chapter.id,
title: chapter.title,
startMs,
endMs,
narrationMs: durationOf(chapter.id),
screenshot: path.relative(REPO, screenshotName),
screenshotSha256: sha256File(screenshotName),
sceneStats: await stats(),
engineStatus: await statusLine(),
});
console.log(`${chapter.id} ${startMs}-${endMs}ms`);
}
}
catch (error) {
errors.push(String(error));
await hideOverlay().catch(() => {});
await page.screenshot({ path: path.join(OUT, "record-failure.jpg"), type: "jpeg", quality: 80 }).catch(() => {});
}
finally {
const video = page.video();
await context.close().catch(() => {});
if (video) await video.saveAs(path.join(OUT, "screencast.webm")).catch((error) => errors.push(String(error)));
await browser.close().catch(() => {});
const durationMs = Date.now() - recordingStart;
const duration = Math.round((timeline.at(-1)?.endMs ?? 0) / 1000);
report.durationMs = durationMs;
report.durationSeconds = duration;
report.status = errors.length === 0 && timeline.length === chapters.length && duration >= 480 ? "PASS" : "FAILED";
report.screencast = path.relative(REPO, path.join(OUT, "screencast.webm"));
const payload = { schemaVersion: 1, task: report.task, status: report.status, durationMs, chapters: timeline, errors, screencast: report.screencast };
fs.writeFileSync(path.join(OUT, "timeline.json"), `${JSON.stringify(payload, null, 2)}\n`);
fs.writeFileSync(path.join(OUT, "record-report.json"), `${JSON.stringify({ ...report, chapters: report.chapters }, null, 2)}\n`);
console.log(JSON.stringify({ status: report.status, chapters: timeline.length, durationSeconds: duration, out: OUT }, null, 2));
if (report.status !== "PASS") process.exitCode = 1;
}

View File

@@ -0,0 +1,274 @@
#!/usr/bin/env node
/**
* Record the narrated render course (13 chapters, one per render execution path).
*
* Prepare narration first:
* python3 -I /home/mes123456/workinf_Blender_Wasm/tools/web/generate-re-pbr-narration.py \
* --mode prepare --chapters /home/mes123456/workinf_Blender_Wasm/tools/web/render-tutorial-chapters.json \
* --out /home/mes123456/workinf_Blender_Wasm/tests/golden/RENDER-TUTORIAL-001/video
*
* Then:
* DISPLAY=:1 CHROME_PATH=/usr/bin/google-chrome \
* node tools/web/course/record-render-tutorial.mjs --port 5185 --gpu hardware
*
* Outputs: tests/golden/RENDER-TUTORIAL-001/video/{screencast.webm,timeline.json,record-report.json}
*
* The four render paths have different URLs (`?ui=web`, `/`, `?ui=desktop`), and
* a browser context cannot change its origin's UI mode mid-recording, so the
* whole course is recorded against `?ui=web` and the paths that need another
* surface get their own chapter with an inline comparison. Paths B and C are
* both reachable from `?ui=web` when the server backend is absent/present; the
* recording states which surface each chapter shows rather than faking a
* surface switch that the recording cannot actually contain.
*/
import fs from "node:fs";
import path from "node:path";
import {
REPO, parseArgs, waitForServer, launchBrowser, openFile, waitScene, domClick, installOverlay, sha256File,
} from "./lib/lesson-recorder.mjs";
const args = parseArgs();
const BASE = args.baseUrl || `http://127.0.0.1:${args.port}`;
const OUT = path.join(args.out, "video");
const CHAPTERS = path.join(REPO, "tools/web/render-tutorial-chapters.json");
const SCENE = path.join(REPO, "web/app/public/tutorial/rendering/render-studio.blend");
const FINAL = path.join(REPO, "web/app/public/tutorial/rendering/video/rendering-lesson-720p.mp4");
fs.mkdirSync(OUT, { recursive: true });
fs.mkdirSync(path.dirname(FINAL), { recursive: true });
const chapters = JSON.parse(fs.readFileSync(CHAPTERS, "utf8")).chapters;
const narrationPath = path.join(OUT, "narration.json");
if (!fs.existsSync(narrationPath)) {
console.error(`missing ${narrationPath}; run --mode prepare first`);
process.exit(1);
}
const narration = JSON.parse(fs.readFileSync(narrationPath, "utf8"));
const durationOf = (id) => narration.chapters.find((chapter) => chapter.id === id)?.durationMs ?? 6000;
const only = args.modules ? new Set(args.modules.split(",").map((item) => item.trim()).filter(Boolean)) : null;
const t0 = Date.now();
await waitForServer(`${BASE}/?ui=web`);
const browser = await launchBrowser(args.gpu);
const context = await browser.newContext({ viewport: { width: 1600, height: 900 }, recordVideo: { dir: OUT, size: { width: 1600, height: 900 } } });
const page = await context.newPage();
await page.goto(`${BASE}/?ui=web`, { waitUntil: "domcontentloaded" });
await page.locator("main.blender-app").waitFor({ timeout: 180_000 });
await installOverlay(page);
page.setDefaultTimeout(8_000);
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const timeline = [];
const report = { schemaVersion: 1, task: "RENDER-TUTORIAL-001", voice: narration.voice, startedAt: new Date().toISOString(), chapters: [] };
const workspace = async (name) => {
await domClick(page.locator(".workspace-tabs button", { hasText: name }).first());
await sleep(500);
};
const caption = async (text) => { await page.evaluate((value) => window.__lessonSetCaption?.(value), text).catch(() => {}); };
const engineStatus = () => page.locator('[data-testid="engine-status"]').innerText().catch(() => "");
const waitObjects = async (objects) => {
await page.waitForFunction((count) => {
const stats = document.querySelector('[data-testid="scene-stats"]')?.textContent ?? "";
return new RegExp(`Objects\\s*:?\\s*${count}\\b`).test(stats);
}, objects, { timeout: 300_000 }).catch(() => {});
};
// The native panel is hidden inside a collapsed <details>; a hidden subtree
// makes innerText empty, so open it by clicking the React-owned summary.
const openNativePanel = async () => {
const details = page.locator("details.native-render-fallback").first();
if (!(await details.count())) return false;
if (!(await details.evaluate((element) => element.open))) {
await details.locator("summary").first().click({ force: true }).catch(() => {});
}
return page.locator(".native-render-panel").first().waitFor({ timeout: 60_000 }).then(() => true).catch(() => false);
};
const nativeOutput = () => page.locator(".native-render-panel .native-workflow-output").first()
.evaluate((element) => element.textContent ?? "").catch(() => "");
const nativeSettle = async (timeout) => {
await page.waitForFunction(() => {
const output = document.querySelector(".native-render-panel .native-workflow-output")?.textContent ?? "";
const status = document.querySelector('[data-testid="engine-status"]')?.textContent ?? "";
return /SUCCEEDED|FAILED|CANCELLED|NATIVE_RENDER_|NATIVE_PROCESS_|PYTHON|失败/.test(`${output}\n${status}`);
}, null, { timeout }).catch(() => {});
};
const renderFromMenu = async (animation) => {
await domClick(page.getByRole("button", { name: "渲染", exact: true }).first());
await page.getByRole("menuitem", { name: animation ? /渲染动画/ : /渲染图像/ }).first().click({ force: true });
await sleep(1500);
};
const pbrRender = async () => {
await workspace("Rendering");
const panel = page.locator(".pbr-render-panel").first();
if (!(await panel.count())) return;
await domClick(panel.getByRole("button", { name: /渲染 PBR/ }).first());
};
const pbrSettle = async (timeout) => {
await page.waitForFunction(() => {
const image = document.querySelector(".pbr-render-result img");
return image instanceof HTMLImageElement && image.complete && image.naturalWidth > 0;
}, null, { timeout }).catch(() => {});
};
const actions = {
intro: async () => { await workspace("Layout"); },
// Path A/B/C/D all need the practice scene; recover it if the session lost it.
// A single setInputFiles can land while the engine is still finishing its
// previous open, which surfaces later as a bare "Engine: command failed" on
// every following chapter. Retry the real open path, then verify the object
// count so a half-opened scene cannot silently continue the lesson.
"open-scene": async () => {
await workspace("Layout");
for (let attempt = 0; attempt < 3; attempt++) {
// waitScene throws on timeout; an uncaught throw here aborts the retry
// loop and the remaining chapters run against an empty scene.
await openFile(page, SCENE).catch(() => {});
await waitScene(page, { objects: 7, timeout: 120_000 }).catch(() => {});
const count = await page.locator('[data-testid="scene-stats"]').innerText().catch(() => "");
if (/Objects\s*:?\s*7\b/.test(count)) return;
await sleep(6000);
}
throw new Error(`practice scene did not open (scene-stats: ${await page.locator('[data-testid="scene-stats"]').innerText().catch(() => "")})`);
},
viewport: async () => {
await workspace("Layout");
const shading = page.locator('[aria-label*="着色"], .shading-mode button').first();
if (await shading.count()) await domClick(shading).catch(() => {});
await sleep(1500);
},
"pbr-render": async () => { await pbrRender(); await pbrSettle(180_000); },
"pbr-camera-res": async () => {
await workspace("Rendering");
const resolution = page.locator('select[aria-label="PBR 渲染分辨率"]').first();
if (await resolution.count()) for (const value of ["512", "2048"]) {
await resolution.selectOption(value).catch(() => {});
await pbrRender();
await pbrSettle(120_000);
await sleep(1200);
}
},
"pbr-diagnostics": async () => {
await workspace("Rendering");
const diagnostics = page.locator('select[aria-label="PBR 诊断视图"]').first();
if (await diagnostics.count()) for (const value of ["NORMAL", "BASE_COLOR", "ROUGHNESS"]) {
await diagnostics.selectOption(value).catch(() => {});
await pbrRender();
await pbrSettle(120_000);
await sleep(1200);
}
},
"save-reopen": async () => {
await workspace("Layout");
await domClick(page.locator('button[aria-label="保存项目"]').first());
await page.waitForFunction(() => document.querySelector("main.blender-app")?.getAttribute("data-user-action-save-status") === "SUCCEEDED", null, { timeout: 180_000 }).catch(() => {});
await sleep(1500);
await openFile(page, SCENE);
await waitScene(page, { objects: 7, timeout: 300_000 });
},
"render-settings": async () => {
await workspace("Rendering");
await renderFromMenu(true);
await openNativePanel();
const engine = page.locator('.native-render-panel select[aria-label="Engine"]').first();
if (await engine.count()) {
const options = await engine.locator("option").allTextContents().catch(() => []);
for (const name of options) { await engine.selectOption({ label: name }).catch(() => {}); await sleep(900); }
await engine.selectOption(options[0] ?? "SCENE").catch(() => {});
}
await page.keyboard.press("Escape").catch(() => {});
},
"native-frame": async () => {
await workspace("Rendering");
await renderFromMenu(false);
await openNativePanel();
await nativeSettle(300_000);
await sleep(3000);
},
"native-animation": async () => {
await workspace("Rendering");
await renderFromMenu(true);
await openNativePanel();
const panel = page.locator(".native-render-panel").first();
const format = panel.locator('select[aria-label="Format"]').first();
if (await format.count()) await format.selectOption("FFMPEG").catch(() => {});
const inputs = panel.locator('input[type="number"]');
if (await inputs.count() >= 3) {
await inputs.nth(1).fill("1").catch(() => {});
await inputs.nth(2).fill("4").catch(() => {});
}
await domClick(panel.getByRole("button", { name: "Render Animation", exact: true }).first());
await nativeSettle(420_000);
await sleep(3000);
},
// Chapters 11 and 12 are the whole point of the "four paths" story, so they
// must show the surface they describe. Same page, same video: navigating
// inside the recorded context keeps one continuous screencast.
"wasm-embedded": async () => {
await page.goto(`${BASE}/`, { waitUntil: "domcontentloaded" });
await page.locator("main.blender-app").waitFor({ timeout: 300_000 });
await installOverlay(page);
await openFile(page, SCENE);
await waitScene(page, { objects: 7, timeout: 300_000 });
await page.keyboard.press("F12");
await sleep(60_000);
},
"desktop-session": async () => {
await page.goto(`${BASE}/?ui=desktop`, { waitUntil: "domcontentloaded" });
const footer = page.locator("footer.desktop-browser-tools").first();
await footer.waitFor({ timeout: 120_000 });
await page.waitForFunction(() => /READY|FAILED|DISCONNECTED/.test(document.querySelector("footer.desktop-browser-tools")?.textContent ?? ""), null, { timeout: 300_000 }).catch(() => {});
const keyboard = page.locator("textarea.desktop-keyboard-input").first();
if (await keyboard.count()) await keyboard.focus().catch(() => {});
await sleep(2000);
await page.keyboard.press("F12");
await sleep(25_000);
},
summary: async () => {
// The last chapter compares all four paths, so return to the product face.
await page.goto(`${BASE}/?ui=web`, { waitUntil: "domcontentloaded" });
await page.locator("main.blender-app").waitFor({ timeout: 300_000 });
await installOverlay(page);
await workspace("Layout");
},
};
try {
for (const chapter of chapters) {
if (only && !only.has(chapter.id)) continue;
await page.keyboard.press("Escape").catch(() => {});
await sleep(150);
const startMs = Date.now() - t0;
await caption(chapter.title);
const action = actions[chapter.id];
if (action) await action().catch((error) => console.log(`chapter ${chapter.id} action failed: ${error.message}`));
const target = startMs + durationOf(chapter.id) + 8000;
while (Date.now() - t0 < target) await sleep(250);
const endMs = Date.now() - t0;
timeline.push({ id: chapter.id, title: chapter.title, startMs, endMs });
report.chapters.push({ id: chapter.id, title: chapter.title, startMs, endMs, narrationMs: durationOf(chapter.id), engineStatus: await engineStatus() });
console.log(`${chapter.id} ${startMs}-${endMs}ms`);
}
}
finally {
await caption("").catch(() => {});
const video = page.video();
await context.close();
await browser.close();
if (video && !only && !fs.existsSync(path.join(OUT, "screencast.webm"))) {
try { await video.saveAs(path.join(OUT, "screencast.webm")); }
catch {
// Playwright already writes the recording into recordVideo.dir at close;
// saveAs can reject once the page is gone, so adopt that file instead.
const recorded = fs.readdirSync(OUT).filter((name) => /^page@[0-9a-f]+\.webm$/.test(name))
.map((name) => ({ name, mtime: fs.statSync(path.join(OUT, name)).mtimeMs }))
.sort((a, b) => b.mtime - a.mtime)[0];
if (recorded) fs.renameSync(path.join(OUT, recorded.name), path.join(OUT, "screencast.webm"));
}
}
report.timeline = timeline;
report.finishedAt = new Date().toISOString();
if (fs.existsSync(path.join(OUT, "screencast.webm"))) report.screencastSha256 = sha256File(path.join(OUT, "screencast.webm"));
fs.writeFileSync(path.join(OUT, "timeline.json"), `${JSON.stringify({ chapters: timeline }, null, 2)}\n`);
fs.writeFileSync(path.join(OUT, "record-report.json"), `${JSON.stringify(report, null, 2)}\n`);
console.log(JSON.stringify({ chapters: report.chapters.length, out: OUT, final: FINAL }, null, 2));
}

View File

@@ -0,0 +1,199 @@
#!/usr/bin/env python3
"""Generate small COLLADA 1.4.1 fixtures for the Web Blender COLLADA import case.
Run: python3 tools/web/generate-collada-fixtures.py
Writes `web/tests/fixtures/collada/<name>.dae` plus `expected.json`, which records the
values the import path is expected to reproduce (objects, triangles, raw bounds, unit
scale). The fixtures are generated, deterministic and independent of YT2.dae.
"""
from __future__ import annotations
import json
import pathlib
ROOT = pathlib.Path(__file__).resolve().parents[2]
OUT = ROOT / "web" / "tests" / "fixtures" / "collada"
def source(geometry_id: str, positions: list[tuple[float, float, float]]) -> str:
flat = " ".join(f"{value:g}" for point in positions for value in point)
return f""" <source id="{geometry_id}-positions">
<float_array id="{geometry_id}-positions-array" count="{len(positions) * 3}">{flat}</float_array>
<technique_common>
<accessor source="#{geometry_id}-positions-array" count="{len(positions)}" stride="3">
<param name="X" type="float"/><param name="Y" type="float"/><param name="Z" type="float"/>
</accessor>
</technique_common>
</source>
"""
def geometry(geometry_id: str, positions: list[tuple[float, float, float]], triangles: list[tuple[int, int, int]]) -> str:
index_list = " ".join(str(index) for triangle in triangles for index in triangle)
return f""" <geometry id="{geometry_id}" name="{geometry_id}">
<mesh>
{source(geometry_id, positions)} <vertices id="{geometry_id}-vertices">
<input semantic="POSITION" source="#{geometry_id}-positions"/>
</vertices>
<triangles count="{len(triangles)}">
<input semantic="VERTEX" source="#{geometry_id}-vertices" offset="0"/>
<p>{index_list}</p>
</triangles>
</mesh>
</geometry>
"""
def effect(effect_id: str, color: str) -> str:
return f""" <effect id="{effect_id}">
<profile_COMMON>
<technique sid="common">
<lambert><diffuse><color>{color}</color></diffuse></lambert>
</technique>
</profile_COMMON>
</effect>
"""
def material(material_id: str, name: str, effect_id: str) -> str:
return f""" <material id="{material_id}" name="{name}">
<instance_effect url="#{effect_id}"/>
</material>
"""
def instance(geometry_id: str, material_symbol: str | None = None, material_id: str | None = None) -> str:
if material_symbol and material_id:
bind = f"""<bind_material><technique_common>
<instance_material symbol="{material_symbol}" target="#{material_id}"/>
</technique_common></bind_material>"""
else:
bind = ""
return f' <instance_geometry url="#{geometry_id}">{bind}</instance_geometry>\n'
def collada(geometries: str, effects: str, materials: str, scene: str, unit_meter: float, unit_name: str, up_axis: str) -> str:
return f"""<?xml version="1.0" encoding="utf-8"?>
<COLLADA xmlns="http://www.collada.org/2005/11/COLLADASchema" version="1.4.1">
<asset>
<contributor><author>WebBlender fixtures</author></contributor>
<created>2026-11-21T00:00:00Z</created>
<modified>2026-11-21T00:00:00Z</modified>
<unit meter="{unit_meter:g}" name="{unit_name}"/>
<up_axis>{up_axis}</up_axis>
</asset>
<library_geometries>
{geometries} </library_geometries>
<library_effects>
{effects} </library_effects>
<library_materials>
{materials} </library_materials>
<library_visual_scenes>
<visual_scene id="Scene" name="Scene">
{scene} </visual_scene>
</library_visual_scenes>
<scene><instance_visual_scene url="#Scene"/></scene>
</COLLADA>
"""
def bounds(positions: list[tuple[float, float, float]]) -> tuple[list[float], list[float]]:
minimum = [min(point[axis] for point in positions) for axis in range(3)]
maximum = [max(point[axis] for point in positions) for axis in range(3)]
return minimum, maximum
def write(name: str, text: str, expected: dict) -> None:
OUT.mkdir(parents=True, exist_ok=True)
(OUT / f"{name}.dae").write_text(text, encoding="utf-8")
expected.setdefault("file", f"{name}.dae")
print(f"wrote {name}.dae")
def main() -> None:
manifest: dict[str, dict] = {}
# 1. Minimal triangle, meters, Z-up.
tri = [(0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (0.0, 2.0, 0.0)]
text = collada(
geometry("MinimalTriangle", tri, [(0, 1, 2)]),
"", "", ' <node id="Root" name="Root">\n' + instance("MinimalTriangle") + " </node>\n",
1.0, "meter", "Z_UP")
write("triangle_minimal", text, {
"objects": 1, "triangles": 1, "vertices": 3, "materials": 0,
"raw_min": [0, 0, 0], "raw_max": [1, 2, 0], "unit_meter": 1.0,
})
manifest["triangle_minimal"] = {"objects": 1, "triangles": 1}
# 2. Nested hierarchy: parent translate, child rotate+scale, two geometries.
quad = [(0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, 1.0, 0.0), (0.0, 1.0, 0.0)]
quad_tris = [(0, 1, 2), (0, 2, 3)]
marker = [(0.0, 0.0, 0.0), (0.5, 0.0, 0.0), (0.0, 0.5, 0.0)]
scene = (
' <node id="Root" name="Root">\n'
' <translate sid="location">0 0 2</translate>\n'
+ instance("Marker")
+ ' <node id="Child" name="Child">\n'
' <rotate sid="rotationZ">0 0 1 90</rotate>\n'
' <scale sid="scale">2 2 2</scale>\n'
+ instance("Panel")
+ ' </node>\n'
' </node>\n'
)
text = collada(
geometry("Marker", marker, [(0, 1, 2)]) + geometry("Panel", quad, quad_tris),
"", "", scene, 1.0, "meter", "Z_UP")
write("nested_hierarchy", text, {
"objects": 2, "triangles": 3, "vertices": 7, "materials": 0,
"unit_meter": 1.0, "parent_translate": [0, 0, 2], "child_scale": [2, 2, 2],
})
manifest["nested_hierarchy"] = {"objects": 2, "triangles": 3}
# 3. Two materials bound per instance.
left = [(-1.0, 0.0, 0.0), (0.0, 0.0, 0.0), (0.0, 1.0, 0.0)]
right = [(0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (0.0, 1.0, 0.0)]
scene = (
' <node id="Root" name="Root">\n'
+ instance("Left", "MatRed", "Red")
+ instance("Right", "MatGreen", "Green")
+ ' </node>\n'
)
text = collada(
geometry("Left", left, [(0, 1, 2)]) + geometry("Right", right, [(0, 1, 2)]),
effect("FxRed", "1 0 0 1") + effect("FxGreen", "0 1 0 1"),
material("Red", "Red", "FxRed") + material("Green", "Green", "FxGreen"),
scene, 1.0, "meter", "Z_UP")
write("two_materials", text, {
"objects": 2, "triangles": 2, "vertices": 6, "materials": 2,
"unit_meter": 1.0, "material_colors": {"Red": [1, 0, 0, 1], "Green": [0, 1, 0, 1]},
})
manifest["two_materials"] = {"objects": 2, "triangles": 2, "materials": 2}
# 4. Millimeter units with Y-up: 1000 mm cube becomes 1 m after import.
cube_vertices = [
(0, 0, 0), (1000, 0, 0), (1000, 1000, 0), (0, 1000, 0),
(0, 0, 1000), (1000, 0, 1000), (1000, 1000, 1000), (0, 1000, 1000),
]
cube_faces = [
(0, 1, 2), (0, 2, 3), (4, 6, 5), (4, 7, 6),
(0, 4, 5), (0, 5, 1), (1, 5, 6), (1, 6, 2),
(2, 6, 7), (2, 7, 3), (3, 7, 4), (3, 4, 0),
]
text = collada(
geometry("Cube", cube_vertices, cube_faces),
"", "", ' <node id="Root" name="Root">\n' + instance("Cube") + " </node>\n",
0.001, "millimeter", "Y_UP")
write("millimeter_yup", text, {
"objects": 1, "triangles": 12, "vertices": 8, "materials": 0,
"raw_min": [0, 0, 0], "raw_max": [1000, 1000, 1000], "unit_meter": 0.001,
"expected_size_m": [1, 1, 1],
})
manifest["millimeter_yup"] = {"objects": 1, "triangles": 12, "size_m": [1, 1, 1]}
(OUT / "expected.json").write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")
print(f"wrote expected.json ({len(manifest)} fixtures) -> {OUT}")
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,160 @@
#!/usr/bin/env node
/**
* Bake the 27 workbench matcaps into raw half-float blobs the browser can bind.
*
* The source art is 512x512 half-float OpenEXR compressed with DWA. Nothing in
* the web app can decode EXR: `createImageBitmap` rejects it,
* `web/protocol/render-assets.ts:63-65` refuses the mime type, and the vendored
* three has no RGBELoader. Rather than ship a DWA decoder we convert at build
* time with `oiiotool` (OpenImageIO 2.4.17 / OpenEXR 3.1.5 on this machine) and
* emit plain half-float RGB, which `DataTexture(HalfFloatType)` binds directly.
*
* Layer split follows the desktop: `studiolight.cc:326-349` takes the layer
* literally named `diffuse` as diffuse and `specular` as specular — it is a
* name match, not channel arithmetic.
*
* Output format, little-endian:
* bytes 0..7 magic "WBMATCAP"
* uint32 width
* uint32 height
* uint32 flags bit 0 = a specular layer is present
* half[3]*w*h diffuse
* half[3]*w*h specular (present only when bit 0 is set)
*/
import { execFileSync } from "node:child_process";
import { mkdir, readFile, readdir, writeFile, unlink } from "node:fs/promises";
import path from "node:path";
import os from "node:os";
const ROOT = "/home/mes123456/workinf_Blender_Wasm";
const SOURCE_DIR = path.join(ROOT, "blender-5.2.0/release/datafiles/studiolights/matcap");
const OUTPUT_DIR = path.join(ROOT, "web/app/public/assets/studiolights/matcap");
const SIZE = 256;
const MAGIC = Buffer.from("WBMATCAP", "ascii");
const oiio = (...args) => {
try {
return execFileSync("oiiotool", args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });
} catch (error) {
throw new Error(`oiiotool ${args.join(" ")} failed: ${error.stderr ?? error.message}`);
}
};
/** Reads the `channel list:` line so a non-multilayer matcap can be detected. */
function channelNames(file) {
const info = oiio("--info", "-v", file);
const line = info.split("\n").find((entry) => entry.includes("channel list:"));
return line ? line.split("channel list:")[1].split(",").map((name) => name.trim()) : [];
}
/**
* Converts one EXR to an uncompressed half-float scanline EXR and returns the
* raw pixels. Uncompressed scanline blocks are fixed-size and in y order, so the
* only thing we have to parse is the v2 int64 offset table.
*/
async function readHalfRgb(source, channels, workDir, tag) {
const target = path.join(workDir, `${tag}.exr`);
oiio(source, "--ch", channels.join(","), "--resize", `${SIZE}x${SIZE}`,
"-d", "half", "--compression", "none", "--noautocc", "-o", target);
const buffer = await readFile(target);
await unlink(target);
if (buffer.readUInt32LE(0) !== 0x01312f76) throw new Error(`${tag}: not an EXR`);
const version = buffer.readUInt32LE(4);
if (version & 0x200) throw new Error(`${tag}: tiled EXR is not supported`);
/* Walk the header attribute list to find the terminator. */
let cursor = 8;
let dataWindow = null;
let channelCount = 0;
for (;;) {
if (buffer[cursor] === 0) { cursor += 1; break; }
const nameEnd = buffer.indexOf(0, cursor);
const name = buffer.toString("ascii", cursor, nameEnd);
const typeEnd = buffer.indexOf(0, nameEnd + 1);
const type = buffer.toString("ascii", nameEnd + 1, typeEnd);
const size = buffer.readInt32LE(typeEnd + 1);
const valueAt = typeEnd + 5;
if (name === "dataWindow") {
dataWindow = [
buffer.readInt32LE(valueAt), buffer.readInt32LE(valueAt + 4),
buffer.readInt32LE(valueAt + 8), buffer.readInt32LE(valueAt + 12),
];
}
if (name === "channels") {
/* chlist entries are null-terminated names; count them by scanning. */
let at = valueAt;
channelCount = 0;
while (buffer[at] !== 0) {
at = buffer.indexOf(0, at) + 1;
at += 16; /* pixelType + pLinear + 3 reserved + xSampling + ySampling */
channelCount += 1;
}
}
cursor = valueAt + size;
}
if (!dataWindow) throw new Error(`${tag}: no dataWindow`);
const width = dataWindow[2] - dataWindow[0] + 1;
const height = dataWindow[3] - dataWindow[1] + 1;
const rowBytes = width * channelCount * 2;
const offsets = [];
for (let index = 0; index < height; index += 1) {
offsets.push(Number(buffer.readBigUInt64LE(cursor + index * 8)));
}
const out = Buffer.alloc(width * height * 3 * 2);
for (let y = 0; y < height; y += 1) {
const blockStart = offsets[y];
const blockSize = buffer.readInt32LE(blockStart + 4);
if (blockSize !== rowBytes) {
throw new Error(`${tag}: row ${y} is ${blockSize} bytes, expected ${rowBytes}`);
}
buffer.copy(out, y * width * 3 * 2, blockStart + 8, blockStart + 8 + rowBytes);
}
return { width, height, pixels: out };
}
await mkdir(OUTPUT_DIR, { recursive: true });
const workDir = await mkdir(`${os.tmpdir()}/wbmc-${process.pid}`, { recursive: true });
const files = (await readdir(SOURCE_DIR)).filter((name) => name.endsWith(".exr")).sort();
let total = 0;
for (const file of files) {
const source = path.join(SOURCE_DIR, file);
const names = channelNames(source);
const hasLayers = names.some((name) => name.startsWith("diffuse."));
const stem = path.basename(file, ".exr");
/* Multilayer matcaps carry `diffuse.*` + `specular.*`. A single-layer file
* (check_normal+y.exr) falls back to its plain R/G/B channels and gets no
* specular layer, matching studiolight.cc:404-416. */
const diffuseChannels = hasLayers ? ["diffuse.R", "diffuse.G", "diffuse.B"]
: ["R", "G", "B"].filter((name) => names.includes(name));
if (diffuseChannels.length !== 3) {
throw new Error(`${file}: cannot find three diffuse channels in ${names.join(",")}`);
}
const specularChannels = hasLayers && names.includes("specular.R")
? ["specular.R", "specular.G", "specular.B"] : null;
const diffuse = await readHalfRgb(source, diffuseChannels, workDir, `${stem}-d`);
let specular = null;
if (specularChannels) {
specular = await readHalfRgb(source, specularChannels, workDir, `${stem}-s`);
}
const header = Buffer.alloc(20);
MAGIC.copy(header, 0);
header.writeUInt32LE(diffuse.width, 8);
header.writeUInt32LE(diffuse.height, 12);
header.writeUInt32LE(specular ? 1 : 0, 16);
const payload = specular ? Buffer.concat([diffuse.pixels, specular.pixels]) : diffuse.pixels;
const target = path.join(OUTPUT_DIR, `${stem}.bin`);
await writeFile(target, Buffer.concat([header, payload]));
total += 20 + payload.length;
console.log(`${stem}.bin ${diffuse.width}x${diffuse.height} ${specular ? "diffuse+specular" : "diffuse only"} ${(payload.length / 1024).toFixed(0)} KB`);
}
await unlink(workDir).catch(() => {});
console.log(`\n${files.length} matcaps, ${(total / 1048576).toFixed(1)} MB total`);

View File

@@ -48,8 +48,14 @@ def prepare(chapters_path, output):
chapter_id = chapter["id"]
mp3 = audio_dir / f"{chapter_id}.mp3"
wav = audio_dir / f"{chapter_id}.wav"
if not mp3.exists():
# Cache on the spoken text, not on file existence: editing a chapter's
# narration must re-synthesize instead of silently reusing stale audio.
text_stamp = audio_dir / f"{chapter_id}.text.sha256"
digest = hashlib.sha256(f"{voice}\n{chapter['narration']}".encode("utf-8")).hexdigest()
if not mp3.exists() or not text_stamp.exists() or text_stamp.read_text(encoding="utf-8").strip() != digest:
mp3.unlink(missing_ok=True)
run([str(EDGE_TTS), "--voice", voice, "--text", chapter["narration"], "--write-media", str(mp3)])
text_stamp.write_text(digest + "\n", encoding="utf-8")
if not wav.exists() or wav.stat().st_mtime < mp3.stat().st_mtime:
run([str(FFMPEG), "-y", "-hide_banner", "-loglevel", "error", "-i", str(mp3),
"-ar", str(SAMPLE_RATE), "-ac", str(CHANNELS), "-c:a", "pcm_s16le", str(wav)])
@@ -94,7 +100,7 @@ def timestamp(milliseconds):
return f"{hours:02d}:{minutes:02d}:{seconds:02d}.{ms:03d}"
def mix(output, video):
def mix(output, video, poster_ms=1000, scale="1280:720", poster_path=None):
timeline_path = output / "timeline.json"
narration_path = output / "narration.json"
if not timeline_path.exists():
@@ -133,20 +139,27 @@ def mix(output, video):
vtt = ["WEBVTT", ""]
for cue in cues:
vtt.extend([f"{timestamp(cue['startMs'])} --> {timestamp(cue['endMs'])}", f"{cue['title']}:{cue['narration']}", ""])
vtt_path = video.parent / "re-pbr-lesson.zh-Hans.vtt"
vtt_path = video.with_name(re.sub(r"-\d+p$", "", video.stem) + ".zh-Hans.vtt")
vtt_path.write_text("\n".join(vtt), encoding="utf-8")
video.parent.mkdir(parents=True, exist_ok=True)
webm_seconds = float(run([str(FFPROBE), "-v", "error", "-show_entries", "format=duration",
"-of", "default=nw=1:nk=1", str(output / "screencast.webm")]).stdout.strip())
# -shortest silently cuts to whichever input ends first. On a long screencast
# whose narration bed is shorter, that drops whole trailing chapters without
# any error (measured: 230.56 s webm -> 187.007 s output). Mux to an explicit
# target length instead, then verify the result actually matches it.
target_seconds = min(webm_seconds, total_samples / SAMPLE_RATE)
run([str(FFMPEG), "-y", "-hide_banner", "-loglevel", "error", "-i", str(output / "screencast.webm"),
"-i", str(narration_wav), "-vf", "scale=1280:720", "-c:v", "libx264", "-crf", "23", "-preset", "medium",
"-c:a", "aac", "-b:a", "128k", "-movflags", "+faststart", "-shortest", str(video)])
poster = video.parent / "poster.jpg"
poster_ms = 1000
for chapter in timeline.get("chapters", []):
if chapter.get("id") == "hq-2048":
poster_ms = max(1000, min(int(chapter.get("endMs", 0)) - 8000,
int(timeline.get("durationMs", 0)) - 2000))
"-i", str(narration_wav), "-vf", f"scale={scale}", "-c:v", "libx264", "-crf", "23", "-preset", "medium",
"-c:a", "aac", "-b:a", "128k", "-movflags", "+faststart", "-t", f"{target_seconds:.3f}", str(video)])
muxed_seconds = float(run([str(FFPROBE), "-v", "error", "-show_entries", "format=duration",
"-of", "default=nw=1:nk=1", str(video)]).stdout.strip())
if abs(muxed_seconds - target_seconds) > 2.0:
raise SystemExit(f"mux duration mismatch: target {target_seconds:.3f}s, got {muxed_seconds:.3f}s")
poster = pathlib.Path(poster_path) if poster_path else video.parent / "poster.jpg"
poster_ms = max(0, min(int(poster_ms), max(0, total_ms - 2000)))
run([str(FFMPEG), "-y", "-hide_banner", "-loglevel", "error", "-ss", f"{poster_ms / 1000:.3f}", "-i", str(video),
"-frames:v", "1", "-vf", "scale=1280:720", str(poster)])
"-frames:v", "1", "-vf", f"scale={scale}", str(poster)])
probe = run([str(FFPROBE), "-v", "error", "-show_entries",
"format=duration,size:stream=codec_type,codec_name,width,height", "-of", "json", str(video)])
(output / "video-probe.json").write_text(probe.stdout + "\n", encoding="utf-8")
@@ -171,13 +184,16 @@ def main():
parser.add_argument("--chapters", default="/home/mes123456/workinf_Blender_Wasm/tools/web/re-pbr-video-chapters.json")
parser.add_argument("--out", default="/home/mes123456/workinf_Blender_Wasm/tests/golden/RE-PBR-VIDEO-001")
parser.add_argument("--video", default="/home/mes123456/workinf_Blender_Wasm/web/app/public/tutorial/pbr/lesson/video/re-pbr-lesson-720p.mp4")
parser.add_argument("--poster-ms", type=int, default=1000)
parser.add_argument("--scale", default="1280:720", help="ffmpeg output scale, e.g. 1920:1080")
parser.add_argument("--poster", default=None, help="poster output path; defaults to <video dir>/poster.jpg")
args = parser.parse_args()
output = pathlib.Path(args.out)
output.mkdir(parents=True, exist_ok=True)
if args.mode == "prepare":
prepare(pathlib.Path(args.chapters), output)
else:
mix(output, pathlib.Path(args.video))
mix(output, pathlib.Path(args.video), args.poster_ms, args.scale, args.poster)
if __name__ == "__main__":

View File

@@ -0,0 +1,104 @@
#!/usr/bin/env node
/**
* Bake the five `studio/*.sl` presets into a TypeScript module.
*
* The desktop parser lives in
* `blender-5.2.0/source/blender/blenkernel/intern/studiolight.cc:183-226` and is
* deliberately dumb: for every key it scans all lines with
* `strstr(line, "<key> ")` — the key must be followed by exactly one space —
* and runs `atof` on the remainder. There is no version check, no comment
* syntax, no missing-key error, and a later duplicate overwrites an earlier one.
* We reproduce that literally so a preset cannot diverge from the desktop.
*
* Output is generated rather than fetched at runtime so
* `createSolidStudioMaterial()` can stay synchronous, and so the app does not
* need filesystem access to `blender-5.2.0/` outside the vite root.
*/
import { readFile, writeFile } from "node:fs/promises";
import path from "node:path";
const ROOT = "/home/mes123456/workinf_Blender_Wasm";
const SOURCE_DIR = path.join(ROOT, "blender-5.2.0/release/datafiles/studiolights/studio");
const OUTPUT = path.join(ROOT, "web/app/src/three-adapter/studio-light-presets.ts");
/** Mirrors READ_VAL: substring match on `"<id> "`, last occurrence wins. */
function readValue(lines, id, parse) {
const needle = `${id} `;
let value = null;
for (const line of lines) {
const at = line.indexOf(needle);
if (at < 0) continue;
value = parse(line.slice(at + needle.length));
}
return value;
}
const readFloat = (lines, id) => readValue(lines, id, (text) => Number.parseFloat(text) || 0);
const readInt = (lines, id) => readValue(lines, id, (text) => Number.parseInt(text, 10) || 0);
const readVec3 = (lines, id) => [
readFloat(lines, `${id}.x`) ?? 0,
readFloat(lines, `${id}.y`) ?? 0,
readFloat(lines, `${id}.z`) ?? 0,
];
/* SolidLight defaults, DNA_userdef_types.h:727-733 (used when a key is absent). */
const LIGHT_DEFAULTS = { smooth: 0, col: [0.8, 0.8, 0.8], spec: [0.8, 0.8, 0.8], vec: [0, 0, 1] };
function parseSolidLight(text) {
const lines = text.split("\n");
const lights = [];
for (let index = 0; index < 4; index += 1) {
const flag = readInt(lines, `light[${index}].flag`) ?? 0;
const light = {
smooth: readFloat(lines, `light[${index}].smooth`) ?? LIGHT_DEFAULTS.smooth,
col: readVec3(lines, `light[${index}].col`),
spec: readVec3(lines, `light[${index}].spec`),
vec: readVec3(lines, `light[${index}].vec`),
};
/* workbench_resources.cc:68 skips a light whose flag is clear. The shader
* keeps four slots, so a disabled light becomes an exact no-op instead of
* shifting the array (zero diffuse and zero specular contribute nothing). */
lights.push(flag
? light
: { smooth: 0, col: [0, 0, 0], spec: [0, 0, 0], vec: light.vec });
}
return { ambient: readVec3(lines, "light_ambient"), lights };
}
const files = ["basic.sl", "outdoor.sl", "paint.sl", "rim.sl", "studio.sl"];
const entries = [];
for (const file of files) {
const text = await readFile(path.join(SOURCE_DIR, file), "utf8");
entries.push([file, parseSolidLight(text)]);
}
const fmt = (value) => (Number.isInteger(value) ? String(value) : value.toFixed(6));
const vec = (value) => `[${value.map(fmt).join(", ")}]`;
const rig = (entry) => `{
ambient: ${vec(entry.ambient)},
lights: [
${entry.lights.map((light) => ` { smooth: ${fmt(light.smooth)}, col: ${vec(light.col)}, spec: ${vec(light.spec)}, vec: ${vec(light.vec)} },`).join("\n")}
],
}`;
const body = `import type { StudioLightRig } from "./studio-light";
/**
* GENERATED by /home/mes123456/workinf_Blender_Wasm/tools/web/generate-studiolight-presets.mjs
* Source: blender-5.2.0/release/datafiles/studiolights/studio/*.sl
* Do not edit by hand; re-run the generator instead.
*
* Keys match the desktop registry, which stores the basename *with* its
* extension (studiolight.cc:600-618) — so the UI shows "studio.sl", not "studio".
*/
export const STUDIO_LIGHT_PRESETS: Record<string, StudioLightRig> = {
${entries.map(([name, entry]) => ` "${name}": ${rig(entry)},`).join("\n")}
};
/** The internal, non-file light that desktop always lists first. */
export const STUDIO_LIGHT_PRESET_NAMES: string[] = ["Default", ...Object.keys(STUDIO_LIGHT_PRESETS)];
`;
await writeFile(OUTPUT, body, "utf8");
console.log(`wrote ${OUTPUT} (${entries.length} presets, ${body.length} bytes)`);

View File

@@ -0,0 +1,115 @@
#!/usr/bin/env python3
"""Import one desktop Blender studiolight world EXR as web environment data.
Desktop Material Preview lights from `blender-5.2.0/release/datafiles/
studiolights/world/forest.exr` (STUDIOLIGHT_WORLD_DEFAULT in
`blenkernel/intern/studiolight.cc`). The browser has no EXR decoder, so this
script decodes the EXR with the same oiiotool the datafiles were produced with,
and writes the exact float32 pixels plus a manifest.
Output:
<name>.bin "WBENV1\n" + u32 width + u32 height + RGB float32 LE, row 0 = top
<name>.json manifest: source EXR sha256, pixel-block sha256, samples
"""
import argparse
import hashlib
import json
import pathlib
import struct
import subprocess
import tempfile
import numpy as np
MAGIC = b"WBENV1\n"
def read_tiff_float(path: pathlib.Path):
"""Minimal baseline-TIFF reader for the oiiotool float RGB output."""
data = path.read_bytes()
endian = "<" if data[:2] == b"II" else ">"
if struct.unpack(endian + "H", data[2:4])[0] != 42:
raise SystemExit("not a baseline TIFF")
ifd = struct.unpack(endian + "I", data[4:8])[0]
entries = {}
count = struct.unpack(endian + "H", data[ifd:ifd + 2])[0]
for index in range(count):
offset = ifd + 2 + index * 12
tag, field_type, length = struct.unpack(endian + "HHI", data[offset:offset + 8])
raw = data[offset + 8:offset + 12]
sizes = {1: 1, 2: 1, 3: 2, 4: 4, 5: 8, 11: 4, 12: 8}
size = sizes.get(field_type, 1) * length
payload = raw if size <= 4 else data[struct.unpack(endian + "I", raw)[0]:][:size]
if field_type == 3:
entries[tag] = list(struct.unpack(endian + str(length) + "H", payload[:2 * length]))
elif field_type == 4:
entries[tag] = list(struct.unpack(endian + str(length) + "I", payload[:4 * length]))
width, height = entries[256][0], entries[257][0]
bits = entries.get(258, [32])
sample_format = entries.get(339, [1])
planar = entries.get(284, [1])[0]
if bits[0] != 32 or sample_format[0] != 3 or planar != 1:
raise SystemExit("expected one uncompressed chunky float32 TIFF")
strips = entries[273]
rows = entries.get(278, [height])[0]
rows = min(rows, height)
block = b"".join(
data[offset:offset + rows * width * 3 * 4]
for offset in strips
)
pixels = np.frombuffer(block, dtype=np.dtype(endian + "f4"))
expected = width * height * 3
if pixels.size < expected:
raise SystemExit(f"short pixel block: {pixels.size} < {expected}")
return width, height, pixels[:expected]
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--source", required=True, help="desktop world EXR path")
parser.add_argument("--output-dir", required=True)
parser.add_argument("--name", required=True, help="asset base name, e.g. forest")
args = parser.parse_args()
source = pathlib.Path(args.source)
output = pathlib.Path(args.output_dir)
output.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory() as temporary:
tiff = pathlib.Path(temporary) / "world.tiff"
subprocess.run(
["oiiotool", str(source), "--ch", "R,G,B", "-d", "float",
"--compression", "none", "-o", str(tiff)],
check=True,
)
width, height, pixels = read_tiff_float(tiff)
pixel_bytes = pixels.astype("<f4", copy=False).tobytes()
(output / f"{args.name}.bin").write_bytes(
MAGIC + struct.pack("<II", width, height) + pixel_bytes
)
def sample(x: int, y: int):
index = (y * width + x) * 3
return [x, y] + [round(float(value), 6) for value in pixels[index:index + 3]]
(output / f"{args.name}.json").write_text(json.dumps({
"name": args.name,
"source": str(source),
"sourceSha256": hashlib.sha256(source.read_bytes()).hexdigest(),
"width": width,
"height": height,
"format": "rgb-float32",
"generator": "tools/web/import-studiolight-world.py",
"decode": "oiiotool <source> --ch R,G,B -d float --compression none -o world.tiff",
"pixelsSha256": hashlib.sha256(pixel_bytes).hexdigest(),
"samples": [sample(0, 0), sample(width // 4, height // 8),
sample(width // 2, height // 2),
sample(width - 1, height - 1)],
}, indent=2) + "\n")
print(f"wrote {args.name}: {width}x{height}, "
f"{len(pixel_bytes)} bytes, sha256 {hashlib.sha256(pixel_bytes).hexdigest()}")
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,60 @@
#!/usr/bin/env node
/**
* Audit image evidence: does each file actually contain a picture?
*
* node tools/web/inspect-image.mjs <file|dir> [...] [--json] [--allow-blank]
*
* node tools/web/inspect-image.mjs web/app/public/tutorial/render-basics/evidence
* node tools/web/inspect-image.mjs /tmp/frames --json
*
* Prints width/height, alpha coverage, brightest channel and a verdict for each
* PNG; JPEGs report dimensions only. Exits 2 when a blank frame is found, which
* makes it usable as a gate in a capture pipeline.
*
* Why this exists: a render can report SUCCEEDED, write ~220 KB, and still be an
* all-transparent frame. File size proves nothing; the pixels do.
*/
import {collectImages, imageStats} from "./lib/image-stats.mjs";
const argv = process.argv.slice(2);
const json = argv.includes("--json");
const allowBlank = argv.includes("--allow-blank");
const inputs = argv.filter((item) => !item.startsWith("--"));
if (!inputs.length) {
console.error("usage: node tools/web/inspect-image.mjs <file|dir> [...] [--json] [--allow-blank]");
process.exit(1);
}
const results = collectImages(inputs).map((file) => {
try { return imageStats(file); }
catch (error) { return {path: file, verdict: "error", error: String(error?.message ?? error)}; }
});
if (json) {
console.log(JSON.stringify(results, null, 2));
}
else {
const rows = results.map((stats) => ({
file: stats.path.replace(`${process.cwd()}/`, ""),
size: stats.width ? `${stats.width}×${stats.height}` : "—",
bytes: stats.bytes ? `${Math.round(stats.bytes / 1024)} KiB` : "—",
alpha: stats.maxAlpha === null || stats.maxAlpha === undefined ? "—" : String(stats.maxAlpha),
opaque: stats.opaqueRatio === null || stats.opaqueRatio === undefined ? "—" : `${(stats.opaqueRatio * 100).toFixed(1)}%`,
rgb: stats.maxRgb === null || stats.maxRgb === undefined ? "—" : String(stats.maxRgb),
verdict: stats.verdict,
}));
const width = (key) => Math.max(4, ...rows.map((row) => String(row[key]).length));
const widths = {file: width("file"), size: width("size"), bytes: width("bytes"), alpha: width("alpha"), opaque: width("opaque"), rgb: width("rgb"), verdict: width("verdict")};
const line = (row, keys) => keys.map((key) => String(row[key]).padEnd(widths[key])).join(" ");
const keys = ["file", "size", "bytes", "alpha", "opaque", "rgb", "verdict"];
console.log(line({file: "file", size: "size", bytes: "bytes", alpha: "alpha", opaque: "opaque", rgb: "maxRGB", verdict: "verdict"}, keys));
console.log(keys.map((key) => "-".repeat(widths[key])).join(" "));
for (const row of rows) console.log(line(row, keys));
}
const blank = results.filter((stats) => stats.verdict === "transparent" || stats.verdict === "noise-only" || stats.verdict === "error");
if (blank.length) {
console.error(`\n${blank.length} image(s) contain no picture: ${blank.map((stats) => stats.path).join(", ")}`);
if (!allowBlank) process.exit(2);
}
else console.error(`\n${results.length} image(s) checked, all contain a picture.`);

View File

@@ -0,0 +1,198 @@
/**
* Image statistics for render evidence.
*
* Shared by tools/web/inspect-image.mjs, capture-render-basics.mjs and
* check-render-basics.mjs. Written because a frame whose pixels are all
* transparent still reports SUCCEEDED and still has a plausible file size:
* the only way to tell "rendered a picture" from "wrote an empty PNG" is to
* decode the pixels.
*
* Two details that were learned the hard way:
* - PNG rows carry a filter byte. Without undoing the filter every value is a
* delta against its neighbour and even a truly empty frame reports a
* handful of "opaque" pixels.
* - An empty EEVEE frame can still carry RGB values (dither noise, max 1/255).
* Alpha alone is not enough; look at maxRgb as well.
*/
import crypto from "node:crypto";
import fs from "node:fs";
import zlib from "node:zlib";
export function sha256File(file) {
return crypto.createHash("sha256").update(fs.readFileSync(file)).digest("hex");
}
const PNG_MAGIC = 0x89504e47;
const JPEG_SOF = new Set([0xc0, 0xc1, 0xc2, 0xc3, 0xc5, 0xc6, 0xc7, 0xc9, 0xca, 0xcb, 0xcd, 0xce, 0xcf]);
export function formatOf(bytes) {
if (bytes.length > 8 && bytes.readUInt32BE(0) === PNG_MAGIC) return "png";
if (bytes.length > 3 && bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) return "jpeg";
return "unknown";
}
/** Decode a non-interlaced 8-bit PNG into raw samples. Throws on anything else. */
export function decodePng(bytes) {
if (bytes.length < 8 || bytes.readUInt32BE(0) !== PNG_MAGIC) throw new Error("not a PNG");
let offset = 8;
let width = 0, height = 0, bitDepth = 0, colorType = 0, interlace = 0;
let palette = null, transparency = null;
const idat = [];
while (offset + 8 <= bytes.length) {
const length = bytes.readUInt32BE(offset);
const type = bytes.toString("ascii", offset + 4, offset + 8);
const data = bytes.subarray(offset + 8, offset + 8 + length);
if (type === "IHDR") {
width = data.readUInt32BE(0);
height = data.readUInt32BE(4);
bitDepth = data[8];
colorType = data[9];
interlace = data[12];
}
else if (type === "PLTE") palette = data;
else if (type === "tRNS") transparency = data;
else if (type === "IDAT") idat.push(data);
else if (type === "IEND") break;
offset += 12 + length;
}
if (!width || !height) throw new Error("PNG has no IHDR");
if (interlace) throw new Error("interlaced PNG is not supported");
if (bitDepth !== 8) throw new Error(`unsupported PNG bit depth ${bitDepth} (only 8 is supported)`);
const channels = {0: 1, 2: 3, 3: 1, 4: 2, 6: 4}[colorType];
if (!channels) throw new Error(`unsupported PNG color type ${colorType}`);
if (colorType === 3 && !palette) throw new Error("palette PNG without PLTE");
const raw = zlib.inflateSync(Buffer.concat(idat));
const stride = width * channels;
if (raw.length < height * (stride + 1)) throw new Error("PNG image data is truncated");
const pixels = Buffer.alloc(width * height * channels);
// Undo the per-row filter (None / Sub / Up / Average / Paeth).
for (let y = 0; y < height; y += 1) {
const filter = raw[y * (stride + 1)];
const rowIn = y * (stride + 1) + 1;
const rowOut = y * stride;
for (let index = 0; index < stride; index += 1) {
const value = raw[rowIn + index];
const left = index >= channels ? pixels[rowOut + index - channels] : 0;
const up = y ? pixels[rowOut - stride + index] : 0;
const upLeft = y && index >= channels ? pixels[rowOut - stride + index - channels] : 0;
let predictor = 0;
if (filter === 1) predictor = left;
else if (filter === 2) predictor = up;
else if (filter === 3) predictor = (left + up) >> 1;
else if (filter === 4) {
const estimate = left + up - upLeft;
const [a, b, c] = [Math.abs(estimate - left), Math.abs(estimate - up), Math.abs(estimate - upLeft)];
predictor = a <= b && a <= c ? left : b <= c ? up : upLeft;
}
pixels[rowOut + index] = (value + predictor) & 255;
}
}
return {width, height, colorType, channels, pixels, palette, transparency};
}
/** Expand any supported PNG layout to tightly packed RGBA. */
export function toRgba(image) {
const {width, height, colorType, channels, pixels, palette, transparency} = image;
const count = width * height;
const out = Buffer.alloc(count * 4);
const key = transparency && colorType === 3 ? transparency : null;
for (let index = 0; index < count; index += 1) {
const source = index * channels;
const target = index * 4;
let r, g, b, a = 255;
if (colorType === 6) { r = pixels[source]; g = pixels[source + 1]; b = pixels[source + 2]; a = pixels[source + 3]; }
else if (colorType === 2) { r = pixels[source]; g = pixels[source + 1]; b = pixels[source + 2]; }
else if (colorType === 4) { r = g = b = pixels[source]; a = pixels[source + 1]; }
else if (colorType === 0) { r = g = b = pixels[source]; }
else {
const slot = pixels[source] * 3;
r = palette[slot]; g = palette[slot + 1]; b = palette[slot + 2];
if (key && pixels[source] < key.length) a = key[pixels[source]];
}
out[target] = r; out[target + 1] = g; out[target + 2] = b; out[target + 3] = a;
}
return out;
}
/** Dimensions of a JPEG without decoding it (baseline + progressive SOF markers). */
export function jpegSize(bytes) {
let offset = 2;
while (offset + 4 <= bytes.length) {
if (bytes[offset] !== 0xff) { offset += 1; continue; }
const marker = bytes[offset + 1];
if (marker === 0xd8 || marker === 0x01 || (marker >= 0xd0 && marker <= 0xd7)) { offset += 2; continue; }
const length = bytes.readUInt16BE(offset + 2);
if (JPEG_SOF.has(marker)) {
return {height: bytes.readUInt16BE(offset + 5), width: bytes.readUInt16BE(offset + 7)};
}
offset += 2 + length;
}
throw new Error("JPEG has no SOF marker");
}
/**
* Pixels-in-the-frame verdict.
* picture — a real image: enough opaque pixels and real colour values
* transparent — alpha is (nearly) everywhere 0; nothing was drawn
* noise-only — opaque but every channel is <= 2; a cleared buffer, not a scene
*/
export function verdictOf({opaqueRatio, maxRgb}) {
if (opaqueRatio < 0.02) return "transparent";
if (maxRgb <= 2) return "noise-only";
return "picture";
}
/** Full statistics for one image file. JPEG reports dimensions only. */
export function imageStats(file) {
const bytes = fs.readFileSync(file);
const format = formatOf(bytes);
const base = {path: file, format, bytes: bytes.length, sha256: crypto.createHash("sha256").update(bytes).digest("hex")};
if (format === "jpeg") {
const {width, height} = jpegSize(bytes);
return {...base, width, height, maxAlpha: null, opaqueRatio: null, maxRgb: null, verdict: "opaque-jpeg"};
}
if (format !== "png") return {...base, width: null, height: null, verdict: "unknown-format"};
const decoded = decodePng(bytes);
const rgba = toRgba(decoded);
const pixels = decoded.width * decoded.height;
let opaque = 0, maxAlpha = 0, maxRgb = 0, lumaSum = 0;
const colours = new Set();
for (let index = 0; index < pixels; index += 1) {
const target = index * 4;
const [r, g, b, a] = [rgba[target], rgba[target + 1], rgba[target + 2], rgba[target + 3]];
if (a > maxAlpha) maxAlpha = a;
if (a > 8) opaque += 1;
const max = r > g ? (r > b ? r : b) : (g > b ? g : b);
if (max > maxRgb) maxRgb = max;
lumaSum += 0.2126 * r + 0.7152 * g + 0.0722 * b;
if (colours.size < 4096) colours.add((r << 16) | (g << 8) | b);
}
const stats = {
...base,
width: decoded.width,
height: decoded.height,
maxAlpha,
opaqueRatio: Number((opaque / pixels).toFixed(4)),
maxRgb,
meanLuma: Number((lumaSum / pixels).toFixed(2)),
distinctColors: colours.size,
};
return {...stats, verdict: verdictOf(stats)};
}
/** Directory or list of files, expanded, sorted. Missing paths are reported, not skipped. */
export function collectImages(inputs) {
const files = [];
for (const input of inputs) {
const stat = fs.existsSync(input) ? fs.statSync(input) : null;
if (!stat) { files.push(input); continue; }
if (stat.isDirectory()) {
for (const name of fs.readdirSync(input).sort()) {
if (/\.(png|jpe?g)$/i.test(name)) files.push(`${input.replace(/\/$/, "")}/${name}`);
}
}
else files.push(input);
}
return files;
}

View File

@@ -126,6 +126,124 @@ async function main() {
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 });

View File

@@ -22,23 +22,23 @@
{ "area": "Animation", "feature": "Timeline/Dope Sheet/关键帧/Action", "status": "usable", "route": "local", "chapter": "ch19" },
{ "area": "Animation", "feature": "Graph Editor/NLA/驱动器", "status": "usable", "route": "local", "note": "Graph 为简化 SVG;NLA 表单式;驱动器表达式可写、变量/目标只读", "chapter": "ch20" },
{ "area": "Animation", "feature": "Web 播放/音频", "status": "usable", "route": "local", "note": "原生持久 depsgraph 逐帧求值;音频走 WebAudio", "chapter": "ch19" },
{ "area": "Rendering", "feature": "PBR 渲染/诊断视图/PNG 手动下载", "status": "usable", "route": "local", "chapter": "ch23" },
{ "area": "Rendering", "feature": "原生 EEVEE/Cycles 渲染", "status": "usable", "route": "server", "note": "经 server Blender 渲染并回写产物", "chapter": "ch23" },
{ "area": "Compositing", "feature": "节点/连线/执行/Viewer/提交", "status": "usable", "route": "server", "note": "节点图写入 Main;WASM CPU 求值命令已接通,服务端合成渲染可用", "chapter": "ch24" },
{ "area": "Rendering", "feature": "PBR 渲染/诊断视图/PNG 手动下载", "status": "usable", "route": "local", "note": "ch23 为猴头 GLB 实操;配套 11 章中文解说视频课 /tutorial/rendering/monkey-render-lesson.html", "chapter": "ch23" },
{ "area": "Rendering", "feature": "原生 EEVEE/Cycles 渲染", "status": "usable", "route": "server", "note": "经 server Blender 渲染并回写产物", "chapter": "ch25" },
{ "area": "Compositing", "feature": "节点/连线/执行/Viewer/提交", "status": "usable", "route": "server", "note": "节点图写入 Main;WASM CPU 求值命令已接通,服务端合成渲染可用", "chapter": "ch27" },
{ "area": "Geometry Nodes", "feature": "allowlist 节点/连线/提交", "status": "usable", "route": "local", "note": "目录已扩到 40 类;Simulation Zone/Repeat/Foreach 仍为明确边界", "chapter": "ch18" },
{ "area": "Geometry Nodes", "feature": "Spreadsheet 对象/顶点/边/面/UV/属性/CSV", "status": "usable", "route": "local", "note": "可读取 GN 修改器求值后的属性域;分页替代整表截断", "chapter": "ch18" },
{ "area": "Scripting", "feature": "Text Editor/Python Console/Info", "status": "usable", "route": "local", "note": "WASM 内嵌 CPython 控制台与文本执行", "chapter": "ch26" },
{ "area": "Scripting", "feature": "Text Editor/Python Console/Info", "status": "usable", "route": "local", "note": "WASM 内嵌 CPython 控制台与文本执行", "chapter": "ch29" },
{ "area": "Files", "feature": "新建/打开/最近项目/恢复/撤销", "status": "usable", "route": "local", "chapter": "ch03" },
{ "area": "Files", "feature": "保存到 OPFS/下载 .blend/另存为/副本", "status": "usable", "route": "local", "chapter": "ch04" },
{ "area": "Files", "feature": "自动恢复点/诊断报告", "status": "usable", "route": "local", "chapter": "ch05" },
{ "area": "IO", "feature": "GLTF/GLB/OBJ/STL/PLY 导入", "status": "usable", "route": "local", "note": "新增 glTF 文件夹导入(外部 .bin/贴图);OBJ 走 OBJ 导入面板", "chapter": "ch25" },
{ "area": "IO", "feature": "浏览器 GLB/OBJ 导出", "status": "usable", "route": "local", "chapter": "ch25" },
{ "area": "IO", "feature": "USD/Alembic/FBX 导出", "status": "usable", "route": "server", "note": "USD/Alembic 由浏览器引擎导出;FBX 经 server Blender 导出并下载产物", "chapter": "ch25" },
{ "area": "IO", "feature": "图像/VFont/URDF 导入", "status": "usable", "route": "local", "chapter": "ch25" },
{ "area": "Settings", "feature": "Preferences/Keymap/区域布局/相机锁定持久化", "status": "usable", "route": "local", "chapter": "ch27" },
{ "area": "Settings", "feature": "主题预设/系统/Add-ons/键位编辑", "status": "usable", "route": "local", "note": "主题预设与 Add-ons 启停已接通;完整桌面主题颜色表与全部键位为明确边界", "chapter": "ch27" },
{ "area": "IO", "feature": "GLTF/GLB/OBJ/STL/PLY 导入", "status": "usable", "route": "local", "note": "新增 glTF 文件夹导入(外部 .bin/贴图);OBJ 走 OBJ 导入面板", "chapter": "ch28" },
{ "area": "IO", "feature": "浏览器 GLB/OBJ 导出", "status": "usable", "route": "local", "chapter": "ch28" },
{ "area": "IO", "feature": "USD/Alembic/FBX 导出", "status": "usable", "route": "server", "note": "USD/Alembic 由浏览器引擎导出;FBX 经 server Blender 导出并下载产物", "chapter": "ch28" },
{ "area": "IO", "feature": "图像/VFont/URDF 导入", "status": "usable", "route": "local", "chapter": "ch28" },
{ "area": "Settings", "feature": "Preferences/Keymap/区域布局/相机锁定持久化", "status": "usable", "route": "local", "chapter": "ch30" },
{ "area": "Settings", "feature": "主题预设/系统/Add-ons/键位编辑", "status": "usable", "route": "local", "note": "主题预设与 Add-ons 启停已接通;完整桌面主题颜色表与全部键位为明确边界", "chapter": "ch30" },
{ "area": "Simulation", "feature": "物理参数/缓存入口/播放", "status": "usable", "route": "local", "note": "参数写入 Main;Simulate Range 逐帧推进 depsgraph;重负载走 server bake", "chapter": "ch21" },
{ "area": "Sequencer", "feature": "Strip 表单/本地媒体/原生传输", "status": "usable", "route": "local", "note": "本地媒体写入 OPFS 并暂存 VFS;最终导出走 server Blender", "chapter": "ch25" },
{ "area": "Sequencer", "feature": "Strip 表单/本地媒体/原生传输", "status": "usable", "route": "local", "note": "本地媒体写入 OPFS 并暂存 VFS;最终导出走 server Blender", "chapter": "ch28" },
{ "area": "Camera", "feature": "Numpad0/Camera to View/对象作相机/自动关键帧/约束", "status": "usable", "route": "local", "chapter": "ch07" }
]
}

View File

@@ -0,0 +1,61 @@
{
"schemaVersion": 1,
"voice": "zh-CN-XiaoxiaoNeural",
"chapters": [
{
"id": "intro",
"title": "开场:用浏览器把猴头渲染出来",
"narration": "这支视频只做一件事:用 Web Blender 自己的网页渲染能力,在浏览器里把猴头渲染成一张图。整个过程不连接任何服务器,模型读取、着色器编译、出图,全部在你的浏览器里完成。你会依次做四件事:打开网页版 Blender,进入渲染工作区,导入猴头并用相机取好景,最后点一下渲染按钮拿到图片。中途遇到的每个按钮,我都会停下来指给你看。整支视频大约十分钟,你可以一边看一边跟着做;做完之后,你会得到一张可以下载的 PNG,也会知道这张图是怎么来的、边界在哪里。"
},
{
"id": "workspace",
"title": "认识渲染工作区",
"narration": "打开之后先认识界面。页面上方有一排工作区标签,布局、建模、渲染、动画,它们对应桌面 Blender 的各个工作区。点渲染这一个,进入渲染工作区。这里的布局分几块:最上面这一条是渲染结果区域,渲出来的图会显示在这里,还可以切换一比一和适应窗口;中间是 Web PBR 渲染面板,它是网页自带的渲染器,标着 three.js WebGL2 和 physical one,说明它走的是显卡实时渲染这条通路;面板里依次是视角预设、位移强度、诊断视图、曝光、分辨率和相机。请注意,渲染工作区里没有三维视口,摆相机要回到布局工作区。"
},
{
"id": "import",
"title": "导入猴头模型",
"narration": "现在导入猴头。启动工程里自带一个立方体、一台相机和一盏灯。先点一下视口里的立方体把它选中,再点快捷工具栏上的 Delete 把它删掉,否则它会正好挡在猴头的位置上。然后回到渲染工作区,找到导入猴头 G L B 按钮,点一下,在弹出的文件框里选中你本地的猴头文件。文件只在浏览器内部读取,不会上传到任何地方,这个过程没有网络请求。导入完成后看一眼底部状态栏:物体数变成三,引擎状态显示 G L B imported,当前对象是 Suzanne。如果物体数没有变化,先检查文件名后缀是不是点 G L B。"
},
{
"id": "camera",
"title": "摆好相机",
"narration": "接下来摆相机。切回布局工作区,把鼠标放到三维视口上,点一下让视口获得焦点。视口右侧有一列导航按钮:先点那个圆圈里带圆心的框显所选按钮,把猴头放到画面中间;再点圆圈带射线的对齐相机到视图按钮,让场景相机记住现在的角度;然后点相机视图按钮,画面里会出现一圈黑边,黑边以内就是相机实际拍到的范围,你会立刻知道哪些东西会被拍进去、哪些会被裁掉;最后点小锁图标的锁定相机按钮,之后你转动视角,相机也不会跟着乱跑。如果你习惯键盘,也可以用数字键盘的零进入相机视图,用小键盘的点框显所选。取好景之后,再回到渲染工作区出图。"
},
{
"id": "first-render",
"title": "第一次渲染:512",
"narration": "第一次渲染。回到 PBR 面板,先把分辨率设成五一二乘五一二,相机选场景相机,这样用的是我们刚刚摆好的那台相机;诊断视图保持最终材质,曝光保持零。然后点渲染 PBR。第一次会明显慢,因为浏览器要现场编译着色器,可能要几十秒,屏幕看起来像没反应,这不是卡死,请耐心等到图片出现。之后的渲染通常只要零点几秒。如果等了很久仍然没有图,先看面板里有没有红色报错,再检查贴图状态是不是 ready。"
},
{
"id": "result",
"title": "看结果并手动下载",
"narration": "渲染完成后,面板中间会出现图片,图片下方显示分辨率和文件大小,如果写入了浏览器存储,还会显示保存记录的编号。最上面的渲染结果区域里也能看到同一张图,点一下图片上方的按钮,可以在原始大小和适应窗口之间切换,用来检查细节。需要把图拿到本地时,点下载 PNG。注意,这是一个独立的手动动作:保存工程不会自动下载图片,网页也不会偷偷往你的下载文件夹里写文件。这条规则贯穿整个 Web Blender。"
},
{
"id": "quality",
"title": "分辨率与代价",
"narration": "再试试更高的分辨率。把分辨率改成一千零二十四,再渲染一次,画面明显更清晰,代价是渲染时间和文件大小都会增加。规律很简单:边长翻一倍,像素数是四倍。日常用法可以记成三档:五一二用来快速试构图,一零二四用来检查材质,二零四八留给最终成片。渲出来的每一张图都会记录在面板下方的本工程渲染记录里,可以随时点开对比,不用重新渲染。如果只想换个角度看看,也可以先用视口实时预览,满意了再出图。"
},
{
"id": "diagnostics",
"title": "诊断视图看材质",
"narration": "诊断视图是排查材质问题的利器。切到法线,画面会变成一张彩色图,颜色代表猴头表面每个点的朝向;如果某个地方颜色突然跳变,那里多半有法线错误。切到基础色,你看到的是材质本身的颜色,完全不带光照,用来确认颜色有没有设对。切到粗糙度,亮的区域更粗糙,暗的区域更光滑,金属和塑料的差别主要就体现在这里。调材质时最容易犯的错,是看着带光照的画面反复改颜色,越改越乱;正确顺序是先看基础色确认颜色,再看粗糙度,最后回到最终材质看整体。"
},
{
"id": "viewport",
"title": "视口着色:实时预览",
"narration": "视口着色是另一个层次的能力。注意看视口右上角的着色模式按钮,点一下就在材质、渲染、线框、实体四种显示方式之间循环,也可以直接按键盘的 Z。实体模式用的是影棚灯光,打开视口右侧的视图面板,可以换灯光预设、打开阴影、调腔体和曲率,甚至套一个 MATCAP。这些都是浏览器实时计算,转视角立刻有反馈,适合快速看形状和光影关系。但要记住:它们不是出图。视口预览会按性能做取舍,要拿到可以交付的图片,仍然要回到渲染工作区点渲染 PBR。"
},
{
"id": "storage",
"title": "渲染记录与保存",
"narration": "渲染记录保存在浏览器的 OPFS 文件系统里,按工程归档。点顶部的保存项目,工程和渲染记录一起落盘;关掉标签页,重新打开最近的工程,猴头、相机和面板设置都还在,渲染记录也还在。下载 blend 文件和下载 PNG 一样,都需要你主动点按钮。理解这一点,你就能分清三件事:浏览器存储是工作现场,下载是你主动交付,两者互不替代。"
},
{
"id": "limits",
"title": "能力边界与下一步",
"narration": "最后说清楚能力边界。这个网页渲染器叫 physical one,是给初学者练习用的实时渲染近似,不是 EEVEE 也不是 Cycles;它没有采样数、透明背景和 H D R I 这些设置,玻璃、金属的物理精度也和桌面版不同。它能稳定做出教材级的静帧,帮你理解相机、材质、分辨率和诊断视图,而且完全在浏览器里跑,打开网页就能用。需要桌面级的物理精度时,再换到原生 Blender。现在你可以打开自己的模型,按同样的步骤,渲出属于你的第一张图。"
}
]
}

View File

@@ -91,7 +91,13 @@ async function finish(entry){
await entry.process.completion;
if(entry.result)return;
if(entry.process.receipt.cancelRequested)throw new Error('NATIVE_JOB_TIMEOUT');
if(entry.process.child.exitCode!==0)throw new Error('NATIVE_PROCESS_FAILED: '+entry.stderr.slice(-4096));
if(entry.process.child.exitCode!==0){
// `Killed` in stderr says a signal ended the process, not which one or who
// sent it. Record the child's own signal and the supervisor's tree signal
// so the next occurrence identifies its source instead of being guessed at.
const receipt=entry.process.receipt,detail=`exit=${entry.process.child.exitCode} signal=${entry.process.child.signalCode??'none'} treeSignal=${receipt?.treeSignal??'none'} cancel=${receipt?.cancelRequested??false}`;
throw new Error(`NATIVE_PROCESS_FAILED[${detail}]: `+entry.stderr.slice(-4096));
}
const p=path.join(entry.workspace,'result.json');
if(fs.lstatSync(p).isSymbolicLink()||fs.statSync(p).size>2*1024*1024)throw new Error('NATIVE_RESULT_INVALID');
const result=JSON.parse(fs.readFileSync(p,'utf8'));if(result.status==='FAILED'&&typeof result.error==='string'){const code=/^([A-Z][A-Z0-9_.-]*)(?::|$)/u.exec(result.error)?.[1];if(code)result.errorCode=code;}
@@ -164,7 +170,18 @@ function launch(workspace,request,options,persistent=false,sessionWorkspace){
args.push('--setenv',`BLENDER_USER_${name.toUpperCase()}`,directory);
}
const prlimit=executable('prlimit');if(!prlimit)fail('NATIVE_RESOURCE_LIMITER_NOT_INSTALLED',503);
args.push(prlimit,'--as=8589934592','--fsize=536870912',persistent?'--cpu=7200':'--cpu=600','--');
// RLIMIT_CPU counts CPU-seconds summed over every thread, not wall time, so a
// threaded EEVEE render burns a 600 s budget in tens of seconds (measured:
// 3821 s CPU in 250 s wall on 20 cores) and dies by SIGKILL mid-animation.
// Blender's own animation render has no CPU-time cap; the job's wall-clock
// timeoutMs already bounds the run, so only guard against a CPU runaway.
// RLIMIT_AS is the address-space cap, and an FFMPEG animation render needs
// more than a still: measured 8 GiB dying with a bare `Killed` two frames in.
// Keep a bounded default but let a deployment raise it, and give renders
// headroom because encoding holds frames in memory.
const memoryLimit=Number(options.memoryBytes??process.env.BLENDER_WORKFLOW_MEMORY_BYTES??0)
|| (request.kind==='RENDER'?16*1024*1024*1024:8*1024*1024*1024);
args.push(prlimit,`--as=${Math.trunc(memoryLimit)}`,'--fsize=536870912',persistent?'--cpu=86400':'--cpu=21600','--');
const width=persistent?request.desktop?.width??1280:1280,height=persistent?request.desktop?.height??900:900;
if(gui){const xvfb=executable('xvfb-run');if(!xvfb)fail('NATIVE_VIRTUAL_DISPLAY_NOT_INSTALLED',503);args.push(xvfb,'-a',`--server-args=-screen 0 ${width}x${height}x24 -nolisten tcp`);}
if(persistent)args.push('/usr/bin/python3',path.join(ROOT,'tools/web/native-desktop-host.py'),workspace);

View File

@@ -0,0 +1,53 @@
#!/usr/bin/env node
/** One-off probe: dump the native render panel DOM after a still and an animation. */
import fs from "node:fs";
import path from "node:path";
import { REPO, parseArgs, waitForServer, launchBrowser, newPage, openFile, waitScene } from "./course/lib/lesson-recorder.mjs";
const args = parseArgs();
const BASE = args.baseUrl || `http://127.0.0.1:${args.port}`;
const SCENE = path.join(REPO, "web/app/public/tutorial/rendering/render-studio.blend");
const OUT = path.join(REPO, "tests/golden/RENDER-PATHS-001/server-native");
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
await waitForServer(`${BASE}/?ui=web`);
const browser = await launchBrowser(args.gpu);
const { context } = await newPage(browser, { baseUrl: `${BASE}/?ui=web` });
const page = context.pages()[0] ?? await context.newPage();
const log = [];
page.on("console", (message) => log.push(`${message.type()}: ${message.text()}`));
page.on("requestfailed", (request) => log.push(`requestfailed: ${request.url()} ${request.failure()?.errorText}`));
page.on("response", async (response) => {
if (!response.url().includes("/api/blender-workflow")) return;
const request = response.request();
if (request.method() !== "POST") return;
log.push(`workflow-response ${response.status()} ${response.url()}`);
});
await page.locator("main.blender-app").waitFor({ timeout: 180_000 });
await openFile(page, SCENE);
await waitScene(page, { objects: 7, timeout: 180_000 });
await page.getByRole("button", { name: "渲染", exact: true }).click({ force: true });
await page.getByRole("menuitem", { name: /渲染图像/ }).first().click();
await page.locator("details.native-render-fallback").first().evaluate((element) => { element.open = true; });
await sleep(45_000);
const still = await page.locator(".native-render-panel").evaluate((element) => element.outerHTML);
fs.writeFileSync(path.join(OUT, "probe-still.html"), still);
const stillOutput = await page.locator(".native-render-panel .native-workflow-output").innerText().catch(() => "");
const status = await page.locator('[data-testid="engine-status"]').innerText().catch(() => "");
await page.screenshot({ path: path.join(OUT, "probe-still.png") });
const panel = page.locator(".native-render-panel");
await panel.locator('select[aria-label="Format"]').selectOption("FFMPEG");
await panel.locator('input[type="number"]').nth(1).fill("1");
await panel.locator('input[type="number"]').nth(2).fill("4");
await panel.getByRole("button", { name: "Render Animation", exact: true }).click({ force: true });
await sleep(90_000);
const animation = await page.locator(".native-render-panel").evaluate((element) => element.outerHTML);
fs.writeFileSync(path.join(OUT, "probe-animation.html"), animation);
const animationOutput = await page.locator(".native-render-panel .native-workflow-output").innerText().catch(() => "");
const status2 = await page.locator('[data-testid="engine-status"]').innerText().catch(() => "");
await page.screenshot({ path: path.join(OUT, "probe-animation.png") });
fs.writeFileSync(path.join(OUT, "probe-log.txt"), log.join("\n"));
console.log(JSON.stringify({ stillOutput, status, animationOutput, status2, log: log.slice(-25) }, null, 2));
await context.close();
await browser.close();

View File

@@ -0,0 +1,112 @@
#!/usr/bin/env node
/**
* Ask the real page what is actually painted at a place, instead of trusting
* the DOM order.
*
* node tools/web/probe-ui-paint.mjs --port 5186 --url "/?ui=web" \
* [--blend <file|->] [--workspace Rendering] [--selector '<css>'] [--point x,y] [--json]
*
* For each selector it prints the element's box, which elements are on top of
* its centre and of its top strip, and the nearest scroll containers. That is
* enough to tell "the component did not render" from "the component rendered
* but something absolutely positioned is covering it".
*
* Written after a capture showed a toolbar box at y 58–83 while the quick
* toolbar's buttons were painted there: the toolbar existed and was invisible.
*/
import path from "node:path";
import {parseArgs, waitForServer, launchBrowser, newPage, openFile, waitScene} from "./course/lib/lesson-recorder.mjs";
// parseArgs only knows the course runner's flags, so tool-specific options are
// read here rather than ignored.
const argv = process.argv.slice(2);
const opt = (name, fallback) => { const index = argv.indexOf(`--${name}`); return index >= 0 && argv[index + 1] ? argv[index + 1] : fallback; };
const args = parseArgs();
const BASE = `http://127.0.0.1:${args.port}`;
const URL_PATH = opt("url", "/?ui=web");
const BLEND = opt("blend", null);
const WORKSPACE = opt("workspace", "");
const SELECTORS = opt("selector", '[data-testid="render-result-view"]').split(",").map((item) => item.trim()).filter(Boolean);
const POINTS = opt("point", "").split(";").map((item) => item.trim()).filter(Boolean);
// Selectors clicked in order before measuring, so the page can be driven into
// the state under test (open a panel, start a render) without a bespoke script.
const CLICKS = opt("click", "").split(";").map((item) => item.trim()).filter(Boolean);
await waitForServer(`${BASE}/`);
const browser = await launchBrowser(args.gpu ?? "hardware");
const {context} = await newPage(browser, {baseUrl: null});
const page = context.pages()[0] ?? await context.newPage();
await page.goto(`${BASE}${URL_PATH}`, {waitUntil: "domcontentloaded"});
await page.locator("main.blender-app").waitFor({timeout: 180_000});
if (BLEND && BLEND !== "-") {
await openFile(page, path.resolve(BLEND));
await waitScene(page, {objects: Number(args.objects ?? 7), timeout: 180_000});
}
if (WORKSPACE) {
await page.waitForFunction(() => [...document.querySelectorAll(".workspace-tab")].some((tab) => tab.getAttribute("aria-current") !== null), null, {timeout: 90_000});
await page.evaluate((name) => {
const tab = [...document.querySelectorAll(".workspace-tab")].find((element) => element.textContent === name);
if (tab instanceof HTMLElement) tab.click();
}, WORKSPACE);
await page.waitForTimeout(1500);
}
for (const selector of CLICKS) {
const target = page.locator(selector).first();
await target.waitFor({timeout: 120_000});
await target.click({force: true});
await page.waitForTimeout(Number(opt("settle", 1500)));
}
const result = await page.evaluate(({selectors, points}) => {
const describe = (element) => {
if (!element) return null;
const style = getComputedStyle(element);
return {tag: element.tagName, className: typeof element.className === "string" ? element.className : "", id: element.id || undefined,
text: (element.textContent ?? "").replace(/\s+/g, " ").trim().slice(0, 40)};
};
const box = (element) => { const rect = element.getBoundingClientRect(); return {x: Math.round(rect.x), y: Math.round(rect.y), width: Math.round(rect.width), height: Math.round(rect.height), top: Math.round(rect.top), bottom: Math.round(rect.bottom)}; };
const scrollChain = (element) => {
const chain = [];
for (let node = element.parentElement; node && node !== document.documentElement; node = node.parentElement) {
const style = getComputedStyle(node);
if (style.overflowY === "auto" || style.overflowY === "scroll") chain.push({...describe(node), scrollTop: node.scrollTop, clientHeight: node.clientHeight, scrollHeight: node.scrollHeight});
}
return chain;
};
const report = {selectors: {}, points: {}};
for (const selector of selectors) {
const element = document.querySelector(selector);
if (!element) { report.selectors[selector] = {missing: true}; continue; }
const rect = box(element);
const centre = document.elementsFromPoint(rect.x + rect.width / 2, Math.min(rect.y + rect.height / 2, window.innerHeight - 2));
const strip = document.elementsFromPoint(rect.x + Math.min(rect.width / 2, 300), Math.min(rect.y + 4, window.innerHeight - 2));
report.selectors[selector] = {
box: rect,
coveredAtCentre: !centre.includes(element),
coveredAtTop: !strip.includes(element),
onTopAtCentre: centre.slice(0, 4).map(describe),
onTopAtTop: strip.slice(0, 4).map(describe),
scrollChain: scrollChain(element),
};
}
for (const point of points) {
const [x, y] = point.split(",").map(Number);
report.points[point] = document.elementsFromPoint(x, y).slice(0, 5).map(describe);
}
return report;
}, {selectors: SELECTORS, points: POINTS});
if (args.json) console.log(JSON.stringify(result, null, 2));
else {
for (const [selector, info] of Object.entries(result.selectors)) {
console.log(selector);
if (info.missing) { console.log(" missing"); continue; }
console.log(` box x${info.box.x} y${info.box.y} ${info.box.width}×${info.box.height}`);
console.log(` covered at top: ${info.coveredAtTop}${info.coveredAtTop ? ` by ${info.onTopAtTop.map((item) => `${item.tag}.${item.className.split(" ")[0] ?? ""}`).join(" > ")}` : ""}`);
console.log(` covered at centre: ${info.coveredAtCentre}`);
for (const scroller of info.scrollChain) console.log(` scroller ${scroller.tag}.${scroller.className.split(" ")[0] ?? ""} scrollTop=${scroller.scrollTop} ${scroller.clientHeight}/${scroller.scrollHeight}`);
}
for (const [point, stack] of Object.entries(result.points)) console.log(`${point}: ${stack.map((item) => `${item.tag}.${item.className.split(" ")[0] ?? ""}`).join(" > ")}`);
}
await context.close();
await browser.close();

View File

@@ -0,0 +1,34 @@
#!/usr/bin/env node
/** Probe: console/GPU errors during an in-page (WASM) EEVEE render. */
import path from "node:path";
import { REPO, parseArgs, waitForServer, launchBrowser, newPage, openFile, waitScene } from "./course/lib/lesson-recorder.mjs";
const args = parseArgs();
const BASE = `http://127.0.0.1:${args.port}`;
const SCENE = path.join(REPO, "web/app/public/tutorial/rendering/render-studio.blend");
await waitForServer(`${BASE}/`);
const browser = await launchBrowser(args.gpu);
const { context } = await newPage(browser, { baseUrl: null });
const page = context.pages()[0] ?? await context.newPage();
const logs = [];
page.on("console", (m) => { const t = m.text().replace(/\s+/g, " "); if (!/EEVEE|eevee|shader|Shader|GPU|gpu|gl_|ERROR|error/i.test(t)) return; logs.push(`${m.type()}: ${t.slice(0, 400)}`); });
page.on("pageerror", (e) => logs.push(`pageerror: ${String(e).slice(0, 300)}`));
await page.goto(`${BASE}/`, { waitUntil: "domcontentloaded" });
await page.locator("main.blender-app").waitFor({ timeout: 120_000 });
await openFile(page, SCENE);
await waitScene(page, { objects: 7, timeout: 120_000 });
await page.waitForFunction(() => [...document.querySelectorAll(".workspace-tab")].some((t) => t.getAttribute("aria-current") !== null), null, { timeout: 90_000 });
// Ask the app's own engine directly: what does the scene say its engine is, and
// what does render.render report?
const out = await page.evaluate(async () => {
const client = globalThis.__webEngineClient;
if (!client) return { missing: true, keys: Object.keys(globalThis).filter((k) => /engine|Engine|client/i.test(k)) };
return { ok: true };
});
console.log("client", JSON.stringify(out).slice(0, 400));
console.log("LOGS", logs.length);
for (const l of logs.slice(0, 60)) console.log(l);
await context.close();
await browser.close();

View File

@@ -0,0 +1,62 @@
#!/usr/bin/env node
/** Probe: which engines produce real pixels on the WASM-embedded (default URL) path. */
import path from "node:path";
import fs from "node:fs";
import { REPO, parseArgs, waitForServer, launchBrowser, newPage, openFile, waitScene } from "./course/lib/lesson-recorder.mjs";
const args = parseArgs();
const BASE = `http://127.0.0.1:${args.port}`;
const SCENE = path.join(REPO, "web/app/public/tutorial/rendering/render-studio.blend");
const OUT = "/tmp/render-basics-probe";
fs.mkdirSync(OUT, { recursive: true });
await waitForServer(`${BASE}/`);
const browser = await launchBrowser(args.gpu);
const { context } = await newPage(browser, { baseUrl: null });
const page = context.pages()[0] ?? await context.newPage();
await page.goto(`${BASE}/`, { waitUntil: "domcontentloaded" });
await page.locator("main.blender-app").waitFor({ timeout: 120_000 });
await openFile(page, SCENE);
await waitScene(page, { objects: 7, timeout: 120_000 });
await page.waitForFunction(() => [...document.querySelectorAll(".workspace-tab")].some((t) => t.getAttribute("aria-current") !== null), null, { timeout: 90_000 });
await page.evaluate(() => { const t = [...document.querySelectorAll(".workspace-tab")].find((i) => i.textContent === "Rendering"); if (t instanceof HTMLElement) t.click(); });
await page.waitForTimeout(1500);
const toggle = page.getByTestId("native-web-tools-toggle");
if (await toggle.count() && await toggle.first().isVisible().catch(() => false)) { await toggle.first().click({ force: true }); await page.waitForTimeout(1500); }
// The React subtree holding the panel only mounts once a render hands the
// screen back (App.tsx clears gpuSurfaceOpen inside `if (stored.length)`), so
// the first F12 is what makes the panel reachable at all.
await page.evaluate(() => { if (document.activeElement instanceof HTMLElement) document.activeElement.blur(); });
await page.keyboard.press("F12");
await page.waitForFunction(() => document.querySelector(".native-render-panel") !== null, null, { timeout: 120_000 });
const details = page.locator("details.native-render-fallback").first();
await details.waitFor({ timeout: 120_000 });
if (!(await details.evaluate((e) => e.open))) await details.locator("summary").first().click({ force: true });
await page.locator(".native-render-panel").first().waitFor({ timeout: 60_000 });
for (const engine of ["SCENE", "BLENDER_WORKBENCH", "BLENDER_EEVEE"]) {
const started = Date.now();
try {
const panel = page.locator(".native-render-panel").first();
await panel.locator('select[aria-label="Engine"]').selectOption(engine);
await panel.getByRole("button", { name: "Render Frame", exact: true }).click();
await page.waitForFunction(() => {
const p = document.querySelector(".native-render-panel");
const text = p?.querySelector(".native-workflow-output")?.textContent ?? "";
if (/FAILED|CANCELLED/.test(text)) return true;
return /SUCCEEDED/.test(text) && p.querySelector(".native-workflow-artifacts a[download]") !== null;
}, null, { timeout: 240_000 });
const links = panel.locator(".native-workflow-artifacts a[download]");
const names = await links.evaluateAll((nodes) => nodes.map((n) => n.getAttribute("download") ?? ""));
const idx = names.findIndex((n) => /\.png$/i.test(n));
if (idx < 0) { console.log(engine, "no png", names); continue; }
const [dl] = await Promise.all([page.waitForEvent("download", { timeout: 60_000 }), links.nth(idx).click({ force: true })]);
const file = path.join(OUT, `wasm-${engine}.png`);
await dl.saveAs(file);
console.log(engine, "saved", file, fs.statSync(file).size, "ms", Date.now() - started);
}
catch (error) { console.log(engine, "FAIL", String(error?.message ?? error).split("\n")[0], Date.now() - started); }
}
await context.close();
await browser.close();

View File

@@ -0,0 +1,146 @@
#!/usr/bin/env node
/**
* Drive the real Web Blender UI in a headed browser and render one frame per
* engine, then judge the pixels instead of the status line.
*
* node tools/web/probe-web-engine.mjs --port 5186 # in-page WASM (/)
* node tools/web/probe-web-engine.mjs --port 5186 --path server # server Blender (/?ui=web)
* node tools/web/probe-web-engine.mjs --engines BLENDER_EEVEE --console
*
* Options: --port 5184 --gpu hardware|swiftshader --blend <file> --objects 7
* --engines SCENE,BLENDER_WORKBENCH,BLENDER_EEVEE
* --path wasm|server --out /tmp/web-engine-probe --console --json
*
* This replaces probe-wasm-engines.mjs and probe-wasm-eevee-console.mjs: the
* console lines are collected per engine, so "SUCCEEDED with an empty frame"
* comes back with the shader errors that caused it.
*
* Exit code: 0 all engines produced a picture, 1 any engine produced none.
*/
import fs from "node:fs";
import path from "node:path";
import {REPO, parseArgs, waitForServer, launchBrowser, newPage, openFile, waitScene, sha256File} from "./course/lib/lesson-recorder.mjs";
import {imageStats} from "./lib/image-stats.mjs";
// parseArgs only knows the course runner's flags, so tool-specific options are
// read here rather than silently ignored.
const argv = process.argv.slice(2);
const opt = (name, fallback) => { const index = argv.indexOf(`--${name}`); return index >= 0 && argv[index + 1] ? argv[index + 1] : fallback; };
const has = (name) => argv.includes(`--${name}`);
const args = parseArgs();
const BASE = `http://127.0.0.1:${args.port}`;
const BLEND = path.resolve(opt("blend", path.join(REPO, "web/app/public/tutorial/rendering/render-studio.blend")));
const OBJECTS = Number(opt("objects", 7));
const ENGINES = opt("engines", "SCENE,BLENDER_WORKBENCH,BLENDER_EEVEE").split(",").map((name) => name.trim()).filter(Boolean);
const PATH_KIND = opt("path", "wasm");
const OUT = path.resolve(opt("out", "/tmp/web-engine-probe"));
const TARGET = PATH_KIND === "server" ? `${BASE}/?ui=web` : `${BASE}/`;
const TIMEOUT = Number(opt("timeout", 240_000));
fs.mkdirSync(OUT, {recursive: true});
await waitForServer(`${BASE}/`);
const browser = await launchBrowser(args.gpu ?? "hardware");
const {context} = await newPage(browser, {baseUrl: null});
const page = context.pages()[0] ?? await context.newPage();
// Every console message is kept; each engine start clears the buffer so the
// errors printed below belong to that engine's render.
let logs = [];
page.on("console", (message) => logs.push(`[${message.type()}] ${message.text().replace(/\s+/g, " ").slice(0, 400)}`));
page.on("pageerror", (error) => logs.push(`[pageerror] ${String(error).slice(0, 400)}`));
const report = {base: TARGET, blend: BLEND, blendSha256: sha256File(BLEND), path: PATH_KIND, engines: [], status: "PASS", startedAt: new Date().toISOString()};
const openPanel = async () => {
const toggle = page.getByTestId("native-web-tools-toggle");
if (await toggle.count() && await toggle.first().isVisible().catch(() => false)) {
await toggle.first().click({force: true});
await page.waitForTimeout(1500);
}
// On the in-page path the React subtree holding the panel only mounts once a
// render hands the screen back, so the first F12 is what makes it reachable.
if (PATH_KIND === "wasm") {
await page.evaluate(() => { if (document.activeElement instanceof HTMLElement) document.activeElement.blur(); });
await page.keyboard.press("F12");
await page.waitForFunction(() => document.querySelector(".native-render-panel") !== null, null, {timeout: 180_000});
}
const details = page.locator("details.native-render-fallback").first();
await details.waitFor({timeout: 120_000});
if (!(await details.evaluate((element) => element.open))) await details.locator("summary").first().click({force: true});
await page.locator(".native-render-panel").first().waitFor({timeout: 60_000});
};
await page.goto(TARGET, {waitUntil: "domcontentloaded"});
await page.locator("main.blender-app").waitFor({timeout: 180_000});
await openFile(page, BLEND);
await waitScene(page, {objects: OBJECTS, timeout: 180_000});
await page.waitForFunction(() => [...document.querySelectorAll(".workspace-tab")].some((tab) => tab.getAttribute("aria-current") !== null), null, {timeout: 90_000});
await page.evaluate(() => {
const tab = [...document.querySelectorAll(".workspace-tab")].find((element) => element.textContent === "Rendering");
if (tab instanceof HTMLElement) tab.click();
});
await page.waitForTimeout(1500);
await openPanel();
// The shader-compile errors are printed the first time a program is built, which
// on the in-page path happens during the warm-up F12 above. Keep them instead of
// clearing the buffer, and slice per engine so nothing is silently dropped.
const relevant = (line) => /eevee|EEVEE|shader|Shader|GPU|gpu|compute|WebGPU|ERROR|error|unsupported/i.test(line);
report.prelude = logs.filter(relevant).slice(0, 40);
for (const engine of ENGINES) {
const started = Date.now();
const entry = {engine, status: "FAIL"};
const mark = logs.length;
try {
const panel = page.locator(".native-render-panel").first();
await panel.locator('select[aria-label="Engine"]').selectOption(engine);
await panel.getByRole("button", {name: "Render Frame", exact: true}).click();
await page.waitForFunction(() => {
const node = document.querySelector(".native-render-panel");
const text = node?.querySelector(".native-workflow-output")?.textContent ?? "";
if (/FAILED|CANCELLED/.test(text)) return true;
return /SUCCEEDED/.test(text) && node.querySelector(".native-workflow-artifacts a[download]") !== null;
}, null, {timeout: TIMEOUT});
entry.output = ((await panel.locator(".native-workflow-output").first().textContent().catch(() => "")) ?? "").trim();
const links = panel.locator(".native-workflow-artifacts a[download]");
const names = await links.evaluateAll((nodes) => nodes.map((node) => node.getAttribute("download") ?? ""));
const index = names.findIndex((name) => /\.png$/i.test(name));
if (index < 0) throw new Error(`render produced no PNG (artifacts: ${names.join(", ") || "none"})`);
const [download] = await Promise.all([page.waitForEvent("download", {timeout: 60_000}), links.nth(index).click({force: true})]);
const file = path.join(OUT, `${PATH_KIND}-${engine.toLowerCase()}.png`);
await download.saveAs(file);
entry.artifact = {path: file, bytes: fs.statSync(file).size, sha256: sha256File(file)};
entry.pixels = imageStats(file);
entry.status = entry.pixels.verdict === "picture" ? "PASS" : "BLANK";
}
catch (error) { entry.error = String(error?.message ?? error).split("\n")[0]; }
entry.ms = Date.now() - started;
entry.console = logs.slice(mark).filter(relevant).slice(0, 40);
report.engines.push(entry);
if (entry.status !== "PASS") report.status = "FAIL";
}
report.finishedAt = new Date().toISOString();
fs.writeFileSync(path.join(OUT, "probe.json"), `${JSON.stringify(report, null, 2)}\n`);
const unique = (lines) => [...new Set(lines)];
if (args.json) console.log(JSON.stringify(report, null, 2));
else {
for (const entry of report.engines) {
const pixels = entry.pixels ? `${entry.pixels.width}×${entry.pixels.height} opaque ${(entry.pixels.opaqueRatio * 100).toFixed(1)}% maxRGB ${entry.pixels.maxRgb}` : "no frame";
console.log(`${entry.engine.padEnd(18)} ${entry.status.padEnd(6)} ${String(entry.ms).padStart(7)} ms ${pixels}`);
if (entry.error) console.log(` error: ${entry.error}`);
if (has("console") && entry.console.length) for (const line of unique(entry.console)) console.log(` ${line}`);
}
// Shader programs are built once, so the compile errors that explain a blank
// frame are usually printed during warm-up rather than during the engine run.
if (has("console") && report.prelude.length) {
console.log("\nwarm-up console (first render):");
for (const line of unique(report.prelude)) console.log(` ${line}`);
}
console.log(`\n${report.status} — report: ${path.join(OUT, "probe.json")}`);
}
await context.close();
await browser.close();
process.exit(report.status === "PASS" ? 0 : 1);

View File

@@ -0,0 +1,30 @@
#!/usr/bin/env node
/** Probe: is the WebGPU compute broker available in the embedded page? */
import { parseArgs, waitForServer, launchBrowser, newPage } from "./course/lib/lesson-recorder.mjs";
const args = parseArgs();
const BASE = `http://127.0.0.1:${args.port}`;
await waitForServer(`${BASE}/`);
const browser = await launchBrowser(args.gpu);
const { context } = await newPage(browser, { baseUrl: null });
const page = context.pages()[0] ?? await context.newPage();
await page.goto(`${BASE}/`, { waitUntil: "domcontentloaded" });
await page.locator("main.blender-app").waitFor({ timeout: 120_000 });
const caps = await page.evaluate(async () => {
const out = { hasNavigatorGPU: Boolean(navigator.gpu), crossOriginIsolated: globalThis.crossOriginIsolated };
try {
const mod = globalThis.Module;
out.hasModule = Boolean(mod);
out.hasCaps = typeof mod?.webGPUComputeCapabilities === "function";
if (out.hasCaps) out.caps = mod.webGPUComputeCapabilities();
} catch (error) { out.capsError = String(error?.message ?? error); }
try {
const adapter = navigator.gpu ? await navigator.gpu.requestAdapter() : null;
out.adapter = adapter ? (adapter.info ? `${adapter.info.vendor} ${adapter.info.architecture}` : "adapter") : null;
if (adapter) out.limits = { storageBuffers: adapter.limits.maxStorageBuffersPerShaderStage, workgroups: adapter.limits.maxComputeWorkgroupsPerDimension };
} catch (error) { out.adapterError = String(error?.message ?? error); }
return out;
});
console.log(JSON.stringify(caps, null, 2));
await context.close();
await browser.close();

View File

@@ -0,0 +1,71 @@
{
"schemaVersion": 1,
"voice": "zh-CN-XiaoxiaoNeural",
"chapters": [
{
"id": "intro",
"title": "开场:这节课专门讲渲染",
"narration": "这一节课只讲一件事:渲染。我们打开一个真实的小工程,把 Web Blender 里四条能出图的通路全部走一遍。第一条是视口里的实时预览,它用显卡直接算,改一下材质马上就能看到。第二条是 PBR 渲染,它把视口的画面按你选的分辨率真正拍成一张图片。第三条是本机的原生 Blender 后端,浏览器把工程交给它,它按 Blender 自己的引擎出图,还能直接出动画视频。第四条是 WASM 内嵌渲染,用的是编译进浏览器的同一个 Blender。四条通路各有各的用处,也各有各的限制,走完之后你会知道什么时候该用哪一条。"
},
{
"id": "open-scene",
"title": "打开练习工程",
"narration": "先打开练习工程。点左上角的文件菜单,选打开,在弹出的文件选择框里选中 render-studio 这个文件。这个工程里有一台相机、四盏灯、一块地面,还有一个正在旋转的方块,一共七个物体。请留意底部的状态栏,它显示的物体数应该变成七,引擎状态里应该出现 Scene I R。这两项对上,说明几何数据真的进了浏览器,不是在显示一张旧图。工程打开之后先不要急着渲染,我们在 Layout 布局里看一眼默认的实体视图,这时看到的是灰模,因为实体视图不计算材质,它只关心形状。"
},
{
"id": "viewport",
"title": "视口实时预览与着色方式",
"narration": "把视图切到材质预览,画面立刻从灰模变成带光照的彩色。这一步没有经过任何后台任务,全部由显卡在浏览器里实时计算。你可以按住鼠标中键拖动视角,滚动滚轮缩放,画面会跟着你的操作连续变化,这就是实时预览的意义:它给你的是感觉,不是成品。再切到渲染预览,光照和阴影会更完整一些,代价是每一帧都要多算一点。新手常见的一个疑问是,预览里看到的和最后渲出来的是不是一样。答案是接近但不完全相同,预览会按性能做一些取舍,真正定稿还是要点渲染。"
},
{
"id": "pbr-render",
"title": "第一次 PBR 渲染",
"narration": "现在切到渲染工作区,找到 PBR 渲染面板。分辨率先留在一零二四,相机选择场景相机,诊断视图保持最终效果,然后点渲染 PBR。第一次渲染会明显慢一些,原因是着色器要现场编译,这一步通常要几十秒;之后再渲就只要几百毫秒了。出图之后你会看到画面里那个橙色金属方块,它有明显的反射和高光,这正是 PBR 材质在起作用。面板下方会显示这次渲染的纹理状态,只要显示 ready,就说明贴图加载成功、没有被拒绝。"
},
{
"id": "pbr-camera-res",
"title": "相机取景与分辨率对比",
"narration": "渲染之前先确认相机。面板里相机有两个选项,选场景相机,用的是工程里那台真实相机,它的位置和焦距决定了构图;选视图相机,用的是你当前视角,适合快速看效果。接着比较分辨率。把分辨率改成五一二,再渲一次,你会发现速度快了很多,但放大会看到方块边缘发软。再改成二零四八,画面清晰了,文件也大了好几倍。实际工作中,五一二用来快速试构图,一零二四用来检查材质,二零四八才用于出成片。分辨率是按平方增长的,翻一倍边长,像素数是四倍。"
},
{
"id": "pbr-diagnostics",
"title": "诊断视图看材质",
"narration": "诊断视图是排查材质问题的利器。切到法线,画面会变成一张彩色图,颜色代表方块表面的朝向,如果某个地方颜色突变,那里多半有法线错误。切到基础色,你看到的是材质本身的颜色,完全不带光照,能确认颜色有没有设对。切到粗糙度,亮的区域更粗糙,暗的区域更光滑。新手调材质最容易犯的错,是看着带光照的画面反复改颜色,越改越乱。正确做法是先看基础色确认颜色,再看粗糙度和金属度,最后才回到最终效果看整体。"
},
{
"id": "save-reopen",
"title": "保存工程并在浏览器里重开",
"narration": "渲出来的图不该只留在屏幕上。点保存项目,工程会写进浏览器的 OPFS 文件系统,这是浏览器自己的存储,关掉标签页也不会丢。注意这里的保存不会自动往你的下载文件夹塞文件,仓库的规矩是下载必须由你主动点。保存完成后,用最近项目重新打开这个工程,检查三件事:物体数还是七,材质还在,渲染面板的设置还在。这三项都对,说明你的工作过程真的被持久化了。渲染出来的图同样落在工程的 renders 目录下,重开之后依然能找到。"
},
{
"id": "render-settings",
"title": "渲染设置:引擎、格式、帧范围",
"narration": "原生后端渲染之前,先看懂渲染设置。引擎有三个选择,EEVEE 是实时引擎,速度快,适合大部分镜头;Cycles 是路径追踪,质量最高,慢得多;Workbench 是工作台引擎,适合看结构和拓扑。格式决定输出什么,选图片就得到单帧,选视频就得到动画文件。帧范围决定渲染哪一段,起始帧和结束帧都要填对,填错的话要么少渲一段,要么渲到你不需要的地方。分辨率百分比是在场景设定尺寸上再乘一个比例,百分之五十就是一零二四工程出五一二的图。"
},
{
"id": "native-frame",
"title": "用原生 Blender 渲染单帧",
"narration": "现在走第三条通路。点顶部菜单的渲染,选渲染图像,快捷键是 F12。浏览器会把当前工程打包,交给本机的 Blender 进程,由它按自己的引擎算出结果,再送回来。面板里会实时显示进度,出图之后你会看到一张真实的 Blender 渲染结果,和一个可以下载的链接。这条通路和刚才的 PBR 渲染有本质区别:PBR 渲染是显卡在浏览器里实时算的,原生渲染是真的跑了一遍 Blender。所以它的灯光、阴影、材质响应会更接近你在桌面版看到的样子,代价是要等。"
},
{
"id": "native-animation",
"title": "用原生 Blender 渲染动画",
"narration": "单帧会了,动画就是把同样的过程重复很多帧。把格式改成 FFMPEG,起始帧填一,结束帧填四,点渲染动画。这时面板会逐帧显示进度,你要做的是等,不要中途切换工作区。渲完之后会得到一个视频文件和一个逐帧压缩包,视频可以直接播放,压缩包适合后期单独处理某一帧。这里用四帧只是为了让演示快一点,真实项目把结束帧改成你的最后一帧就行。要提醒的是,动画渲染很吃时间,一零二四分辨率下每帧大约十几秒,所以先用低分辨率渲一遍看运动对不对,再上高分辨率。"
},
{
"id": "wasm-embedded",
"title": "WASM 内嵌渲染",
"narration": "接下来换一个入口,打开不带参数的默认地址,也就是不指定界面模式的那个地址。这个模式下的渲染不走服务器,而是走编译进浏览器的 WASM 版本的 Blender。也就是说,同一份 Blender 源码,一份被编译成原生程序跑在后台,一份被编译成 WebAssembly 跑在页面里。在这里按 F12,渲染由页面内部的 Python 解释器执行,出图之后同样可以看到结果和下载入口。这条通路的好处是完全不依赖后台服务,断网也能用;代价是浏览器里的算力有限,复杂场景会很慢。"
},
{
"id": "desktop-session",
"title": "桌面串流会话里的渲染",
"narration": "最后一条通路是桌面串流。打开带 ui 等于 desktop 参数的地址,页面会连上后台一个长期运行的 Blender 进程,把你在这个进程里的操作结果以画面形式传回来。在这个界面里按 F12,渲染发生在后台那个真实的 Blender 里,你在页面上看到的是它的屏幕。这条通路最接近桌面版体验,适合长时间、复杂的工作;代价是它依赖后台服务和一条稳定的连接,服务没起来就用不了。到这一步,四条通路都走完了,我们来做个对比。"
},
{
"id": "summary",
"title": "四条通路对比与已知限制",
"narration": "总结一下。视口实时预览最快,用来一边改一边看,但它不是成品。PBR 渲染把视口画面按固定分辨率拍成图片,几百毫秒一张,适合快速出图和批量比较。原生后端渲染跑的是真正的 Blender,质量最高,单帧要几十秒,动画按每帧十几秒累加,适合定稿。WASM 内嵌渲染不依赖后台服务,断网可用,但算力受限。选择的原则很简单:改材质看视口,比较方案用 PBR,定稿出片用原生后端,没有后台服务时才用内嵌。还有两点要记住,渲染音频目前是不可用的,另外所有产物都先落进工程的 OPFS,需要本地文件时要你自己点下载。"
}
]
}

View File

@@ -0,0 +1 @@
{"schemaVersion":1,"batchId":"B3","workflow":"COLLADA single feature: Apply a 0.5 Decimate modifier to every mesh; total triangles halve","nativeSession":false,"timeoutMs":180000,"sourcePaths":["web/app/src/app/App.tsx","web/app/src/app/model-convert-client.ts","web/app/src/workers/model-convert.worker.ts","web/app/src/vendor/assimp/assimpjs.js","web/app/src/engine-client/WebEngineClient.ts","blender-5.2.0/source/blender/web_engine/web_engine_api.cpp","blender-5.2.0/source/blender/web_engine/web_engine_main_state.cpp","blender-5.2.0/source/blender/web_engine/web_engine_decimate.cpp","tools/web/generate-collada-fixtures.py","blender-5.2.0/tests/python/batch_import.py"],"remainingGates":["Single-feature case; see docs/status/WBV2-COLLADA-001.md for the memory fix and remaining gaps"],"fixtures":[{"kind":"source","path":"web/tests/fixtures/collada/yt2-imported.blend","spec":"tests/e2e/collada-model-pipeline.spec.ts","grep":"COLLADA decimate reduces","scope":["Apply a 0.5 Decimate modifier to every mesh; total triangles halve"]}],"sourceSuite":"blender-5.2.0/tests/python/batch_import.py"}

View File

@@ -0,0 +1 @@
{"schemaVersion":1,"batchId":"B3","workflow":"COLLADA single feature: Native export_scene.gltf GLB download payload parses as glTF 2.0","nativeSession":false,"timeoutMs":180000,"sourcePaths":["web/app/src/app/App.tsx","web/app/src/app/model-convert-client.ts","web/app/src/workers/model-convert.worker.ts","web/app/src/vendor/assimp/assimpjs.js","web/app/src/engine-client/WebEngineClient.ts","blender-5.2.0/source/blender/web_engine/web_engine_api.cpp","blender-5.2.0/source/blender/web_engine/web_engine_main_state.cpp","blender-5.2.0/source/blender/web_engine/web_engine_decimate.cpp","tools/web/generate-collada-fixtures.py","blender-5.2.0/tests/python/batch_import.py"],"remainingGates":["Single-feature case; see docs/status/WBV2-COLLADA-001.md for the memory fix and remaining gaps"],"fixtures":[{"kind":"source","path":"web/tests/fixtures/collada/yt2-imported.blend","spec":"tests/e2e/collada-model-pipeline.spec.ts","grep":"COLLADA exports native","scope":["Native export_scene.gltf GLB download payload parses as glTF 2.0"]}],"sourceSuite":"blender-5.2.0/tests/python/batch_import.py"}

View File

@@ -0,0 +1 @@
{"schemaVersion":1,"batchId":"B3","workflow":"COLLADA single feature: generated fixture millimeter_yup imports with its expected structure","nativeSession":false,"timeoutMs":180000,"sourcePaths":["web/app/src/app/App.tsx","web/app/src/app/model-convert-client.ts","web/app/src/workers/model-convert.worker.ts","web/app/src/vendor/assimp/assimpjs.js","web/app/src/engine-client/WebEngineClient.ts","tools/web/generate-collada-fixtures.py","blender-5.2.0/tests/python/batch_import.py"],"remainingGates":["Single-feature case; expectations live in web/tests/fixtures/collada/expected.json"],"fixtures":[{"kind":"source","path":"web/tests/fixtures/collada/yt2-imported.blend","spec":"tests/e2e/collada-model-pipeline.spec.ts","grep":"COLLADA fixture millimeter_yup","scope":["Generated fixture millimeter_yup"]}],"sourceSuite":"blender-5.2.0/tests/python/batch_import.py"}

View File

@@ -0,0 +1 @@
{"schemaVersion":1,"batchId":"B3","workflow":"COLLADA single feature: generated fixture nested_hierarchy imports with its expected structure","nativeSession":false,"timeoutMs":180000,"sourcePaths":["web/app/src/app/App.tsx","web/app/src/app/model-convert-client.ts","web/app/src/workers/model-convert.worker.ts","web/app/src/vendor/assimp/assimpjs.js","web/app/src/engine-client/WebEngineClient.ts","tools/web/generate-collada-fixtures.py","blender-5.2.0/tests/python/batch_import.py"],"remainingGates":["Single-feature case; expectations live in web/tests/fixtures/collada/expected.json"],"fixtures":[{"kind":"source","path":"web/tests/fixtures/collada/yt2-imported.blend","spec":"tests/e2e/collada-model-pipeline.spec.ts","grep":"COLLADA fixture nested_hierarchy","scope":["Generated fixture nested_hierarchy"]}],"sourceSuite":"blender-5.2.0/tests/python/batch_import.py"}

View File

@@ -0,0 +1 @@
{"schemaVersion":1,"batchId":"B3","workflow":"COLLADA single feature: generated fixture triangle_minimal imports with its expected structure","nativeSession":false,"timeoutMs":180000,"sourcePaths":["web/app/src/app/App.tsx","web/app/src/app/model-convert-client.ts","web/app/src/workers/model-convert.worker.ts","web/app/src/vendor/assimp/assimpjs.js","web/app/src/engine-client/WebEngineClient.ts","tools/web/generate-collada-fixtures.py","blender-5.2.0/tests/python/batch_import.py"],"remainingGates":["Single-feature case; expectations live in web/tests/fixtures/collada/expected.json"],"fixtures":[{"kind":"source","path":"web/tests/fixtures/collada/yt2-imported.blend","spec":"tests/e2e/collada-model-pipeline.spec.ts","grep":"COLLADA fixture triangle_minimal","scope":["Generated fixture triangle_minimal"]}],"sourceSuite":"blender-5.2.0/tests/python/batch_import.py"}

View File

@@ -0,0 +1 @@
{"schemaVersion":1,"batchId":"B3","workflow":"COLLADA single feature: generated fixture two_materials imports with its expected structure","nativeSession":false,"timeoutMs":180000,"sourcePaths":["web/app/src/app/App.tsx","web/app/src/app/model-convert-client.ts","web/app/src/workers/model-convert.worker.ts","web/app/src/vendor/assimp/assimpjs.js","web/app/src/engine-client/WebEngineClient.ts","tools/web/generate-collada-fixtures.py","blender-5.2.0/tests/python/batch_import.py"],"remainingGates":["Single-feature case; expectations live in web/tests/fixtures/collada/expected.json"],"fixtures":[{"kind":"source","path":"web/tests/fixtures/collada/yt2-imported.blend","spec":"tests/e2e/collada-model-pipeline.spec.ts","grep":"COLLADA fixture two_materials","scope":["Generated fixture two_materials"]}],"sourceSuite":"blender-5.2.0/tests/python/batch_import.py"}

View File

@@ -0,0 +1 @@
{"schemaVersion":1,"batchId":"B3","workflow":"COLLADA single feature: Export GLB then re-import it through the native glTF importer","nativeSession":false,"timeoutMs":180000,"sourcePaths":["web/app/src/app/App.tsx","web/app/src/app/model-convert-client.ts","web/app/src/workers/model-convert.worker.ts","web/app/src/vendor/assimp/assimpjs.js","web/app/src/engine-client/WebEngineClient.ts","blender-5.2.0/source/blender/web_engine/web_engine_api.cpp","blender-5.2.0/source/blender/web_engine/web_engine_main_state.cpp","blender-5.2.0/source/blender/web_engine/web_engine_decimate.cpp","tools/web/generate-collada-fixtures.py","blender-5.2.0/tests/python/batch_import.py"],"remainingGates":["Single-feature case; see docs/status/WBV2-COLLADA-001.md for the memory fix and remaining gaps"],"fixtures":[{"kind":"source","path":"web/tests/fixtures/collada/yt2-imported.blend","spec":"tests/e2e/collada-model-pipeline.spec.ts","grep":"COLLADA GLB round-trip","scope":["Export GLB then re-import it through the native glTF importer"]}],"sourceSuite":"blender-5.2.0/tests/python/batch_import.py"}

View File

@@ -0,0 +1 @@
{"schemaVersion":1,"batchId":"B3","workflow":"COLLADA single feature: Clear parents and reparent 236 meshes to YT2-HA_______ without moving geometry","nativeSession":false,"timeoutMs":180000,"sourcePaths":["web/app/src/app/App.tsx","web/app/src/app/model-convert-client.ts","web/app/src/workers/model-convert.worker.ts","web/app/src/vendor/assimp/assimpjs.js","web/app/src/engine-client/WebEngineClient.ts","blender-5.2.0/source/blender/web_engine/web_engine_api.cpp","blender-5.2.0/source/blender/web_engine/web_engine_main_state.cpp","blender-5.2.0/source/blender/web_engine/web_engine_decimate.cpp","tools/web/generate-collada-fixtures.py","blender-5.2.0/tests/python/batch_import.py"],"remainingGates":["Single-feature case; see docs/status/WBV2-COLLADA-001.md for the memory fix and remaining gaps"],"fixtures":[{"kind":"source","path":"web/tests/fixtures/collada/yt2-imported.blend","spec":"tests/e2e/collada-model-pipeline.spec.ts","grep":"COLLADA hierarchy reparents","scope":["Clear parents and reparent 236 meshes to YT2-HA_______ without moving geometry"]}],"sourceSuite":"blender-5.2.0/tests/python/batch_import.py"}

View File

@@ -0,0 +1 @@
{"schemaVersion":1,"batchId":"B3","workflow":"COLLADA single feature: Import doc2/YT2.dae: 238 objects / 236 meshes / 133,926 tris / hierarchy / bounds","nativeSession":false,"timeoutMs":180000,"sourcePaths":["web/app/src/app/App.tsx","web/app/src/app/model-convert-client.ts","web/app/src/workers/model-convert.worker.ts","web/app/src/vendor/assimp/assimpjs.js","web/app/src/engine-client/WebEngineClient.ts","blender-5.2.0/source/blender/web_engine/web_engine_api.cpp","blender-5.2.0/source/blender/web_engine/web_engine_main_state.cpp","blender-5.2.0/source/blender/web_engine/web_engine_decimate.cpp","tools/web/generate-collada-fixtures.py","blender-5.2.0/tests/python/batch_import.py"],"remainingGates":["Single-feature case; see docs/status/WBV2-COLLADA-001.md for the memory fix and remaining gaps"],"fixtures":[{"kind":"source","path":"web/tests/fixtures/collada/yt2-imported.blend","spec":"tests/e2e/collada-model-pipeline.spec.ts","grep":"COLLADA import assembles","scope":["Import doc2/YT2.dae: 238 objects / 236 meshes / 133,926 tris / hierarchy / bounds"]}],"sourceSuite":"blender-5.2.0/tests/python/batch_import.py"}

View File

@@ -0,0 +1 @@
{"schemaVersion":1,"batchId":"B3","workflow":"COLLADA single feature: Assign one material to every mesh mesh-data slot","nativeSession":false,"timeoutMs":180000,"sourcePaths":["web/app/src/app/App.tsx","web/app/src/app/model-convert-client.ts","web/app/src/workers/model-convert.worker.ts","web/app/src/vendor/assimp/assimpjs.js","web/app/src/engine-client/WebEngineClient.ts","blender-5.2.0/source/blender/web_engine/web_engine_api.cpp","blender-5.2.0/source/blender/web_engine/web_engine_main_state.cpp","blender-5.2.0/source/blender/web_engine/web_engine_decimate.cpp","tools/web/generate-collada-fixtures.py","blender-5.2.0/tests/python/batch_import.py"],"remainingGates":["Single-feature case; see docs/status/WBV2-COLLADA-001.md for the memory fix and remaining gaps"],"fixtures":[{"kind":"source","path":"web/tests/fixtures/collada/yt2-imported.blend","spec":"tests/e2e/collada-model-pipeline.spec.ts","grep":"COLLADA material assignment","scope":["Assign one material to every mesh mesh-data slot"]}],"sourceSuite":"blender-5.2.0/tests/python/batch_import.py"}

View File

@@ -0,0 +1 @@
{"schemaVersion":1,"batchId":"B3","workflow":"COLLADA import through assimpjs -> native glTF assembly -> hierarchy -> set origin -> decimate -> material -> native glTF 2.0 export","nativeSession":false,"timeoutMs":900000,"sourcePaths":["web/app/src/app/App.tsx","web/app/src/app/model-convert-client.ts","web/app/src/workers/model-convert.worker.ts","web/app/src/vendor/assimp/assimpjs.js","web/app/src/engine-client/WebEngineClient.ts","blender-5.2.0/source/blender/web_engine/web_engine_api.cpp","blender-5.2.0/source/blender/web_engine/web_engine_main_state.cpp","blender-5.2.0/source/blender/web_engine/web_engine_decimate.cpp","blender-5.2.0/source/blender/editors/object/object_transform.cc","tools/web/generate-collada-fixtures.py"],"remainingGates":["COLLADA unit/up-axis parity is asserted against computed DAE bounds, not a desktop Collada oracle (Blender 5.2 has no COLLADA importer)","Native decimate totals compared with the pre-import triangle count, not a desktop replay","Origin median verified against the arithmetic vertex mean used by desktop ORIGIN_GEOMETRY","Native GLB export round-trips through the native glTF importer"],"fixtures":[{"kind":"minimal","path":"blender-5.2.0/tests/files/io_tests/empty.blend","spec":"tests/e2e/collada-model-pipeline.spec.ts","grep":"YT2.dae imports","scope":["COLLADA import through assimpjs and native GLB assembly","hierarchy clear/re-parent round-trip","origin to geometry median","batch decimate over selected meshes","batch material assignment","native glTF 2.0 export download","save/reopen and GLB re-import","truncated COLLADA rejection without Main mutation"]},{"kind":"production","path":"blender-5.2.0/tests/files/web/basic_scene.blend","spec":"tests/e2e/collada-model-pipeline.spec.ts","grep":"YT2.dae imports","scope":["production COLLADA asset doc2/YT2.dae","full six-step workflow","native export round-trip"]}]}

View File

@@ -0,0 +1 @@
{"schemaVersion":1,"batchId":"B3","workflow":"COLLADA single feature: Truncated COLLADA is rejected without mutating Main or history","nativeSession":false,"timeoutMs":180000,"sourcePaths":["web/app/src/app/App.tsx","web/app/src/app/model-convert-client.ts","web/app/src/workers/model-convert.worker.ts","web/app/src/vendor/assimp/assimpjs.js","web/app/src/engine-client/WebEngineClient.ts","blender-5.2.0/source/blender/web_engine/web_engine_api.cpp","blender-5.2.0/source/blender/web_engine/web_engine_main_state.cpp","blender-5.2.0/source/blender/web_engine/web_engine_decimate.cpp","tools/web/generate-collada-fixtures.py","blender-5.2.0/tests/python/batch_import.py"],"remainingGates":["Single-feature case; see docs/status/WBV2-COLLADA-001.md for the memory fix and remaining gaps"],"fixtures":[{"kind":"source","path":"web/tests/fixtures/collada/yt2-imported.blend","spec":"tests/e2e/collada-model-pipeline.spec.ts","grep":"COLLADA truncated input","scope":["Truncated COLLADA is rejected without mutating Main or history"]}],"sourceSuite":"blender-5.2.0/tests/python/batch_import.py"}

View File

@@ -0,0 +1 @@
{"schemaVersion":1,"batchId":"B3","workflow":"COLLADA single feature: Save through the OPFS entry and reopen from the recent-project list","nativeSession":false,"timeoutMs":180000,"sourcePaths":["web/app/src/app/App.tsx","web/app/src/app/model-convert-client.ts","web/app/src/workers/model-convert.worker.ts","web/app/src/vendor/assimp/assimpjs.js","web/app/src/engine-client/WebEngineClient.ts","blender-5.2.0/source/blender/web_engine/web_engine_api.cpp","blender-5.2.0/source/blender/web_engine/web_engine_main_state.cpp","blender-5.2.0/source/blender/web_engine/web_engine_decimate.cpp","tools/web/generate-collada-fixtures.py","blender-5.2.0/tests/python/batch_import.py"],"remainingGates":["Single-feature case; see docs/status/WBV2-COLLADA-001.md for the memory fix and remaining gaps"],"fixtures":[{"kind":"source","path":"web/tests/fixtures/collada/yt2-imported.blend","spec":"tests/e2e/collada-model-pipeline.spec.ts","grep":"COLLADA saves to OPFS","scope":["Save through the OPFS entry and reopen from the recent-project list"]}],"sourceSuite":"blender-5.2.0/tests/python/batch_import.py"}

View File

@@ -0,0 +1 @@
{"schemaVersion":1,"batchId":"B3","workflow":"COLLADA single feature: Set origin to geometry (median) for all meshes; world bounds unchanged","nativeSession":false,"timeoutMs":180000,"sourcePaths":["web/app/src/app/App.tsx","web/app/src/app/model-convert-client.ts","web/app/src/workers/model-convert.worker.ts","web/app/src/vendor/assimp/assimpjs.js","web/app/src/engine-client/WebEngineClient.ts","blender-5.2.0/source/blender/web_engine/web_engine_api.cpp","blender-5.2.0/source/blender/web_engine/web_engine_main_state.cpp","blender-5.2.0/source/blender/web_engine/web_engine_decimate.cpp","tools/web/generate-collada-fixtures.py","blender-5.2.0/tests/python/batch_import.py"],"remainingGates":["Single-feature case; see docs/status/WBV2-COLLADA-001.md for the memory fix and remaining gaps"],"fixtures":[{"kind":"source","path":"web/tests/fixtures/collada/yt2-imported.blend","spec":"tests/e2e/collada-model-pipeline.spec.ts","grep":"COLLADA origin uses","scope":["Set origin to geometry (median) for all meshes; world bounds unchanged"]}],"sourceSuite":"blender-5.2.0/tests/python/batch_import.py"}

View File

@@ -0,0 +1 @@
{"schemaVersion":1,"batchId":"B3","workflow":"COLLADA single feature: origin edits restore through native undo and redo","nativeSession":false,"timeoutMs":180000,"sourcePaths":["web/app/src/app/App.tsx","web/app/src/engine-client/WebEngineClient.ts","blender-5.2.0/source/blender/web_engine/web_engine_api.cpp","blender-5.2.0/source/blender/web_engine/web_engine_main_state.cpp","blender-5.2.0/tests/python/batch_import.py"],"remainingGates":["Single-feature case; history rebuild-from-Main path"],"fixtures":[{"kind":"source","path":"web/tests/fixtures/collada/yt2-imported.blend","spec":"tests/e2e/collada-model-pipeline.spec.ts","grep":"COLLADA edits undo","scope":["Origin edits restore through native undo and redo"]}],"sourceSuite":"blender-5.2.0/tests/python/batch_import.py"}