Files
FreeCADWasmDev/tools/part-section-cut-container-business-cases.mjs
wangdequan 65f59aba25 Remove OpenSCAD from the web port
Web FreeCAD does not implement OpenSCAD. Drop the module end to end
instead of keeping a blocked or placeholder shell:

- delete the parity-matrix row and regenerate the module registry
  (31 modules, OpenSCAD absent)
- remove the OpenSCAD-only frontend modules (worker, facades, slice,
  mesh backend, desktop/preferences tasks) and strip the OpenSCAD
  branches from the dispatchers, shells, storage and router
- neutralise the two shared owners that outlived the module:
  openscad-desktop-view -> scene-viewport (SceneViewport) and
  openscad-desktop-adapter -> scene-document (SceneDocument), so Part,
  Mesh and the other consumers keep working
- drop the FreeCADWebOpenSCADRuntimeProbe target and
  FREECAD_WEB_ENABLE_OPENSCAD option from the kernel CMake;
  BUILD_OPENSCAD stays in the forced-off list
- delete web/openscad.html, its Vite input, the kernel artifacts and
  the 17 OpenSCAD tool entry points

AGENTS.md records the removal rule. tsc --noEmit is clean and
grep -ri openscad web/src is empty.

Also carry the Boost pthread guard: under Emscripten a plain -lpthread
implies -sUSE_PTHREADS=1 and therewith --shared-memory, which the
non-atomics VTK archives cannot link against.

Validation NOT_RUN / PARTIAL_FAILED, Acceptance NOT_CLAIMED.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 06:53:03 +08:00

811 lines
61 KiB
JavaScript

