Rust-Kern: Dachgeometrie (roof.rs, roof_skeleton.rs) aus dem TS-Kern portiert

Alle Dachformen (flach/pult/sattel/walm/mansarde/zelt, Kruppelwalm, Ueberstand Traufe/Ortgang,
First entlang x/y) und das Skelett fuer L/T/U- und schiefe Umrisse (Kehlen, Giebel, Mansard-Knick,
konvexe Zerlegung) rechnet jetzt dossier-core; Polygon-Booleans direkt ueber i_overlay ohne
WASM-Grenze. roof.ts uebergibt die Dachparameter flach (roof_geometry_flat) und baut daraus die
RoofGeometry; Memo je Dach-Objekt bleibt in TS. roofUndersideAt rechnet ebenfalls in Rust ueber
die gemerkten flachen Dachflaechen. roofSkeleton.ts geloescht, seine Hilfsfunktionen sind in Rust
getestet; roofSkeleton.test.ts prueft dieselben Erwartungen ueber roofGeometry.

Ergebnis bitgleich mit der TS-Fassung (10 Referenzdaecher), ungecacht 2.9 -> 1.3 ms je 10 Daecher,
roofUndersideAt 1.3 -> 0.75 us je Aufruf. Rust-Tests je Dachform und fuer Unsinn-Eingaben.
This commit is contained in:
Claude committed 2026-10-27 21:20:24 +00:00
1 parent 054df6e1e3
commit 95ad01046d
9 files changed
+1433 -946

No files matched your search

