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>
316 lines
18 KiB
TypeScript
316 lines
18 KiB
TypeScript
import { expect, test, type Page } from "@playwright/test";
|
|
import fs from "node:fs";
|
|
import path from "node:path";
|
|
import { exposeWebTools, observeNative } from "../fixtures/native-ui-workflow";
|
|
|
|
const root = path.resolve(import.meta.dirname, "../../..");
|
|
const outputDir = path.join(root, "tests/golden/WEB-ENVIRONMENT-CAMERA-VIEW-20261122");
|
|
fs.mkdirSync(outputDir, { recursive: true });
|
|
|
|
type WorldSnapshot = {
|
|
revision: number;
|
|
worlds: Array<{ id: string; environmentRotation?: number | null; environmentImageId?: string | null; environmentStrength?: number | null }>;
|
|
images: Array<{ id: string; name: string }>;
|
|
};
|
|
|
|
async function readSnapshot(page: Page): Promise<WorldSnapshot> {
|
|
return page.evaluate(() => new Promise<WorldSnapshot>((resolve, reject) => {
|
|
const worker = (window as unknown as { __nativeWorkflowEngine: Worker }).__nativeWorkflowEngine;
|
|
const requestId = `camera-${Date.now()}-${Math.random().toString(16).slice(2)}`;
|
|
const timer = setTimeout(() => { worker.removeEventListener("message", onMessage); reject(new Error("snapshot timeout")); }, 30_000);
|
|
const onMessage = ({ data }: MessageEvent) => {
|
|
if (data?.requestId !== requestId) return;
|
|
clearTimeout(timer);
|
|
worker.removeEventListener("message", onMessage);
|
|
resolve(data?.result?.snapshot as WorldSnapshot);
|
|
};
|
|
worker.addEventListener("message", onMessage);
|
|
worker.postMessage({ requestId, command: { type: "snapshot" } });
|
|
}));
|
|
}
|
|
|
|
async function setInputValue(page: Page, label: string, value: string): Promise<void> {
|
|
await page.locator(`[aria-label="${label}"]`).first().evaluate((element, next) => {
|
|
const input = element as HTMLInputElement;
|
|
Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, next);
|
|
input.dispatchEvent(new Event("input", { bubbles: true }));
|
|
input.dispatchEvent(new Event("change", { bubbles: true }));
|
|
}, value);
|
|
}
|
|
|
|
/** Grab the rendered viewport pixels (the canvas keeps its drawing buffer). */
|
|
async function captureCanvas(page: Page, selector = "canvas[data-studio-lighting]"): Promise<{ width: number; height: number; data: number[] }> {
|
|
return page.evaluate((query) => {
|
|
const canvas = document.querySelector<HTMLCanvasElement>(query)!;
|
|
const copy = document.createElement("canvas");
|
|
copy.width = canvas.width; copy.height = canvas.height;
|
|
const context = copy.getContext("2d", { willReadFrequently: true })!;
|
|
context.drawImage(canvas, 0, 0);
|
|
const image = context.getImageData(0, 0, copy.width, copy.height);
|
|
return { width: copy.width, height: copy.height, data: Array.from(image.data) };
|
|
}, selector);
|
|
}
|
|
|
|
test("camera view: world background is the environment map and follows the world rotation", async ({ page }) => {
|
|
test.setTimeout(300_000);
|
|
await observeNative(page);
|
|
await page.goto("/?ui=web");
|
|
await page.getByTestId("blend-file-input").setInputFiles(path.join(root, "tests/files/web/basic_scene.blend"));
|
|
await expect(page.getByTestId("engine-status")).toContainText(/SceneIR r\d+/, { timeout: 120_000 });
|
|
await exposeWebTools(page);
|
|
|
|
const canvas = page.locator("canvas[data-studio-lighting]").first();
|
|
|
|
/* Scene World with an environment image: the map is both light and the
|
|
* camera-view background (desktop world background). */
|
|
await page.getByLabel("场景世界").check();
|
|
await page.getByRole("tab").filter({ hasText: "世界环境" }).click();
|
|
await expect(page.getByTestId("world-workbench")).toBeVisible({ timeout: 30_000 });
|
|
await page.getByLabel("加载环境贴图").setInputFiles(path.join(root, "tests/files/web/m12_obj_multi_v1/m12_obj_texture.png"));
|
|
await expect.poll(async () => (await readSnapshot(page)).images.find((image) => image.name === "m12_obj_texture")?.id ?? "", { timeout: 60_000 }).not.toBe("");
|
|
const imageId = (await readSnapshot(page)).images.find((image) => image.name === "m12_obj_texture")!.id;
|
|
await page.getByLabel("环境贴图", { exact: true }).selectOption(imageId);
|
|
await expect.poll(async () => (await readSnapshot(page)).worlds[0]?.environmentImageId ?? "", { timeout: 60_000 }).toBe(imageId);
|
|
await setInputValue(page, "环境强度", "1");
|
|
/* The untouched slider already sits at 0; the snapshot omits the field
|
|
* until a Mapping node exists, so an absent value also means "no rotation". */
|
|
await expect.poll(async () => {
|
|
const rotation = (await readSnapshot(page)).worlds[0]?.environmentRotation;
|
|
return rotation === undefined || rotation === null ? 0 : Number(rotation.toFixed(3));
|
|
}, { timeout: 60_000 }).toBeCloseTo(0, 2);
|
|
await expect.poll(() => canvas.getAttribute("data-ibl-status"), { timeout: 60_000 }).toBe("ready");
|
|
|
|
/* Camera view (Numpad 0 equivalent). */
|
|
await page.getByLabel("相机视图", { exact: true }).click();
|
|
await expect.poll(() => page.evaluate(() => Boolean((window as unknown as { __webViewportCamera?: unknown }).__webViewportCamera)), { timeout: 60_000 }).toBe(true);
|
|
await page.waitForTimeout(1200);
|
|
|
|
const captureA = await captureCanvas(page);
|
|
const camera = await page.evaluate(() => (window as unknown as { __webViewportCamera: { matrixWorld: number[]; fov: number; zoom: number; aspect: number; width: number; height: number } }).__webViewportCamera);
|
|
expect(captureA.width).toBe(camera.width);
|
|
|
|
/* Rotate the World by 90 degrees: the background must rotate with it. */
|
|
const theta = Math.PI / 2;
|
|
await setInputValue(page, "环境旋转", "90");
|
|
await expect.poll(async () => {
|
|
const rotation = (await readSnapshot(page)).worlds[0]?.environmentRotation;
|
|
return rotation === undefined || rotation === null ? -999 : Number(rotation.toFixed(3));
|
|
}, { timeout: 60_000 }).toBeCloseTo(theta, 2);
|
|
await expect.poll(async () => {
|
|
const capture = await captureCanvas(page);
|
|
let changed = 0;
|
|
for (let index = 0; index < capture.data.length; index += 4 * 97) {
|
|
if (Math.abs(capture.data[index] - captureA.data[index]) > 4) changed += 1;
|
|
}
|
|
return changed;
|
|
}, { timeout: 60_000 }).toBeGreaterThan(10);
|
|
const captureB = await captureCanvas(page);
|
|
|
|
/* For each background sample in B, the same colour must appear in A at the
|
|
* world direction rotated back by theta (sky rows only: no geometry). */
|
|
const analysis = await page.evaluate(({ a, b, view, angle }) => {
|
|
const tanHalf = Math.tan((view.fov * Math.PI) / 360) / Math.max(1e-6, view.zoom);
|
|
// matrixWorld is column-major; the viewport camera has no scale.
|
|
const m = view.matrixWorld;
|
|
const rotation = [[m[0], m[4], m[8]], [m[1], m[5], m[9]], [m[2], m[6], m[10]]];
|
|
const ray = (width: number, height: number, px: number, py: number) => {
|
|
const ndcX = ((px + 0.5) / width) * 2 - 1;
|
|
const ndcY = 1 - ((py + 0.5) / height) * 2;
|
|
const v = [ndcX * tanHalf * view.aspect, ndcY * tanHalf, -1];
|
|
const world = [
|
|
rotation[0][0] * v[0] + rotation[0][1] * v[1] + rotation[0][2] * v[2],
|
|
rotation[1][0] * v[0] + rotation[1][1] * v[1] + rotation[1][2] * v[2],
|
|
rotation[2][0] * v[0] + rotation[2][1] * v[1] + rotation[2][2] * v[2],
|
|
];
|
|
const length = Math.hypot(world[0], world[1], world[2]);
|
|
return [world[0] / length, world[1] / length, world[2] / length];
|
|
};
|
|
const project = (width: number, height: number, direction: number[]) => {
|
|
const v = [
|
|
rotation[0][0] * direction[0] + rotation[1][0] * direction[1] + rotation[2][0] * direction[2],
|
|
rotation[0][1] * direction[0] + rotation[1][1] * direction[1] + rotation[2][1] * direction[2],
|
|
rotation[0][2] * direction[0] + rotation[1][2] * direction[1] + rotation[2][2] * direction[2],
|
|
];
|
|
if (v[2] >= -1e-6) return null;
|
|
const ndcX = (v[0] / -v[2]) / (tanHalf * view.aspect);
|
|
const ndcY = (v[1] / -v[2]) / tanHalf;
|
|
return [((ndcX + 1) / 2) * width - 0.5, ((1 - ndcY) / 2) * height - 0.5];
|
|
};
|
|
const rotateY = (direction: number[], sign: number) => {
|
|
const cos = Math.cos(sign * angle), sin = Math.sin(sign * angle);
|
|
return [direction[0] * cos + direction[2] * sin, direction[1], -direction[0] * sin + direction[2] * cos];
|
|
};
|
|
const sample = (image: { width: number; height: number; data: number[] }, px: number, py: number) => {
|
|
const x = Math.round(px), y = Math.round(py);
|
|
if (x < 0 || y < 0 || x >= image.width || y >= image.height) return null;
|
|
const index = (y * image.width + x) * 4;
|
|
return [image.data[index], image.data[index + 1], image.data[index + 2]];
|
|
};
|
|
const compare = (sign: number) => {
|
|
let matches = 0, total = 0;
|
|
for (let py = Math.round(b.height * 0.02); py < Math.round(b.height * 0.3); py += 17) {
|
|
for (let px = Math.round(b.width * 0.05); px < Math.round(b.width * 0.95); px += 23) {
|
|
const target = sample(b, px, py);
|
|
if (!target) continue;
|
|
const direction = rotateY(ray(b.width, b.height, px, py), sign);
|
|
const projected = project(a.width, a.height, direction);
|
|
if (!projected) continue;
|
|
const source = sample(a, projected[0], projected[1]);
|
|
if (!source) continue;
|
|
total += 1;
|
|
const delta = (Math.abs(target[0] - source[0]) + Math.abs(target[1] - source[1]) + Math.abs(target[2] - source[2])) / 3;
|
|
if (delta <= 10) matches += 1;
|
|
}
|
|
}
|
|
return { sign, matches, total, ratio: total ? matches / total : 0 };
|
|
};
|
|
return [compare(1), compare(-1)];
|
|
}, { a: captureA, b: captureB, view: camera, angle: theta });
|
|
|
|
const best = analysis.reduce((left, right) => (right.ratio > left.ratio ? right : left));
|
|
const worst = analysis.find((entry) => entry !== best)!;
|
|
expect(best.total).toBeGreaterThan(100);
|
|
expect(best.ratio).toBeGreaterThan(0.9);
|
|
expect(best.ratio).toBeGreaterThan(worst.ratio + 0.2);
|
|
|
|
fs.writeFileSync(path.join(outputDir, "camera-view.json"), JSON.stringify({
|
|
schemaVersion: 1,
|
|
browser: "chromium",
|
|
storage: "OPFS",
|
|
fixture: "tests/files/web/basic_scene.blend",
|
|
workflow: "Scene World + environment image -> camera view -> background pixels vs world rotation",
|
|
environmentImage: imageId,
|
|
rotationRadians: theta,
|
|
sampledPoints: best.total,
|
|
matchingRotationSign: best.sign,
|
|
matchRatio: Number(best.ratio.toFixed(4)),
|
|
oppositeSignRatio: Number(worst.ratio.toFixed(4)),
|
|
status: "PASS",
|
|
acceptance: "NOT_CLAIMED",
|
|
}, null, 2));
|
|
});
|
|
|
|
async function captureDataUrl(page: Page, selector: string): Promise<string> {
|
|
return page.evaluate((query) => {
|
|
const canvas = document.querySelector<HTMLCanvasElement>(query)!;
|
|
const copy = document.createElement("canvas");
|
|
copy.width = canvas.width; copy.height = canvas.height;
|
|
copy.getContext("2d")!.drawImage(canvas, 0, 0);
|
|
return copy.toDataURL("image/png");
|
|
}, selector);
|
|
}
|
|
|
|
test("offscreen viewport: world background follows the world rotation and matches the on-screen frame", async ({ page }) => {
|
|
test.setTimeout(300_000);
|
|
await page.setViewportSize({ width: 1280, height: 800 });
|
|
const basic = path.join(root, "tests/files/web/basic_scene.blend");
|
|
const envImage = path.join(root, "tests/files/web/m12_obj_multi_v1/m12_obj_texture.png");
|
|
|
|
const setup = async (offscreen: boolean): Promise<void> => {
|
|
await observeNative(page);
|
|
await page.goto(offscreen ? "/?ui=web&offscreen=1" : "/?ui=web");
|
|
await page.getByTestId("blend-file-input").setInputFiles(basic);
|
|
await expect(page.getByTestId("engine-status")).toContainText(/SceneIR r\d+/, { timeout: 120_000 });
|
|
await exposeWebTools(page);
|
|
await page.getByLabel("场景世界").check();
|
|
await page.getByRole("tab").filter({ hasText: "世界环境" }).click();
|
|
await expect(page.getByTestId("world-workbench")).toBeVisible({ timeout: 30_000 });
|
|
await page.getByLabel("加载环境贴图").setInputFiles(envImage);
|
|
await expect.poll(async () => (await readSnapshot(page)).images.find((image) => image.name === "m12_obj_texture")?.id ?? "", { timeout: 60_000 }).not.toBe("");
|
|
const imageId = (await readSnapshot(page)).images.find((image) => image.name === "m12_obj_texture")!.id;
|
|
await page.getByLabel("环境贴图", { exact: true }).selectOption(imageId);
|
|
await expect.poll(async () => (await readSnapshot(page)).worlds[0]?.environmentImageId ?? "", { timeout: 60_000 }).toBe(imageId);
|
|
if (offscreen) {
|
|
await expect(page.locator("canvas").first()).toHaveAttribute("data-renderer-backend", "offscreen-worker", { timeout: 60_000 });
|
|
await expect.poll(async () => Number(await page.locator("canvas").first().getAttribute("data-renderer-pixels") ?? "0"), { timeout: 60_000 }).toBeGreaterThan(0);
|
|
}
|
|
/* BasicScene ships a cube in front of the camera; hide every mesh so only
|
|
* the world background is compared (no geometry interference). */
|
|
for (const node of (await readSnapshot(page)).nodes.filter((candidate) => candidate.type === "MESH" && candidate.visible !== false)) {
|
|
await page.getByLabel(`隐藏 ${node.name}`, { exact: true }).first().click();
|
|
}
|
|
await expect.poll(async () => (await readSnapshot(page)).nodes.filter((candidate) => candidate.type === "MESH" && candidate.visible !== false).length, { timeout: 60_000 }).toBe(0);
|
|
await page.getByLabel("相机视图", { exact: true }).click();
|
|
await page.waitForTimeout(offscreen ? 2500 : 1200);
|
|
};
|
|
|
|
/* On-screen reference at rotation 0 / 90. */
|
|
await setup(false);
|
|
const onScreenA = await captureCanvas(page);
|
|
const onScreenAUrl = await captureDataUrl(page, "canvas[data-studio-lighting]");
|
|
await setInputValue(page, "环境旋转", "90");
|
|
await page.waitForTimeout(1200);
|
|
const onScreenB = await captureCanvas(page);
|
|
fs.writeFileSync(path.join(outputDir, "offscreen-onscreen-rotation-90.png"), Buffer.from(await captureDataUrl(page, "canvas[data-studio-lighting]").then((url) => url.split(",")[1]), "base64"));
|
|
await setInputValue(page, "环境旋转", "-90");
|
|
await page.waitForTimeout(1200);
|
|
const onScreenC = await captureCanvas(page);
|
|
|
|
/* Offscreen worker at the same two rotations. */
|
|
await setup(true);
|
|
const selector = "canvas";
|
|
const offscreenA = await captureCanvas(page, selector);
|
|
const theta = Math.PI / 2;
|
|
await setInputValue(page, "环境旋转", "90");
|
|
await expect.poll(async () => {
|
|
const rotation = (await readSnapshot(page)).worlds[0]?.environmentRotation;
|
|
return rotation === undefined || rotation === null ? -999 : Number(rotation.toFixed(3));
|
|
}, { timeout: 60_000 }).toBeCloseTo(theta, 2);
|
|
await page.waitForTimeout(1200);
|
|
const offscreenB = await captureCanvas(page, selector);
|
|
fs.writeFileSync(path.join(outputDir, "offscreen-worker-rotation-90.png"), Buffer.from((await captureDataUrl(page, selector)).split(",")[1], "base64"));
|
|
fs.writeFileSync(path.join(outputDir, "onscreen-rotation-0.png"), Buffer.from(onScreenAUrl.split(",")[1], "base64"));
|
|
|
|
/* Sky-only NDC grid comparison (no geometry, so both backends must agree). */
|
|
const compare = await page.evaluate(({ left, right, baseline, opposite }) => {
|
|
const sample = (image: { width: number; height: number; data: number[] }, u: number, v: number) => {
|
|
const x = Math.min(image.width - 1, Math.max(0, Math.round(u * image.width)));
|
|
const y = Math.min(image.height - 1, Math.max(0, Math.round(v * image.height)));
|
|
const index = (y * image.width + x) * 4;
|
|
return [image.data[index], image.data[index + 1], image.data[index + 2]];
|
|
};
|
|
let matches = 0, baselineMatches = 0, oppositeMatches = 0, changed = 0, total = 0;
|
|
for (let row = 0; row <= 28; row += 1) {
|
|
for (let column = 0; column <= 44; column += 1) {
|
|
const u = 0.05 + (column / 44) * 0.9;
|
|
const v = 0.02 + (row / 28) * 0.28;
|
|
const a = sample(left[0], u, v), b = sample(left[1], u, v), c = sample(right, u, v), d = sample(baseline, u, v), e = sample(opposite, u, v);
|
|
total += 1;
|
|
if ((Math.abs(b[0] - c[0]) + Math.abs(b[1] - c[1]) + Math.abs(b[2] - c[2])) / 3 <= 12) matches += 1;
|
|
if ((Math.abs(a[0] - d[0]) + Math.abs(a[1] - d[1]) + Math.abs(a[2] - d[2])) / 3 <= 12) baselineMatches += 1;
|
|
if ((Math.abs(b[0] - e[0]) + Math.abs(b[1] - e[1]) + Math.abs(b[2] - e[2])) / 3 <= 12) oppositeMatches += 1;
|
|
if ((Math.abs(a[0] - b[0]) + Math.abs(a[1] - b[1]) + Math.abs(a[2] - b[2])) / 3 > 4) changed += 1;
|
|
}
|
|
}
|
|
return { total, matches, baselineMatches, oppositeMatches, changed };
|
|
}, { left: [offscreenA, offscreenB], right: onScreenB, baseline: onScreenA, opposite: onScreenC });
|
|
|
|
console.info(`canvas sizes: onScreenA=${onScreenA.width}x${onScreenA.height} onScreenB=${onScreenB.width}x${onScreenB.height} offscreenA=${offscreenA.width}x${offscreenA.height} offscreenB=${offscreenB.width}x${offscreenB.height}`);
|
|
expect(compare.total).toBeGreaterThan(1000);
|
|
/* The worker's background rotates: the offscreen frame changes with rotation. */
|
|
expect(compare.changed / compare.total).toBeGreaterThan(0.5);
|
|
/* And it matches the on-screen render of the same rotation at least as well
|
|
* as the same-rotation baseline (renderer differences cancel out). */
|
|
const rotatedRatio = compare.matches / compare.total;
|
|
const baselineRatio = compare.baselineMatches / compare.total;
|
|
const oppositeRatio = compare.oppositeMatches / compare.total;
|
|
console.info(`offscreen parity: rotated=${rotatedRatio.toFixed(3)} baseline=${baselineRatio.toFixed(3)} opposite=${oppositeRatio.toFixed(3)} changed=${(compare.changed / compare.total).toFixed(3)}`);
|
|
expect(rotatedRatio).toBeGreaterThan(baselineRatio - 0.05);
|
|
expect(rotatedRatio).toBeGreaterThan(0.95);
|
|
|
|
fs.writeFileSync(path.join(outputDir, "camera-view-offscreen.json"), JSON.stringify({
|
|
schemaVersion: 1,
|
|
browser: "chromium",
|
|
storage: "OPFS",
|
|
fixture: "tests/files/web/basic_scene.blend",
|
|
workflow: "Scene World + environment image -> camera view -> offscreen worker (?offscreen=1) background pixels vs on-screen frame at the same rotation",
|
|
rotationRadians: theta,
|
|
sampledPoints: compare.total,
|
|
changedRatio: Number((compare.changed / compare.total).toFixed(4)),
|
|
onScreenRotatedMatchRatio: Number(rotatedRatio.toFixed(4)),
|
|
onScreenBaselineMatchRatio: Number(baselineRatio.toFixed(4)),
|
|
status: "PASS",
|
|
acceptance: "NOT_CLAIMED",
|
|
}, null, 2));
|
|
});
|