import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import { createHash } from "node:crypto";
import { playwright } from "./part-primitive-business-cases.mjs";
// Isolate the uncolored-base/colored-tool boundary without replaying the
// already recorded placement, cutter-size, opacity and lifecycle scenarios.
export const runSectionCutFaceAlphaCases = ids => runSectionCutToolColorCases(ids, true);
export const runSectionCutFragmentColorCases = ids => runSectionCutToolColorCases(ids, true, true);
export const runSectionCutFragmentTransparencyCases = ids => runSectionCutToolColorCases(ids, true, true, true);
export const runSectionCutMultiSourceAppearanceCases = ids => runSectionCutToolColorCases(ids, true, true, true, true);
export const runSectionCutSourceInheritanceCases = ids => runSectionCutToolColorCases(ids, false, false, false, false, true);
export async function runSectionCutToolColorCases(ids, faceAlpha = false, fragmentColor = false, fragmentAlpha = false, multiSource = false, sourceInheritance = false) {
const capabilityId = "Part:desktop:Part_SectionCut";
if (!ids.includes(capabilityId)) return [];
const directory = path.resolve(sourceInheritance ? "docs/current/part-section-cut-source-inheritance" : multiSource ? "docs/current/part-section-cut-multi-source-appearance" : fragmentAlpha ? "docs/current/part-section-cut-fragment-transparency" : fragmentColor ? "docs/current/part-section-cut-fragment-color" : faceAlpha ? "docs/current/part-section-cut-face-alpha" : "docs/current/part-section-cut-tool-colors", new Date().toISOString().replace(/[:.]/g, "-"));
fs.mkdirSync(directory, { recursive: true });
const result = { capabilityId, status: "failed", cases: [], evidenceFiles: {},
deferredCases: ["runSectionCutContainerCases", "runLegacySectionCutCases", "runSectionCutEmptySourcesCases",
"runSectionCutFragmentsCases", "runSectionCutOpacityCases", "runSectionCutPersistenceCases",
...(sourceInheritance ? ["runSectionCutCompoundHistoryCases", "runSectionCutMultiSourceAppearanceCases"] : [])],
remaining: [sourceInheritance ? "Curved and transformed BooleanFragments source material coverage; desktop automatic color controls" : multiSource ? "Source face material inheritance in BooleanFragments" : fragmentAlpha ? "BooleanFragments appearance with multiple intersecting sources; source face material inheritance" : faceAlpha ? "Fragment color/transparency and desktop cut/fragment appearance interaction" : "Independent cut-face and fragment appearance/transparency",
"Container reparenting", "Unexpected post-mutation failure history behavior"] };
const started = performance.now();
const stages = [];
const stage = name => {
stages.push({ name, elapsedMs: performance.now() - started });
fs.writeFileSync(path.join(directory, "stages.json"), JSON.stringify(stages, null, 2) + "\n");
process.stderr.write(`Section cut tool colors: ${name}\n`);
};
const record = (input, actual, name) => result.cases.push({ input, actual, assertions: [{ name, passed: true }] });
let browser;
try {
for (const file of ["tools/part-section-cut-container-business-cases.mjs", "tools/part-section-cut-business-cases.mjs",
"web/src/part-section-cut-task.tsx", "web/src/part-desktop-adapter.ts", "web/src/part-document-facade.ts",
"web/src/workbench-shell.tsx", "freecad-source/src/WebAssembly/FreeCADCoreProbe/PartColoredIO.h",
"web/src/scene-viewport.tsx", "freecad-source/src/WebAssembly/FreeCADCoreProbe/DocumentProbe.cpp",
"freecad-source/src/WebAssembly/FreeCADCoreProbe/PartSectionCutDocument.h",
...["js", "wasm", "worker.js"].map(ext => `web/public/kernel/FreeCADWebDocumentProbe.${ext}`)])
result.evidenceFiles[file] = createHash("sha256").update(fs.readFileSync(file)).digest("hex");
stage("browser-launch-enter");
browser = await playwright().chromium.launch({ executablePath: process.env.FREECAD_CHROME ?? "/usr/bin/google-chrome",
headless: process.env.HEADLESS !== "0", args: ["--no-sandbox", "--disable-dev-shm-usage"] });
const page = await browser.newPage({ viewport: { width: 1440, height: 900 } });
const errors = []; page.on("pageerror", error => errors.push(String(error)));
const documentId = "SectionCutToolColors";
await page.goto(`${process.env.FREECAD_BROWSER_ORIGIN ?? "http://127.0.0.1:5180"}/workbench.html?module=Part&command=part.document&document=${documentId}`);
const run = async (args, expectError = false) => {
stage(`request-${args.action}-enter`);
await page.locator("aside > button.command").filter({ has: page.getByText("part.document", { exact: true }) }).click();
await page.locator("#payload-editor").fill(JSON.stringify({ schema: "freecad-web-part/document/v1", module: "Part",
document: documentId, builderInfo: true, includeMesh: true, ...args }));
await page.evaluate(() => { if (window.__freecadWorkbenchState) window.__freecadWorkbenchState.response = null; });
await page.getByRole("button", { name: "执行选中命令", exact: true }).click();
await page.waitForFunction(() => window.__freecadWorkbenchState?.response && !document.querySelector("button.run")?.disabled);
const reply = await page.evaluate(() => window.__freecadWorkbenchState.response);
assert.equal(reply.kind, expectError ? "error" : "result", JSON.stringify(reply));
stage(`request-${args.action}-complete`);
return expectError ? reply.error : reply.result;
};
if (sourceInheritance) {
await assertSourceInheritance({ page, run, record, stage, directory, result, documentId });
assert.deepEqual(errors, []);
} else if (multiSource) {
await assertMultiSourceAppearance({ page, run, record, stage, directory, result });
assert.deepEqual(errors, []);
} else {
await run({ action: "create" });
await run({ action: "setBox", object: "Box", dimensions: [10,10,10] });
await page.locator(".matrix-list button").filter({ has: page.locator("span", { hasText: /^Part_SectionCut$/ }) }).click();
const panel = page.getByRole("region", { name: "Section cutting", exact: true });
const ready = () => page.waitForFunction(() => {
const fieldset = document.querySelector('section[aria-label="Section cutting"] fieldset'); return fieldset && !fieldset.disabled;
});
await ready();
await panel.getByRole("checkbox", { name: "Cut X", exact: true }).check();
await panel.getByRole("spinbutton", { name: "Cut X position", exact: true }).fill("5");
await panel.getByLabel("Cut face color", { exact: true }).fill("#00ff00");
if (faceAlpha) await panel.getByLabel("Cut face transparency", { exact: true }).fill("65");
if (fragmentColor) {
await panel.getByLabel("Custom fragment color", { exact: true }).check();
await panel.getByLabel("Fragment color", { exact: true }).fill("#ffff00");
}
if (fragmentAlpha) await panel.getByLabel("Fragment transparency", { exact: true }).fill("60");
await panel.getByRole("button", { name: "Apply section cut", exact: true }).click(); await ready();
assert.deepEqual(await panel.getByRole("status").allTextContents(), []);
const initial = await run({ action: "snapshot" });
const session = state => state.objects.find(item => item.sectionCutSession).sectionCutSession;
const cut = state => state.objects.find(item => item.name === session(state).result);
const tool = initial.objects.find(item => item.type === "Part::Box" && item.name.startsWith("SectionCutBox"));
assert.ok(tool); assert.equal(initial.objects.find(item => item.name === "Box").faceColors?.length ?? 0, 0);
const green = [0,1,0,faceAlpha ? 0.35 : 1], red = [1,0,0,faceAlpha ? 0.7 : 1];
const baseAlpha = fragmentAlpha ? 0.4 : 1;
const check = (state, color, volume) => {
const output = cut(state);
assert.ok(Math.abs(output.volume - volume) < 1e-6); assert.equal(output.topology.valid, true);
assert.equal(output.faceColors.length, 6);
const matches = value => value.slice(0,3).every((channel, i) => Math.abs(channel - color[i]) < 1e-6);
assert.equal(output.faceColors.filter(matches).length, 1, "Only the new section face inherits the cutter color");
const expectedBase = fragmentColor ? [1, 1, 0] : [0.8, 0.8, 0.8];
for (const value of output.faceColors.filter(value => !matches(value)))
value.slice(0,3).forEach((channel, i) => assert.ok(Math.abs(channel - expectedBase[i]) < 1e-6, "Surviving source faces retain the selected fragment material"));
assert.equal(output.mesh.colors.length, output.mesh.triangleCount * 9);
const rgb = output.mesh.colors;
const coloredVertices = Array.from({ length: rgb.length / 3 }, (_, i) => rgb.slice(i * 3, i * 3 + 3)).filter(matches).length;
assert.equal(coloredVertices, 6, "Two native cut-face triangles carry the tool material");
if (faceAlpha) {
const near = (actual, expected) => assert.ok(Math.abs(actual - expected) < 1e-6, `${actual} != ${expected}`);
output.faceColors.forEach(value => near(value[3], matches(value) ? color[3] : baseAlpha));
assert.equal(output.mesh.alphas.length, output.mesh.triangleCount * 3);
output.mesh.alphas.forEach((alpha, i) => near(alpha, matches(rgb.slice(i * 3, i * 3 + 3)) ? color[3] : baseAlpha));
assert.equal(output.displayOpacity, 1, "Cut transparency does not fade surviving source faces");
}
return { volume: output.volume, faceColors: output.faceColors, coloredVertices };
};
const setColor = color => run({ action: "setFaceColors", selection: [{ documentId, object: tool.name }],
faceColors: Array.from({ length: tool.topology.Face }, () => color) });
const colored = initial;
assert.equal(session(colored).cutColor, "#00ff00");
if (fragmentColor) assert.equal(session(colored).fragmentColor, "#ffff00");
if (fragmentAlpha) assert.equal(session(colored).fragmentTransparency, 60);
if (faceAlpha) assert.equal(session(colored).cutTransparency, 65);
fs.writeFileSync(path.join(directory, "colored.json"), JSON.stringify(colored, null, 2) + "\n");
record({ source: "uncolored Box", planeX: 5, toolColor: green }, check(colored, green, 500),
"Native Boolean history separates the generated cut-face material from the five surviving source faces");
const recolored = await setColor(red); check(recolored, red, 500);
const undone = await run({ action: "undo" }); check(undone, green, 500);
const failure = await run({ action: "sectionCut", sectionCut: { operation: "apply", cutColor: "not-a-color" } }, true);
assert.match(failure.message, /six-digit RGB/);
const afterFailure = await run({ action: "snapshot" });
assert.deepEqual(afterFailure.objects, undone.objects);
assert.equal(afterFailure.undoCount, undone.undoCount); assert.equal(afterFailure.redoCount, undone.redoCount);
if (fragmentColor) {
for (const value of ["red", "#12345g", 123, null, true]) {
const rejected = await run({ action: "sectionCut", sectionCut: { operation: "apply", fragmentColor: value } }, true);
assert.match(rejected.message, /Fragment color/);
const preserved = await run({ action: "snapshot" });
assert.deepEqual(preserved.objects, undone.objects);
assert.equal(preserved.undoCount, undone.undoCount); assert.equal(preserved.redoCount, undone.redoCount);
}
}
if (faceAlpha) {
for (const cutTransparency of [-1, 101, 0.5, "50", true]) {
const rejected = await run({ action: "sectionCut", sectionCut: { operation: "apply", cutTransparency } }, true);
assert.match(rejected.message, /Cut face transparency/);
const preserved = await run({ action: "snapshot" });
assert.deepEqual(preserved.objects, undone.objects);
assert.equal(preserved.undoCount, undone.undoCount); assert.equal(preserved.redoCount, undone.redoCount);
}
}
if (fragmentAlpha) {
for (const fragmentTransparency of [-1, 101, 0.5, "60", true, null]) {
const rejected = await run({ action: "sectionCut", sectionCut: { operation: "apply", fragmentTransparency } }, true);
assert.match(rejected.message, /Fragment transparency/);
const preserved = await run({ action: "snapshot" });
assert.deepEqual(preserved.objects, undone.objects);
assert.equal(preserved.undoCount, undone.undoCount); assert.equal(preserved.redoCount, undone.redoCount);
}
}
check(await run({ action: "redo" }), red, 500);
const edited = await run({ action: "setBox", object: "Box", dimensions: [10,10,12] });
record({ toolColor: red, sourceDimensions: [10,10,12], operations: ["recolor", "undo", "redo", "source edit"] },
check(edited, red, 600), "Tool material follows native history through color history and source recompute");
await run({ action: "save", path: "/tmp/SectionCutToolColors.FCStd" }); await run({ action: "close" });
const reopened = await run({ action: "open", path: "/tmp/SectionCutToolColors.FCStd" });
assert.equal(session(reopened).cutColor, "#00ff00");
if (fragmentColor) assert.equal(session(reopened).fragmentColor, "#ffff00");
if (fragmentAlpha) assert.equal(session(reopened).fragmentTransparency, 60);
if (faceAlpha) assert.equal(session(reopened).cutTransparency, 65);
// FCStd packs App::PropertyColorList channels into eight-bit RGBA values.
const savedRed = faceAlpha ? red.map(channel => Math.round(channel * 255) / 255) : red;
record({ operation: "save-close-open", expectedStoredColor: savedRed }, check(reopened, savedRed, 600),
"FCStd restores packed native tool material and recomputed face-history mapping");
await panel.getByRole("button", { name: "Refresh section cut", exact: true }).click(); await ready();
assert.equal(await panel.getByLabel("Cut face color", { exact: true }).inputValue(), "#00ff00");
if (fragmentColor) {
assert.equal(await panel.getByLabel("Custom fragment color", { exact: true }).isChecked(), true);
assert.equal(await panel.getByLabel("Fragment color", { exact: true }).inputValue(), "#ffff00");
}
if (faceAlpha) assert.equal(await panel.getByLabel("Cut face transparency", { exact: true }).inputValue(), "65");
if (fragmentAlpha) assert.equal(await panel.getByLabel("Fragment transparency", { exact: true }).inputValue(), "60");
await panel.getByLabel("Cut face color", { exact: true }).fill("#0000ff");
await panel.getByRole("checkbox", { name: "Cut Y", exact: true }).check();
await panel.getByRole("spinbutton", { name: "Cut Y position", exact: true }).fill("4");
await panel.getByRole("button", { name: "Apply section cut", exact: true }).click(); await ready();
const twoAxes = await run({ action: "snapshot" });
const blueFaces = cut(twoAxes).faceColors.filter(color => color[0] === 0 && color[1] === 0 && color[2] === 1);
assert.equal(blueFaces.length, 2, "Both sequential cut faces receive the chosen material through native history");
if (faceAlpha) {
assert.ok(blueFaces.every(color => Math.abs(color[3] - 0.35) < 1e-6));
assert.equal(cut(twoAxes).mesh.alphas.filter(alpha => Math.abs(alpha - 0.35) < 1e-6).length, 12);
assert.equal(cut(twoAxes).mesh.alphas.filter(alpha => Math.abs(alpha - baseAlpha) < 1e-6).length, 24);
}
assert.equal(cut(twoAxes).faceColors.length, 6); assert.ok(Math.abs(cut(twoAxes).volume - 240) < 1e-6);
assert.equal(session(twoAxes).cutColor, "#0000ff");
await panel.getByRole("button", { name: "Refresh cut sources", exact: true }).click(); await ready();
const refreshed = await run({ action: "snapshot" });
assert.deepEqual(cut(refreshed).faceColors, cut(twoAxes).faceColors);
assert.equal(session(refreshed).cutColor, "#0000ff");
if (fragmentColor) {
assert.equal(session(refreshed).fragmentColor, "#ffff00");
assert.equal(cut(refreshed).faceColors.filter(color => color[0] === 1 && color[1] === 1 && color[2] === 0 && Math.abs(color[3] - baseAlpha) < 1e-6).length, 4);
assert.equal(refreshed.objects.find(item => item.name === "Box").faceColors?.length ?? 0, 0);
}
if (faceAlpha) assert.equal(session(refreshed).cutTransparency, 65);
if (fragmentAlpha) assert.equal(session(refreshed).fragmentTransparency, 60);
record({ operation: "mounted color change and source refresh", axes: ["X=5", "Y=4"], cutColor: "#0000ff" },
{ faceColors: cut(refreshed).faceColors, volume: cut(refreshed).volume },
"Mounted color control restores native session state and colors both sequential section faces across refresh");
await panel.getByRole("button", { name: "Refresh section cut", exact: true }).click(); await ready();
assert.deepEqual(await panel.getByRole("status").allTextContents(), []);
const pixels = [];
for (const width of [1440, 390]) {
await page.setViewportSize({ width, height: 900 });
const canvas = panel.locator("canvas").first(); await canvas.waitFor();
await page.waitForTimeout(300);
const imageFile = path.join(directory, `tool-color-canvas-${width}.png`);
const bytes = await canvas.screenshot({ path: imageFile });
const bluePixels = await page.evaluate(async data => {
const img = new Image(); img.src = `data:image/png;base64,${data}`; await img.decode();
const target = document.createElement("canvas"); target.width = img.width; target.height = img.height;
const context = target.getContext("2d"); context.drawImage(img, 0, 0);
const rgba = context.getImageData(0, 0, target.width, target.height).data;
let blue = 0;
for (let i = 0; i < rgba.length; i += 4)
if (rgba[i + 2] > 40 && rgba[i + 2] > rgba[i] * 1.4 && rgba[i + 2] > rgba[i + 1] * 1.4) ++blue;
return blue;
}, bytes.toString("base64"));
assert.ok(bluePixels > 30, `Native blue cut faces must render at width ${width}: ${bluePixels}`);
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), true);
pixels.push({ width, bluePixels });
result.evidenceFiles[path.relative(process.cwd(), imageFile)] = createHash("sha256").update(bytes).digest("hex");
if (fragmentAlpha) {
await panel.getByLabel("Fragment transparency", { exact: true }).fill("100");
await panel.getByRole("button", { name: "Apply section cut", exact: true }).click(); await ready();
const hidden = await run({ action: "snapshot" });
const isBlue = color => color[0] === 0 && color[1] === 0 && color[2] === 1;
assert.equal(session(hidden).fragmentTransparency, 100);
assert.equal(cut(hidden).faceColors.filter(color => !isBlue(color) && color[3] === 0).length, 4);
assert.equal(cut(hidden).faceColors.filter(color => isBlue(color) && Math.abs(color[3] - 0.35) < 1e-6).length, 2);
assert.ok(Math.abs(cut(hidden).volume - 240) < 1e-6);
await page.waitForTimeout(300);
const file = path.join(directory, `transparent-fragment-canvas-${width}.png`);
const hiddenBytes = await canvas.screenshot({ path: file });
const count = async data => page.evaluate(async encoded => {
const image = new Image(); image.src = `data:image/png;base64,${encoded}`; await image.decode();
const target = document.createElement("canvas"); target.width = image.width; target.height = image.height;
const context = target.getContext("2d"); context.drawImage(image, 0, 0);
const values = context.getImageData(0, 0, target.width, target.height).data;
let blue = 0, yellow = 0;
for (let i = 0; i < values.length; i += 4) {
if (values[i + 2] > 40 && values[i + 2] > values[i] * 1.4 && values[i + 2] > values[i + 1] * 1.4) ++blue;
if (values[i] > 40 && values[i + 1] > 40 && values[i] > values[i + 2] * 1.4 && values[i + 1] > values[i + 2] * 1.4) ++yellow;
}
return { blue, yellow };
}, data.toString("base64"));
const before = await count(bytes), after = await count(hiddenBytes);
assert.ok(before.yellow > 100, "Partially transparent fragment faces remain visible");
assert.ok(after.yellow < before.yellow * 0.05, "Fully transparent fragments remove yellow surface pixels");
assert.ok(after.blue > 30, "Independent blue cut faces remain visible");
pixels.at(-1).fragments = { before, after };
result.evidenceFiles[path.relative(process.cwd(), file)] = createHash("sha256").update(hiddenBytes).digest("hex");
await panel.getByRole("button", { name: "Section cut undo", exact: true }).click(); await ready();
assert.equal(await panel.getByLabel("Fragment transparency", { exact: true }).inputValue(), "60");
}
if (faceAlpha) {
await panel.getByLabel("Cut face transparency", { exact: true }).fill("100");
await panel.getByRole("button", { name: "Apply section cut", exact: true }).click(); await ready();
await page.waitForTimeout(300);
const clearFile = path.join(directory, `transparent-cut-canvas-${width}.png`);
const clearBytes = await canvas.screenshot({ path: clearFile });
const clearPixels = await page.evaluate(async data => {
const image = new Image(); image.src = `data:image/png;base64,${data}`; await image.decode();
const target = document.createElement("canvas"); target.width = image.width; target.height = image.height;
const context = target.getContext("2d"); context.drawImage(image, 0, 0);
const values = context.getImageData(0, 0, target.width, target.height).data;
let blue = 0, geometry = 0, yellow = 0;
for (let i = 0; i < values.length; i += 4) {
if (values[i + 2] > 40 && values[i + 2] > values[i] * 1.4 && values[i + 2] > values[i + 1] * 1.4) ++blue;
if (Math.max(...values.slice(i, i + 3)) - Math.min(...values.slice(i, i + 3)) < 12 && values[i] < 225) ++geometry;
if (values[i] > 40 && values[i + 1] > 40 && values[i] > values[i + 2] * 1.4 && values[i + 1] > values[i + 2] * 1.4) ++yellow;
}
return { blue, geometry, yellow };
}, clearBytes.toString("base64"));
assert.ok(clearPixels.blue < bluePixels * 0.05, "Fully transparent cut faces remove the blue pixels");
assert.ok((fragmentColor ? clearPixels.yellow : clearPixels.geometry) > 100, "Fragment faces remain rendered behind transparent cuts");
assert.notEqual(createHash("sha256").update(clearBytes).digest("hex"), createHash("sha256").update(bytes).digest("hex"));
result.evidenceFiles[path.relative(process.cwd(), clearFile)] = createHash("sha256").update(clearBytes).digest("hex");
pixels.at(-1).transparent = clearPixels;
const panelFile = path.join(directory, `section-cut-panel-${width}.png`);
const panelBytes = await panel.screenshot({ path: panelFile });
result.evidenceFiles[path.relative(process.cwd(), panelFile)] = createHash("sha256").update(panelBytes).digest("hex");
await canvas.scrollIntoViewIfNeeded();
const bounds = await canvas.boundingBox(); assert.ok(bounds);
await page.mouse.move(bounds.x + bounds.width / 2, bounds.y + bounds.height / 2);
await page.mouse.down();
await page.mouse.move(bounds.x + bounds.width / 2 + 40, bounds.y + bounds.height / 2 + 20, { steps: 8 });
await page.mouse.up(); await page.waitForTimeout(200);
const orbitFile = path.join(directory, `transparent-cut-orbit-${width}.png`);
const orbitBytes = await canvas.screenshot({ path: orbitFile });
const orbitHash = createHash("sha256").update(orbitBytes).digest("hex");
assert.notEqual(orbitHash, createHash("sha256").update(clearBytes).digest("hex"), "Native transparent mesh responds to orbit");
result.evidenceFiles[path.relative(process.cwd(), orbitFile)] = orbitHash;
pixels.at(-1).orbitChanged = true;
await panel.getByRole("button", { name: "Section cut undo", exact: true }).click(); await ready();
assert.equal(await panel.getByLabel("Cut face transparency", { exact: true }).inputValue(), "65");
}
}
record({ operation: "render native face colors", widths: [1440, 390] }, pixels,
"Chosen cut-face color is visible in desktop and mobile native-mesh canvases without horizontal overflow");
if (faceAlpha) record({ cutTransparency: [65, 100], editedToolAlpha: 0.7, sourceAlpha: baseAlpha,
operations: ["apply", "undo", "redo", "invalid native values", "edit source", "FCStd reopen", "sequential cuts", "refresh"] },
{ pixels, fragmentAlpha: baseAlpha }, "Independent native face alpha survives history and persistence and changes actual desktop/mobile pixels");
assert.deepEqual(errors, []);
if (fragmentColor) {
await panel.getByLabel("Custom fragment color", { exact: true }).uncheck();
await panel.getByRole("button", { name: "Apply section cut", exact: true }).click(); await ready();
const automatic = await run({ action: "snapshot" });
assert.equal(session(automatic).fragmentColor, "");
assert.equal(cut(automatic).faceColors.filter(color => color.slice(0, 3).every(channel => Math.abs(channel - 0.8) < 1e-6)).length, 4);
assert.equal(cut(automatic).faceColors.filter(color => color[2] === 1 && Math.abs(color[3] - 0.35) < 1e-6).length, 2);
const restored = await run({ action: "undo" });
assert.equal(session(restored).fragmentColor, "#ffff00");
assert.equal(cut(restored).faceColors.filter(color => color[0] === 1 && color[1] === 1 && color[2] === 0).length, 4);
assert.equal(session(await run({ action: "redo" })).fragmentColor, "");
record({ fragmentColor: "#ffff00", cutColor: "#0000ff", cutTransparency: 65, reset: "source appearance" },
{ pixels, sourceUnmodified: true, automaticFaces: cut(automatic).faceColors },
"Mounted fragment color changes only surviving source faces, persists through refresh and FCStd, and resets with undo/redo");
}
if (fragmentAlpha) {
const minimum = await run({ action: "sectionCut", sectionCut: { operation: "apply", axes: session(refreshed).axes, cutTransparency: 0 } });
assert.equal(session(minimum).cutTransparency, 1);
assert.equal(session(minimum).fragmentTransparency, 60);
const blue = color => color[0] === 0 && color[1] === 0 && color[2] === 1;
assert.equal(cut(minimum).faceColors.filter(blue).length, 2);
cut(minimum).faceColors.forEach(color => assert.ok(Math.abs(color[3] - (blue(color) ? 0.99 : 0.4)) < 1e-6));
await panel.getByRole("button", { name: "Refresh section cut", exact: true }).click(); await ready();
assert.equal(await panel.getByLabel("Cut face transparency", { exact: true }).inputValue(), "1");
const input = panel.getByLabel("Fragment transparency", { exact: true });
await input.fill("");
assert.equal(await panel.getByRole("button", { name: "Apply section cut", exact: true }).isDisabled(), true);
await panel.getByRole("button", { name: "Refresh section cut", exact: true }).click(); await ready();
assert.equal(await input.inputValue(), "60");
await input.fill("0");
await panel.getByLabel("Cut face transparency", { exact: true }).fill("0");
await panel.getByRole("button", { name: "Apply section cut", exact: true }).click(); await ready();
const opaque = await run({ action: "snapshot" });
assert.equal(session(opaque).fragmentTransparency, 0); assert.equal(session(opaque).cutTransparency, 0);
assert.ok(cut(opaque).faceColors.every(color => color[3] === 1));
const undo = await run({ action: "undo" });
assert.deepEqual(cut(undo).faceColors, cut(minimum).faceColors);
assert.deepEqual(cut(await run({ action: "redo" })).faceColors, cut(opaque).faceColors);
record({ fragmentTransparency: [60, 0], cutTransparency: 0, operations: ["minimum", "invalid UI", "undo", "redo"] },
{ minimum: cut(minimum).faceColors, opaque: cut(opaque).faceColors },
"Transparent fragments enforce the desktop one-percent cut minimum; clearing transparency restores opaque faces through history");
}
}
result.status = "not_implemented";
stage("assertions-complete");
} catch (error) { result.error = error.stack ?? String(error); stage("failed"); }
finally { await browser?.close(); stage("cleanup-complete"); }
fs.writeFileSync(path.join(directory, "result.json"), JSON.stringify(result, null, 2) + "\n");
return [result];
}
async function assertSourceInheritance({ page, run, record, stage, directory, result, documentId }) {
await run({ action: "create" });
await run({ action: "setBox", object: "Box", dimensions: [10,8,10] });
await run({ action: "setBox", object: "CrossingBox", dimensions: [8,10,10] });
const setColor = (object, color) => run({ action: "setFaceColors", selection: [{ documentId, object }],
faceColors: Array.from({ length: 6 }, () => color) });
await setColor("Box", [1,0,0,1]);
await setColor("CrossingBox", [0,0,1,1]);
await page.locator(".matrix-list button").filter({ has: page.locator("span", { hasText: /^Part_SectionCut$/ }) }).click();
const panel = page.getByRole("region", { name: "Section cutting", exact: true });
const ready = () => page.waitForFunction(() => {
const fieldset = document.querySelector('section[aria-label="Section cutting"] fieldset');
return fieldset && !fieldset.disabled;
});
const click = async name => { await panel.getByRole("button", { name, exact: true }).click(); await ready(); };
await ready();
await panel.getByLabel("Intersecting objects", { exact: true }).check();
await panel.getByLabel("Cut Z", { exact: true }).check();
await panel.getByLabel("Cut Z position", { exact: true }).fill("5");
await panel.getByLabel("Cut face color", { exact: true }).fill("#00ff00");
await panel.getByLabel("Custom fragment color", { exact: true }).uncheck();
await click("Apply section cut");
assert.deepEqual(await panel.getByRole("status").allTextContents(), [], "Mounted Section Cut apply must succeed");
const check = (state, firstColor = [1,0,0], height = 5) => {
const session = state.objects.find(item => item.sectionCutSession)?.sectionCutSession;
assert.ok(session, JSON.stringify(state));
const output = state.objects.find(item => item.name === session.result);
assert.equal(session.fragmentColor, "");
assert.equal(output.topology.valid, true);
assert.ok(Math.abs(output.volume - 96 * height) < 1e-6);
const fragments = state.objects.find(item => item.name.startsWith("SectionCutCompound"));
assert.equal(fragments.topology.Solid, 3);
assert.ok(fragments.mesh.triangleCount > fragments.faceColors.length * 2,
"Fixture exercises repeated shared rectangular faces, not just disjoint solids");
const { positions, colors, alphas, triangleCount } = output.mesh;
assert.equal(colors.length, triangleCount * 9);
assert.equal(alphas.length, triangleCount * 3);
let red = 0, blue = 0, green = 0;
for (let t = 0; t < triangleCount; ++t) {
const vertices = [0,3,6].map(v => positions.slice(t * 9 + v, t * 9 + v + 3));
const section = vertices.every(v => Math.abs(v[2] - height) < 1e-6);
// Exterior x=10 belongs only to Box; y=10 only to CrossingBox.
const onlyFirst = vertices.every(v => Math.abs(v[0] - 10) < 1e-6);
const onlySecond = vertices.every(v => Math.abs(v[1] - 10) < 1e-6);
const rgb = colors.slice(t * 9, t * 9 + 3);
const expected = section ? [0,1,0] : onlyFirst ? firstColor : onlySecond ? [0,0,1] : null;
if (expected) assert.deepEqual(rgb, expected, JSON.stringify({ vertices, rgb, expected }));
else assert.ok([firstColor, [0,0,1]].some(c => c.every((v,i) => v === rgb[i])), JSON.stringify({vertices,rgb}));
for (let v = 0; v < 3; ++v) {
assert.deepEqual(colors.slice(t * 9 + v * 3, t * 9 + v * 3 + 3), rgb);
assert.equal(alphas?.[t * 3 + v] ?? 1, 1);
}
if (section) green++; else if (rgb[2] === 1) blue++; else red++;
}
assert.ok(red > 0 && blue > 0 && green > 0, JSON.stringify({red,blue,green}));
return { volume: output.volume, red, blue, green, faceColors: output.faceColors };
};
const initial = check(await run({ action: "snapshot" }));
record({ sources: ["red Box", "blue CrossingBox"], cut: "green Z=5", fragmentColor: "inherited" }, initial,
"OCCT split faces inherit source materials; spatially distinct source faces and cut faces carry correct RGB");
check(await setColor("Box", [1,1,0,1]), [1,1,0]);
check(await run({ action: "undo" }));
check(await run({ action: "redo" }), [1,1,0]);
await run({ action: "save", path: "/tmp/SectionCutSourceInheritance.FCStd" });
await run({ action: "close" });
check(await run({ action: "open", path: "/tmp/SectionCutSourceInheritance.FCStd" }), [1,1,0]);
await click("Refresh section cut");
assert.equal(await panel.getByLabel("Custom fragment color", { exact: true }).isChecked(), false);
await panel.getByLabel("Cut Z position", { exact: true }).fill("4");
await click("Apply section cut");
check(await run({ action: "snapshot" }), [1,1,0], 4);
await click("Refresh cut sources");
const restored = check(await run({ action: "snapshot" }), [1,1,0], 4);
record({ operations: ["live source color", "undo", "redo", "FCStd reopen", "plane edit", "source refresh"] }, restored,
"Inherited fragment colors follow current source properties and regenerated topology through native history and persistence");
await click("Refresh section cut");
const canvas = panel.locator("canvas").first();
for (const width of [1440,390]) {
await page.setViewportSize({ width, height: 900 });
await canvas.scrollIntoViewIfNeeded(); await page.waitForTimeout(300);
const file = path.join(directory, `inherited-${width}.png`);
const png = await canvas.screenshot({ path: file });
result.evidenceFiles[file] = createHash("sha256").update(png).digest("hex");
const pixels = await page.evaluate(async base64 => {
const image = new Image(); image.src = `data:image/png;base64,${base64}`; await image.decode();
const raster = document.createElement("canvas"); raster.width = image.width; raster.height = image.height;
const ctx = raster.getContext("2d"); ctx.drawImage(image,0,0);
const data = ctx.getImageData(0,0,raster.width,raster.height).data;
let yellow = 0, blue = 0, green = 0;
for (let i=0;i<data.length;i+=4) {
if (data[i] > data[i+2]+20 && data[i+1] > data[i+2]+20) yellow++;
if (data[i+2] > data[i]+20 && data[i+2] > data[i+1]+20) blue++;
if (data[i+1] > data[i]+20 && data[i+1] > data[i+2]+20) green++;
}
return { yellow, blue, green };
}, png.toString("base64"));
assert.ok(pixels.yellow > 100 && pixels.blue > 100 && pixels.green > 100, JSON.stringify(pixels));
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false);
record({ viewport: width }, pixels, "Mounted native geometry shows both inherited materials and the independent section material");
}
stage("source-inheritance-complete");
}
async function assertMultiSourceAppearance({ page, run, record, stage, directory, result }) {
await run({ action: "create" });
await run({ action: "setBox", object: "Box", dimensions: [10, 8, 10] });
await run({ action: "setBox", object: "CrossingBox", dimensions: [8, 10, 10] });
await page.locator(".matrix-list button").filter({ has: page.locator("span", { hasText: /^Part_SectionCut$/ }) }).click();
const panel = page.getByRole("region", { name: "Section cutting", exact: true });
const ready = () => page.waitForFunction(() => {
const fieldset = document.querySelector('section[aria-label="Section cutting"] fieldset');
return fieldset && !fieldset.disabled;
});
const click = async name => { await panel.getByRole("button", { name, exact: true }).click(); await ready(); };
await ready();
await panel.getByLabel("Intersecting objects", { exact: true }).check();
await panel.getByLabel("Cut X", { exact: true }).check();
await panel.getByLabel("Cut X position", { exact: true }).fill("5");
await panel.getByLabel("Custom fragment color", { exact: true }).check();
await panel.getByLabel("Fragment color", { exact: true }).fill("#ffff00");
await panel.getByLabel("Fragment transparency", { exact: true }).fill("60");
await panel.getByLabel("Cut face color", { exact: true }).fill("#00ff00");
await panel.getByLabel("Cut face transparency", { exact: true }).fill("65");
await click("Apply section cut");
const session = state => state.objects.find(item => item.sectionCutSession).sectionCutSession;
const output = state => state.objects.find(item => item.name === session(state).result);
const near = (actual, expected) => assert.ok(Math.abs(actual - expected) < 1e-6, `${actual} != ${expected}`);
const check = (state, volume, plane, fragmentAlpha = 0.4, cutAlpha = 0.35) => {
const cut = output(state), settings = session(state);
assert.equal(settings.intersecting, true);
assert.deepEqual([...settings.sources].sort(), ["Box", "CrossingBox"]);
assert.equal(cut.topology.valid, true); near(cut.volume, volume);
const compound = state.objects.find(item => item.name.startsWith("SectionCutCompound"));
assert.equal(compound.type, "Part::FeaturePython");
assert.equal(compound.topology.Solid, 3, "Actual BooleanFragments partition overlapping sources");
const { positions, colors, alphas, triangleCount } = cut.mesh;
assert.equal(colors.length, triangleCount * 9); assert.equal(alphas.length, triangleCount * 3);
let sectionTriangles = 0, sourceTriangles = 0;
for (let triangle = 0; triangle < triangleCount; ++triangle) {
const start = triangle * 9;
const section = [0, 3, 6].every(offset => Math.abs(positions[start + offset] - plane) < 1e-6);
section ? ++sectionTriangles : ++sourceTriangles;
for (let vertex = 0; vertex < 3; ++vertex) {
const rgb = colors.slice(start + vertex * 3, start + vertex * 3 + 3);
assert.deepEqual(rgb, section ? [0, 1, 0] : [1, 1, 0],
JSON.stringify({ triangle, section, positions: positions.slice(start, start + 9), rgb, faceColors: cut.faceColors }));
near(alphas[triangle * 3 + vertex], section ? cutAlpha : fragmentAlpha);
}
}
assert.ok(sectionTriangles > 0 && sourceTriangles > 0);
return { volume: cut.volume, solids: compound.topology.Solid, sectionTriangles, sourceTriangles };
};
const initial = await run({ action: "snapshot" });
const snapshotFile = path.join(directory, "initial-native-snapshot.json");
fs.writeFileSync(snapshotFile, JSON.stringify(initial, null, 2) + "\n");
result.evidenceFiles[snapshotFile] = createHash("sha256").update(fs.readFileSync(snapshotFile)).digest("hex");
record({ boxes: [[10,8,10], [8,10,10]], cutX: 5, intersecting: true }, check(initial, 500, 5),
"Overlapping sources produce partitioned OCCT geometry and spatially correct independent cut and fragment RGBA");
await panel.getByLabel("Cut X position", { exact: true }).fill("4");
await click("Apply section cut");
const changed = await run({ action: "snapshot" }); check(changed, 400, 4);
check(await run({ action: "undo" }), 500, 5);
check(await run({ action: "redo" }), 400, 4);
await run({ action: "save", path: "/tmp/SectionCutMultiSourceAppearance.FCStd" });
await run({ action: "close" });
const reopened = await run({ action: "open", path: "/tmp/SectionCutMultiSourceAppearance.FCStd" });
const restoredCutAlpha = Math.round(0.35 * 255) / 255;
check(reopened, 400, 4, 0.4, restoredCutAlpha);
output(reopened).faceColors.forEach((color, face) => color.forEach((value, channel) =>
near(value, Math.round(output(changed).faceColors[face][channel] * 255) / 255)));
await click("Refresh section cut");
assert.equal(await panel.getByLabel("Intersecting objects", { exact: true }).isChecked(), true);
assert.equal(await panel.getByLabel("Fragment transparency", { exact: true }).inputValue(), "60");
await click("Refresh cut sources");
check(await run({ action: "snapshot" }), 400, 4);
record({ operations: ["plane edit", "undo", "redo", "FCStd reopen", "source refresh"] }, check(reopened, 400, 4, 0.4, restoredCutAlpha),
"Intersecting-source materials follow edited topology and survive transactions and FCStd restoration");
const pixels = [];
const canvas = panel.locator("canvas").first();
const sample = async file => {
// The renderer does not preserve its drawing buffer after composition.
// Read the visible canvas image, as the other appearance cases do.
const png = await canvas.screenshot({ path: file });
result.evidenceFiles[file] = createHash("sha256").update(png).digest("hex");
return page.evaluate(async base64 => {
const image = new Image(); image.src = `data:image/png;base64,${base64}`; await image.decode();
const raster = document.createElement("canvas"); raster.width = image.width; raster.height = image.height;
const ctx = raster.getContext("2d"); ctx.drawImage(image, 0, 0);
const bytes = ctx.getImageData(0, 0, raster.width, raster.height).data;
let yellow = 0, green = 0;
for (let i = 0; i < bytes.length; i += 4) {
if (bytes[i] > bytes[i+2] + 20 && bytes[i+1] > bytes[i+2] + 20) ++yellow;
if (bytes[i+1] > bytes[i] + 20 && bytes[i+1] > bytes[i+2] + 20) ++green;
}
return { yellow, green };
}, png.toString("base64"));
};
for (const width of [1440, 390]) {
await page.setViewportSize({ width, height: 900 }); await canvas.scrollIntoViewIfNeeded();
await page.waitForTimeout(500);
const file = path.join(directory, `multi-source-${width}.png`);
const before = await sample(file); assert.ok(before.yellow > 100); assert.ok(before.green > 100);
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false);
await panel.getByLabel("Fragment transparency", { exact: true }).fill("100");
await click("Apply section cut"); check(await run({ action: "snapshot" }), 400, 4, 0);
await canvas.scrollIntoViewIfNeeded(); await page.waitForTimeout(500);
const after = await sample(path.join(directory, `multi-source-hidden-${width}.png`));
assert.ok(after.yellow < before.yellow * 0.05); assert.ok(after.green > 100);
pixels.push({ width, before, after });
await panel.getByLabel("Fragment transparency", { exact: true }).fill("60");
await click("Apply section cut");
}
record({ widths: [1440,390], fragmentTransparency: [60,100] }, pixels,
"Actual desktop/mobile canvases hide transparent BooleanFragments surfaces while retaining independent cut faces");
stage("multi-source-appearance-complete");
}
export async function runSectionCutContainerCases(ids) {
const capabilityId = "Part:desktop:Part_SectionCut";
if (!ids.includes(capabilityId)) return [];
const directory = path.resolve("docs/current/part-section-cut-containers", new Date().toISOString().replace(/[:.]/g, "-"));
fs.mkdirSync(directory, { recursive: true });
const started = performance.now();
const stages = [];
const stage = (name, detail = {}) => {
stages.push({ name, elapsedMs: performance.now() - started, ...detail });
fs.writeFileSync(path.join(directory, "stages.json"), JSON.stringify(stages, null, 2) + "\n");
};
const result = { capabilityId, status: "failed", cases: [], evidenceFiles: {},
deferredCases: ["runLegacySectionCutCases", "runSectionCutEmptySourcesCases", "runSectionCutFragmentsCases", "runSectionCutOpacityCases", "runSectionCutPersistenceCases"],
remaining: ["Automatic cut-face coloring and color controls", "Independent cut-face and fragment appearance/transparency",
"Container reparenting", "Unexpected post-mutation failure history behavior"] };
const record = (input, actual, name) => {
result.cases.push({ input, actual, assertions: [{ name, passed: true }] });
fs.writeFileSync(path.join(directory, "result.json"), JSON.stringify(result, null, 2) + "\n");
};
const session = state => state.objects.find(item => item.sectionCutSession)?.sectionCutSession;
const objects = state => Object.fromEntries(state.objects.map(item => [item.name, item]));
const signature = state => ({ objects: objects(state), undoCount: state.undoCount, redoCount: state.redoCount });
const near = (actual, expected) => assert.ok(Number.isFinite(actual) && Math.abs(actual - expected) < 1e-6, `${actual} != ${expected}`);
const check = (state, bounds, volume) => {
const cut = state.objects.find(item => item.name === session(state)?.result);
assert.ok(cut); near(cut.volume, volume); assert.equal(cut.topology.valid, true);
assert.ok(cut.mesh.triangleCount > 0); cut.mesh.bounds.forEach((value, i) => near(value, bounds[i]));
assert.equal(cut.faceColors?.length, 6, "Cut retains a material for each native face after edits/history/reopen");
assert.ok(new Set(cut.faceColors.map(color => color.join(","))).size >= 5,
"Five distinct surviving source materials persist through geometry edits, history and FCStd reopen");
assert.equal(cut.mesh.colors?.length, cut.mesh.triangleCount * 9, "Native face materials reach every rendered vertex");
assert.deepEqual(session(state).sources, ["Box"]);
return { bounds: cut.mesh.bounds, volume: cut.volume, triangles: cut.mesh.triangleCount };
};
const sameNativeResult = (state, expected, bounds, volume) => {
assert.deepEqual(state.objects.map(item => item.name).sort(), expected.objects.map(item => item.name).sort());
assert.equal(session(state).result, session(expected).result);
return check(state, bounds, volume);
};
let browser;
try {
for (const file of ["tools/part-section-cut-container-business-cases.mjs", "tools/part-section-cut-business-cases.mjs",
"web/src/part-section-cut-task.tsx", "web/src/part-desktop-adapter.ts", "web/src/part-document-facade.ts",
"web/src/part-view-facade.ts", "web/src/workbench-shell.tsx",
"freecad-source/src/WebAssembly/FreeCADCoreProbe/PartSectionCutDocument.h",
"freecad-source/src/WebAssembly/FreeCADCoreProbe/PartColoredIO.h",
...["js", "wasm", "worker.js"].map(ext => `web/public/kernel/FreeCADWebDocumentProbe.${ext}`)])
result.evidenceFiles[file] = createHash("sha256").update(fs.readFileSync(file)).digest("hex");
stage("browser-launch-enter");
browser = await playwright().chromium.launch({ executablePath: process.env.FREECAD_CHROME ?? "/usr/bin/google-chrome",
headless: process.env.HEADLESS !== "0", args: ["--no-sandbox", "--disable-dev-shm-usage"] });
stage("browser-launch-complete");
const page = await browser.newPage({ viewport: { width: 1440, height: 900 } });
const errors = []; page.on("pageerror", error => errors.push(String(error)));
const documentId = "SectionCutContainers";
await page.goto(`${process.env.FREECAD_BROWSER_ORIGIN ?? "http://127.0.0.1:5180"}/workbench.html?module=Part&command=part.document&document=${documentId}`);
const dispatch = async (command, payload, expectError = false) => {
stage("request-enter", { command, action: payload.action ?? payload.parameters?.operation });
await page.locator("aside > button.command").filter({ has: page.getByText(command, { exact: true }) }).click();
await page.locator("#payload-editor").fill(JSON.stringify(payload));
await page.evaluate(() => { if (window.__freecadWorkbenchState) window.__freecadWorkbenchState.response = null; });
await page.getByRole("button", { name: "执行选中命令", exact: true }).click();
await page.waitForFunction(() => window.__freecadWorkbenchState?.response && !document.querySelector("button.run")?.disabled);
const reply = await page.evaluate(() => window.__freecadWorkbenchState.response);
assert.equal(reply.kind, expectError ? "error" : "result", JSON.stringify(reply));
stage("request-complete", { command, action: payload.action ?? payload.parameters?.operation, kind: reply.kind });
return expectError ? reply.error : reply.result;
};
const run = (args, expectError = false) => dispatch("part.document", { schema: "freecad-web-part/document/v1", module: "Part",
document: documentId, builderInfo: true, includeMesh: true, ...args }, expectError);
const python = async source => {
const reply = await dispatch("part.documentViewCommand", { schema: "freecad-web/document-view/v1", owner: "DocumentProbe",
document: documentId, command: "Std_CommandLine", parameters: { operation: "submit", source: `exec(${JSON.stringify(source)})` } });
assert.equal(reply.stderr, "", JSON.stringify(reply));
};
const snapshot = () => run({ action: "snapshot" });
await run({ action: "create" });
await python(`import FreeCAD as App\nd=App.getDocument('${documentId}')\np=d.addObject('App::Part','Outer')\nn=d.addObject('App::Part','Inner')\np.addObject(n)\nb=d.addObject('Part::Box','Box')\nb.Length=2\nb.Width=4\nb.Height=6\nn.addObject(b)\np.Placement=App.Placement(App.Vector(20,30,40),App.Rotation(App.Vector(0,0,1),90))\nn.Placement.Base=App.Vector(3,0,0)\nb.Placement.Base=App.Vector(1,0,0)\nd.recompute()`);
const palette = [[1,0,0,1],[0,1,0,1],[0,0,1,1],[1,1,0,1],[1,0,1,1],[0,1,1,1]];
await python(`b.addProperty('App::PropertyColorList','WebFaceColors')\nb.WebFaceColors=[tuple(float(x) for x in color) for color in ${JSON.stringify(palette)}]\nd.recompute()`);
const before = await snapshot();
const source = objects(before).Box; source.mesh.bounds.forEach((v, i) => near(v, [16,34,40,20,36,46][i]));
const other = await run({ action: "create", document: "ContainerCutOther" }); await snapshot();
await page.locator(".matrix-list button").filter({ has: page.locator("span", { hasText: /^Part_SectionCut$/ }) }).click();
const panel = page.getByRole("region", { name: "Section cutting", exact: true });
const ready = () => page.waitForFunction(() => {
const fieldset = document.querySelector('section[aria-label="Section cutting"] fieldset'); return fieldset && !fieldset.disabled;
});
const click = async name => {
stage("panel-request-enter", { button: name });
await panel.getByRole("button", { name, exact: true }).click(); await ready();
assert.deepEqual(await panel.getByRole("status").allTextContents(), []);
stage("panel-request-complete", { button: name });
};
await ready(); await panel.getByRole("checkbox", { name: "Cut X", exact: true }).check();
await panel.getByRole("spinbutton", { name: "Cut X position", exact: true }).fill("18");
await click("Apply section cut"); const first = await snapshot();
const firstGeometry = check(first, [16,34,40,18,36,46], 24);
const firstCut = objects(first)[session(first).result];
// Under the parent's Z rotation, the blue source Y-min face is the
// removed world X-max face. All five other source planes survive.
const faceRgb = firstCut.faceColors.map(color => color.slice(0, 3).join(","));
for (const color of [palette[0], palette[1], palette[3], palette[4], palette[5]])
assert.ok(faceRgb.includes(color.slice(0,3).join(",")), `Surviving source face lost material ${color}`);
assert.ok(!faceRgb.includes("0,0,1"), "Removed source face cannot color the result");
const vertexColors = new Set(Array.from({ length: firstCut.mesh.colors.length / 3 },
(_, i) => firstCut.mesh.colors.slice(i * 3, i * 3 + 3).join(",")));
assert.deepEqual([...vertexColors].sort(), [...new Set(faceRgb)].sort());
await python("d.openTransaction('Edit section source colors')\nb.WebFaceColors=[(0.25,0.5,0.75,1)]\nd.recompute()\nd.commitTransaction()");
const recolored = await snapshot();
const recoloredCut = objects(recolored)[session(recolored).result];
assert.deepEqual(recoloredCut.faceColors, Array.from({ length: 6 }, () => [0.25,0.5,0.75,1]));
assert.deepEqual(recolored.objects.map(item => item.name), first.objects.map(item => item.name));
assert.deepEqual(recoloredCut.mesh.colors, Array.from({ length: recoloredCut.mesh.triangleCount * 3 }, () => [0.25,0.5,0.75]).flat());
const colorUndo = await run({ action: "undo" });
assert.deepEqual(objects(colorUndo)[session(colorUndo).result].faceColors, firstCut.faceColors);
const colorRedo = await run({ action: "redo" });
assert.deepEqual(objects(colorRedo)[session(colorRedo).result].faceColors, recoloredCut.faceColors);
await run({ action: "undo" });
record({ operation: "inherit six source face colors through rotated link, compound and cut; edit and undo/redo colors" },
{ faceColors: firstCut.faceColors, renderedVertexColors: [...vertexColors], liveColorEdit: true },
"Native face history preserves surviving source materials and current colors reach browser mesh without rebuilding helpers");
assert.deepEqual(objects(first).Outer, objects(before).Outer); assert.deepEqual(objects(first).Inner, objects(before).Inner);
const link = first.objects.find(item => item.type === "App::Link");
link.mesh.bounds.forEach((v, i) => near(v, source.mesh.bounds[i]));
await click("Section cut undo"); assert.deepEqual(objects(await snapshot()), objects(before));
await click("Section cut redo"); assert.deepEqual(objects(await snapshot()), objects(first));
record({ outer: { position: [20,30,40], rotationZ: 90 }, inner: [3,0,0], source: [1,0,0], planeX: 18 }, firstGeometry,
"Nested container rotation and translation reach the native cut link and world-space plane without changing source membership");
await python("d.openTransaction('Move outer')\np.Placement.Base=App.Vector(21,30,40)\nd.recompute()\nd.commitTransaction()");
const automatic = await snapshot(); check(automatic, [17,34,40,18,36,46], 12);
assert.deepEqual(automatic.objects.map(item => item.name).sort(), first.objects.map(item => item.name).sort());
assert.equal(session(automatic).result, session(first).result);
await click("Section cut undo"); check(await snapshot(), [16,34,40,18,36,46], 24);
await click("Section cut redo"); assert.deepEqual(objects(await snapshot()), objects(automatic));
record({ operation: "move ancestor and recompute without sources refresh" }, check(automatic, [17,34,40,18,36,46], 12),
"Ancestor placement changes recompute the existing native cut, with undo/redo and stable helper identity");
await click("Refresh cut sources"); const moved = await snapshot(); check(moved, [17,34,40,18,36,46], 12);
await click("Section cut undo"); check(await snapshot(), [17,34,40,18,36,46], 12);
await click("Section cut redo"); assert.deepEqual(objects(await snapshot()), objects(moved));
await run({ action: "setPosition", object: "Box", position: [2,0,0] });
const edited = await snapshot(); check(edited, [17,35,40,18,37,46], 12);
await click("Section cut undo"); const stable = await snapshot(); check(stable, [17,34,40,18,36,46], 12);
assert.ok(stable.redoCount > 0);
const rejected = await run({ action: "sectionCut", sectionCut: { operation: "apply",
axes: session(stable).axes.map((axis, i) => i ? axis : { ...axis, position: 1 }) } }, true);
assert.match(rejected.message, /outside source bounds/); assert.deepEqual(signature(await snapshot()), signature(stable));
await click("Section cut redo"); assert.deepEqual(objects(await snapshot()), objects(edited));
record({ operation: "move ancestor, refresh, edit source, reject local-space plane, redo" }, { volumes: [24,12], redoPreserved: true },
"Refresh preserves ancestor movement; linked source edits recompute in container coordinates and invalid world planes preserve redo");
await python("d.openTransaction('Move beyond original cutter')\np.Placement.Base=App.Vector(21,130,140)\nd.recompute()\nd.commitTransaction()");
const distant = await snapshot(); check(distant, [17,135,140,18,137,146], 12);
assert.deepEqual(distant.objects.map(item => item.name).sort(), edited.objects.map(item => item.name).sort());
await click("Section cut undo"); sameNativeResult(await snapshot(), edited, [17,35,40,18,37,46], 12);
await click("Section cut redo"); sameNativeResult(await snapshot(), distant, [17,135,140,18,137,146], 12);
await python("d.openTransaction('Enlarge linked source')\nb.Height=120\nd.recompute()\nd.commitTransaction()");
const enlarged = await snapshot(); check(enlarged, [17,135,140,18,137,260], 240);
const flipped = await run({ action: "sectionCut", sectionCut: { operation: "apply",
axes: session(enlarged).axes.map((axis, i) => i ? axis : { ...axis, flipped: true }) } });
check(flipped, [18,135,140,21,137,260], 720);
await python("d.openTransaction('Move flipped cutter bounds')\np.Placement.Base=App.Vector(21,230,240)\nd.recompute()\nd.commitTransaction()");
const flippedMoved = await snapshot(); check(flippedMoved, [18,235,240,21,237,360], 720);
await click("Section cut undo"); sameNativeResult(await snapshot(), flipped, [18,135,140,21,137,260], 720);
await click("Section cut redo"); sameNativeResult(await snapshot(), flippedMoved, [18,235,240,21,237,360], 720);
await click("Section cut undo");
await click("Section cut undo"); sameNativeResult(await snapshot(), enlarged, [17,135,140,18,137,260], 240);
await click("Section cut undo"); sameNativeResult(await snapshot(), distant, [17,135,140,18,137,146], 12);
await click("Section cut undo"); sameNativeResult(await snapshot(), edited, [17,35,40,18,37,46], 12);
record({ operation: "move source 100 mm in Y/Z and enlarge height to 120 without refresh", planeX: 18 },
{ moved: check(distant, [17,135,140,18,137,146], 12), enlarged: check(enlarged, [17,135,140,18,137,260], 240),
flippedMoved: check(flippedMoved, [18,235,240,21,237,360], 720) },
"Native cutter bounds follow movement and resizing beyond original extents in both cut directions, preserving helper identity and undo/redo");
await run({ action: "save", path: "/tmp/SectionCutContainers.FCStd" }); await run({ action: "close" });
const reopened = await run({ action: "open", path: "/tmp/SectionCutContainers.FCStd" });
check(reopened, [17,35,40,18,37,46], 12);
assert.deepEqual(session(reopened), session(edited));
assert.deepEqual(objects(reopened).Outer.groupMembers, ["Inner"]); assert.deepEqual(objects(reopened).Inner.groupMembers, ["Box"]);
await python(`d=App.getDocument('${documentId}')\nn=d.getObject('Inner')\nd.openTransaction('Rotate restored inner')\nn.Placement.Rotation=App.Rotation(App.Vector(0,0,1),90)\nd.recompute()\nd.commitTransaction()`);
const rotated = await snapshot(); check(rotated, [17,29,40,18,33,46], 24);
await click("Section cut undo"); check(await snapshot(), [17,35,40,18,37,46], 12);
await click("Section cut redo"); assert.deepEqual(objects(await snapshot()), objects(rotated));
record({ operation: "rotate inner ancestor after FCStd reopen without sources refresh", rotationZ: 90 },
check(rotated, [17,29,40,18,33,46], 24), "FCStd preserves native ancestor expression dependencies and noncommuting placement order");
await python("p=d.getObject('Outer')\nd.openTransaction('Move restored cutter bounds')\np.Placement.Base=App.Vector(21,130,140)\nd.recompute()\nd.commitTransaction()");
const restoredDistant = await snapshot(); check(restoredDistant, [17,129,140,18,133,146], 24);
await click("Section cut undo"); assert.deepEqual(objects(await snapshot()), objects(rotated));
await click("Section cut redo"); assert.deepEqual(objects(await snapshot()), objects(restoredDistant));
await click("Section cut undo");
record({ operation: "move restored ancestor beyond original cutter extents without refresh" },
check(restoredDistant, [17,129,140,18,133,146], 24),
"FCStd restores cutter bound expressions as live native dependencies with executable undo/redo");
await click("Refresh section cut");
for (const [name, width, height] of [["desktop",1440,900],["mobile",390,844]]) {
await page.setViewportSize({ width, height });
const canvas = panel.locator('[aria-label="Section cut geometry"] canvas');
const beforeOrbit = await canvas.screenshot();
const area = await canvas.boundingBox(); assert.ok(area);
await page.mouse.move(area.x + area.width * 0.5, area.y + area.height * 0.5);
await page.mouse.down();
await page.mouse.move(area.x + area.width * 0.65, area.y + area.height * 0.6, { steps: 8 });
await page.mouse.up(); await page.waitForTimeout(150);
const png = await canvas.screenshot();
assert.notDeepEqual(png, beforeOrbit, `${name}: orbit must change rendered geometry`);
const count = await page.evaluate(async base64 => {
const image = new Image(); image.src = `data:image/png;base64,${base64}`; await image.decode();
const canvas = document.createElement("canvas"); canvas.width=image.width; canvas.height=image.height;
const ctx=canvas.getContext("2d");ctx.drawImage(image,0,0);const data=ctx.getImageData(0,0,canvas.width,canvas.height).data;
let count=0;for(let i=0;i<data.length;i+=4) if(Math.max(data[i],data[i+1],data[i+2])-Math.min(data[i],data[i+1],data[i+2])>12)count++;
return count;
},png.toString("base64"));
assert.ok(count>100,`${name}: ${count} geometry pixels`);
const file=path.join(directory,`${name}-canvas.png`);fs.writeFileSync(file,png);
result.evidenceFiles[path.relative(process.cwd(),file)]=createHash("sha256").update(png).digest("hex");
assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);
record({operation:"FCStd restored container cut after ancestor rotation",viewport:[width,height]},{pixels:count,volume:24,orbitChanged:true},
"Saved container/link placement restores actual world-space cut geometry and visible desktop/mobile canvas");
}
assert.deepEqual(signature(await run({action:"snapshot",document:"ContainerCutOther"})),signature(other));
assert.deepEqual(errors,[]);result.status="not_implemented";
} catch(error) {result.error=String(error.stack??error);process.stderr.write(result.error+"\n");}
finally {stage("cleanup-enter"); await browser?.close(); stage("cleanup-complete");}
fs.writeFileSync(path.join(directory,"result.json"),JSON.stringify(result,null,2)+"\n");return [result];
}