+81 -486
View File
@@ -1,17 +1,15 @@
// Dach-Geometrie: leitet aus einem (rechteckigen) Grundriss-Umriss + Dachform +
// Neigung die Grundriss-Linien (Traufe/First/Grat/Knick) UND die 3D-Dachflächen
// ab. Bewusst auf der BOUNDING-BOX des Umrisses gerechnet (First entlang einer
// Hauptachse) — die gängige, intuitive Vereinfachung, die alle Standardformen
// (Flach/Pult/Sattel/Walm/Mansarde/Zelt) exakt und ohne Straight-Skeleton abdeckt.
// Dach-Geometrie: Grundriss-Linien (Traufe/First/Grat/Knick) und 3D-Dachflächen eines Dachs.
// Gerechnet wird im Rust-Kern (`src-tauri/core/src/roof.rs`, Skelett für L/T/U und schiefe
// Umrisse in `roof_skeleton.rs`); hier bleiben die Typen, die flache Übergabe an die WASM-Grenze,
// die Memoisierung und `roofBaseElevation` (liest das Projekt).
//
// Koordinaten: Grundriss (x, y) in Metern; 3D-Punkte als [x, y, z] mit z = Höhe.
// Reine Datenschicht (kein React/Store), voll unit-testbar.
//
// Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md).
import type { Project, Roof, Vec2 } from "../model/types";
import type { Project, Roof, RoofShape, Vec2 } from "../model/types";
import { getFloor } from "../model/types";
import { cleanRing, convexPieces, isRectilinearNonRect, isSkeletonRoofable, offsetRectilinear, rectilinearHipRoof } from "./roofSkeleton";
import { core } from "../engine/coreWasm";
/** 3D-Punkt [x, y, z=Höhe] in Modell-Metern. */
export type Vec3 = [number, number, number];
@@ -39,8 +37,6 @@ export interface RoofGeometry {
ridgeHeight: number;
}
const DEG = Math.PI / 180;
/** Bounding-Box eines Umrisses. */
export function roofBBox(outline: Vec2[]): { x0: number; y0: number; x1: number; y1: number } {
let x0 = Infinity;
@@ -71,485 +67,91 @@ export function roofBaseElevation(project: Project, roof: Roof): number {
}
}
const P = (x: number, y: number): Vec2 => ({ x, y });
// ── Flache Übergabe (Kodierung s. `roof.rs`) ────────────────────────────────
/**
* Kanonische Berechnung mit First entlang der X-Achse auf dem Rechteck
* [x0,x1]×[y0,y1] (Traufe, inkl. Überstand) auf Traufhöhe `e`. Die „y"-First-
* Richtung wird im Wrapper durch Transponieren (x↔y) erreicht.
*/
function computeCanonical(
x0: number,
y0: number,
x1: number,
y1: number,
e: number,
roof: Roof,
): RoofGeometry {
const xc = (x0 + x1) / 2;
const yc = (y0 + y1) / 2;
const halfW = (x1 - x0) / 2;
const halfD = (y1 - y0) / 2;
const a = Math.max(0, roof.pitchDeg) * DEG;
const tan = Math.tan(a);
const h = halfD * tan; // Firsthöhe (Sattel/Walm/Mansarde)
const SHAPE_CODE: Record<RoofShape, number> = { flach: 0, pult: 1, sattel: 2, walm: 3, mansarde: 4, zelt: 5 };
const MANSARD_CODE = { giebel: 0, walm: 1, zelt: 2 } as const;
const eaves: Vec2[] = [P(x0, y0), P(x1, y0), P(x1, y1), P(x0, y1)];
const flat = (): RoofGeometry => ({
eaves,
ridges: [],
hips: [],
breaks: [],
planes: [{ pts: [[x0, y0, e], [x1, y0, e], [x1, y1, e], [x0, y1, e]] }],
gables: [],
ridgeHeight: 0,
});
switch (roof.shape) {
case "flach":
return flat();
case "pult": {
// Eine Fläche: tiefe Seite y0 auf Traufe, hohe Seite y1 auf e+H.
const H = (y1 - y0) * tan;
return {
eaves,
ridges: [[P(x0, y1), P(x1, y1)]], // hohe Kante (First-Ersatz)
hips: [],
breaks: [],
planes: [{ pts: [[x0, y0, e], [x1, y0, e], [x1, y1, e + H], [x0, y1, e + H]] }],
gables: [
[[x0, y0, e], [x0, y1, e + H], [x0, y1, e]],
[[x1, y0, e], [x1, y1, e + H], [x1, y1, e]],
],
ridgeHeight: H,
};
}
case "sattel": {
const rz = e + h;
const hh = Math.min(0.9, Math.max(0, roof.halfHipRatio ?? 0));
if (hh > 1e-6 && halfW > halfD * hh + 1e-6) {
// Krüppelwalm: oberer Giebelteil (Anteil `hh` der Firsthöhe) als kleine Walmflächen
// gleicher Neigung — Walmlauf = halbe Tiefe · hh, First entsprechend verkürzt.
const kz = e + h * (1 - hh);
const yk0 = y0 + halfD * (1 - hh);
const yk1 = y1 - halfD * (1 - hh);
const d = halfD * hh;
return {
eaves,
ridges: [[P(x0 + d, yc), P(x1 - d, yc)]],
hips: [
[P(x0, yk0), P(x0 + d, yc)],
[P(x0, yk1), P(x0 + d, yc)],
[P(x1, yk0), P(x1 - d, yc)],
[P(x1, yk1), P(x1 - d, yc)],
],
breaks: [],
planes: [
{ pts: [[x0, y0, e], [x1, y0, e], [x1, yk0, kz], [x1 - d, yc, rz], [x0 + d, yc, rz], [x0, yk0, kz]] },
{ pts: [[x0, y1, e], [x1, y1, e], [x1, yk1, kz], [x1 - d, yc, rz], [x0 + d, yc, rz], [x0, yk1, kz]] },
{ pts: [[x0, yk0, kz], [x0, yk1, kz], [x0 + d, yc, rz]] },
{ pts: [[x1, yk0, kz], [x1, yk1, kz], [x1 - d, yc, rz]] },
],
gables: [
[[x0, y0, e], [x0, y1, e], [x0, yk1, kz], [x0, yk0, kz]],
[[x1, y0, e], [x1, y1, e], [x1, yk1, kz], [x1, yk0, kz]],
],
ridgeHeight: h,
};
}
return {
eaves,
ridges: [[P(x0, yc), P(x1, yc)]],
hips: [],
breaks: [],
planes: [
{ pts: [[x0, y0, e], [x1, y0, e], [x1, yc, rz], [x0, yc, rz]] },
{ pts: [[x0, y1, e], [x1, y1, e], [x1, yc, rz], [x0, yc, rz]] },
],
gables: [
[[x0, y0, e], [x0, y1, e], [x0, yc, rz]],
[[x1, y0, e], [x1, y1, e], [x1, yc, rz]],
],
ridgeHeight: h,
};
}
case "walm": {
const rz = e + h;
// First um die halbe Tiefe an beiden Enden verkürzt (45°-Grate bei
// gleicher Neigung). Bei schmalem Baukörper (halfW<halfD) degeneriert er
// zum Punkt (xc) → Walm wird zeltartig.
let ra = x0 + halfD;
let rb = x1 - halfD;
if (ra > rb) ra = rb = xc;
return {
eaves,
ridges: [[P(ra, yc), P(rb, yc)]],
hips: [
[P(x0, y0), P(ra, yc)],
[P(x0, y1), P(ra, yc)],
[P(x1, y0), P(rb, yc)],
[P(x1, y1), P(rb, yc)],
],
breaks: [],
planes: [
{ pts: [[x0, y0, e], [x1, y0, e], [rb, yc, rz], [ra, yc, rz]] },
{ pts: [[x0, y1, e], [x1, y1, e], [rb, yc, rz], [ra, yc, rz]] },
{ pts: [[x0, y0, e], [x0, y1, e], [ra, yc, rz]] },
{ pts: [[x1, y0, e], [x1, y1, e], [rb, yc, rz]] },
],
gables: [],
ridgeHeight: h,
};
}
case "mansarde": {
// Mansarde: steile untere Neigung (pitchDeg) bis zur Knicklinie, dann
// flache obere (pitchUpperDeg ?? halbe Hauptneigung). Untertyp steuert, ob
// die Knickform an ZWEI Seiten sitzt (Giebel) oder RINGSUM (Walm/Zelt).
const aLow = a;
const aUp = Math.max(0, roof.pitchUpperDeg ?? roof.pitchDeg / 2) * DEG;
const ratio = Math.min(0.49, Math.max(0.05, roof.mansardKneeRatio ?? 0.4));
const mType = roof.mansardType ?? "giebel";
if (mType === "giebel") {
// Mansard-Satteldach: Knick nur an den beiden Traufseiten, Giebel an den
// Enden (bisheriges Verhalten, jetzt mit parametrierbarem Knick).
const d1 = halfD * ratio;
const z1 = e + d1 * Math.tan(aLow);
const z2 = z1 + (halfD - d1) * Math.tan(aUp);
const yf = y0 + d1;
const yb = y1 - d1;
return {
eaves,
ridges: [[P(x0, yc), P(x1, yc)]],
hips: [],
breaks: [
[P(x0, yf), P(x1, yf)],
[P(x0, yb), P(x1, yb)],
],
planes: [
{ pts: [[x0, y0, e], [x1, y0, e], [x1, yf, z1], [x0, yf, z1]] },
{ pts: [[x0, yf, z1], [x1, yf, z1], [x1, yc, z2], [x0, yc, z2]] },
{ pts: [[x0, y1, e], [x1, y1, e], [x1, yb, z1], [x0, yb, z1]] },
{ pts: [[x0, yb, z1], [x1, yb, z1], [x1, yc, z2], [x0, yc, z2]] },
],
gables: [
[[x0, y0, e], [x0, yf, z1], [x0, yc, z2], [x0, yb, z1], [x0, y1, e]],
[[x1, y0, e], [x1, yf, z1], [x1, yc, z2], [x1, yb, z1], [x1, y1, e]],
],
ridgeHeight: z2 - e,
};
}
// Allseitige Mansarde (Walm/Zelt): steiler Sockel ringsum bis zur
// Knicklinie (inneres Rechteck), darüber flacher Walm bzw. flache Spitze.
const dLow = Math.min(halfW, halfD) * ratio;
const z1 = e + dLow * Math.tan(aLow);
const ix0 = x0 + dLow;
const iy0 = y0 + dLow;
const ix1 = x1 - dLow;
const iy1 = y1 - dLow;
const ihalfD = (iy1 - iy0) / 2;
const ihalfW = (ix1 - ix0) / 2;
// Sockel-Trapeze (4 Seiten, steil) + Sockel-Grate (Ecken aussen→innen) +
// Knicklinie (inneres Rechteck) sind beiden allseitigen Formen gemein.
const socketPlanes = [
{ pts: [[x0, y0, e], [x1, y0, e], [ix1, iy0, z1], [ix0, iy0, z1]] as Vec3[] },
{ pts: [[x1, y1, e], [x0, y1, e], [ix0, iy1, z1], [ix1, iy1, z1]] as Vec3[] },
{ pts: [[x0, y1, e], [x0, y0, e], [ix0, iy0, z1], [ix0, iy1, z1]] as Vec3[] },
{ pts: [[x1, y0, e], [x1, y1, e], [ix1, iy1, z1], [ix1, iy0, z1]] as Vec3[] },
];
const socketHips: [Vec2, Vec2][] = [
[P(x0, y0), P(ix0, iy0)],
[P(x1, y0), P(ix1, iy0)],
[P(x1, y1), P(ix1, iy1)],
[P(x0, y1), P(ix0, iy1)],
];
const kneeBreaks: [Vec2, Vec2][] = [
[P(ix0, iy0), P(ix1, iy0)],
[P(ix1, iy0), P(ix1, iy1)],
[P(ix1, iy1), P(ix0, iy1)],
[P(ix0, iy1), P(ix0, iy0)],
];
if (mType === "walm") {
// Oberer Walm auf dem inneren Rechteck (First entlang X).
const z2 = z1 + ihalfD * Math.tan(aUp);
let ra = ix0 + ihalfD;
let rb = ix1 - ihalfD;
if (ra > rb) ra = rb = xc;
return {
eaves,
ridges: [[P(ra, yc), P(rb, yc)]],
hips: [
...socketHips,
[P(ix0, iy0), P(ra, yc)],
[P(ix1, iy0), P(rb, yc)],
[P(ix1, iy1), P(rb, yc)],
[P(ix0, iy1), P(ra, yc)],
],
breaks: kneeBreaks,
planes: [
...socketPlanes,
{ pts: [[ix0, iy0, z1], [ix1, iy0, z1], [rb, yc, z2], [ra, yc, z2]] },
{ pts: [[ix1, iy1, z1], [ix0, iy1, z1], [ra, yc, z2], [rb, yc, z2]] },
{ pts: [[ix0, iy1, z1], [ix0, iy0, z1], [ra, yc, z2]] },
{ pts: [[ix1, iy0, z1], [ix1, iy1, z1], [rb, yc, z2]] },
],
gables: [],
ridgeHeight: z2 - e,
};
}
// "zelt": flache Spitze über der Mitte des inneren Rechtecks.
const z2 = z1 + Math.min(ihalfW, ihalfD) * Math.tan(aUp);
return {
eaves,
ridges: [],
hips: [
...socketHips,
[P(ix0, iy0), P(xc, yc)],
[P(ix1, iy0), P(xc, yc)],
[P(ix1, iy1), P(xc, yc)],
[P(ix0, iy1), P(xc, yc)],
],
breaks: kneeBreaks,
planes: [
...socketPlanes,
{ pts: [[ix0, iy0, z1], [ix1, iy0, z1], [xc, yc, z2]] },
{ pts: [[ix1, iy0, z1], [ix1, iy1, z1], [xc, yc, z2]] },
{ pts: [[ix1, iy1, z1], [ix0, iy1, z1], [xc, yc, z2]] },
{ pts: [[ix0, iy1, z1], [ix0, iy0, z1], [xc, yc, z2]] },
],
gables: [],
ridgeHeight: z2 - e,
};
}
case "zelt": {
// Allseitig zur Spitze über der Mitte.
const hz = Math.min(halfW, halfD) * tan;
const az = e + hz;
return {
eaves,
ridges: [],
hips: [
[P(x0, y0), P(xc, yc)],
[P(x1, y0), P(xc, yc)],
[P(x1, y1), P(xc, yc)],
[P(x0, y1), P(xc, yc)],
],
breaks: [],
planes: [
{ pts: [[x0, y0, e], [x1, y0, e], [xc, yc, az]] },
{ pts: [[x1, y0, e], [x1, y1, e], [xc, yc, az]] },
{ pts: [[x1, y1, e], [x0, y1, e], [xc, yc, az]] },
{ pts: [[x0, y1, e], [x0, y0, e], [xc, yc, az]] },
],
gables: [],
ridgeHeight: hz,
};
}
function encodeRoof(roof: Roof): Float64Array {
const pts = roof.outline;
const buf = new Float64Array(10 + 2 * pts.length);
buf[0] = SHAPE_CODE[roof.shape] ?? 0;
buf[1] = roof.pitchDeg;
buf[2] = roof.pitchUpperDeg ?? NaN;
buf[3] = MANSARD_CODE[roof.mansardType ?? "giebel"] ?? 0;
buf[4] = roof.mansardKneeRatio ?? NaN;
buf[5] = roof.halfHipRatio ?? NaN;
buf[6] = roof.overhang;
buf[7] = roof.overhangGable ?? NaN;
buf[8] = roof.ridgeAxis === "y" ? 1 : 0;
buf[9] = pts.length;
for (let i = 0; i < pts.length; i++) {
buf[10 + 2 * i] = pts[i].x;
buf[11 + 2 * i] = pts[i].y;
}
return buf;
}
const swap2 = (p: Vec2): Vec2 => ({ x: p.y, y: p.x });
const swap3 = (p: Vec3): Vec3 => [p[1], p[0], p[2]];
const swapLine = (l: [Vec2, Vec2]): [Vec2, Vec2] => [swap2(l[0]), swap2(l[1])];
/** Flächen der Geometrie als flacher Puffer `[n, (m, (x, y, z)…)…]` (für `roofUndersideAt`). */
const planesFlat = new WeakMap<RoofGeometry, Float64Array>();
function decodeGeometry(b: Float64Array): RoofGeometry {
let i = 0;
const ridgeHeight = b[i++];
const pt = (): Vec2 => ({ x: b[i++], y: b[i++] });
const eaves: Vec2[] = [];
for (let n = b[i++]; n > 0; n--) eaves.push(pt());
const lines = (): [Vec2, Vec2][] => {
const out: [Vec2, Vec2][] = [];
for (let n = b[i++]; n > 0; n--) out.push([pt(), pt()]);
return out;
};
const ridges = lines();
const hips = lines();
const breaks = lines();
const planesStart = i;
const polys = (): Vec3[][] => {
const out: Vec3[][] = [];
for (let n = b[i++]; n > 0; n--) {
const poly: Vec3[] = [];
for (let m = b[i++]; m > 0; m--) poly.push([b[i++], b[i++], b[i++]]);
out.push(poly);
}
return out;
};
const planes = polys().map((pts) => ({ pts }));
const planesEnd = i;
const gables = polys();
const geo: RoofGeometry = { eaves, ridges, hips, breaks, planes, gables, ridgeHeight };
planesFlat.set(geo, b.subarray(planesStart, planesEnd));
return geo;
}
/**
* Dach-Geometrie aus Form/Neigung/Überstand + Traufhöhe `eavesZ`. Rechnet auf
* der Bounding-Box des Umrisses, um `overhang` nach aussen geweitet. Für
* `ridgeAxis:"y"` wird kanonisch (First entlang X) gerechnet und danach x↔y
* transponiert.
* Dach-Geometrie aus Form/Neigung/Überstand + Traufhöhe `eavesZ` (Rust-Kern). Rechteck: auf der
* Bounding-Box des Umrisses, um den Überstand geweitet, First entlang `ridgeAxis`; L/T/U und
* schiefe Umrisse: Skelett mit Graten, Kehlen und Giebeln.
*/
export function roofGeometry(roof: Roof, eavesZ: number): RoofGeometry {
// Memo je Dach-Objekt: Dächer sind immutabel (structural sharing), die Berechnung (Skelett über
// Polygon-Booleans) kostet ~50 ms je Dach und wird je Ableitung (3D, Schnitt, Pick, Highlight …)
// mehrfach gebraucht — vorher rechnete jeder Aufruf neu (projectToModel3d: ~550 ms bei 10 Dächern).
// Memo je Dach-Objekt: Dächer sind immutabel (structural sharing), die Geometrie wird je
// Ableitung (3D, Schnitt, Pick, Highlight …) mehrfach gebraucht — ungecacht rechnete
// projectToModel3d bei 10 Dächern ~550 ms (TS-Skelett), mit Memo ~3 ms.
const hit = roofGeometryCache.get(roof);
if (hit && hit.eavesZ === eavesZ) return hit.geo;
const geo = roofGeometryUncached(roof, eavesZ);
const geo = decodeGeometry(core().roof_geometry_flat(encodeRoof(roof), eavesZ));
roofGeometryCache.set(roof, { eavesZ, geo });
return geo;
}
const roofGeometryCache = new WeakMap<Roof, { eavesZ: number; geo: RoofGeometry }>();
function roofGeometryUncached(roof: Roof, eavesZ: number): RoofGeometry {
// Walmdach über einem rechtwinkligen, nicht-rechteckigen Grundriss (L/T/U …):
// echte Flächen mit Graten und Kehlen statt Bounding-Box (s. roofSkeleton.ts).
// Zeltdach/Mansard-Zelt auf L/T/U: eine einzelne Spitze gibt es dort nicht — sinnvolles
// Gegenstück ist das allseitig geneigte Skelett-Dach (wie Walm, ohne Giebel).
if (
(roof.shape === "walm" || roof.shape === "sattel" || roof.shape === "mansarde" || roof.shape === "zelt") &&
isRectilinearNonRect(roof.outline)
) {
return rectilinearWalm(roof, eavesZ);
}
// Beliebiger einfacher Umriss (Fünfeck, Pfeil, schiefe Winkel, gedrehtes Rechteck):
// nur allseitig gleich geneigte Formen (Walm/Zelt/Mansard-Walm/-Zelt) — Giebel brauchen
// achsparallele Kanten und bleiben bei der Bounding-Box.
const allround =
roof.shape === "walm" ||
roof.shape === "zelt" ||
(roof.shape === "mansarde" && (roof.mansardType ?? "giebel") !== "giebel");
if (allround && isSkeletonRoofable(roof.outline)) {
return rectilinearWalm(roof, eavesZ);
}
if (roof.shape === "pult" && isRectilinearNonRect(roof.outline)) {
return rectilinearPult(roof, eavesZ);
}
const bb = roofBBox(roof.outline);
const oe = Math.max(0, roof.overhang); // Traufüberstand (senkrecht zum First)
const og = Math.max(0, roof.overhangGable ?? roof.overhang); // Ortgang (entlang First)
// Der First liegt entlang der `ridgeAxis`-Achse: dort wirkt der Ortgang-, quer
// dazu der Traufüberstand. In OUTLINE-Koordinaten je nach Firstrichtung mappen.
const ox = roof.ridgeAxis === "x" ? og : oe;
const oy = roof.ridgeAxis === "x" ? oe : og;
let x0 = bb.x0 - ox;
let y0 = bb.y0 - oy;
let x1 = bb.x1 + ox;
let y1 = bb.y1 + oy;
const flip = roof.ridgeAxis === "y";
if (flip) {
[x0, y0, x1, y1] = [y0, x0, y1, x1];
}
const g = computeCanonical(x0, y0, x1, y1, eavesZ, roof);
if (!flip) return g;
return {
eaves: g.eaves.map(swap2),
ridges: g.ridges.map(swapLine),
hips: g.hips.map(swapLine),
breaks: g.breaks.map(swapLine),
planes: g.planes.map((pl) => ({ pts: pl.pts.map(swap3) })),
gables: g.gables.map((poly) => poly.map(swap3)),
ridgeHeight: g.ridgeHeight,
};
}
/**
* Walmdach auf rechtwinkligem Grundriss: Traufe = Umriss um den Traufüberstand
* nach aussen versetzt (ringsum gleich — beim Walm ist jede Kante Traufe),
* Flächen/Linien aus {@link rectilinearHipRoof}.
*/
function rectilinearWalm(roof: Roof, eavesZ: number): RoofGeometry {
let ring = cleanRing(roof.outline);
let area = 0;
for (let i = 0; i < ring.length; i++) {
const p = ring[i];
const q = ring[(i + 1) % ring.length];
area += p.x * q.y - q.x * p.y;
}
if (area < 0) ring = [...ring].reverse();
const oe = Math.max(0, roof.overhang);
const og = Math.max(0, roof.overhangGable ?? roof.overhang);
// Satteldach: Kanten quer zum First sind Ortgang (eigener Überstand), sonst Traufe.
const eaves = offsetRectilinear(
ring,
roof.shape === "sattel"
? (a, b) => {
const alongX = Math.abs(b.x - a.x) > Math.abs(b.y - a.y);
return alongX === (roof.ridgeAxis === "x") ? oe : og;
}
: oe,
);
const tan = Math.tan(Math.max(0, roof.pitchDeg) * DEG);
const gabled = roof.shape === "sattel" || (roof.shape === "mansarde" && (roof.mansardType ?? "giebel") === "giebel");
const ridgeAxis = gabled ? roof.ridgeAxis : undefined;
let knee: { d: number; tanUp: number } | undefined;
if (roof.shape === "mansarde") {
// Knick bei `mansardKneeRatio` der maximalen Dachtiefe (Abstand First–Traufe).
const depth = rectilinearHipRoof(eaves, 1, 0, ridgeAxis).ridgeHeight;
const ratio = Math.min(0.49, Math.max(0.05, roof.mansardKneeRatio ?? 0.4));
const aUp = Math.max(0, roof.pitchUpperDeg ?? roof.pitchDeg / 2) * DEG;
knee = { d: depth * ratio, tanUp: Math.tan(aUp) };
}
const sk = rectilinearHipRoof(eaves, tan, eavesZ, ridgeAxis, knee);
return {
eaves,
ridges: sk.ridges,
hips: sk.hips,
breaks: sk.breaks,
planes: sk.planes.map((pts) => ({ pts })),
gables: sk.gables,
ridgeHeight: sk.ridgeHeight,
};
}
/**
* Pultdach auf rechtwinkligem Grundriss: EINE Ebene über dem (um Traufe/Ortgang
* geweiteten) Umriss. Tief bei kleinstem y (First entlang x) bzw. x (First entlang y),
* Steigung wie beim Rechteck-Pult; Kanten quer zum First bekommen senkrechte Giebel.
*/
function rectilinearPult(roof: Roof, eavesZ: number): RoofGeometry {
let ring = cleanRing(roof.outline);
let area = 0;
for (let i = 0; i < ring.length; i++) {
const p = ring[i];
const q = ring[(i + 1) % ring.length];
area += p.x * q.y - q.x * p.y;
}
if (area < 0) ring = [...ring].reverse();
const oe = Math.max(0, roof.overhang);
const og = Math.max(0, roof.overhangGable ?? roof.overhang);
const ax = roof.ridgeAxis === "x";
const eaves = offsetRectilinear(ring, (a, b) => {
const alongX = Math.abs(b.x - a.x) > Math.abs(b.y - a.y);
return alongX === ax ? oe : og;
});
const tan = Math.tan(Math.max(0, roof.pitchDeg) * DEG);
const s = (p: Vec2) => (ax ? p.y : p.x);
const smin = Math.min(...eaves.map(s));
const smax = Math.max(...eaves.map(s));
const z = (p: Vec2) => eavesZ + tan * (s(p) - smin);
const up = (p: Vec2): Vec3 => [p.x, p.y, z(p)];
const base = (p: Vec2): Vec3 => [p.x, p.y, eavesZ];
const gables: Vec3[][] = [];
eaves.forEach((a, i) => {
const b = eaves[(i + 1) % eaves.length];
const alongX = Math.abs(b.x - a.x) > Math.abs(b.y - a.y);
if (alongX === ax) return;
gables.push([base(a), base(b), up(b), up(a)]);
});
return {
eaves,
ridges: [], // höchste Kante(n): Rand bei smax
hips: [],
breaks: [],
planes: convexPieces(eaves).map((pc) => ({ pts: pc.map(up) })),
gables,
ridgeHeight: (smax - smin) * tan,
};
}
/** Punkt-in-Polygon (Ray-Casting), 2D-Aufsicht. */
function pointInPolygon2D(p: Vec2, poly: Vec2[]): boolean {
let inside = false;
const n = poly.length;
for (let i = 0, j = n - 1; i < n; j = i++) {
const a = poly[i];
const b = poly[j];
const intersect =
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;
if (intersect) inside = !inside;
}
return inside;
}
/**
* Dach-UNTERKANTE (Innenseite der untersten Schicht) an einem Grundriss-Punkt
* (x,y) — `null`, wenn der Punkt ausserhalb aller Dachflächen liegt (Aufsicht).
* Ebenengleichung je Fläche über die Newell-Normale (identische Herleitung wie
* `toSection.ts::appendRoofSections`, dort inline für den Vertikalschnitt) minus
* `totalLayerThickness` (Summe aller Dachschicht-Dicken, s. `roofLayers`).
* Dient dem Wand-Zuschnitt unter geneigten Dächern ({@link trimWallTopForRoofs}
* in `toWalls3d.ts`) — vermeidet, dass ein flacher Wand-Top die Dachfläche
* durchdringt (Z-Fighting).
* Ebene der ersten Fläche, die den Punkt enthält, minus `totalLayerThickness`
* (Summe aller Dachschicht-Dicken, s. `roofLayers`). Dient dem Wand-Zuschnitt unter
* geneigten Dächern (`toWalls3d/bands.ts`) — vermeidet, dass ein flacher Wand-Top die
* Dachfläche durchdringt (Z-Fighting).
*/
export function roofUndersideAt(
geo: RoofGeometry,
@@ -557,23 +159,16 @@ export function roofUndersideAt(
x: number,
y: number,
): number | null {
for (const pl of geo.planes) {
const pts = pl.pts;
if (pts.length < 3) continue;
if (!pointInPolygon2D({ x, y }, pts.map((p) => ({ x: p[0], y: p[1] })))) continue;
let A = 0;
let B = 0;
let C = 0;
for (let i = 0; i < pts.length; i++) {
const c = pts[i];
const d = pts[(i + 1) % pts.length];
A += (c[1] - d[1]) * (c[2] + d[2]);
B += (c[2] - d[2]) * (c[0] + d[0]);
C += (c[0] - d[0]) * (c[1] + d[1]);
let flat = planesFlat.get(geo);
if (!flat) {
const vals = [geo.planes.length];
for (const pl of geo.planes) {
vals.push(pl.pts.length);
for (const v of pl.pts) vals.push(v[0], v[1], v[2]);
}
if (Math.abs(C) < 1e-9) continue; // (nahezu) vertikale Fläche
const topZ = pts[0][2] - (A * (x - pts[0][0]) + B * (y - pts[0][1])) / C;
return topZ - Math.max(0, totalLayerThickness);
flat = Float64Array.from(vals);
planesFlat.set(geo, flat);
}
return null;
const z = core().roof_underside_at(flat, totalLayerThickness, x, y);
return Number.isNaN(z) ? null : z;
}
+28 -7
View File
@@ -1,7 +1,11 @@
import { describe, expect, it } from "vitest";
import type { Roof, Vec2 } from "../model/types";
import { roofGeometry } from "./roof";
import { convexPieces, isRectilinearNonRect, rectilinearHipRoof } from "./roofSkeleton";
// Das Skelett rechnet der Rust-Kern (`src-tauri/core/src/roof_skeleton.rs`, dort auch die Tests
// der Hilfsfunktionen: Säubern, Versatz, konvexe Zerlegung, Umriss-Erkennung). Hier wird es über
// `roofGeometry` geprüft: Walm/Sattel mit 45° ohne Überstand auf Traufhöhe 0 entspricht dem
// früheren direkten Aufruf `rectilinearHipRoof(L, 1, 0[, "x"])`.
const L: Vec2[] = [{ x: 0, y: 0 }, { x: 11, y: 0 }, { x: 11, y: 4 }, { x: 8, y: 4 }, { x: 8, y: 6 }, { x: 0, y: 6 }];
@@ -14,14 +18,32 @@ const planArea = (pts: number[][]) => {
return Math.abs(a) / 2;
};
describe("rectilinearHipRoof (L-Grundriss)", () => {
const r = rectilinearHipRoof(L, 1, 0);
const skeleton = (outline: Vec2[], shape: "walm" | "sattel", ridgeAxis: "x" | "y" = "x") => {
const g = roofGeometry({ id: "R", type: "roof", floorId: "eg", categoryCode: "31", outline, shape, pitchDeg: 45, overhang: 0, ridgeAxis } as unknown as Roof, 0);
return { ...g, planes: g.planes.map((p) => p.pts) };
};
/** Konvex (CCW oder CW, kollineare Punkte erlaubt). */
const isConvex = (pts: number[][]) => {
let sign = 0;
for (let i = 0; i < pts.length; i++) {
const [a, b, c] = [pts[i], pts[(i + 1) % pts.length], pts[(i + 2) % pts.length]];
const cr = (b[0] - a[0]) * (c[1] - b[1]) - (b[1] - a[1]) * (c[0] - b[0]);
if (Math.abs(cr) < 1e-12) continue;
if (sign !== 0 && Math.sign(cr) !== sign) return false;
sign = Math.sign(cr);
}
return true;
};
describe("Skelett-Walmdach (L-Grundriss)", () => {
const r = skeleton(L, "walm");
it("Flächen decken den Grundriss exakt (44 + 18 = 62 m² … L = 11·4 + 8·2)", () => {
const total = r.planes.reduce((s, p) => s + planArea(p), 0);
expect(total).toBeCloseTo(11 * 4 + 8 * 2, 6);
});
it("alle Flächen konvex, Höhe = Abstand zur Traufe, Firsthöhe 3 m (halbe Breite 6 → Flügel 4 m: 2 m … )", () => {
for (const p of r.planes) expect(convexPieces(p.map(([x, y]) => ({ x, y }))).length).toBe(1);
for (const p of r.planes) expect(isConvex(p)).toBe(true);
expect(r.ridgeHeight).toBeCloseTo(3, 6);
});
it("Kehle: einspringende Ecke (8,4) steigt zum Kehlpunkt (6,2)", () => {
@@ -32,7 +54,6 @@ describe("rectilinearHipRoof (L-Grundriss)", () => {
describe("roofGeometry", () => {
const base = { id: "R", type: "roof", floorId: "eg", categoryCode: "31", outline: L, shape: "walm", pitchDeg: 45, overhang: 0, ridgeAxis: "x" } as unknown as Roof;
it("Walm auf L nutzt das Skelett, Rechteck bleibt Bounding-Box", () => {
expect(isRectilinearNonRect(L)).toBe(true);
// Sechs Dachebenen (Süd, Ost, Nord und West des Hauptbaus, Kehl- und Flügelfläche); wie viele
// konvexe Stücke je Ebene entstehen, hängt vom Polygon-Kern ab und wird nicht geprüft.
const g = roofGeometry(base, 0);
@@ -52,7 +73,7 @@ describe("roofGeometry", () => {
});
describe("Satteldach auf L-Grundriss", () => {
const r = rectilinearHipRoof(L, 1, 0, "x");
const r = skeleton(L, "sattel");
it("Flächen decken den Grundriss, Giebel statt Walm-Schrägen", () => {
const total = r.planes.reduce((s, p) => s + planArea(p), 0);
expect(total).toBeCloseTo(11 * 4 + 8 * 2, 6);
@@ -67,7 +88,7 @@ describe("Satteldach auf L-Grundriss", () => {
describe("Satteldach, First entlang y", () => {
it("gedrehter L-Grundriss liefert dieselbe Flächensumme und Giebel quer zu y", () => {
const Lt = L.map((p) => ({ x: p.y, y: p.x }));
const r = rectilinearHipRoof(Lt, 1, 0, "y");
const r = skeleton(Lt, "sattel", "y");
expect(r.planes.reduce((s, p) => s + planArea(p), 0)).toBeCloseTo(11 * 4 + 8 * 2, 6);
expect(r.gables.length).toBe(3);
});
-451
View File
@@ -1,451 +0,0 @@
// Walmdach über einem RECHTWINKLIGEN, nicht-rechteckigen Grundriss (L/T/U/Z …):
// echte Dachflächen mit Graten UND Kehlen statt der Bounding-Box-Vereinfachung
// aus `roof.ts` (dort wurde z. B. ein L-Grundriss mit einem Rechteck-Walmdach
// überdeckt — Dach über Luft, im Schnitt/in der Ansicht sichtbar falsch).
//
// Modell (Straight-Skeleton-Dach bei gleicher Neigung ringsum, für achs-
// parallele Kanten): jede Traufkante e "regiert" in ihrem Keil — begrenzt von
// der Kante selbst und den beiden 45°-Winkelhalbierenden an ihren Enden (an
// einer einspringenden Ecke wird die Halbierende zur Kehle). Die Dachhöhe ist
// die NIEDRIGSTE Ebene aller Kanten, deren Keil den Punkt enthält:
// z(p) = e + tan(Neigung) · min{ dist(p, Gerade f) | p ∈ Keil(f) }.
// Die Fläche von e = (Traufpolygon ∩ Keil(e)) minus alle Bereiche, in denen eine
// andere Kante tiefer liegt. Polygon-Booleans über den Rust-Kern (`polygonBool`)
// (Martinez, wie `editors/booleanOps.ts`). Danach in KONVEXE Teilflächen zerlegt
// (Ohr-Schnitt + Hertel–Mehlhorn), weil Renderer/Schnitt konvexe Flächen
// erwarten (Fächer-Triangulierung, Cyrus–Beck).
//
// Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md).
import * as polygonClipping from "./polygonBool";
import type { MultiPolygon, Ring } from "./polygonBool";
import type { Vec2 } from "../model/types";
import type { Vec3 } from "./roof";
/** Ausgabe-Raster (Meter): entfernt Rundungsrauschen der Polygon-Booleans. */
const SNAP = 1e-6;
const snap = (v: number) => Math.round(v / SNAP) * SNAP;
/** Signierte Fläche (CCW > 0). */
function signedArea(pts: Vec2[]): number {
let a = 0;
for (let i = 0; i < pts.length; i++) {
const p = pts[i];
const q = pts[(i + 1) % pts.length];
a += p.x * q.y - q.x * p.y;
}
return a / 2;
}
/** Doppelte und kollineare Punkte entfernen. */
export function cleanRing(pts: Vec2[]): Vec2[] {
let out = pts.filter((p, i) => {
const q = pts[(i + 1) % pts.length];
return Math.hypot(p.x - q.x, p.y - q.y) > 1e-9;
});
let changed = true;
while (changed && out.length > 3) {
changed = false;
for (let i = 0; i < out.length; i++) {
const a = out[(i + out.length - 1) % out.length];
const b = out[i];
const c = out[(i + 1) % out.length];
const cr = (b.x - a.x) * (c.y - b.y) - (b.y - a.y) * (c.x - b.x);
if (Math.abs(cr) < 1e-9) {
out = out.filter((_, k) => k !== i);
changed = true;
break;
}
}
}
return out;
}
/** Ob alle Kanten achsparallel sind (und es mehr als ein Rechteck ist). */
export function isRectilinearNonRect(outline: Vec2[]): boolean {
const pts = cleanRing(outline);
if (pts.length <= 4) return false;
return pts.every((p, i) => {
const q = pts[(i + 1) % pts.length];
return Math.abs(p.x - q.x) < 1e-9 || Math.abs(p.y - q.y) < 1e-9;
});
}
/**
* Ring (CCW) um `dist` nach aussen versetzen (Traufüberstand) — Gehrung an jeder
* Ecke (Schnitt der beiden versetzten Kantengeraden), auch bei schiefen Winkeln.
* `dist` kann je Kante verschieden sein (Traufe/Ortgang).
*/
export function offsetRectilinear(ring: Vec2[], dist: number | ((a: Vec2, b: Vec2) => number)): Vec2[] {
if (typeof dist === "number" && dist <= 0) return ring.map((p) => ({ ...p }));
const n = ring.length;
// Aussen-Normale (Einheit) + Versatz je Kante (CCW → rechte Normale).
const edges = ring.map((p, i) => {
const q = ring[(i + 1) % n];
const len = Math.hypot(q.x - p.x, q.y - p.y) || 1;
return { nx: (q.y - p.y) / len, ny: -(q.x - p.x) / len, d: typeof dist === "number" ? dist : dist(p, q) };
});
return ring.map((p, i) => {
const a = edges[(i + n - 1) % n];
const b = edges[i];
const det = a.nx * b.ny - a.ny * b.nx;
// (fast) kollineare Nachbarkanten: einfach entlang der Normale versetzen.
if (Math.abs(det) < 1e-6) return { x: p.x + a.nx * a.d, y: p.y + a.ny * a.d };
let dx = (a.d * b.ny - b.d * a.ny) / det;
let dy = (a.nx * b.d - b.nx * a.d) / det;
// Sehr spitze Ecken: Gehrungsspitze begrenzen.
const lim = 4 * Math.max(a.d, b.d);
const len = Math.hypot(dx, dy);
if (len > lim && len > 0) {
dx *= lim / len;
dy *= lim / len;
}
return { x: p.x + dx, y: p.y + dy };
});
}
/** Schneiden sich zwei Strecken echt (nicht nur an einem gemeinsamen Endpunkt)? */
function segmentsCross(a: Vec2, b: Vec2, c: Vec2, d: Vec2): boolean {
const o = (p: Vec2, q: Vec2, r: Vec2) => (q.x - p.x) * (r.y - p.y) - (q.y - p.y) * (r.x - p.x);
const d1 = o(a, b, c), d2 = o(a, b, d), d3 = o(c, d, a), d4 = o(c, d, b);
return d1 * d2 < -1e-12 && d3 * d4 < -1e-12;
}
/**
* Ob der Umriss ein einfaches (selbstüberschneidungsfreies) Polygon ist, das KEIN
* achsparalleles Rechteck ist — dafür liefert das Skelett ({@link rectilinearHipRoof})
* für gleichmässig geneigte Dächer (Walm/Zelt) die echten Flächen statt der Bounding-Box.
*/
export function isSkeletonRoofable(outline: Vec2[]): boolean {
const pts = cleanRing(outline);
const n = pts.length;
if (n < 3) return false;
if (n === 4) {
const axisRect =
pts.every((p, i) => {
const q = pts[(i + 1) % n];
return Math.abs(p.x - q.x) < 1e-9 || Math.abs(p.y - q.y) < 1e-9;
});
if (axisRect) return false; // Rechteck: Bounding-Box-Dach reicht
}
if (Math.abs(signedArea(pts)) < 1e-6) return false;
for (let i = 0; i < n; i++) {
for (let j = i + 2; j < n; j++) {
if (i === 0 && j === n - 1) continue; // benachbarte Kanten
if (segmentsCross(pts[i], pts[(i + 1) % n], pts[j], pts[(j + 1) % n])) return false;
}
}
return true;
}
/** Konvexes Polygon gegen die Halbebene f(p) ≥ 0 schneiden (Sutherland–Hodgman). */
function clipHalf(poly: Vec2[], f: (p: Vec2) => number): Vec2[] {
const out: Vec2[] = [];
for (let i = 0; i < poly.length; i++) {
const a = poly[i];
const b = poly[(i + 1) % poly.length];
const fa = f(a);
const fb = f(b);
if (fa >= 0) out.push(a);
if ((fa >= 0) !== (fb >= 0)) {
const t = fa / (fa - fb);
out.push({ x: a.x + t * (b.x - a.x), y: a.y + t * (b.y - a.y) });
}
}
return out;
}
/** Polygon-Booleans brauchen exakt zusammenfallende Punkte: auf ein feines Raster runden. */
let ROUND = 1e-9;
const rnd = (v: number) => Math.round(v / ROUND) * ROUND;
const toRing = (pts: Vec2[]): Ring => pts.map((p) => [rnd(p.x), rnd(p.y)] as [number, number]);
interface EdgeInfo {
a: Vec2;
b: Vec2;
/** Innen-Normale (Einheit). */
n: Vec2;
}
/** Ergebnis: Dachflächen (konvex, 3D), Grundriss-Linien, Firsthöhe. */
export interface SkeletonRoof {
planes: Vec3[][];
ridges: [Vec2, Vec2][];
hips: [Vec2, Vec2][];
/** Knicklinien der Mansarde. */
breaks: [Vec2, Vec2][];
/** Senkrechte Giebelflächen (nur Satteldach, s. `ridgeAxis`). */
gables: Vec3[][];
ridgeHeight: number;
}
/**
* Walmdach-Flächen über dem rechtwinkligen Traufring `eaves` (beliebige
* Orientierung) bei Neigung `tan` und Traufhöhe `e`.
*/
function buildHipRoof(
eavesIn: Vec2[],
tan: number,
e: number,
/** Gesetzt → Satteldach: Kanten quer zu dieser Firstrichtung sind senkrechte Giebel (Ortgang). */
ridgeAxis?: "x" | "y",
/** Mansarde: ab Traufabstand `d` flacher (Steigung `tanUp`); Knicklinien landen in `breaks`. */
knee?: { d: number; tanUp: number },
): SkeletonRoof {
let eaves = cleanRing(eavesIn);
if (signedArea(eaves) < 0) eaves = [...eaves].reverse();
const n = eaves.length;
const edges: EdgeInfo[] = eaves.map((a, i) => {
const b = eaves[(i + 1) % n];
const len = Math.hypot(b.x - a.x, b.y - a.y) || 1;
return { a, b, n: { x: -(b.y - a.y) / len, y: (b.x - a.x) / len } };
});
// Giebelkante = quer zur Firstrichtung: keine Neigung, begrenzt nur die Nachbarkeile.
const isGable = edges.map((ed) =>
ridgeAxis === undefined
? false
: ridgeAxis === "x"
? Math.abs(ed.b.x - ed.a.x) < Math.abs(ed.b.y - ed.a.y)
: Math.abs(ed.b.y - ed.a.y) < Math.abs(ed.b.x - ed.a.x),
);
const dist = (k: number, p: Vec2) => (p.x - edges[k].a.x) * edges[k].n.x + (p.y - edges[k].a.y) * edges[k].n.y;
let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
for (const p of eaves) {
minX = Math.min(minX, p.x); minY = Math.min(minY, p.y);
maxX = Math.max(maxX, p.x); maxY = Math.max(maxY, p.y);
}
const pad = (maxX - minX + maxY - minY) * 2 + 10;
const big: Vec2[] = [
{ x: minX - pad, y: minY - pad },
{ x: maxX + pad, y: minY - pad },
{ x: maxX + pad, y: maxY + pad },
{ x: minX - pad, y: maxY + pad },
];
// Keil je Kante: Innenseite der Kante ∩ Innenseiten der beiden Halbierenden.
const wedge = edges.map((ed, k) => {
const prev = edges[(k + n - 1) % n];
const next = edges[(k + 1) % n];
// An Giebelkanten steht die Keilgrenze senkrecht zur Traufe (= Verlängerung des Giebels).
const bisA = isGable[(k + n - 1) % n] ? ed.n : { x: ed.n.x + prev.n.x, y: ed.n.y + prev.n.y };
const bisB = isGable[(k + 1) % n] ? ed.n : { x: ed.n.x + next.n.x, y: ed.n.y + next.n.y };
const side = (o: Vec2, dir: Vec2, ref: Vec2) => {
const s = Math.sign(dir.x * (ref.y - o.y) - dir.y * (ref.x - o.x)) || 1;
return (p: Vec2) => s * (dir.x * (p.y - o.y) - dir.y * (p.x - o.x));
};
let w = clipHalf(big, (p) => dist(k, p));
// Giebelgrenze minimal nach aussen schieben: deckungsgleich mit der Traufring-Kante
// würde der Polygon-Boolean an kollinearen Segmenten scheitern.
const len = Math.hypot(ed.b.x - ed.a.x, ed.b.y - ed.a.y) || 1;
const ux = ((ed.b.x - ed.a.x) / len) * 1e-4;
const uy = ((ed.b.y - ed.a.y) / len) * 1e-4;
const oa = isGable[(k + n - 1) % n] ? { x: ed.a.x - ux, y: ed.a.y - uy } : ed.a;
const ob = isGable[(k + 1) % n] ? { x: ed.b.x + ux, y: ed.b.y + uy } : ed.b;
w = clipHalf(w, side(oa, bisA, ed.b));
w = clipHalf(w, side(ob, bisB, ed.a));
return w;
});
const eavesPoly = [toRing(eaves)];
const planes: Vec3[][] = [];
const lineKeys = new Set<string>();
const ridges: [Vec2, Vec2][] = [];
const hips: [Vec2, Vec2][] = [];
const breaks: [Vec2, Vec2][] = [];
let ridgeHeight = 0;
// Liegt die Strecke p–q auf einer Traufkante (Gerade UND innerhalb der Strecke)?
const onSeg = (k: number, p: Vec2) => {
const { a, b } = edges[k];
const len2 = (b.x - a.x) ** 2 + (b.y - a.y) ** 2;
const t = ((p.x - a.x) * (b.x - a.x) + (p.y - a.y) * (b.y - a.y)) / (len2 || 1);
return Math.abs(dist(k, p)) < 1e-5 && t > -1e-6 && t < 1 + 1e-6;
};
const onEaves = (p: Vec2, q: Vec2) => edges.some((_, k) => onSeg(k, p) && onSeg(k, q));
edges.forEach((_, k) => {
if (isGable[k] || wedge[k].length < 3) return;
let face: MultiPolygon = polygonClipping.intersection(eavesPoly, [toRing(wedge[k])]);
// Bereiche, in denen eine andere Kante tiefer liegt, abziehen.
const subtract: Ring[][] = [];
for (let f = 0; f < n; f++) {
if (f === k || isGable[f] || wedge[f].length < 3) continue;
// Deckungsgleiche Ebenen (gleiche Gerade/Normale, z. B. zwei Traufkanten einer Flucht
// mit Versatz dazwischen): g ≡ 0 — nur EINE der beiden Flächen darf die andere
// abziehen, sonst fällt der überlappende Teil aus beiden heraus (Lücke im Dach).
const coplanar =
Math.abs(edges[k].n.x - edges[f].n.x) < 1e-9 &&
Math.abs(edges[k].n.y - edges[f].n.y) < 1e-9 &&
Math.abs(dist(f, edges[k].a)) < 1e-9;
if (coplanar && f > k) continue;
// dist_f(p) < dist_k(p) ⇔ g(p) = dist_k(p) − dist_f(p) > 0
const lower = clipHalf(wedge[f], (p) => dist(k, p) - dist(f, p));
if (lower.length >= 3 && Math.abs(signedArea(lower)) > 1e-9) subtract.push([toRing(lower)]);
}
if (subtract.length > 0 && face.length > 0) face = polygonClipping.difference(face, ...subtract);
for (const poly of face) {
const outer = cleanRing(poly[0].slice(0, -1).map(([x, y]) => ({ x: snap(x), y: snap(y) })));
if (outer.length < 3 || Math.abs(signedArea(outer)) < 1e-6) continue;
const z = (p: Vec2) => {
const d = Math.max(0, dist(k, p));
return knee ? e + tan * Math.min(d, knee.d) + knee.tanUp * Math.max(0, d - knee.d) : e + tan * d;
};
for (const piece of convexPieces(outer)) {
// Mansarde: Teilfläche an der Knicklinie (Traufabstand = knee.d) teilen.
const parts = knee
? [clipHalf(piece, (p) => knee.d - dist(k, p)), clipHalf(piece, (p) => dist(k, p) - knee.d)]
: [piece];
for (const part of parts) {
if (part.length < 3 || Math.abs(signedArea(part)) < 1e-9) continue;
planes.push(part.map((p) => [p.x, p.y, z(p)] as Vec3));
}
if (knee) {
const low = clipHalf(piece, (p) => knee.d - dist(k, p));
for (let i = 0; i < low.length; i++) {
const p = low[i];
const q = low[(i + 1) % low.length];
if (Math.abs(dist(k, p) - knee.d) < 1e-6 && Math.abs(dist(k, q) - knee.d) < 1e-6) breaks.push([p, q]);
}
}
}
// Grat-/Kehl-/Firstlinien: Flächenränder, die nicht auf der Traufe liegen.
for (let i = 0; i < outer.length; i++) {
const p = outer[i];
const q = outer[(i + 1) % outer.length];
if (onEaves(p, q)) continue;
const r = (v: number) => Math.round(v * 1e5);
const kp = `${r(p.x)},${r(p.y)}`;
const kq = `${r(q.x)},${r(q.y)}`;
const key = kp < kq ? `${kp}|${kq}` : `${kq}|${kp}`;
if (lineKeys.has(key)) continue;
lineKeys.add(key);
const zp = z(p);
const zq = z(q);
ridgeHeight = Math.max(ridgeHeight, zp - e, zq - e);
if (Math.abs(zp - zq) < 1e-6) ridges.push([p, q]);
else hips.push([p, q]);
}
}
});
// Giebelflächen: Profil = alle Flächenecken auf der Giebelkante, nach Lage sortiert.
const gables: Vec3[][] = [];
edges.forEach((ed, k) => {
if (!isGable[k]) return;
const len2 = (ed.b.x - ed.a.x) ** 2 + (ed.b.y - ed.a.y) ** 2;
const top: { t: number; v: Vec3 }[] = [];
for (const pl of planes) {
for (const v of pl) {
const t = ((v[0] - ed.a.x) * (ed.b.x - ed.a.x) + (v[1] - ed.a.y) * (ed.b.y - ed.a.y)) / len2;
if (Math.abs(dist(k, { x: v[0], y: v[1] })) < 1e-5 && t > -1e-6 && t < 1 + 1e-6) top.push({ t, v });
}
}
top.sort((p, q) => p.t - q.t);
const prof = top.filter((p, i) => i === 0 || Math.abs(p.t - top[i - 1].t) > 1e-6);
if (prof.length < 2) return;
const poly: Vec3[] = [
[ed.a.x, ed.a.y, e],
[ed.b.x, ed.b.y, e],
...prof.reverse().map((p) => p.v),
];
gables.push(poly);
});
return { planes, ridges, hips, breaks, gables, ridgeHeight };
}
/**
* Walm-/Satteldach-Flächen über dem Traufring (s. {@link buildHipRoof}). Die Polygon-
* Booleans scheitern bei schiefen Winkeln gelegentlich an Rundungsrauschen ("Unable to
* complete output ring") — dann mit gröberem Raster erneut versuchen.
*/
export function rectilinearHipRoof(
eavesIn: Vec2[],
tan: number,
e: number,
ridgeAxis?: "x" | "y",
knee?: { d: number; tanUp: number },
): SkeletonRoof {
let lastError: unknown;
for (const step of [1e-9, 1e-7, 1e-6, 1e-5]) {
ROUND = step;
try {
return buildHipRoof(eavesIn, tan, e, ridgeAxis, knee);
} catch (err) {
lastError = err;
}
}
ROUND = 1e-9;
throw lastError;
}
// ── Konvexe Zerlegung ───────────────────────────────────────────────────────
const cross = (o: Vec2, a: Vec2, b: Vec2) => (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x);
function isConvex(poly: Vec2[]): boolean {
for (let i = 0; i < poly.length; i++) {
if (cross(poly[i], poly[(i + 1) % poly.length], poly[(i + 2) % poly.length]) < -1e-12) return false;
}
return true;
}
/** Ohr-Schnitt eines einfachen CCW-Polygons → Dreiecke (Indizes). */
function earClip(poly: Vec2[]): number[][] {
const idx = poly.map((_, i) => i);
const tris: number[][] = [];
const inTri = (p: Vec2, a: Vec2, b: Vec2, c: Vec2) =>
cross(a, b, p) >= -1e-12 && cross(b, c, p) >= -1e-12 && cross(c, a, p) >= -1e-12;
let guard = 0;
while (idx.length > 3 && guard++ < 10000) {
let cut = false;
for (let i = 0; i < idx.length; i++) {
const ia = idx[(i + idx.length - 1) % idx.length];
const ib = idx[i];
const ic = idx[(i + 1) % idx.length];
const a = poly[ia], b = poly[ib], c = poly[ic];
if (cross(a, b, c) <= 1e-12) continue; // einspringend/entartet
const blocked = idx.some((j) => j !== ia && j !== ib && j !== ic && inTri(poly[j], a, b, c));
if (blocked) continue;
tris.push([ia, ib, ic]);
idx.splice(i, 1);
cut = true;
break;
}
if (!cut) break; // numerisch entartet: Rest als Fächer
}
for (let i = 1; i + 1 < idx.length; i++) tris.push([idx[0], idx[i], idx[i + 1]]);
return tris;
}
/** Konvexe Teilpolygone (CCW-Eingabe): Ohr-Schnitt, dann Hertel–Mehlhorn-Verschmelzen. */
export function convexPieces(polyIn: Vec2[]): Vec2[][] {
const poly = signedArea(polyIn) < 0 ? [...polyIn].reverse() : polyIn;
if (isConvex(poly)) return [poly];
let pieces: number[][] = earClip(poly);
let merged = true;
while (merged) {
merged = false;
outer: for (let i = 0; i < pieces.length; i++) {
for (let j = i + 1; j < pieces.length; j++) {
const A = pieces[i];
const B = pieces[j];
// Gemeinsame Kante (u→v in A, v→u in B) suchen.
for (let s = 0; s < A.length; s++) {
const u = A[s];
const v = A[(s + 1) % A.length];
const t = B.findIndex((x, k) => x === v && B[(k + 1) % B.length] === u);
if (t < 0) continue;
// A ab v rundum bis u, dann B ab u (ohne u) bis vor v.
const rotA: number[] = [];
for (let k = 0; k < A.length; k++) rotA.push(A[(s + 1 + k) % A.length]); // v … u
const rotB: number[] = [];
for (let k = 2; k < B.length; k++) rotB.push(B[(t + k) % B.length]); // nach u … vor v
const cand = [...rotA, ...rotB];
if (isConvex(cand.map((q) => poly[q]))) {
pieces = pieces.filter((_, k) => k !== i && k !== j);
pieces.push(cand);
merged = true;
break outer;
}
}
}
}
}
return pieces.map((pc) => pc.map((q) => poly[q]));
}