truck: Mesh-CSG-Fallback bei bündigen B-Rep-Booleans, Befehl 'Koerper verschneiden', Rotationskoerper valide (cone), Tests gegen echtes WASM; STEP-Dateien in FreeCAD geprueft

This commit is contained in:
karim committed 2026-10-23 13:22:50 +02:00
1 parent 2b250a1efa
commit cf608b4438
9 files changed
+432 -8

No files matched your search

+37
View File
@@ -0,0 +1,37 @@
import { describe, expect, it } from "vitest";
import { sampleProject } from "../../model/sampleProject";
import type { ExtrudedSolid } from "../../model/types";
import { combineSolids } from "./solidbool";
const box = (id: string, x0: number, y0: number, x1: number, y1: number, h: number): ExtrudedSolid => ({
id,
type: "extrudedSolid",
levelId: "eg",
points: [{ x: x0, y: y0 }, { x: x1, y: y0 }, { x: x1, y: y1 }, { x: x0, y: y1 }],
height: h,
});
describe("combineSolids", () => {
const a = box("a", 0, 0, 4, 4, 3);
const b = box("b", 2, 2, 6, 6, 2);
it("Vereinigung: Grundfläche = Hüll-Rechteck, Höhe = Maximum, Boolean-Spezifikation über beiden Operanden", () => {
const r = combineSolids(sampleProject, a, b, "union")!;
expect(r.height).toBe(3);
expect(r.points).toEqual([{ x: 0, y: 0 }, { x: 6, y: 0 }, { x: 6, y: 6 }, { x: 0, y: 6 }]);
expect(r.brep!.spec).toMatchObject({ kind: "boolean", op: "union", a: { kind: "extrude" }, b: { kind: "extrude" } });
expect(r.brep!.origin).toEqual(r.points[0]);
});
it("Differenz behält die Grundfläche des ersten Körpers, Durchschnitt die Überlappung", () => {
expect(combineSolids(sampleProject, a, b, "difference")!.points).toEqual(a.points);
const i = combineSolids(sampleProject, a, b, "intersection")!;
expect(i.points).toEqual([{ x: 2, y: 2 }, { x: 4, y: 2 }, { x: 4, y: 4 }, { x: 2, y: 4 }]);
expect(i.height).toBe(2);
});
it("Durchschnitt ohne Überlappung und Pyramiden als Operand ergeben null", () => {
expect(combineSolids(sampleProject, a, box("c", 10, 10, 12, 12, 1), "intersection")).toBeNull();
expect(combineSolids(sampleProject, { ...a, taper: 1 }, b, "union")).toBeNull();
});
});
+188
View File
@@ -0,0 +1,188 @@
// SolidBool — Boolesche Operation (Vereinigung / Differenz / Durchschnitt) zweier Körper
// (`ExtrudedSolid`). Das Ergebnis ist EIN Körper mit B-Rep-Spezifikation (`brep.spec` =
// `boolean`-Knoten über den beiden Operanden): truck rechnet auf B-Rep-Ebene und fällt bei
// koinzidenten Flächen automatisch auf Mesh-CSG zurück (trucksolid::solid_mesh_core).
//
// Schritte: „Ersten Körper wählen" (Klick in seine Grundfläche) → „Zweiten Körper wählen" →
// fertig. Die Operation wählt man als Inline-Option (Default Vereinigung); bei Differenz wird
// der ZWEITE vom ERSTEN abgezogen. Beide Quellkörper werden durch das Ergebnis ersetzt.
import type { ExtrudedSolid, Vec2 } from "../../model/types";
import { getFloor } from "../../model/types";
import { uniqueId } from "../../tools/types";
import { extrudedSolidSpec } from "../../plan/extrudedSolidSpec";
import type { Command, CommandResult, CommandState, CmdOption, Project, ToolDraft } from "../types";
export type SolidBoolOp = "union" | "difference" | "intersection";
const OP_OPTIONS: CmdOption[] = [
{ id: "union", labelKey: "cmd.solidbool.op.union" },
{ id: "difference", labelKey: "cmd.solidbool.op.difference" },
{ id: "intersection", labelKey: "cmd.solidbool.op.intersection" },
];
const OP_IDS = new Set(OP_OPTIONS.map((o) => o.id));
let lastOp: SolidBoolOp = "union";
interface BoolState extends CommandState {
phase: "first" | "second";
op: SolidBoolOp;
firstId: string | null;
}
function pointInPolygon(p: Vec2, poly: Vec2[]): boolean {
let inside = false;
for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) {
const a = poly[i];
const b = poly[j];
if (a.y > p.y !== b.y > p.y && p.x < ((b.x - a.x) * (p.y - a.y)) / (b.y - a.y || 1e-12) + a.x) {
inside = !inside;
}
}
return inside;
}
function bbox(pts: Vec2[]): { x0: number; y0: number; x1: number; y1: number } {
return {
x0: Math.min(...pts.map((p) => p.x)),
y0: Math.min(...pts.map((p) => p.y)),
x1: Math.max(...pts.map((p) => p.x)),
y1: Math.max(...pts.map((p) => p.y)),
};
}
const rect = (b: { x0: number; y0: number; x1: number; y1: number }): Vec2[] => [
{ x: b.x0, y: b.y0 },
{ x: b.x1, y: b.y0 },
{ x: b.x1, y: b.y1 },
{ x: b.x0, y: b.y1 },
];
/** Körper auf der aktiven Ebene, dessen Grundfläche den Punkt enthält (der kleinste gewinnt). */
function pickSolid(project: Project, levelId: string, pt: Vec2): ExtrudedSolid | null {
let best: ExtrudedSolid | null = null;
let bestArea = Infinity;
for (const s of project.extrudedSolids ?? []) {
if (s.levelId !== levelId || !pointInPolygon(pt, s.points)) continue;
const b = bbox(s.points);
const area = (b.x1 - b.x0) * (b.y1 - b.y0);
if (area < bestArea) {
best = s;
bestArea = area;
}
}
return best;
}
/** Ergebnis-Körper aus zwei Operanden (reiner Kern, getestet). `null`, wenn ein Operand keine B-Rep-Beschreibung hat. */
export function combineSolids(
project: Project,
a: ExtrudedSolid,
b: ExtrudedSolid,
op: SolidBoolOp,
): ExtrudedSolid | null {
let baseZ = 0;
try {
baseZ = getFloor(project, a.levelId).baseElevation ?? 0;
} catch {
baseZ = 0;
}
// Operanden mit UK 0 beschreiben (lokales Z ab Geschoss-UK), Verschiebung ist eingebacken.
const sa = extrudedSolidSpec(a, 0);
const sb = extrudedSolidSpec(b, 0);
void baseZ;
if (!sa || !sb) return null;
const ba = bbox(a.points);
const bb = bbox(b.points);
let points: Vec2[];
let height: number;
let label: string;
if (op === "union") {
points = rect({ x0: Math.min(ba.x0, bb.x0), y0: Math.min(ba.y0, bb.y0), x1: Math.max(ba.x1, bb.x1), y1: Math.max(ba.y1, bb.y1) });
height = Math.max(a.height, b.height);
label = "Vereinigung";
} else if (op === "difference") {
points = a.points.map((p) => ({ ...p }));
height = a.height;
label = "Differenz";
} else {
const x0 = Math.max(ba.x0, bb.x0);
const y0 = Math.max(ba.y0, bb.y0);
const x1 = Math.min(ba.x1, bb.x1);
const y1 = Math.min(ba.y1, bb.y1);
if (x1 - x0 < 1e-6 || y1 - y0 < 1e-6) return null;
points = rect({ x0, y0, x1, y1 });
height = Math.min(a.height, b.height);
label = "Durchschnitt";
}
return {
id: uniqueId("body"),
type: "extrudedSolid",
levelId: a.levelId,
points,
height,
brep: {
spec: { kind: "boolean", op, a: sa, b: sb } as unknown as Record<string, unknown>,
origin: points[0],
label,
},
};
}
const reset = (op: SolidBoolOp): BoolState => ({ phase: "first", op, firstId: null, lastPoint: null });
function highlight(project: Project, id: string | null): ToolDraft | null {
const s = id ? (project.extrudedSolids ?? []).find((x) => x.id === id) : null;
return s ? { preview: [{ kind: "poly", pts: s.points, closed: true }], vertices: [] } : null;
}
export const solidBoolCommand: Command = {
name: "solidbool",
labelKey: "cmd.solidbool.label",
floorOnly: true,
prompt: (st) => ((st as BoolState).phase === "second" ? "cmd.solidbool.second" : "cmd.solidbool.first"),
accepts: () => ["point", "option"],
options: () => OP_OPTIONS,
init: (): BoolState => reset(lastOp),
onInput: (state, input, ctx): [CommandState, CommandResult] => {
const s = state as BoolState;
if (input.kind === "option" && OP_IDS.has(input.id)) {
lastOp = input.id as SolidBoolOp;
const ns: BoolState = { ...s, op: lastOp };
return [ns, { draft: highlight(ctx.project, s.firstId) }];
}
if (input.kind !== "point") return [s, { draft: highlight(ctx.project, s.firstId) }];
const hit = pickSolid(ctx.project, ctx.level.id, input.point);
if (!hit) return [s, { draft: highlight(ctx.project, s.firstId) }];
if (s.phase === "first") {
const ns: BoolState = { ...s, phase: "second", firstId: hit.id, lastPoint: input.point };
return [ns, { draft: highlight(ctx.project, hit.id) }];
}
if (hit.id === s.firstId) return [s, { draft: highlight(ctx.project, s.firstId) }];
const firstId = s.firstId!;
const op = s.op;
return [
reset(op),
{
draft: null,
done: true,
commit: (p: Project) => {
const a = (p.extrudedSolids ?? []).find((x) => x.id === firstId);
const b = (p.extrudedSolids ?? []).find((x) => x.id === hit.id);
if (!a || !b) return p;
const merged = combineSolids(p, a, b, op);
if (!merged) return p;
return {
...p,
extrudedSolids: [...(p.extrudedSolids ?? []).filter((x) => x.id !== a.id && x.id !== b.id), merged],
};
},
},
];
},
onMove: (state): [CommandState, CommandResult] => [state, { draft: null }],
onConfirm: (state): [CommandState, CommandResult] => [reset((state as BoolState).op), { draft: null, done: true }],
onCancel: (state): [CommandState, CommandResult] => [reset((state as BoolState).op), { draft: null, done: true }],
};
+5
View File
@@ -15,6 +15,7 @@ import { stairCommand } from "./cmds/stair";
import { columnCommand } from "./cmds/column";
import { roofCommand } from "./cmds/roof";
import { solidCommand } from "./cmds/solid";
import { solidBoolCommand } from "./cmds/solidbool";
import { ceilingOpeningCommand } from "./cmds/ceilingOpening";
import { roomCommand } from "./cmds/room";
import { rectCommand } from "./cmds/rect";
@@ -71,6 +72,7 @@ export const COMMANDS: Record<string, Command> = {
column: columnCommand,
roof: roofCommand,
solid: solidCommand,
solidbool: solidBoolCommand,
ceilingopening: ceilingOpeningCommand,
room: roomCommand,
line: lineCommand,
@@ -142,6 +144,9 @@ export const ALIASES: Record<string, string> = {
stütze: "column",
dach: "roof",
koerper: "solid",
koerperbool: "solidbool",
verschneiden: "solidbool",
bool: "solidbool",
körper: "solid",
kugel: "solid",
body: "solid",
+74
View File
@@ -0,0 +1,74 @@
// Ende-zu-Ende gegen das echte trucksolid-WASM (wie exportStep.test.ts): B-Rep-Körper,
// Mesh-Fallback bei bündigen Flächen, Eckenradius, Rotationskörper, STEP-Roundtrip.
import { describe, expect, it, beforeAll } from "vitest";
import { readFileSync } from "node:fs";
import { sampleProject } from "../model/sampleProject";
import { combineSolids } from "../commands/cmds/solidbool";
import { extrudedSolidSpec } from "../plan/extrudedSolidSpec";
import type { ExtrudedSolid } from "../model/types";
let mod: any;
beforeAll(async () => {
mod = await import("./pkgTruck/trucksolid.js");
await mod.default({ module_or_path: readFileSync("src/engine/pkgTruck/trucksolid_bg.wasm") });
});
const volume = (m: { positions: number[]; indices: number[] }): number => {
let v = 0;
const p = (i: number) => [m.positions[i * 3], m.positions[i * 3 + 1], m.positions[i * 3 + 2]];
for (let t = 0; t < m.indices.length; t += 3) {
const [a, b, c] = [p(m.indices[t]), p(m.indices[t + 1]), p(m.indices[t + 2])];
v += (a[0] * (b[1] * c[2] - b[2] * c[1]) - a[1] * (b[0] * c[2] - b[2] * c[0]) + a[2] * (b[0] * c[1] - b[1] * c[0])) / 6;
}
return Math.abs(v);
};
const build = (spec: unknown, tol = 0.01) => JSON.parse(mod.build_solid_mesh(JSON.stringify({ spec, tol })));
const box = (id: string, x0: number, y0: number, x1: number, y1: number, h: number): ExtrudedSolid => ({
id, type: "extrudedSolid", levelId: "eg", height: h,
points: [{ x: x0, y: y0 }, { x: x1, y: y0 }, { x: x1, y: y1 }, { x: x0, y: y1 }],
});
describe("trucksolid-WASM", () => {
it("Körper verschneiden (bündige Böden → Mesh-Fallback): Vereinigung 72 m³, Differenz 40 m³", () => {
const a = box("a", 0, 0, 4, 4, 3);
const b = box("b", 2, 2, 6, 6, 2);
const u = combineSolids(sampleProject, a, b, "union")!;
expect(volume(build(u.brep!.spec))).toBeCloseTo(48 + 32 - 8, 2);
const d = combineSolids(sampleProject, a, b, "difference")!;
expect(volume(build(d.brep!.spec))).toBeCloseTo(48 - 8, 2);
});
it("Verschobener Grundkörper: Mesh liegt an der neuen Stelle", () => {
const s: ExtrudedSolid = {
...box("k", 5, 5, 7, 7, 2),
brep: { spec: { kind: "cylinder", cx: 1, cy: 1, z0: 0, r: 1, height: 2 }, origin: { x: 0, y: 0 } },
};
const spec = extrudedSolidSpec(s, 3)!; // Verschiebung (5,5), UK 3
const m = build(spec, 0.002);
const xs = m.positions.filter((_: number, i: number) => i % 3 === 0);
const zs = m.positions.filter((_: number, i: number) => i % 3 === 2);
expect(Math.min(...xs)).toBeCloseTo(5, 2); // 1 − 1 + 5
expect(Math.max(...xs)).toBeCloseTo(7, 2);
expect(Math.min(...zs)).toBeCloseTo(3, 3);
expect(Math.max(...zs)).toBeCloseTo(5, 3);
});
it("Eckenradius am Projekt-Körper: Volumen des abgerundeten Rechtecks", () => {
const s: ExtrudedSolid = { ...box("r", 0, 0, 4, 3, 2), cornerRadius: 0.5 };
expect(volume(build(extrudedSolidSpec(s, 0), 0.001))).toBeCloseTo((12 - (4 - Math.PI) * 0.25) * 2, 1);
});
it("Rotationskörper (Revolve) einer Rechteck-Halbebene = Zylinder", () => {
const m = build({ kind: "revolve", profile: [0, 0, 1, 0, 1, 2, 0, 2], angleDeg: 360 }, 0.002);
expect(volume(m)).toBeCloseTo(Math.PI * 2, 1);
});
it("STEP-Export eines Grundkörper-Baums und Wiedereinlesen", () => {
const spec = { kind: "torus", center: [0, 0, 0.5], major: 2, minor: 0.5 };
const step: string = mod.export_step(JSON.stringify({ solids: [spec], fileName: "t.stp" }));
const back = JSON.parse(mod.import_step(step, 0.002));
expect(back).toHaveLength(1);
expect(volume(back[0])).toBeCloseTo(2 * Math.PI * Math.PI * 2 * 0.25, 0);
});
});
+6
View File
@@ -1270,6 +1270,12 @@ export const de = {
"cmd.ceiling.label": "Decke",
"cmd.ceiling.start": "Erster Umrisspunkt der Decke:",
"cmd.ceiling.next": "Nächster Punkt ( Schliessen ):",
"cmd.solidbool.label": "Körper verschneiden",
"cmd.solidbool.first": "Ersten Körper wählen:",
"cmd.solidbool.second": "Zweiten Körper wählen:",
"cmd.solidbool.op.union": "Vereinigung",
"cmd.solidbool.op.difference": "Differenz",
"cmd.solidbool.op.intersection": "Durchschnitt",
"cmd.solid.label": "Körper",
"cmd.solid.center": "Mittelpunkt bzw. erste Ecke:",
"cmd.solid.radius": "Radius:",
+6
View File
@@ -1259,6 +1259,12 @@ export const en: Record<TranslationKey, string> = {
"cmd.ceiling.label": "Ceiling",
"cmd.ceiling.start": "First outline point of ceiling:",
"cmd.ceiling.next": "Next point ( Close ):",
"cmd.solidbool.label": "Boolean solids",
"cmd.solidbool.first": "Select first solid:",
"cmd.solidbool.second": "Select second solid:",
"cmd.solidbool.op.union": "Union",
"cmd.solidbool.op.difference": "Difference",
"cmd.solidbool.op.intersection": "Intersection",
"cmd.solid.label": "Solid",
"cmd.solid.center": "Center or first corner:",
"cmd.solid.radius": "Radius:",
+1 -1
View File
@@ -355,7 +355,7 @@ const TOOLS_2D: ToolId[] = [
"image",
];
const TOOLS_3D: ToolId[] = ["wall", "ceiling", "window", "door", "stair", "room"];
const COMMANDS_3D = ["column", "ceilingopening", "roof", "extrude", "solid", "sectionline", "viewline"];
const COMMANDS_3D = ["column", "ceilingopening", "roof", "extrude", "solid", "solidbool", "sectionline", "viewline"];
const COMMANDS_EDIT = ["move", "copy", "array", "rotate", "mirror", "offset", "multiline", "trim", "break", "extend", "fillet", "chamfer", "join", "defblock", "measure"];
type ToolsView = "list" | "icons";
+8
View File
@@ -186,6 +186,14 @@ export function CommandIcon({ name }: { name: string }) {
<path d="M9.5 12.5 L12.5 9.5 L12.5 4.5" />
</svg>
);
case "solidbool":
// Verschneiden: zwei überlappende Körper.
return (
<svg {...common}>
<rect x="2.5" y="3.5" width="7" height="7" />
<circle cx="10" cy="9.5" r="3.6" />
</svg>
);
case "solid":
// Körper: Kugel mit Äquator (B-Rep-Grundkörper).
return (