Abzugskoerper (Boolean im Gebaeude): Durchbruch/Nische zieht sich von Waenden, Decken, Stuetzen ab — Grundriss, Schnitt, 3D (truck-Boolean), STEP; Befehl Durchbruch, Panel-Felder

This commit is contained in:
karim committed 2026-10-23 15:07:43 +02:00
1 parent fd4319d8b2
commit cafbb029fa
47 files changed
+1485 -569

No files matched your search

+2 -1
View File
@@ -10,7 +10,7 @@ import type { Drawing2D, Project, Vec2 } from "../model/types";
import { getFloor } from "../model/types";
import { projectToModel3d } from "../plan/toWalls3d";
import { extrudedSolidSpec } from "../plan/extrudedSolidSpec";
import { wallSpec } from "../export/exportStep";
import { wallSpec } from "../plan/wallSpec";
import { solidClash, solidProps } from "../engine/truckSolid";
import type { SolidSpec } from "../engine/truckSolid";
@@ -56,6 +56,7 @@ export function clashItems(project: Project): ClashItem[] {
});
}
for (const solid of project.extrudedSolids ?? []) {
if (solid.operation === "subtract") continue; // Abzugskörper sind gewollte Durchdringungen
let baseZ = 0;
try {
baseZ = solid.levelId ? (getFloor(project, solid.levelId).baseElevation ?? 0) : 0;
+26
View File
@@ -0,0 +1,26 @@
import { describe, expect, it } from "vitest";
import { sampleProject } from "../../model/sampleProject";
import type { CommandContext } from "../types";
import { voidBoxCommand, voidFromInputs } from "./voidbox";
const ctx = { project: sampleProject, level: { id: "eg" } } as unknown as CommandContext;
describe("Durchbruch", () => {
it("legt einen Abzugskoerper mit Hoehe und Abstand an", () => {
let st = voidBoxCommand.init();
[st] = voidBoxCommand.onInput(st, { kind: "point", point: { x: 1, y: 1 } }, ctx);
[st] = voidBoxCommand.onInput(st, { kind: "point", point: { x: 1.4, y: 2 } }, ctx);
[st] = voidBoxCommand.onInput(st, { kind: "number", value: 0.3 }, ctx);
const [, res] = voidBoxCommand.onInput(st, { kind: "number", value: 1.2 }, ctx);
const p = res.commit!(sampleProject);
const v = p.extrudedSolids!.at(-1)!;
expect(v.operation).toBe("subtract");
expect(v.height).toBe(0.3);
expect(v.baseOffset).toBe(1.2);
expect(v.points).toHaveLength(4);
});
it("entartete Eingaben ergeben nichts", () => {
expect(voidFromInputs("eg", { x: 0, y: 0 }, { x: 0, y: 1 }, 1, 0)).toBeNull();
expect(voidFromInputs("eg", { x: 0, y: 0 }, { x: 1, y: 1 }, 0, 0)).toBeNull();
});
});
+136
View File
@@ -0,0 +1,136 @@
// Durchbruch — legt einen quaderförmigen Abzugskörper an (`ExtrudedSolid.operation =
// "subtract"`, s. `plan/voids.ts`): er zieht sich von allen Wänden, Decken und Stützen ab, die er
// durchdringt (Grundriss, Schnitt, 3D, STEP). Für Leitungsdurchbrüche, Nischen, Schlitze.
//
// Schritte: Ecke → Gegenecke → Höhe → Abstand über Geschoss-UK (Zahl tippen; Enter = 0).
// Beliebige Profile: Polylinie extrudieren und im Objekt-Panel „Abzugskörper" setzen.
import type { ExtrudedSolid } from "../../model/types";
import { uniqueId } from "../../tools/types";
import type { Command, CommandResult, CommandState, Project, ToolDraft, Vec2 } from "../types";
type Step = "corner" | "corner2" | "height" | "offset";
interface VoidState extends CommandState {
step: Step;
p0: Vec2 | null;
p1: Vec2 | null;
height: number | null;
cursor: Vec2 | null;
}
/** Letzte Werte (Enter übernimmt sie beim nächsten Mal). */
let lastHeight = 0.3;
let lastOffset = 1.0;
const rectPts = (a: Vec2, b: Vec2): Vec2[] => {
const [x0, x1] = [Math.min(a.x, b.x), Math.max(a.x, b.x)];
const [y0, y1] = [Math.min(a.y, b.y), Math.max(a.y, b.y)];
return [{ x: x0, y: y0 }, { x: x1, y: y0 }, { x: x1, y: y1 }, { x: x0, y: y1 }];
};
/** Abzugskörper aus den Eingaben (reiner Kern, getestet). */
export function voidFromInputs(levelId: string, a: Vec2, b: Vec2, height: number, offset: number): ExtrudedSolid | null {
if (Math.abs(b.x - a.x) < 1e-6 || Math.abs(b.y - a.y) < 1e-6 || !(height > 1e-6)) return null;
return {
id: uniqueId("void"),
type: "extrudedSolid",
levelId,
points: rectPts(a, b),
height,
operation: "subtract",
...(Math.abs(offset) > 1e-9 ? { baseOffset: offset } : {}),
};
}
function draftOf(s: VoidState): ToolDraft | null {
if (!s.p0) return null;
const b = s.p1 ?? s.cursor ?? s.p0;
const pts = rectPts(s.p0, b);
return {
preview: [
{ kind: "poly", pts, closed: true },
{ kind: "line", a: pts[0], b: pts[2] },
{ kind: "line", a: pts[1], b: pts[3] },
],
vertices: [s.p0],
hud: {
at: b,
text:
s.step === "corner2"
? `${Math.abs(b.x - s.p0.x).toFixed(2)} × ${Math.abs(b.y - s.p0.y).toFixed(2)} m`
: s.step === "height"
? `h = ${lastHeight.toFixed(2)} m (Enter)`
: `UK + ${lastOffset.toFixed(2)} m (Enter)`,
},
};
}
const reset = (): VoidState => ({ phase: "void", step: "corner", p0: null, p1: null, height: null, cursor: null, lastPoint: null });
const PROMPT: Record<Step, string> = {
corner: "cmd.void.corner",
corner2: "cmd.void.corner2",
height: "cmd.void.height",
offset: "cmd.void.offset",
};
function finish(s: VoidState, offset: number, levelId: string): [CommandState, CommandResult] {
lastOffset = offset;
const solid = s.p0 && s.p1 && s.height ? voidFromInputs(levelId, s.p0, s.p1, s.height, offset) : null;
return [
reset(),
{
draft: null,
done: true,
commit: (p: Project) => (solid ? { ...p, extrudedSolids: [...(p.extrudedSolids ?? []), solid] } : p),
},
];
}
export const voidBoxCommand: Command = {
name: "voidbox",
labelKey: "cmd.void.label",
floorOnly: true,
prompt: (st) => PROMPT[(st as VoidState).step] as never,
accepts: (st) => ((st as VoidState).step === "height" || (st as VoidState).step === "offset" ? ["number"] : ["point"]),
options: () => [],
init: (): VoidState => reset(),
onInput: (state, input, ctx): [CommandState, CommandResult] => {
const s = state as VoidState;
if (s.step === "corner" && input.kind === "point") {
const ns: VoidState = { ...s, step: "corner2", p0: input.point, cursor: input.point, lastPoint: input.point };
return [ns, { draft: draftOf(ns) }];
}
if (s.step === "corner2" && input.kind === "point") {
const ns: VoidState = { ...s, step: "height", p1: input.point };
return [ns, { draft: draftOf(ns) }];
}
if (s.step === "height" && input.kind === "number" && input.value > 0) {
lastHeight = input.value;
const ns: VoidState = { ...s, step: "offset", height: input.value };
return [ns, { draft: draftOf(ns) }];
}
if (s.step === "offset" && input.kind === "number") return finish(s, input.value, ctx.level.id);
return [s, { draft: draftOf(s) }];
},
onMove: (state, point): [CommandState, CommandResult] => {
const s = state as VoidState;
const ns: VoidState = { ...s, cursor: point };
return [ns, { draft: draftOf(ns) }];
},
// Enter übernimmt die letzten Werte (Höhe bzw. Abstand).
onConfirm: (state, ctx): [CommandState, CommandResult] => {
const s = state as VoidState;
if (s.step === "height") {
const ns: VoidState = { ...s, step: "offset", height: lastHeight };
return [ns, { draft: draftOf(ns) }];
}
if (s.step === "offset") return finish(s, lastOffset, ctx.level.id);
return [reset(), { draft: null, done: true }];
},
onCancel: (): [CommandState, CommandResult] => [reset(), { draft: null, done: true }],
};
+5
View File
@@ -16,6 +16,7 @@ import { columnCommand } from "./cmds/column";
import { roofCommand } from "./cmds/roof";
import { solidCommand } from "./cmds/solid";
import { solidBoolCommand } from "./cmds/solidbool";
import { voidBoxCommand } from "./cmds/voidbox";
import { ceilingOpeningCommand } from "./cmds/ceilingOpening";
import { roomCommand } from "./cmds/room";
import { rectCommand } from "./cmds/rect";
@@ -73,6 +74,7 @@ export const COMMANDS: Record<string, Command> = {
roof: roofCommand,
solid: solidCommand,
solidbool: solidBoolCommand,
voidbox: voidBoxCommand,
ceilingopening: ceilingOpeningCommand,
room: roomCommand,
line: lineCommand,
@@ -144,6 +146,9 @@ export const ALIASES: Record<string, string> = {
stütze: "column",
dach: "roof",
koerper: "solid",
durchbruch: "voidbox",
nische: "voidbox",
void: "voidbox",
koerperbool: "solidbool",
verschneiden: "solidbool",
bool: "solidbool",
+23
View File
@@ -50,4 +50,27 @@ describe("STEP-Export Ende-zu-Ende (truck-WASM)", () => {
expect(back.length).toBeGreaterThan(5);
expect(back.every((m) => m.indices.length >= 12)).toBe(true);
}, 60_000);
it("Abzugskörper: Wandschichten werden boolesch geschnitten (Volumen kleiner), STEP bleibt gültig", async () => {
const mod: any = await import("../engine/pkgTruck/trucksolid.js");
await mod.default({ module_or_path: readFileSync("src/engine/pkgTruck/trucksolid_bg.wasm") });
const w = sampleProject.walls[0];
const mx = (w.start.x + w.end.x) / 2;
const my = (w.start.y + w.end.y) / 2;
const p = {
...sampleProject,
extrudedSolids: [{
id: "v", type: "extrudedSolid" as const, levelId: w.floorId, operation: "subtract" as const, height: 0.8, baseOffset: 0.5,
points: [{ x: mx - 0.3, y: my - 1 }, { x: mx + 0.3, y: my - 1 }, { x: mx + 0.3, y: my + 1 }, { x: mx - 0.3, y: my + 1 }],
}],
};
const specs = projectSolidSpecs(p);
const bools = specs.filter((s) => s.kind === "boolean");
expect(bools.length).toBeGreaterThan(0);
const vol = (spec: unknown) => JSON.parse(mod.solid_props(JSON.stringify({ spec }))).volume as number;
const b0 = bools[0] as { a: unknown };
expect(vol(bools[0])).toBeLessThan(vol(b0.a) - 1e-4);
const step: string = mod.export_step(JSON.stringify({ solids: bools, fileName: "void.stp" }));
expect(step.startsWith("ISO-10303-21;")).toBe(true);
}, 60_000);
});
+32 -70
View File
@@ -16,103 +16,53 @@
import type { Project } from "../model/types";
import { getFloor, roofLayers } from "../model/types";
import { projectToModel3d } from "../plan/toWalls3d";
import type { RWall } from "../plan/toWalls3d";
import { roofBaseElevation, roofGeometry } from "../geometry/roof";
import { exportStepSolids } from "../engine/truckSolid";
import { extrudedSolidSpec } from "../plan/extrudedSolidSpec";
import type { SolidSpec } from "../engine/truckSolid";
import { wallSpec } from "../plan/wallSpec";
import { bbox, hittingVoids, subtractSpec, voidPrisms, wallCorners } from "../plan/voids";
import type { Box2 } from "../plan/voids";
export { wallProfile, wallSpec } from "../plan/wallSpec";
const EPS = 1e-6;
/** Schicht/Öffnung so dünn, dass sie als nicht vorhanden gilt. */
const MIN_THICKNESS = 1e-4;
/**
* Wandprofil (u = Achse, v = Höhe über Wandfuss) mit Öffnungen: Löcher, die ganz im Profil
* liegen; Öffnungen am Wandfuss (Türen) als Kerben im Aussenring. Öffnungen am Wandkopf
* werden um 1 mm gekappt (ein Loch darf den Rand nicht berühren).
* Boolean-Spezifikation (Bauteil − Abzugskörper) → dieselbe ohne Abzug. Scheitert truck am
* Boolean, exportiert `exportProjectStep` das Bauteil wenigstens ungeschnitten.
*/
export function wallProfile(
length: number,
height: number,
holes: Array<{ from: number; to: number; zBottom: number; zTop: number }>,
baseElevation: number,
): { outer: number[]; holes: number[][] } {
const inner: number[][] = [];
const notches: Array<[number, number, number]> = []; // [from, to, top]
const cut = 1e-3;
for (const h of holes) {
const u0 = Math.max(0, Math.min(length, h.from));
const u1 = Math.max(0, Math.min(length, h.to));
if (u1 - u0 < MIN_THICKNESS) continue;
const v0 = h.zBottom - baseElevation;
const v1 = Math.min(height - cut, h.zTop - baseElevation);
if (v1 - Math.max(v0, 0) < MIN_THICKNESS) continue;
if (v0 <= cut) notches.push([u0, u1, v1]);
else inner.push([u0, v0, u1, v0, u1, v1, u0, v1]);
}
// Kerben sortieren und überlappende zusammenfassen.
notches.sort((a, b) => a[0] - b[0]);
const merged: Array<[number, number, number]> = [];
for (const n of notches) {
const last = merged[merged.length - 1];
if (last && n[0] <= last[1] + EPS) {
last[1] = Math.max(last[1], n[1]);
last[2] = Math.max(last[2], n[2]);
} else merged.push([...n]);
}
// Aussenring CCW in (u,v): Wandfuss links→rechts mit Kerben, dann Kopf rechts→links.
const outer: number[] = [0, 0];
for (const [a, b, top] of merged) {
outer.push(a, 0, a, top, b, top, b, 0);
}
outer.push(length, 0, length, height, 0, height);
return { outer, holes: inner };
}
export function wallSpec(w: RWall): SolidSpec | null {
const dx = w.end[0] - w.start[0];
const dy = w.end[1] - w.start[1];
const len = Math.hypot(dx, dy);
if (len < MIN_THICKNESS || w.height < MIN_THICKNESS || w.thickness < MIN_THICKNESS) return null;
const ux = dx / len;
const uy = dy / len;
// u × v (v = +Z) = (uy, −ux, 0): Extrusionsrichtung. Ursprung = eine Wandfläche.
const nx = uy;
const ny = -ux;
const prof = wallProfile(len, w.height, w.holes ?? [], w.baseElevation);
return {
kind: "extrudePlane",
points: prof.outer,
holes: prof.holes,
origin: [
w.start[0] - (nx * w.thickness) / 2,
w.start[1] - (ny * w.thickness) / 2,
w.baseElevation,
],
uAxis: [ux, uy, 0],
vAxis: [0, 0, 1],
depth: w.thickness,
};
}
const VOID_FALLBACK = new WeakMap<SolidSpec, SolidSpec>();
/** Alle Bauteile des Projekts als B-Rep-Spezifikationen (reiner Kern, kein WASM). */
export function projectSolidSpecs(project: Project): SolidSpec[] {
const out: SolidSpec[] = [];
const model = projectToModel3d(project, { layeredWalls: true });
const voids = voidPrisms(project);
const withVoids = (base: SolidSpec, foot: Box2, z0: number, z1: number): SolidSpec => {
const hits = hittingVoids(voids, foot, z0, z1);
if (hits.length === 0) return base;
const spec = subtractSpec(base, hits);
VOID_FALLBACK.set(spec, base);
return spec;
};
for (const w of model.walls) {
const s = wallSpec(w);
if (s) out.push(s);
if (s) out.push(withVoids(s, bbox(wallCorners(w)), w.baseElevation, w.baseElevation + w.height));
}
for (const s of model.slabs) {
if (s.outline.length < 3 || s.zTop - s.zBottom < MIN_THICKNESS) continue;
out.push({
const base: SolidSpec = {
kind: "extrude",
points: s.outline.flatMap((p) => [p[0], p[1]]),
height: s.zTop - s.zBottom,
z0: s.zBottom,
});
};
out.push(withVoids(base, bbox(s.outline.map((p) => ({ x: p[0], y: p[1] }))), s.zBottom, s.zTop));
}
for (const roof of project.roofs ?? []) {
@@ -148,6 +98,7 @@ export function projectSolidSpecs(project: Project): SolidSpec[] {
}
for (const solid of project.extrudedSolids ?? []) {
if (solid.operation === "subtract") continue; // Abzugskörper sind kein Material
let baseZ = 0;
if (solid.levelId) {
try {
@@ -200,6 +151,17 @@ export async function exportProjectStep(project: Project, fileName = ""): Promis
await exportStepSolids([specs[i]], "");
good.push(specs[i]);
} catch (e) {
const fallback = VOID_FALLBACK.get(specs[i]);
if (fallback) {
try {
await exportStepSolids([fallback], "");
good.push(fallback);
skipped.push({ index: i, error: "Abzugskörper nicht abziehbar — Bauteil ungeschnitten exportiert" });
continue;
} catch {
/* unten melden */
}
}
skipped.push({ index: i, error: e instanceof Error ? e.message : String(e) });
}
}
+8
View File
@@ -712,6 +712,9 @@ export const de = {
"objinfo.extrudedSolid.cornerRadius": "Eckenradius",
"objinfo.extrudedSolid.chamfer": "Fase",
"objinfo.extrudedSolid.brep": "B-Rep-Körper",
"objinfo.extrudedSolid.baseOffset": "Abstand über Geschoss-UK",
"objinfo.extrudedSolid.subtract": "Abzugskörper",
"objinfo.extrudedSolid.subtractHint": "Zieht den Körper von Wänden, Decken und Stützen ab (Aussparung/Durchbruch)",
"objinfo.extrudedSolid.volume": "Volumen",
"objinfo.extrudedSolid.surface": "Oberfläche",
"objinfo.extrudedSolid.centroid": "Schwerpunkt",
@@ -1281,6 +1284,11 @@ export const de = {
"cmd.solidbool.op.union": "Vereinigung",
"cmd.solidbool.op.difference": "Differenz",
"cmd.solidbool.op.intersection": "Durchschnitt",
"cmd.void.label": "Durchbruch",
"cmd.void.corner": "Erste Ecke des Durchbruchs:",
"cmd.void.corner2": "Gegenecke:",
"cmd.void.height": "Höhe (Enter = letzte):",
"cmd.void.offset": "Abstand über Geschoss-UK (Enter = letzter):",
"cmd.solid.label": "Körper",
"cmd.solid.center": "Mittelpunkt bzw. erste Ecke:",
"cmd.solid.radius": "Radius:",
+8
View File
@@ -708,6 +708,9 @@ export const en: Record<TranslationKey, string> = {
"objinfo.extrudedSolid.cornerRadius": "Corner radius",
"objinfo.extrudedSolid.chamfer": "Chamfer",
"objinfo.extrudedSolid.brep": "B-rep solid",
"objinfo.extrudedSolid.baseOffset": "Offset above storey base",
"objinfo.extrudedSolid.subtract": "Subtraction body",
"objinfo.extrudedSolid.subtractHint": "Subtracts the body from walls, slabs and columns (recess/penetration)",
"objinfo.extrudedSolid.volume": "Volume",
"objinfo.extrudedSolid.surface": "Surface",
"objinfo.extrudedSolid.centroid": "Centroid",
@@ -1270,6 +1273,11 @@ export const en: Record<TranslationKey, string> = {
"cmd.solidbool.op.union": "Union",
"cmd.solidbool.op.difference": "Difference",
"cmd.solidbool.op.intersection": "Intersection",
"cmd.void.label": "Penetration",
"cmd.void.corner": "First corner of the penetration:",
"cmd.void.corner2": "Opposite corner:",
"cmd.void.height": "Height (Enter = last):",
"cmd.void.offset": "Offset above storey base (Enter = last):",
"cmd.solid.label": "Solid",
"cmd.solid.center": "Center or first corner:",
"cmd.solid.radius": "Radius:",
+9
View File
@@ -2204,6 +2204,15 @@ export interface ExtrudedSolid {
points: Vec2[];
/** Extrusionshöhe in Metern (> 0), nach +Z ab der Geschoss-UK. */
height: number;
/** Abstand der Körper-UK über der Geschoss-UK (Meter, Default 0). */
baseOffset?: number;
/**
* Boolesche Rolle im Gebäude: "subtract" = Abzugskörper (Aussparung/Durchbruch/Nische).
* Er zieht sich von allen Wänden, Decken und Stützen ab, die er durchdringt — in 3D
* (truck-Boolean), im Grundriss und im Schnitt; selbst wird er nur als Umriss gezeigt.
* Fehlt = normaler Körper.
*/
operation?: "subtract";
/**
* Gesetzt, wenn das Profil ein Kreis ist (aus einem `Drawing2D` mit
* `shape:"circle"`) — `points` bleibt die Tessellierung, `toWalls3d.ts`
+29
View File
@@ -712,6 +712,35 @@ export function ExtrudedSolidSection({
<SolidPropsRows spec={solid.spec} />
{/* Abstand über Geschoss-UK (Brüstungs-/Durchbruchshöhe). */}
<div className="objinfo-field">
<span className="objinfo-flabel">{t("objinfo.extrudedSolid.baseOffset")}</span>
<input
type="number"
className="objinfo-text"
step={0.05}
value={solid.baseOffset}
onChange={(e) => {
const v = Number(e.target.value);
if (Number.isFinite(v)) host.onSetExtrudedSolidBaseOffset(v);
}}
title={t("objinfo.extrudedSolid.baseOffset")}
/>
</div>
{/* Abzugskörper: zieht sich von Wänden/Decken/Stützen ab (Grundriss, Schnitt, 3D, STEP). */}
{solid.canSubtract && (
<div className="objinfo-field">
<span className="objinfo-flabel">{t("objinfo.extrudedSolid.subtract")}</span>
<input
type="checkbox"
checked={solid.subtract}
onChange={(e) => host.onSetExtrudedSolidSubtract(e.target.checked)}
title={t("objinfo.extrudedSolid.subtractHint")}
/>
</div>
)}
{solid.brepLabel && (
<div className="objinfo-field">
<span className="objinfo-flabel">{t("objinfo.extrudedSolid.brep")}</span>
+4
View File
@@ -536,6 +536,10 @@ export interface PanelHostValue {
onSetExtrudedSolidCornerRadius: (radius: number) => void;
/** Setzt die Fase der Aussenkontur (Meter, ≥ 0). */
onSetExtrudedSolidChamfer: (chamfer: number) => void;
/** Abzugskörper ein/aus (zieht sich von Wänden/Decken/Stützen ab). */
onSetExtrudedSolidSubtract: (subtract: boolean) => void;
/** Abstand der Körper-UK über der Geschoss-UK (Meter). */
onSetExtrudedSolidBaseOffset: (offset: number) => void;
// ── Stützen-Attribute (Tragwerk; nur die selektierte Stütze) ────────────
/** Wechselt das Profil (Rechteck/Kreis); leitet ein sinnvolles Mass ab. */
+2 -1
View File
@@ -20,7 +20,8 @@ export function needsBrepPath(solid: ExtrudedSolid): boolean {
* B-Rep-Spezifikation des Körpers, UK auf `baseZ`. `null`, wenn truck dafür (noch) keine
* Beschreibung hat (Pyramide: Spitze als B-Rep entartet).
*/
export function extrudedSolidSpec(solid: ExtrudedSolid, baseZ: number): SolidSpec | null {
export function extrudedSolidSpec(solid: ExtrudedSolid, floorZ: number): SolidSpec | null {
const baseZ = floorZ + (solid.baseOffset ?? 0);
if (solid.brep) {
const p0 = solid.points[0];
const dx = p0 ? p0.x - solid.brep.origin.x : 0;
+5
View File
@@ -70,6 +70,7 @@ import {
type Primitive,
} from "./generatePlan/shared";
import { addCeilingPoche } from "./generatePlan/ceilings";
import { subtractVoidsInPlan } from "./voids";
import { addContextContours } from "./generatePlan/context";
import { DEFAULT_SCALE_DENOMINATOR } from "../model/dimension";
import {
@@ -662,6 +663,9 @@ export function generatePlan(
// Schwarz-Weiss (mono): nachträglich alle Farben auf reine Tinte zwingen.
// Element-/Kategorie-/Hatch-Farben werden ignoriert, Füllungen werden weiss,
// Musterlinien/Striche schwarz — so entsteht ein reiner S/W-Plan.
// Abzugskörper (Aussparungen/Durchbrüche): von Wand-/Stützen-/Decken-Poché abziehen.
subtractVoidsInPlan(primitives, project, (floor?.baseElevation ?? 0) + (floor?.cutHeight ?? 1.0));
if (mono) toMono(primitives);
// Georeferenzierte Luftbilder als Hintergrund-Ebenen (nur interaktive Ansicht,
@@ -925,6 +929,7 @@ export function generateSectionPlan(
ceilingId: kind === "slab" && !cp.stairId ? sourceId : undefined,
roofId: kind === "roof" ? sourceId : undefined,
stairId: cp.stairId,
noStrokeEdges: cp.noStrokeEdges,
greyed: cp.categoryCode !== undefined && catDisplay(cp.categoryCode).greyed,
});
}
+22
View File
@@ -30,6 +30,28 @@ const EXTRUSION_STROKE = "#d98c40";
* keine Schnitt-Poché/Kategorie-Zuordnung hat.
*/
export function addExtrudedSolidOutline(out: Primitive[], solid: ExtrudedSolid): void {
if (solid.operation === "subtract") {
// Abzugskörper (Aussparung): gestrichelter Umriss + Diagonalkreuz (Durchbruch-Symbol),
// darunter eine unsichtbare Fläche für die Auswahl.
out.push({
kind: "polygon",
pts: solid.points,
fill: "none",
stroke: "none",
strokeWidthMm: 0,
hatch: NO_HATCH,
extrudedSolidId: solid.id,
});
const n = solid.points.length;
const seg = (a: (typeof solid.points)[number], b: (typeof solid.points)[number], dash: number[] | null) =>
out.push({ kind: "line", a, b, cls: "void", weightMm: SYMBOL_HAIRLINE_MM, dash, color: EXTRUSION_STROKE });
for (let i = 0; i < n; i++) seg(solid.points[i], solid.points[(i + 1) % n], [2, 1]);
if (n === 4) {
seg(solid.points[0], solid.points[2], null);
seg(solid.points[1], solid.points[3], null);
}
return;
}
out.push({
kind: "polygon",
pts: solid.points,
+1 -1
View File
@@ -87,7 +87,7 @@ export function pushNativeWalls(project: Project): void {
clearTimeout(wallsTimer);
wallsTimer = setTimeout(async () => {
if (!(await isNativeEnabled())) return;
void invokeNative("push_native_walls", { walls: projectToModel3d(project) });
void invokeNative("push_native_walls", { walls: projectToModel3d(project, { voids: true }) });
}, DEBOUNCE_MS);
}
+10
View File
@@ -24,6 +24,7 @@ import { dot, leftNormal, normalize, sub } from "../model/geometry";
import { openingInterval, openingVerticalExtent } from "../geometry/opening";
import { roofBaseElevation, roofGeometry } from "../geometry/roof";
import { projectToModel3d } from "./toWalls3d";
import { subtractVoidsInSection } from "./voids";
import { loadEngine3d } from "../engine/engine3d";
import {
HATCH_INK,
@@ -50,6 +51,8 @@ export interface SectionCutPolygon {
color: [number, number, number];
/** Ring-Ecken (u, v). */
pts: Array<[number, number]>;
/** Nicht gestrichene Kanten (Stege eingehängter Löcher, s. `plan/voids.ts`). */
noStrokeEdges?: number[];
/**
* Echte Poché-Füllfarbe des geschnittenen Bauteils (tragende Wandschicht
* bzw. erste Deckenschicht), von `computeSection` aufgelöst. Fehlt, wenn das
@@ -1266,6 +1269,13 @@ export async function computeSection(
cp.categoryCode = st.categoryCode;
}
output.cutPolygons = mergeMonolithCuts(output.cutPolygons, (i) => model.slabs[i]?.monolith);
// Abzugskörper (Aussparungen/Durchbrüche) aus den geschnittenen Bauteilen entfernen.
output.cutPolygons = subtractVoidsInSection(
output.cutPolygons,
project,
{ x: plane.point[0], y: plane.point[2] },
sectionUAxisModel(plane),
);
// Schnitt-Tiefe: Kanten weiter als `level.depth` hinter der Ebene ausblenden.
if (level.depth !== undefined) filterByDepth(output, project, plane, level.depth);
return output;
+9 -1
View File
@@ -68,6 +68,7 @@ import { emitWall } from "./toWalls3d/bands";
import { emitSlabs } from "./toWalls3d/ceilings";
import { emitStairMeshes, emitStairRailings, emitStairs } from "./toWalls3d/stairs";
import { emitExtrudedSolids, TRUCK_MESH_READY_EVENT } from "./toWalls3d/extrusions";
import { applyVoids3d } from "./toWalls3d/voids3d";
import { emitDrawingLineVerts, pickDrawingSegs } from "./toWalls3d/drawing2d";
import { emitColumns } from "./toWalls3d/columns";
import { emitRoofCutLayers, emitRoofs } from "./toWalls3d/roofs";
@@ -199,13 +200,18 @@ export interface Model3dOptions {
detail?: DetailLevel;
/** Schnitt-Eingabe: Treppen immer als Tritt-Prismen (s. `emitStairs` `forSection`). */
forSection?: boolean;
/**
* 3D-Viewer: Abzugskörper per truck-Boolean von Wänden/Decken abziehen (s.
* `toWalls3d/voids3d.ts`). Schnitt/Ansicht/Export behandeln Abzugskörper selbst.
*/
voids?: boolean;
}
/** Das volle 3D-Modell: Wände (mit Öffnungen) + Deckenplatten + Kontext-Meshes. */
export function projectToModel3d(project: Project, opts: Model3dOptions = {}): RModel3d {
const layered = opts.layeredWalls ?? true;
const detail = opts.detail ?? "fein";
return {
const model: RModel3d = {
walls: projectToWalls3d(project, layered),
// Decken + Treppen (Treppentritte als extrudierte Slabs) — so wird die Treppe
// auch im WASM/wgpu-Renderer sichtbar (der three.js-Pfad rendert sie separat).
@@ -231,6 +237,8 @@ export function projectToModel3d(project: Project, opts: Model3dOptions = {}): R
// weil `section.rs` beliebige Dreiecksnetze nicht schneiden kann.
roofLayers: emitRoofCutLayers(project),
};
if (opts.voids) applyVoids3d(model, project);
return model;
}
/**
+5 -2
View File
@@ -36,7 +36,7 @@ const truckMeshCache = new Map<string, TruckCacheEntry>();
function extrudedSolidSignature(solid: ExtrudedSolid): string {
const brep = solid.brep ? `${JSON.stringify(solid.brep.spec)}@${solid.brep.origin.x},${solid.brep.origin.y}` : "";
return `${solid.height}|${solid.taper ?? 0}|${solid.cornerRadius ?? 0}|${solid.chamfer ?? 0}|${brep}|${solid.points.map((p) => `${p.x},${p.y}`).join(";")}`;
return `${solid.baseOffset ?? 0}|${solid.height}|${solid.taper ?? 0}|${solid.cornerRadius ?? 0}|${solid.chamfer ?? 0}|${brep}|${solid.points.map((p) => `${p.x},${p.y}`).join(";")}`;
}
export function emitExtrudedSolids(project: Project): RMesh[] {
@@ -51,6 +51,8 @@ export function emitExtrudedSolids(project: Project): RMesh[] {
}
for (const solid of project.extrudedSolids ?? []) {
if (solid.points.length < 3 || solid.height <= 0) continue;
// Abzugskörper sind kein Material (sie wirken über `voids3d.ts`).
if (solid.operation === "subtract") continue;
const signature = extrudedSolidSignature(solid);
let entry = truckMeshCache.get(solid.id);
if (!entry || entry.signature !== signature) {
@@ -67,11 +69,12 @@ export function emitExtrudedSolids(project: Project): RMesh[] {
} catch {
// Geschoss nicht (mehr) auflösbar: bei UK 0 extrudieren (Fallback).
}
baseZ += solid.baseOffset ?? 0;
// Kreis-Profil: echte runde truck-Extrusion (extrudeCircle) statt der
// 48-Eck-Tessellierung in `points` — glattes Zylinder-Mesh.
const taper = solid.taper ?? 0;
// B-Rep-Pfad (Grundkörper, Eckenradius): die Spezifikation trägt die UK (baseZ) selbst.
const brepSpec = needsBrepPath(solid) ? extrudedSolidSpec(solid, baseZ) : null;
const brepSpec = needsBrepPath(solid) ? extrudedSolidSpec(solid, baseZ - (solid.baseOffset ?? 0)) : null;
const extrusion = brepSpec
? buildSolidMesh(brepSpec, 0.005)
: solid.circle
+101
View File
@@ -0,0 +1,101 @@
// Abzugskörper im 3D (s. `plan/voids.ts`): jede Wandschicht und Decke, die ein Abzugskörper
// durchdringt, wird über truck als Boolean-Differenz gebaut (B-Rep, bei bündigen Flächen
// automatisch Mesh-CSG) und statt des Prismas als Mesh gezeigt.
//
// Wie die Extrusionen (`extrusions.ts`) asynchron mit modulweitem Cache: solange das Ergebnis
// lädt, bleibt das ungeschnittene Prisma stehen; ist es fertig, feuert
// `TRUCK_MESH_READY_EVENT` und der Viewer pusht das Modell neu.
import type { Project } from "../../model/types";
import { buildSolidMesh } from "../../engine/truckSolid";
import type { SolidSpec } from "../../engine/truckSolid";
import { wallSpec } from "../wallSpec";
import { bbox, hittingVoids, subtractSpec, voidPrisms, wallCorners } from "../voids";
import { TRUCK_MESH_READY_EVENT } from "./extrusions";
import type { RMesh, RModel3d, RSlab, RVec2, RWall } from "./shared";
interface Entry {
signature: string;
/** null = lädt noch; "failed" = Boolean scheiterte (Prisma bleibt). */
mesh: RMesh | null | "failed";
}
const cache = new Map<string, Entry>();
function request(key: string, signature: string, spec: SolidSpec, make: (m: { positions: number[]; indices: number[] }) => RMesh): Entry {
let e = cache.get(key);
if (e && e.signature === signature) return e;
const entry: Entry = { signature, mesh: null };
cache.set(key, entry);
buildSolidMesh(spec, 0.005)
.then((m) => {
const cur = cache.get(key);
if (cur !== entry) return;
entry.mesh = make(m);
window.dispatchEvent(new Event(TRUCK_MESH_READY_EVENT));
})
.catch((err) => {
entry.mesh = "failed";
console.warn("Abzugskörper-Boolean fehlgeschlagen:", err);
});
e = entry;
return e;
}
/**
* Ersetzt in `model` die von Abzugskörpern getroffenen Wandschichten/Decken durch ihre
* Boolean-Meshes (sobald geladen). Ohne `window` (Tests/Node) bleibt das Modell unverändert.
*/
export function applyVoids3d(model: RModel3d, project: Project): void {
if (typeof window === "undefined") return;
const voids = voidPrisms(project);
if (voids.length === 0) return;
const live = new Set<string>();
const walls: RWall[] = [];
model.walls.forEach((w, i) => {
const hits = hittingVoids(voids, bbox(wallCorners(w)), w.baseElevation, w.baseElevation + w.height);
const base = hits.length ? wallSpec(w) : null;
if (!base) {
walls.push(w);
return;
}
const key = `w:${w.wallId}:${i}`;
live.add(key);
const spec = subtractSpec(base, hits);
const e = request(key, JSON.stringify(spec), spec, (m) => ({
positions: m.positions,
indices: m.indices,
kind: "extrusion",
color: w.color,
...(w.materialIndex !== undefined ? { materialIndex: w.materialIndex } : {}),
}));
if (e.mesh && e.mesh !== "failed") model.meshes.push(e.mesh);
else walls.push(w);
});
model.walls = walls;
const slabs: RSlab[] = [];
model.slabs.forEach((s, i) => {
const foot = bbox(s.outline.map((p: RVec2) => ({ x: p[0], y: p[1] })));
const hits = s.outline.length >= 3 ? hittingVoids(voids, foot, s.zBottom, s.zTop) : [];
if (hits.length === 0) {
slabs.push(s);
return;
}
const key = `s:${s.ceilingId}:${i}`;
live.add(key);
const base: SolidSpec = { kind: "extrude", points: s.outline.flatMap((p) => [p[0], p[1]]), height: s.zTop - s.zBottom, z0: s.zBottom };
const spec = subtractSpec(base, hits);
const e = request(key, JSON.stringify(spec), spec, (m) => ({
positions: m.positions,
indices: m.indices,
kind: "extrusion",
color: s.color,
}));
if (e.mesh && e.mesh !== "failed") model.meshes.push(e.mesh);
else slabs.push(s);
});
model.slabs = slabs;
for (const k of cache.keys()) if (!live.has(k)) cache.delete(k);
}
+86
View File
@@ -0,0 +1,86 @@
import { describe, expect, it } from "vitest";
import type { Pair } from "polygon-clipping";
import { generatePlan } from "./generatePlan";
import { sampleProject } from "../model/sampleProject";
import type { ExtrudedSolid, Project } from "../model/types";
import { keyhole, segmentOutside, subtractRings, subtractVoidsInSection, voidPrisms, voidSectionRects } from "./voids";
const sq = (x0: number, y0: number, x1: number, y1: number): Pair[] => [[x0, y0], [x1, y0], [x1, y1], [x0, y1]];
const area = (r: Pair[]) => Math.abs(r.reduce((s, p, i) => s + p[0] * r[(i + 1) % r.length][1] - r[(i + 1) % r.length][0] * p[1], 0) / 2);
function withVoid(p: Project, v: Partial<ExtrudedSolid>): Project {
const solid: ExtrudedSolid = { id: "void1", type: "extrudedSolid", levelId: p.walls[0].floorId, operation: "subtract", height: 2, points: [], ...v };
return { ...p, extrudedSolids: [...(p.extrudedSolids ?? []), solid] };
}
describe("Abzugskoerper — Polygon-Kern", () => {
it("Loch ganz innen: Schluesselloch mit zwei ungestrichenen Stegkanten, Flaeche stimmt", () => {
const r = subtractRings(sq(0, 0, 4, 2), [sq(1, 0.5, 2, 1.5)])!;
expect(r).toHaveLength(1);
expect(area(r[0].pts)).toBeCloseTo(8 - 1, 9);
expect(r[0].noStrokeEdges).toHaveLength(2);
});
it("Durchbruch quer: zwei Restteile", () => {
const r = subtractRings(sq(0, 0, 4, 0.3), [sq(1, -1, 2, 1)])!;
expect(r).toHaveLength(2);
expect(r.reduce((s, x) => s + area(x.pts), 0)).toBeCloseTo(0.9, 9);
});
it("ohne Ueberschneidung: null (Original bleibt)", () => {
expect(subtractRings(sq(0, 0, 1, 1), [sq(5, 5, 6, 6)])).toBeNull();
});
it("ungestrichene Originalkanten bleiben ungestrichen", () => {
// Kante 1 (rechts, x=4) ungestrichen; der Schnitt links lässt sie unberührt.
const r = subtractRings(sq(0, 0, 4, 2), [sq(-1, -1, 1, 3)], [1])!;
const edges = r[0].noStrokeEdges.map((i) => [r[0].pts[i], r[0].pts[(i + 1) % r[0].pts.length]]);
expect(edges.every(([a, b]) => a[0] === 4 && b[0] === 4)).toBe(true);
});
it("keyhole haengt mehrere Loecher ein", () => {
const k = keyhole([sq(0, 0, 10, 2), sq(1, 0.5, 2, 1.5).reverse(), sq(5, 0.5, 6, 1.5).reverse()]);
expect(k.bridges).toHaveLength(4);
});
it("segmentOutside: Linie durch Quadrat in zwei Teile", () => {
const parts = segmentOutside({ x: 0, y: 0.5 }, { x: 4, y: 0.5 }, [sq(1, 0, 2, 1)]);
expect(parts.map(([a, b]) => [a, b])).toEqual([[0, 0.25], [0.5, 1]]);
});
});
describe("Abzugskoerper — Grundriss und Schnitt", () => {
const w = sampleProject.walls[0];
const mx = (w.start.x + w.end.x) / 2;
const my = (w.start.y + w.end.y) / 2;
const box = [{ x: mx - 0.3, y: my - 1 }, { x: mx + 0.3, y: my - 1 }, { x: mx + 0.3, y: my + 1 }, { x: mx - 0.3, y: my + 1 }];
const vis = new Set(sampleProject.layers.map((l) => l.code));
const wallPolys = (p: Project) => generatePlan(p, w.floorId, vis).primitives.filter((q) => q.kind === "polygon" && q.wallId === w.id);
it("Durchbruch auf Schnitthoehe teilt die Wand-Poché, Umrisslinien enden am Koerper", () => {
const p = withVoid(sampleProject, { points: box });
const before = wallPolys(sampleProject).length;
expect(wallPolys(p).length).toBeGreaterThan(before);
const lines = generatePlan(p, w.floorId, vis).primitives.filter(
(q) => q.kind === "line" && (q.cls === "wall-outline" || q.cls === "layer-joint"),
);
for (const l of lines) {
if (l.kind !== "line") continue;
const cx = (l.a.x + l.b.x) / 2;
const cy = (l.a.y + l.b.y) / 2;
const inside = cx > mx - 0.3 + 1e-6 && cx < mx + 0.3 - 1e-6 && cy > my - 1 && cy < my + 1;
expect(inside).toBe(false);
}
});
it("Koerper ueber der Schnitthoehe aendert den Grundriss nicht", () => {
const p = withVoid(sampleProject, { points: box, baseOffset: 1.5, height: 0.5 });
expect(wallPolys(p).length).toBe(wallPolys(sampleProject).length);
});
it("Schnitt: Rechtecke aus Grundflaeche x Hoehenbereich, Abzug aus Cut-Polygonen", () => {
const p = withVoid(sampleProject, { points: box, baseOffset: 0.5, height: 1 });
const [v] = voidPrisms(p);
const rects = voidSectionRects(v, { x: 0, y: my }, { x: 1, y: 0 });
expect(rects).toHaveLength(1);
expect(rects[0][0][0]).toBeCloseTo(mx - 0.3, 9);
expect(rects[0][2][1]).toBeCloseTo(v.z1, 9);
const cuts = [{ pts: sq(mx - 2, 0, mx + 2, 2.5) as Array<[number, number]> }];
const out = subtractVoidsInSection(cuts, p, { x: 0, y: my }, { x: 1, y: 0 });
expect(out).toHaveLength(1);
expect(area(out[0].pts)).toBeCloseTo(4 * 2.5 - 0.6 * 1, 6);
});
});
+421
View File
@@ -0,0 +1,421 @@
// Abzugskörper (`ExtrudedSolid.operation === "subtract"`): Aussparungen, Durchbrüche und
// Nischen, die sich von Wänden, Decken und Stützen abziehen — in ALLEN abgeleiteten
// Ansichten aus demselben Modell:
//
// • Grundriss: Poché-Polygone der getroffenen Bauteile minus Körper-Grundfläche, sofern der
// Körper die Schnitthöhe (Wände/Stützen) bzw. die Platte (Decken) durchdringt.
// • Schnitt: Cut-Polygone minus Körper-Schnitt (Grundfläche ∩ Schnittspur × Höhenbereich).
// • 3D/STEP: Boolean-Differenz (truck, Mesh-CSG-Fallback), s. `toWalls3d/voids3d.ts`
// bzw. `exportStep.ts`.
//
// Abzugskörper sind senkrechte Prismen (Profil × Höhe, ohne Verjüngung/B-Rep) — damit bleiben
// Grundriss und Schnitt exakt analytisch (ein Prisma schneidet eine waagrechte Ebene in seiner
// Grundfläche und eine senkrechte Ebene in Rechtecken).
//
// Polygone mit Loch (Körper ganz im Bauteil) werden über einen Steg an den Aussenring
// gehängt (Schlüsselloch); die beiden Stegkanten sind nicht gestrichen (`noStrokeEdges`).
import polygonClipping from "polygon-clipping";
import type { Pair, Polygon as PcPolygon, MultiPolygon } from "polygon-clipping";
import type { ExtrudedSolid, Project, Vec2 } from "../model/types";
import { getFloor } from "../model/types";
import { ceilingVerticalExtent, columnVerticalExtent } from "../model/wall";
import type { Primitive } from "./generatePlan/shared";
import type { SolidSpec } from "../engine/truckSolid";
import type { RWall } from "./toWalls3d/shared";
export interface VoidPrism {
id: string;
pts: Vec2[];
z0: number;
z1: number;
}
const EPS = 1e-7;
/** Ob ein Körper als Abzugskörper wirkt (Prisma mit gültigem Profil). */
export function isVoidSolid(s: ExtrudedSolid): boolean {
return s.operation === "subtract" && !s.brep && (s.taper ?? 0) < 1e-6 && s.points.length >= 3 && s.height > 0;
}
/** UK des Körpers (Geschoss-UK + `baseOffset`). */
export function solidBaseZ(project: Project, s: ExtrudedSolid): number {
let base = 0;
try {
base = getFloor(project, s.levelId).baseElevation ?? 0;
} catch {
base = 0;
}
return base + (s.baseOffset ?? 0);
}
/** Alle Abzugskörper des Projekts (Welt-Höhen). */
export function voidPrisms(project: Project): VoidPrism[] {
const out: VoidPrism[] = [];
for (const s of project.extrudedSolids ?? []) {
if (!isVoidSolid(s)) continue;
const z0 = solidBaseZ(project, s);
out.push({ id: s.id, pts: s.points, z0, z1: z0 + s.height });
}
return out;
}
// ── Polygon-Booleans ─────────────────────────────────────────────────────────
const ring = (pts: Vec2[]): Pair[] => pts.map((p) => [p.x, p.y] as Pair);
/** Fläche (vorzeichenbehaftet) eines Rings. */
function signedArea(r: Pair[]): number {
let a = 0;
for (let i = 0; i < r.length; i++) {
const p = r[i];
const q = r[(i + 1) % r.length];
a += p[0] * q[1] - q[0] * p[1];
}
return a / 2;
}
/** Ring ohne doppelten Schlusspunkt (polygon-clipping liefert geschlossene Ringe). */
function openRing(r: Pair[]): Pair[] {
if (r.length > 1) {
const a = r[0];
const b = r[r.length - 1];
if (Math.abs(a[0] - b[0]) < EPS && Math.abs(a[1] - b[1]) < EPS) return r.slice(0, -1);
}
return r;
}
/**
* Löcher per Steg in den Aussenring einhängen (Schlüsselloch). Liefert die Punkte und die
* Indizes der Stegkanten (Kante i = pts[i] → pts[i+1]).
*/
export function keyhole(poly: Pair[][]): { pts: Pair[]; bridges: number[] } {
let outer = openRing(poly[0]);
const bridges: number[] = [];
const holes = poly.slice(1).map(openRing).filter((h) => h.length >= 3);
// Löcher von rechts nach links einhängen (Stege kreuzen sich so nicht).
holes.sort((a, b) => Math.max(...b.map((p) => p[0])) - Math.max(...a.map((p) => p[0])));
for (const hole of holes) {
// Lochpunkt mit grösstem x, nächster Aussenring-Punkt dazu.
let hi = 0;
for (let i = 1; i < hole.length; i++) if (hole[i][0] > hole[hi][0]) hi = i;
const h = hole[hi];
let oi = 0;
let best = Infinity;
for (let i = 0; i < outer.length; i++) {
const d = Math.hypot(outer[i][0] - h[0], outer[i][1] - h[1]);
if (d < best) {
best = d;
oi = i;
}
}
const holeSeq = [...hole.slice(hi), ...hole.slice(0, hi), h];
const next: Pair[] = [...outer.slice(0, oi + 1), ...holeSeq, outer[oi], ...outer.slice(oi + 1)];
// Indizes der beiden Stegkanten (alte Stegindizes hinter oi verschieben sich).
const shift = holeSeq.length + 1;
for (let k = 0; k < bridges.length; k++) if (bridges[k] > oi) bridges[k] += shift;
bridges.push(oi, oi + holeSeq.length);
outer = next;
}
return { pts: outer, bridges };
}
/** Liegt Segment a→b auf Segment p→q (kollinear, innerhalb)? */
function onSegment(a: Pair, b: Pair, p: Pair, q: Pair, tol = 1e-6): boolean {
const dx = q[0] - p[0];
const dy = q[1] - p[1];
const len = Math.hypot(dx, dy);
if (len < EPS) return false;
const dist = (r: Pair) => Math.abs((r[0] - p[0]) * dy - (r[1] - p[1]) * dx) / len;
const t = (r: Pair) => ((r[0] - p[0]) * dx + (r[1] - p[1]) * dy) / (len * len);
return dist(a) < tol && dist(b) < tol && t(a) > -tol && t(a) < 1 + tol && t(b) > -tol && t(b) < 1 + tol;
}
/**
* Polygon (Ring `pts`, optional nicht gestrichene Kanten) minus Schneider. Liefert die
* Rest-Polygone mit übertragenen `noStrokeEdges` (eine Kante bleibt ungestrichen, wenn sie
* auf einer ungestrichenen Kante des Originals liegt; Stege sind immer ungestrichen).
* `null` = keine Überschneidung (Original unverändert lassen).
*/
export function subtractRings(
pts: Pair[],
cutters: Pair[][],
noStroke: number[] = [],
): Array<{ pts: Pair[]; noStrokeEdges: number[] }> | null {
if (pts.length < 3 || cutters.length === 0) return null;
const subject: PcPolygon = [pts];
const clips: MultiPolygon = cutters.filter((c) => c.length >= 3).map((c) => [c] as PcPolygon);
if (clips.length === 0) return null;
// Schnell-Test: überlappen die Hüllen überhaupt?
let hit = false;
try {
hit = polygonClipping.intersection(subject, ...clips).length > 0;
} catch {
return null;
}
if (!hit) return null;
let diff: MultiPolygon;
try {
diff = polygonClipping.difference(subject, ...clips);
} catch {
return null;
}
const area0 = Math.abs(signedArea(pts));
const out: Array<{ pts: Pair[]; noStrokeEdges: number[] }> = [];
for (const poly of diff) {
const { pts: kp, bridges } = keyhole(poly);
if (kp.length < 3 || Math.abs(signedArea(openRing(poly[0]))) < area0 * 1e-9) continue;
// Orientierung des Originals beibehalten (Schraffur-/Strich-Logik ist orientierungsfrei,
// aber Tests und Nachbearbeitungen erwarten den Umlaufsinn).
const sameDir = Math.sign(signedArea(kp)) === Math.sign(signedArea(pts)) || signedArea(pts) === 0;
const ringPts = sameDir ? kp : [...kp].reverse();
const n = ringPts.length;
const bridgeSet = new Set(sameDir ? bridges : bridges.map((i) => (n - 2 - i + n) % n));
const ns: number[] = [];
for (let i = 0; i < n; i++) {
const a = ringPts[i];
const b = ringPts[(i + 1) % n];
if (bridgeSet.has(i)) {
ns.push(i);
continue;
}
for (const e of noStroke) {
const p = pts[e];
const q = pts[(e + 1) % pts.length];
if (p && q && onSegment(a, b, p, q)) {
ns.push(i);
break;
}
}
}
out.push({ pts: ringPts, noStrokeEdges: ns });
}
return out;
}
// ── Grundriss ────────────────────────────────────────────────────────────────
function pointInRing(x: number, y: number, r: Pair[]): boolean {
let inside = false;
for (let i = 0, j = r.length - 1; i < r.length; j = i++) {
const [xi, yi] = r[i];
const [xj, yj] = r[j];
if (yi > y !== yj > y && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi) inside = !inside;
}
return inside;
}
/** Teile der Strecke a→b ausserhalb aller Ringe, als Parameter-Intervalle [t0, t1]. */
export function segmentOutside(a: Vec2, b: Vec2, cutters: Pair[][]): Array<[number, number]> {
const ts = [0, 1];
const dx = b.x - a.x;
const dy = b.y - a.y;
for (const r of cutters) {
for (let i = 0; i < r.length; i++) {
const p = r[i];
const q = r[(i + 1) % r.length];
const ex = q[0] - p[0];
const ey = q[1] - p[1];
const den = dx * ey - dy * ex;
if (Math.abs(den) < 1e-14) continue;
const t = ((p[0] - a.x) * ey - (p[1] - a.y) * ex) / den;
const u = ((p[0] - a.x) * dy - (p[1] - a.y) * dx) / den;
if (t > 0 && t < 1 && u >= -1e-9 && u <= 1 + 1e-9) ts.push(t);
}
}
ts.sort((x, y) => x - y);
const out: Array<[number, number]> = [];
for (let i = 0; i + 1 < ts.length; i++) {
const [t0, t1] = [ts[i], ts[i + 1]];
if (t1 - t0 < 1e-9) continue;
const tm = (t0 + t1) / 2;
const mx = a.x + dx * tm;
const my = a.y + dy * tm;
if (cutters.some((r) => pointInRing(mx, my, r))) continue;
const last = out[out.length - 1];
if (last && Math.abs(last[1] - t0) < 1e-9) last[1] = t1;
else out.push([t0, t1]);
}
return out;
}
/** Linien-Klassen der Wand-Poché, die ein Abzugskörper auf Schnitthöhe unterbricht. */
const WALL_LINE_CLS = new Set(["wall-outline", "layer-joint", "layer-joint-l"]);
/**
* Zieht die Abzugskörper von den Bauteil-Polygonen eines Grundrisses ab (in place).
* Wände: wenn der Körper die Schnitthöhe `cutZ` durchdringt. Stützen: ebenso, über ihren
* Höhenbereich. Decken: wenn der Körper die Platte durchdringt (Deckendurchbruch).
*/
export function subtractVoidsInPlan(prims: Primitive[], project: Project, cutZ: number): void {
const voids = voidPrisms(project);
if (voids.length === 0) return;
const ceilings = new Map((project.ceilings ?? []).map((c) => [c.id, c]));
const columns = new Map((project.columns ?? []).map((c) => [c.id, c]));
const cuttersFor = (z0: number, z1: number): Pair[][] =>
voids.filter((v) => v.z0 < z1 - EPS && v.z1 > z0 + EPS).map((v) => ring(v.pts));
const wallCutters = cuttersFor(cutZ - 1e-4, cutZ + 1e-4);
const out: Primitive[] = [];
for (const pr of prims) {
if (pr.kind === "line" && WALL_LINE_CLS.has(pr.cls) && wallCutters.length) {
const parts = segmentOutside(pr.a, pr.b, wallCutters);
const whole = parts.length === 1 && parts[0][0] === 0 && parts[0][1] === 1;
if (whole) out.push(pr);
else
for (const [t0, t1] of parts) {
const at = (t: number) => ({ x: pr.a.x + (pr.b.x - pr.a.x) * t, y: pr.a.y + (pr.b.y - pr.a.y) * t });
out.push({ ...pr, a: at(t0), b: at(t1) });
}
continue;
}
if (pr.kind !== "polygon" || pr.extrudedSolidId) {
out.push(pr);
continue;
}
let cutters: Pair[][] | null = null;
if (pr.wallId) cutters = wallCutters;
else if (pr.ceilingId) {
const c = ceilings.get(pr.ceilingId);
if (c) {
const { zBottom, zTop } = ceilingVerticalExtent(project, c);
cutters = cuttersFor(zBottom, zTop);
}
} else if (pr.columnId) {
const c = columns.get(pr.columnId);
if (c) {
const { zBottom, zTop } = columnVerticalExtent(project, c);
cutters = zBottom <= cutZ && zTop >= cutZ ? wallCutters : cuttersFor(zBottom, zTop);
}
}
if (!cutters || cutters.length === 0) {
out.push(pr);
continue;
}
const rest = subtractRings(ring(pr.pts), cutters, pr.noStrokeEdges ?? []);
if (rest === null) {
out.push(pr);
continue;
}
for (const r of rest) {
out.push({
...pr,
pts: r.pts.map(([x, y]) => ({ x, y })),
noStrokeEdges: r.noStrokeEdges.length ? r.noStrokeEdges : undefined,
});
}
}
prims.length = 0;
for (const p of out) prims.push(p);
}
// ── Schnitt ──────────────────────────────────────────────────────────────────
/**
* Schnitt-Rechtecke (u, v) eines Abzugskörpers mit der senkrechten Ebene durch `base` in
* Richtung `uDir` (Einheitsvektor; u = Abstand entlang uDir ab `base`).
*/
export function voidSectionRects(v: VoidPrism, base: Vec2, uDir: Vec2): Pair[][] {
const ts: number[] = [];
const n = v.pts.length;
// Normale der Schnittspur: Punkt-Seite über das Kreuzprodukt.
const side = (p: Vec2) => (p.x - base.x) * uDir.y - (p.y - base.y) * uDir.x;
for (let i = 0; i < n; i++) {
const a = v.pts[i];
const b = v.pts[(i + 1) % n];
const sa = side(a);
const sb = side(b);
// Halboffene Regel (eine Ecke auf der Spur zählt nur einmal).
if ((sa > 0) === (sb > 0)) continue;
const t = sa / (sa - sb);
const px = a.x + (b.x - a.x) * t;
const py = a.y + (b.y - a.y) * t;
ts.push((px - base.x) * uDir.x + (py - base.y) * uDir.y);
}
ts.sort((a, b) => a - b);
const rects: Pair[][] = [];
for (let i = 0; i + 1 < ts.length; i += 2) {
const [u0, u1] = [ts[i], ts[i + 1]];
if (u1 - u0 < 1e-6) continue;
rects.push([
[u0, v.z0],
[u1, v.z0],
[u1, v.z1],
[u0, v.z1],
]);
}
return rects;
}
/** Minimal-Form eines Schnitt-Polygons (s. `SectionCutPolygon` in toSection.ts). */
interface CutPolyLike {
pts: Array<[number, number]>;
noStrokeEdges?: number[];
}
/** Zieht die Abzugskörper von den Cut-Polygonen eines Schnitts ab (neue Liste). */
export function subtractVoidsInSection<T extends CutPolyLike>(
cuts: T[],
project: Project,
base: Vec2,
uDir: Vec2,
): T[] {
const voids = voidPrisms(project);
if (voids.length === 0) return cuts;
const rects = voids.flatMap((v) => voidSectionRects(v, base, uDir));
if (rects.length === 0) return cuts;
const out: T[] = [];
for (const cp of cuts) {
const rest = subtractRings(cp.pts as Pair[], rects, cp.noStrokeEdges ?? []);
if (rest === null) {
out.push(cp);
continue;
}
for (const r of rest) {
out.push({ ...cp, pts: r.pts as Array<[number, number]>, noStrokeEdges: r.noStrokeEdges.length ? r.noStrokeEdges : undefined });
}
}
return out;
}
// ── 3D / B-Rep ───────────────────────────────────────────────────────────────
export type Box2 = { x0: number; y0: number; x1: number; y1: number };
export const bbox = (pts: Array<{ x: number; y: number }>): Box2 => ({
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 boxHit = (a: Box2, b: Box2) => a.x0 < b.x1 && b.x0 < a.x1 && a.y0 < b.y1 && b.y0 < a.y1;
export function wallCorners(w: RWall): Array<{ x: number; y: number }> {
const dx = w.end[0] - w.start[0];
const dy = w.end[1] - w.start[1];
const len = Math.hypot(dx, dy) || 1;
const nx = (-dy / len) * (w.thickness / 2);
const ny = (dx / len) * (w.thickness / 2);
return [
{ x: w.start[0] + nx, y: w.start[1] + ny },
{ x: w.end[0] + nx, y: w.end[1] + ny },
{ x: w.end[0] - nx, y: w.end[1] - ny },
{ x: w.start[0] - nx, y: w.start[1] - ny },
];
}
const voidSpec = (v: VoidPrism): SolidSpec => ({
kind: "extrude",
points: v.pts.flatMap((p) => [p.x, p.y]),
height: v.z1 - v.z0,
z0: v.z0,
});
/** Bauteil minus alle Körper (verkettete Differenzen). */
export function subtractSpec(base: SolidSpec, voids: VoidPrism[]): SolidSpec {
return voids.reduce<SolidSpec>((acc, v) => ({ kind: "boolean", op: "difference", a: acc, b: voidSpec(v) }), base);
}
/** Abzugskörper, die ein Prisma (Grundriss-Hülle + Höhenbereich) treffen. */
export function hittingVoids(voids: VoidPrism[], foot: Box2, z0: number, z1: number): VoidPrism[] {
return voids.filter((v) => v.z0 < z1 - 1e-6 && v.z1 > z0 + 1e-6 && boxHit(bbox(v.pts), foot));
}
+81
View File
@@ -0,0 +1,81 @@
// B-Rep-Spezifikation einer Wand(schicht) (`RWall`) für truck: Wandprofil (Achse × Höhe) mit
// den Öffnungen als Löcher bzw. Kerben, um die Dicke extrudiert — OHNE Boolean (B-Rep-Booleans
// scheitern an den bündigen Laibungsflächen). Gemeinsame Quelle für STEP-Export, Abzugskörper
// im 3D und Kollisionsprüfung.
import type { SolidSpec } from "../engine/truckSolid";
import type { RWall } from "./toWalls3d/shared";
const EPS = 1e-6;
/** Schicht/Öffnung so dünn, dass sie als nicht vorhanden gilt. */
const MIN_THICKNESS = 1e-4;
/**
* Wandprofil (u = Achse, v = Höhe über Wandfuss) mit Öffnungen: Löcher, die ganz im Profil
* liegen; Öffnungen am Wandfuss (Türen) als Kerben im Aussenring. Öffnungen am Wandkopf
* werden um 1 mm gekappt (ein Loch darf den Rand nicht berühren).
*/
export function wallProfile(
length: number,
height: number,
holes: Array<{ from: number; to: number; zBottom: number; zTop: number }>,
baseElevation: number,
): { outer: number[]; holes: number[][] } {
const inner: number[][] = [];
const notches: Array<[number, number, number]> = []; // [from, to, top]
const cut = 1e-3;
for (const h of holes) {
const u0 = Math.max(0, Math.min(length, h.from));
const u1 = Math.max(0, Math.min(length, h.to));
if (u1 - u0 < MIN_THICKNESS) continue;
const v0 = h.zBottom - baseElevation;
const v1 = Math.min(height - cut, h.zTop - baseElevation);
if (v1 - Math.max(v0, 0) < MIN_THICKNESS) continue;
if (v0 <= cut) notches.push([u0, u1, v1]);
else inner.push([u0, v0, u1, v0, u1, v1, u0, v1]);
}
// Kerben sortieren und überlappende zusammenfassen.
notches.sort((a, b) => a[0] - b[0]);
const merged: Array<[number, number, number]> = [];
for (const n of notches) {
const last = merged[merged.length - 1];
if (last && n[0] <= last[1] + EPS) {
last[1] = Math.max(last[1], n[1]);
last[2] = Math.max(last[2], n[2]);
} else merged.push([...n]);
}
// Aussenring CCW in (u,v): Wandfuss links→rechts mit Kerben, dann Kopf rechts→links.
const outer: number[] = [0, 0];
for (const [a, b, top] of merged) {
outer.push(a, 0, a, top, b, top, b, 0);
}
outer.push(length, 0, length, height, 0, height);
return { outer, holes: inner };
}
export function wallSpec(w: RWall): SolidSpec | null {
const dx = w.end[0] - w.start[0];
const dy = w.end[1] - w.start[1];
const len = Math.hypot(dx, dy);
if (len < MIN_THICKNESS || w.height < MIN_THICKNESS || w.thickness < MIN_THICKNESS) return null;
const ux = dx / len;
const uy = dy / len;
// u × v (v = +Z) = (uy, −ux, 0): Extrusionsrichtung. Ursprung = eine Wandfläche.
const nx = uy;
const ny = -ux;
const prof = wallProfile(len, w.height, w.holes ?? [], w.baseElevation);
return {
kind: "extrudePlane",
points: prof.outer,
holes: prof.holes,
origin: [
w.start[0] - (nx * w.thickness) / 2,
w.start[1] - (ny * w.thickness) / 2,
w.baseElevation,
],
uAxis: [ux, uy, 0],
vAxis: [0, 0, 1],
depth: w.thickness,
};
}
+10 -1
View File
@@ -323,6 +323,12 @@ export interface ExtrudedSolidInfo {
brepLabel?: string;
/** Grundfläche des Profils (m²). */
area: number;
/** Abzugskörper (Aussparung/Durchbruch). */
subtract: boolean;
/** Abzugskörper möglich (senkrechtes Prisma ohne B-Rep/Verjüngung). */
canSubtract: boolean;
/** Abstand der UK über der Geschoss-UK (m). */
baseOffset: number;
/** B-Rep-Beschreibung (Weltkoordinaten) für Kennwerte — `null`, wenn truck keine hat. */
spec: SolidSpec | null;
/** Geschoss, dessen `baseElevation` die UK des Körpers bestimmt. */
@@ -1056,7 +1062,10 @@ function extrudedSolidSelection(project: Project, s: ExtrudedSolid): Selection {
chamfer: s.chamfer ?? 0,
...(s.brep ? { brepLabel: s.brep.label ?? "B-Rep" } : {}),
area: polygonArea(s.points),
spec: extrudedSolidSpec(s, floor?.baseElevation ?? 0),
spec: s.operation === "subtract" ? null : extrudedSolidSpec(s, floor?.baseElevation ?? 0),
subtract: s.operation === "subtract",
canSubtract: !s.brep && (s.taper ?? 0) < 1e-6,
baseOffset: s.baseOffset ?? 0,
floorId: s.levelId,
floorName: floor?.name ?? s.levelId,
};
+20
View File
@@ -1051,6 +1051,26 @@ export function usePanelHostBase(opts: {
),
}));
},
onSetExtrudedSolidSubtract: (subtract) => {
if (selection?.kind !== "extrudedSolid") return;
const id = selection.id;
setProject((p) => ({
...p,
extrudedSolids: (p.extrudedSolids ?? []).map((s) =>
s.id === id ? { ...s, operation: subtract ? ("subtract" as const) : undefined } : s,
),
}));
},
onSetExtrudedSolidBaseOffset: (offset) => {
if (selection?.kind !== "extrudedSolid" || !Number.isFinite(offset)) return;
const id = selection.id;
setProject((p) => ({
...p,
extrudedSolids: (p.extrudedSolids ?? []).map((s) =>
s.id === id ? { ...s, baseOffset: Math.abs(offset) > 1e-9 ? offset : undefined } : s,
),
}));
},
// ── Stützen-Attribute (Tragwerk; nur bei selektierter Stütze) ──────────
onSetColumnProfileKind: (kind) => {
if (selection?.kind !== "column") return;
+9
View File
@@ -186,6 +186,15 @@ export function CommandIcon({ name }: { name: string }) {
<path d="M9.5 12.5 L12.5 9.5 L12.5 4.5" />
</svg>
);
case "voidbox":
// Durchbruch: Wand mit gestricheltem, durchkreuztem Ausschnitt.
return (
<svg {...common}>
<rect x="2.5" y="5.5" width="11" height="5" />
<rect x="6" y="3.5" width="4" height="9" strokeDasharray="1.4 1.2" />
<path d="M6 3.5 L10 12.5 M10 3.5 L6 12.5" />
</svg>
);
case "solidbool":
// Verschneiden: zwei überlappende Körper.
return (
+1 -1
View File
@@ -202,7 +202,7 @@ export function useWasm3dRenderer(
const r = rendererRef.current;
if (!r || !project) return;
try {
r.set_model(JSON.stringify(projectToModel3d(project, { detail })));
r.set_model(JSON.stringify(projectToModel3d(project, { detail, voids: true })));
} catch (e) {
console.warn("render3d set_model fehlgeschlagen:", e);
}