diff --git a/TODO.md b/TODO.md index 9aea3cb3..26ba4842 100644 --- a/TODO.md +++ b/TODO.md @@ -1186,7 +1186,32 @@ Reihenfolge = Abhängigkeiten. Neue Geometrie entsteht in Rust ([K]). Projektion bei schräg zur Ebene stehender Wand nur mit dem Umriss der zugewandten Fläche (Leibungskanten fehlen), Abzugskörper beliebiger Form, nicht in der Tauri-App/Metal geprüft. - ○ **[G4] Exakte Sichtbarkeit (HLR)** für Ansicht und Projektionsteil des Schnitts. · XL -- ○ **[G5] Dächer untereinander, Gauben, Wand ↔ Decke** per Boolean. · L · nach [G1]/[G2]. +- ◐ **[G5] Dächer untereinander, Gauben, Wand ↔ Decke** per Boolean. · L · nach [G1]/[G2]. + - (30.10.) **Dach ↔ Dach und Gauben** über Körper-Booleans ([107] Schritt 2, `solid_bool.rs`). Kern + `roof_assembly.rs`: ein Dach ist „verschnitten", wenn sich sein Traufumriss mit einem anderen überdeckt + (L-/T-Dächer) oder es Gauben trägt — nur dann rechnen 3D, Schnitt, Ansicht und Grundriss mit Körpern, alle + übrigen Dächer bleiben analytisch. Regel je Schicht (Tiefe d0…d1): früheres Dach A − `S_B(d1)`, späteres B − + `S_A(d0)` (`S_X(d)` = Raum unter der um d gesenkten Oberfläche) ⇒ je Schicht die obere Hülle, Kehlen/Grate, + keine Überlappung. **Gauben** (`Roof.dormers`, `dormer.rs`; Schlepp/Sattel/Flach/Walm; Breite, Stirnhöhe, + Neigung oder Tiefe (Schlepp), Überstand, Wandtyp, Dachtyp sonst der des Hauptdachs): Hauptdach − Loch (alle + Schichten), Gaubendach-Schichten − Raum unter der Hauptdach-Oberkante, Stirn/Wangen je Wandschicht bis + Hauptdach-Unterkante und Gaubendach-Unterkante; Fenster = `Opening` mit `hostDormerId` (+ `hostRoofId`) über + die Dachfenster-Mechanik (`host_frame` → senkrechtes System in der Stirn: 3D Rahmen/Glas, Schnitt, Ansicht, + IFC IfcOpeningElement/IfcWindow). Ausgaben: 3D je Schicht (Bauteilfarbe/Material), Schnitt = + `mesh_section` je Schicht mit Bauteil-Schraffur (Kind Roof, Besitzer = Dach), Ansicht = sichtbare Flächen der + Aussenhaut (koplanare Dreiecke zu Flächen, Löcher als Streifen), Grundriss = Dachaufsicht aus den Körpern + (Traufe/First/Grat-Kehle, verdeckte Teile weg). IFC: Gaube gehört zur IfcRoof-Darstellung (Wangen mit; + Entscheid: Gaube ist Dach-Bestandteil, kein eigenes Element), Bauteilliste: Zeile „Gaube". UI: Befehl + „Gaube" (`dormer`, Alias gaube/lukarne, Inline-Option Art), Objekt-Info des Dachs: Abschnitt „Gauben" + (Felder je Gaube, entfernen), 3D-Griffe Breite (links/rechts) und Tiefe (Schlepp). Cache je Dach + (`roof-solids/`, Inhalts-Hash). Geprüft: Rust-Tests (L-Dach ohne Überlappung, alle Teile dicht, Gaube + aller Arten dicht und überlappungsfrei, Hauptdach-Volumen kleiner, Schnitt trifft alle Teile, Griffe, + Befehl), vitest-Robustheit (kaputte Gauben), CLI-Grundriss/-Schnitte/-Ansicht eines Testprojekts + (Schlepp- + Satteldachgaube, T-Dach) als PNG angesehen (Linux). Offen: **Wand ↔ Dach/Decke** per Boolean + (Wände laufen weiter über die Bänder mit `topDrop`, gestuft bei Öffnungen — dafür müssten Wände als Netze + statt `RWall` gehen), 3D-Live-Schnitt-Deckel verschnittener Dächer (zeigen noch die unverschnittenen + Schichten), IFC-Mengen der Gaube, Kehlen symmetrisch je Schicht (heute „überlappt" das frühere Dach), + Gauben über First/Grat hinaus nicht abgefangen, nicht in der Tauri-App/Metal geprüft. - (30.10.) Boolean-Werkzeug dafür: Manifold-Port `manifold-rust`, nicht truck — truck scheitert an Gaube und L-Ecke (bündige Unterseiten), `manifold-rust` rechnet beide exakt und dicht. Details und Plan: [107]. - ○ **[G6] Allgemeine Polygon-Dominanz im Schnitt** (nicht nur Rechtecke). · M @@ -1722,9 +1747,22 @@ Format · [90] Versionsvergleich · [91] Assistent · [92] Speckle. `trucksolid/tests/manifold_cases.rs`: 14 Spike-Fälle (bündiger Abzug, Gaube, Dach-L-Ecke, 30 Öffnungen, 200 Quader, Splitter 1e-7/1e-10, 1e-6 rad) ok, geschlossen, Volumen rel < 1e-9; Orientierung, kaputte Eingaben. **WASM:** `pkgTruck` 3.26 → 4.44 MB (gzip 745 → 1082 KB) — deutlich mehr als im Spike gemessen (Clipper2/dashu - kommen dazu). Offen: Schritt 2 (Kern-Modul `solid_bool.rs` für [G5]/Abzugskörper, Fuzz, Cache), Panik im WASM + kommen dazu). Schritt 2 (30.10.): Kern-Modul `solid_bool.rs` (s. u.). Offen: Panik im WASM (läuft hinter `guarded()`), Tauri/macOS nicht geprüft. · M +- ◐ **[107] Schritt 2: Körper-Booleans im Kern.** (30.10.) `src-tauri/core/src/solid_bool.rs` mit + `manifold-rust` `=0.19.1` (exakter Modus) für synchrone Ableitungen ([G5]): `Solid::new` prüft vorher + (Dreier-Gruppen, Indizes, endlich und |x| < 1e7 m, ≤ 200 000 Dreiecke, Ecken auf 1e-7 m verschweisst, + geschlossen/mannigfaltig, Volumen ≠ 0, innen nach aussen ⇒ gedreht), `status()` nach jeder Operation, + Ergebnis mit `simplify`; `Solid::new_exact` für Manifold-eigene Netze. Flache Kodierung + `[nV, xyz…, nT, ijk…]`, Bindung `solid_boolean` (leer bei Unsinn), TS-Fassade `src/geometry/solidBool.ts`. + Cache je Element (`cached(key, hash, f)`: gleicher Inhalts-Hash ⇒ gespeichert, sonst ersetzt). Fuzz: + Rust 400 zufällige/kaputte Netze (NaN, ∞, Indizes, abgeschnitten, doppelte Flächen, platt, Splitter, + gedreht) + 2000 kaputte flache Puffer, vitest 300 Fälle über WASM — keine Panik. Entscheid: im Kern statt + eigenem Modul, weil nur geprüfte, selbst erzeugte Netze hineingehen; eine Restgefahr durch Panik im + Fremd-Crate bleibt (kein `catch_unwind` auf wasm32). Offen: Abzugskörper beliebiger Form ([G1]/[G3]) über + `solid_bool`. · M + - ◐ **[27] Punktwolken — Stufe 1: Anzeige im 3D.** (28.10.) render3d: eigene Punkt-Pipeline (`render3d/src/points.rs` GPU-frei: Puffer-Aufbau, Farbabbildung, WGSL; `gpu_points.rs`: Pipeline im selben Pass/Tiefen-/MSAA-Ziel wie das Modell). Ein Instanz-Quad je Punkt (6 Vertices aus diff --git a/src-tauri/core/Cargo.lock b/src-tauri/core/Cargo.lock index 5528230f..aee4564c 100644 --- a/src-tauri/core/Cargo.lock +++ b/src-tauri/core/Cargo.lock @@ -2,6 +2,12 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + [[package]] name = "bumpalo" version = "3.20.3" @@ -14,6 +20,15 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" +[[package]] +name = "clipper2-rust" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "210e9ea90a5f6c731c23bf642383ad7c006d8b24803c5c33afd5aaeae5a33f66" +dependencies = [ + "num-traits", +] + [[package]] name = "console_error_panic_hook" version = "0.1.7" @@ -24,6 +39,38 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "dashu-base" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a64b04cdfc4c8533100fe00304eb9687173bda47b1f1dac8af12ba13712ed49d" + +[[package]] +name = "dashu-int" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6ee98721d5d223e5b64b642dd9588b79d9ef415554b13720308b77d628c3be6" +dependencies = [ + "cfg-if", + "dashu-base", + "num-modular", + "num-traits", + "rustversion", + "static_assertions", +] + +[[package]] +name = "dashu-ratio" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "727613e0312d442301147d9e45eb2e7c2797230fc6d223a2c51ecf0e98dfeb5e" +dependencies = [ + "dashu-base", + "dashu-int", + "num-traits", + "rustversion", +] + [[package]] name = "dossier-core" version = "0.1.0" @@ -32,6 +79,7 @@ dependencies = [ "dossier-hatch", "i_overlay", "kernel2d", + "manifold-rust", "render3d", "serde", "serde_json", @@ -136,12 +184,40 @@ version = "0.2.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" +[[package]] +name = "manifold-rust" +version = "0.19.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a60322b26d00d2868b7adde93b823900b0ff5320fd9107498947a913b986b977" +dependencies = [ + "clipper2-rust", + "dashu-int", + "dashu-ratio", + "num-traits", + "rustc-hash", +] + [[package]] name = "memchr" version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" +[[package]] +name = "num-modular" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd8e500409e6cd603b03e477c26a6caecdc27ac58979a53e881c75eafc079f44" + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + [[package]] name = "once_cell" version = "1.21.4" @@ -174,6 +250,12 @@ dependencies = [ "serde", ] +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + [[package]] name = "rustversion" version = "1.0.23" @@ -225,6 +307,12 @@ dependencies = [ "zmij", ] +[[package]] +name = "static_assertions" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + [[package]] name = "syn" version = "2.0.119" diff --git a/src-tauri/core/Cargo.toml b/src-tauri/core/Cargo.toml index eb755358..5f180863 100644 --- a/src-tauri/core/Cargo.toml +++ b/src-tauri/core/Cargo.toml @@ -31,6 +31,8 @@ zmij = "1" wasm-bindgen = { version = "0.2", optional = true } console_error_panic_hook = { version = "0.1", optional = true } # TS-Typen aus dem Rust-Modell ([K4] S4): `src/model/types.generated.ts`, s. `model/ts_export.rs`. +# Körper-Booleans ([107] Schritt 2, `solid_bool.rs`): Manifold-Port, exakter Modus; Version gepinnt (junges Crate). +manifold-rust = "=0.19.1" ts-rs = { version = "12", default-features = false, features = ["serde-compat"] } [profile.release] diff --git a/src-tauri/core/src/cmd_solid.rs b/src-tauri/core/src/cmd_solid.rs index 6cb92671..2a17b1d1 100644 --- a/src-tauri/core/src/cmd_solid.rs +++ b/src-tauri/core/src/cmd_solid.rs @@ -446,6 +446,60 @@ fn roof_window_ops(root: &Map, v: &Value, ctx: &Ctx, ids: &mut Id add_op("openings", vec![obj(f)]) } +/// Gaube ([G5]): ein Klick in eine geneigte Dachfläche setzt die Gaube (Stirnmitte am Punkt) und ein +/// Fenster in ihre Stirn (`hostDormerId`). Art über `kind` (schlepp/sattel/flach/walm). +fn dormer_ops(root: &Map, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec { + let at = p_of(v, "p"); + if !(at.0.is_finite() && at.1.is_finite()) { + return Vec::new(); + } + let on_sloped = |e: &&Value| { + let Ok(r) = serde_json::from_value::((*e).clone()) else { return false }; + crate::roof::roof_geometry(&r.params(), 0.0).planes.iter().any(|pl| { + let n = crate::model3d::plane_normal_up(pl); + pl.len() >= 3 && n[2] > 0.05 && n[2] < 0.99 && crate::dormer::point_in_xy(at.0, at.1, pl) + }) + }; + let on_level = |e: &&Value| crate::cmd_create::floor_of(e) == Some(ctx.level); + let roofs = arr(root.get("roofs")); + let Some(host) = roofs.iter().filter(on_sloped).find(on_level).or_else(|| roofs.iter().find(on_sloped)) else { return Vec::new() }; + let Some(roof_id) = id_of(host) else { return Vec::new() }; + let kind = match s_of(v, "kind") { + k @ ("schlepp" | "sattel" | "flach" | "walm") => k, + _ => "schlepp", + }; + let width = num_or(field(v, "width"), 2.4).clamp(0.8, 20.0); + let front = num_or(field(v, "frontHeight"), 1.5).clamp(0.6, 6.0); + let did = ids.next("G"); + let mut d = vec![("id", s(&did)), ("kind", s(kind)), ("position", pv(at)), ("width", js_num(width)), ("frontHeight", js_num(front))]; + if let Some(wt) = Some(ctx.wall_type).filter(|t| !t.is_empty()) { + d.push(("wallTypeId", s(wt))); + } + let mut dormers = arr(field(host, "dormers")).to_vec(); + dormers.push(obj(d)); + let mut ops = vec![Op::Replace { collection: "roofs".into(), entity: with(host, "dormers", Value::Array(dormers)) }]; + // Fenster: Breite 60 % der Gaube, Höhe bis 15 cm unter das Gaubendach. + let sill = 0.2; + let mut f = vec![ + ("id", s(&ids.next("O"))), + ("type", s("opening")), + ("hostWallId", s("")), + ("hostRoofId", s(roof_id)), + ("hostDormerId", s(&did)), + ("categoryCode", crate::cmd_create::category_or(root, "21", ctx)), + ("kind", s("window")), + ("position", js_num(0.0)), + ("width", js_num(jsnum::round(width * 0.6 * 100.0) / 100.0)), + ("height", js_num(jsnum::round((front - sill - 0.15).max(0.3) * 100.0) / 100.0)), + ("sillHeight", js_num(sill)), + ]; + if let Some(t) = arr(root.get("windowTypes")).first().and_then(|t| field(t, "id")).filter(|id| truthy(Some(id))) { + f.push(("typeId", t.clone())); + } + ops.extend(add_op("openings", vec![obj(f)])); + ops +} + /// Hof-Ring des Dach-Hof-Befehls: ≥ 3 Punkte wie gezeichnet, 2 Punkte als Rechteck. fn hole_ring(points: &[V]) -> Option> { match points { @@ -573,6 +627,7 @@ pub fn ops(root: &Map, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> "ceilingOpening" => ceiling_opening_ops(root, v, ctx), "roofHole" => roof_hole_ops(root, v, ctx), "roofWindow" => roof_window_ops(root, v, ctx, ids), + "dormer" => dormer_ops(root, v, ctx, ids), "sectionline" => sectionline_ops(root, v, ids), _ => return None, }) @@ -634,6 +689,35 @@ mod tests { assert_eq!(extruded_solid_spec(&solid, 1.0).unwrap()["kind"], "loft"); } + /// [G5] Gaube: nur in geneigten Dachflächen; Gaube im Dach + Fenster mit `hostDormerId`. + #[test] + fn gauben_befehl() { + let rect = json!([{"x": 0, "y": 0}, {"x": 10, "y": 0}, {"x": 10, "y": 8}, {"x": 0, "y": 8}]); + let roof = json!({"id": "R", "type": "roof", "floorId": "dg", "categoryCode": "35", "outline": rect, "shape": "sattel", "pitchDeg": 40, "overhang": 0.3, "ridgeAxis": "x", "thickness": 0.3}); + let mut flat = roof.clone(); + flat["id"] = "F".into(); + flat["shape"] = "flach".into(); + flat["outline"] = json!([{"x": 20, "y": 0}, {"x": 25, "y": 0}, {"x": 25, "y": 5}, {"x": 20, "y": 5}]); + let root = json!({"roofs": [roof, flat]}); + let root = root.as_object().unwrap(); + let run = |x: f64, y: f64, kind: &str| { + let mut ids = IdGen::new("s"); + let ctx = Ctx { level: "dg", floor_height: None, cat: "", wall_type: "", text_height: 0.25, symbol: 1.0 }; + ops(root, &json!({"cmd": "dormer", "p": {"x": x, "y": y}, "kind": kind}), &ctx, &mut ids).unwrap() + }; + let o = run(4.0, 1.5, "sattel"); + assert_eq!(o.len(), 2); + let Op::Replace { entity, .. } = &o[0] else { panic!() }; + assert_eq!(entity["dormers"][0]["kind"], "sattel"); + let Op::Add { items, .. } = &o[1] else { panic!() }; + assert_eq!(items[0]["hostDormerId"], entity["dormers"][0]["id"]); + assert_eq!(items[0]["hostRoofId"], "R"); + assert!(run(22.0, 2.0, "sattel").is_empty(), "Flachdach: keine Gaube"); + assert!(run(40.0, 2.0, "sattel").is_empty()); + let Op::Replace { entity, .. } = &run(4.0, 1.5, "unsinn")[0] else { panic!() }; + assert_eq!(entity["dormers"][0]["kind"], "schlepp"); + } + /// [103] Dachfenster: Dach mit dem Punkt im Umriss (aktives Geschoss zuerst), sonst Decke, sonst nichts. #[test] fn dachfenster_befehl() { diff --git a/src-tauri/core/src/dormer.rs b/src-tauri/core/src/dormer.rs new file mode 100644 index 00000000..0583a28b --- /dev/null +++ b/src-tauri/core/src/dormer.rs @@ -0,0 +1,410 @@ +//! Gauben/Lukarnen ([G5]): Geometrie einer Gaube in einer Dachfläche (`Roof.dormers`). +//! +//! **System** ([`DormerFrame`]): `p` = Mitte der Stirnwand-Aussenseite im Grundriss, `h` = waagrecht +//! nach aussen (das Gefälle hinab), `ew` = Breite (von aussen gesehen nach rechts). Lokal `u` (Breite, +//! ab Mitte), `v` (waagrecht das Gefälle hinauf ab der Stirn-Aussenseite), `z` absolut. Die Dach- +//! Oberkante des Hauptdachs ist dort `z_m0 + v·tan P` (längs `ew` waagrecht). +//! +//! **Teile** (alle als Grundriss-Polygone + Höhenfunktionen, Körper baut `roof_assembly`): +//! - Gaubendach: Oberfläche über einem Rechteck mit Überstand, bis über den Anschluss hinaus +//! verlängert (`v_end`); `roof_assembly` schneidet alles unter der Hauptdach-Oberkante weg. +//! - Unterkante Gaubendach `under(u, v)`: Flach waagrecht, Schlepp steigt mit `v`, Sattel fällt zu den +//! Seiten, Walm zusätzlich zur Stirn. +//! - Loch im Hauptdach `hole`: wo die Unterkante über der Hauptdach-Oberkante liegt (|u| ≤ b/2). +//! - Stirnwand (volle Breite, `v` 0 … Wanddicke) und Wangen (bis an den Lochrand), je Wandschicht. + +use crate::model::*; +use crate::opening_shape::V3; + +pub type P = [f64; 2]; + +const DEG: f64 = std::f64::consts::PI / 180.0; + +/// System der Gaube in ihrer Dachfläche. +#[derive(Clone, Debug, PartialEq)] +pub struct DormerFrame { + pub p: P, + pub h: P, + pub ew: P, + /// Hauptdach-Oberkante an der Stirn (über `p`). + pub z_m0: f64, + /// Steigung des Hauptdachs (tan der Neigung). + pub tan_main: f64, + /// Normale der Dachfläche (nach oben) und ihr Index in `roof_geometry().planes`. + pub n: V3, + pub plane: usize, +} + +impl DormerFrame { + /// Lokal (u, v) → Grundriss. + pub fn plan(&self, u: f64, v: f64) -> P { + [self.p[0] + self.ew[0] * u - self.h[0] * v, self.p[1] + self.ew[1] * u - self.h[1] * v] + } + pub fn world(&self, u: f64, v: f64, z: f64) -> V3 { + let q = self.plan(u, v); + [q[0], q[1], z] + } + /// Grundriss → lokal (u, v). + pub fn local(&self, x: f64, y: f64) -> P { + let (dx, dy) = (x - self.p[0], y - self.p[1]); + [dx * self.ew[0] + dy * self.ew[1], -(dx * self.h[0] + dy * self.h[1])] + } + pub fn main_top(&self, v: f64) -> f64 { + self.z_m0 + v * self.tan_main + } +} + +/// Vollständige Gauben-Geometrie. +#[derive(Clone, Debug)] +pub struct DormerGeom { + pub frame: DormerFrame, + pub kind: DormerKind, + /// Aussenbreite, Stirnhöhe, Überstand. + pub width: f64, + pub front_height: f64, + pub overhang: f64, + /// tan der Gaubendach-Neigung. + pub tan_p: f64, + /// Unterkante Gaubendach an der Stirn-Aussenseite. + pub z_e: f64, + /// Dachschichten (Gaubendach) und Wandschichten (aussen zuerst). + pub roof_layers: Vec, + pub wall_layers: Vec, + pub roof_thickness: f64, + pub wall_thickness: f64, + /// Hauptdach-Dicke (senkrecht zur Fläche). + pub main_thickness: f64, + /// Ende der Gaubendach-Flächen hinten (lokal v). + pub v_end: f64, +} + +/// Fläche des Gaubendachs: Grundriss-Polygon (lokal, Gegenuhrzeigersinn) und Ebene `z = a + bu·u + bv·v` +/// der Oberkante. +#[derive(Clone, Debug)] +pub struct DormerPlane { + pub ring: Vec

, + pub a: f64, + pub bu: f64, + pub bv: f64, +} + +impl DormerPlane { + pub fn z(&self, u: f64, v: f64) -> f64 { + self.a + self.bu * u + self.bv * v + } + /// cos der Neigung (senkrechte Dicke → lotrechte). + pub fn cos(&self) -> f64 { + 1.0 / (1.0 + self.bu * self.bu + self.bv * self.bv).sqrt() + } +} + +fn finite_pos(v: f64) -> bool { + v.is_finite() && v > 0.0 +} + +/// System der Gaube: Dachfläche über `position`, Gefälle aus der Flächennormale. `None`, wenn der Punkt +/// in keiner geneigten Fläche liegt. +pub fn frame(p: &Project, roof: &Roof, d: &Dormer) -> Option { + let (x, y) = (d.position.x, d.position.y); + if !(x.is_finite() && y.is_finite()) { + return None; + } + let g = crate::roof::roof_geometry(&roof.params(), p.roof_base_elevation(roof)); + let (plane, pts) = g.planes.iter().enumerate().find(|(_, pl)| pl.len() >= 3 && point_in_xy(x, y, pl))?; + let n = crate::model3d::plane_normal_up(pts); + let hl = (n[0] * n[0] + n[1] * n[1]).sqrt(); + if !(n[2] > 0.05 && hl > 0.05) { + return None; // flach oder senkrecht: keine Gaube + } + let h = [n[0] / hl, n[1] / hl]; + let z_m0 = pts[0][2] - (n[0] * (x - pts[0][0]) + n[1] * (y - pts[0][1])) / n[2]; + Some(DormerFrame { p: [x, y], h, ew: [-h[1], h[0]], z_m0, tan_main: hl / n[2], n, plane }) +} + +pub(crate) fn point_in_xy(x: f64, y: f64, poly: &[V3]) -> bool { + let mut inside = false; + let n = poly.len(); + let mut j = n.wrapping_sub(1); + for i in 0..n { + let (a, b) = (poly[i], poly[j]); + if (a[1] > y) != (b[1] > y) && x < (b[0] - a[0]) * (y - a[1]) / (b[1] - a[1]) + a[0] { + inside = !inside; + } + j = i; + } + inside +} + +/// Wandschichten der Gaube (Wandtyp, sonst eine Schicht 15 cm). +pub fn wall_layers(p: &Project, d: &Dormer) -> Vec { + let t = d.wall_type_id.as_deref().and_then(|id| p.wall_types.iter().find(|t| t.id == id)); + let l: Vec = t.map(|t| t.layers.iter().filter(|l| l.thickness > 1e-6).cloned().collect()).unwrap_or_default(); + if l.is_empty() { + vec![Layer { component_id: String::new(), thickness: 0.15, ..Default::default() }] + } else { + l + } +} + +/// Dachschichten der Gaube (Dachtyp der Gaube, sonst die des Hauptdachs). +pub fn roof_layers(p: &Project, roof: &Roof, d: &Dormer) -> Vec { + let own = d.roof_type_id.as_deref().and_then(|id| p.roof_types.as_deref()?.iter().find(|t| t.id == id)).filter(|t| !t.layers.is_empty()); + let l: Vec = match own { + Some(t) => t.layers.clone(), + None => p.roof_layers(roof), + }; + l.into_iter().filter(|l| l.thickness > 1e-6).collect() +} + +/// Gaubengeometrie; `None` bei unsinnigen Parametern (zu schmal, zu niedrig, Gaubendach steiler als das +/// Hauptdach bei der Schleppgaube, Punkt nicht in einer geneigten Fläche). +pub fn geometry(p: &Project, roof: &Roof, d: &Dormer) -> Option { + let frame = frame(p, roof, d)?; + if !(finite_pos(d.width) && d.width >= 0.4 && d.width <= 30.0 && finite_pos(d.front_height) && d.front_height <= 10.0) { + return None; + } + let overhang = d.overhang.filter(|o| o.is_finite()).unwrap_or(0.15).clamp(0.0, 2.0); + let main_thickness: f64 = p.roof_layers(roof).iter().map(|l| l.thickness.max(0.0)).sum(); + let roof_layers = roof_layers(p, roof, d); + let roof_thickness: f64 = roof_layers.iter().map(|l| l.thickness).sum(); + let wall_layers = wall_layers(p, d); + let wall_thickness: f64 = wall_layers.iter().map(|l| l.thickness).sum(); + if !(roof_thickness > 1e-3 && wall_thickness > 1e-3 && wall_thickness < d.width / 2.0 - 0.05) { + return None; + } + let tm = frame.tan_main; + let pitch = d.pitch_deg.filter(|v| v.is_finite()); + let tan_p = match d.kind { + DormerKind::Flach => 0.0, + DormerKind::Schlepp => match d.depth.filter(|v| v.is_finite() && *v > 0.1) { + Some(depth) => (tm - d.front_height / depth).max(0.0), + None => (pitch.unwrap_or(15.0).clamp(0.0, 80.0) * DEG).tan(), + }, + _ => (pitch.unwrap_or(40.0).clamp(5.0, 75.0) * DEG).tan(), + }; + if d.kind == DormerKind::Schlepp && tan_p >= tm - 0.02 { + return None; + } + let z_e = frame.z_m0 + d.front_height; + let mut g = DormerGeom { frame, kind: d.kind, width: d.width, front_height: d.front_height, overhang, tan_p, z_e, roof_layers, wall_layers, roof_thickness, wall_thickness, main_thickness, v_end: 0.0 }; + // Hinten weit genug, dass die ganze Gaubendach-Unterkante unter der Hauptdach-Unterkante endet. + let main_v = main_thickness * (1.0 + tm * tm).sqrt(); + let top_extra = roof_thickness * (1.0 + tan_p * tan_p).sqrt(); + let v_end = match d.kind { + DormerKind::Schlepp => (d.front_height + top_extra + main_v) / (tm - tan_p), + DormerKind::Flach => (d.front_height + top_extra + main_v) / tm, + _ => (d.front_height + d.width / 2.0 * tan_p + top_extra + main_v) / tm, + }; + if !(v_end.is_finite() && v_end > 0.0 && v_end < 60.0) { + return None; + } + g.v_end = v_end + 0.05; + Some(g) +} + +impl DormerGeom { + /// Unterkante Gaubendach (lokal). + pub fn under(&self, u: f64, v: f64) -> f64 { + let hw = self.width / 2.0; + match self.kind { + DormerKind::Flach => self.z_e, + DormerKind::Schlepp => self.z_e + v * self.tan_p, + DormerKind::Sattel | DormerKind::Unknown => self.z_e + (hw - u.abs()) * self.tan_p, + DormerKind::Walm => self.z_e + (hw - u.abs()).min(v) * self.tan_p, + } + } + + /// Lotrechter Abstand Oberkante − Unterkante (Gaubendach). + pub fn roof_vertical(&self) -> f64 { + self.roof_thickness * (1.0 + self.tan_p * self.tan_p).sqrt() + } + + /// Flächen der Oberkante (lokal) mit Überstand, bis `v_end`. + pub fn planes(&self) -> Vec { + let (hw, o, ve, t) = (self.width / 2.0, self.overhang, self.v_end, self.tan_p); + let top0 = self.z_e + self.roof_vertical(); + let rect = |u0: f64, u1: f64| vec![[u0, -o], [u1, -o], [u1, ve], [u0, ve]]; + match self.kind { + DormerKind::Flach => vec![DormerPlane { ring: rect(-hw - o, hw + o), a: top0, bu: 0.0, bv: 0.0 }], + DormerKind::Schlepp => vec![DormerPlane { ring: rect(-hw - o, hw + o), a: top0, bu: 0.0, bv: t }], + DormerKind::Sattel | DormerKind::Unknown => vec![ + DormerPlane { ring: rect(-hw - o, 0.0), a: top0 + hw * t, bu: t, bv: 0.0 }, + DormerPlane { ring: rect(0.0, hw + o), a: top0 + hw * t, bu: -t, bv: 0.0 }, + ], + DormerKind::Walm => vec![ + DormerPlane { ring: vec![[-hw - o, -o], [hw + o, -o], [0.0, hw]], a: top0, bu: 0.0, bv: t }, + DormerPlane { ring: vec![[0.0, hw], [hw + o, -o], [hw + o, ve], [0.0, ve]], a: top0 + hw * t, bu: -t, bv: 0.0 }, + DormerPlane { ring: vec![[-hw - o, -o], [0.0, hw], [0.0, ve], [-hw - o, ve]], a: top0 + hw * t, bu: t, bv: 0.0 }, + ], + } + } + + /// Höchster Punkt der Gaube (Oberkante Dach). + pub fn z_max(&self) -> f64 { + self.planes().iter().flat_map(|pl| pl.ring.iter().map(|q| pl.z(q[0], q[1])).collect::>()).fold(f64::NEG_INFINITY, f64::max) + } + + /// Lochrand hinten bei Breite `u`: Unterkante = Hauptdach-Oberkante. + pub fn hole_v(&self, u: f64) -> f64 { + let (tm, t, hf) = (self.frame.tan_main, self.tan_p, self.front_height); + let hw = self.width / 2.0; + match self.kind { + DormerKind::Flach => hf / tm, + DormerKind::Schlepp => hf / (tm - t), + _ => (hf + (hw - u.abs()).max(0.0) * t) / tm, + } + } + + /// Loch im Hauptdach (lokal, Gegenuhrzeigersinn): Aussenkontur der Gaube bis zum Anschluss. + pub fn hole(&self) -> Vec

{ + let hw = self.width / 2.0; + match self.kind { + DormerKind::Flach | DormerKind::Schlepp => vec![[-hw, 0.0], [hw, 0.0], [hw, self.hole_v(hw)], [-hw, self.hole_v(-hw)]], + _ => vec![[-hw, 0.0], [hw, 0.0], [hw, self.hole_v(hw)], [0.0, self.hole_v(0.0)], [-hw, self.hole_v(-hw)]], + } + } + + /// Wandschichten: (Schicht-Index, Grundriss-Ring lokal). Stirn über die volle Breite, Wangen ab der + /// Stirn-Innenseite bis an den Lochrand. + pub fn wall_pieces(&self) -> Vec<(usize, Vec

)> { + let hw = self.width / 2.0; + let tw = self.wall_thickness; + let mut out = Vec::new(); + let mut d = 0.0; + for (k, l) in self.wall_layers.iter().enumerate() { + let (a, b) = (d, d + l.thickness); + d = b; + // Stirn: Schicht k von v = a bis b. + out.push((k, vec![[-hw, a], [hw, a], [hw, b], [-hw, b]])); + // Wangen: Schicht k von |u| = hw − a bis hw − b. + for s in [-1.0, 1.0] { + let (u0, u1) = (s * (hw - b), s * (hw - a)); + let (v0, v1) = (self.hole_v(u0), self.hole_v(u1)); + if v0 <= tw + 1e-3 || v1 <= tw + 1e-3 { + continue; + } + let ring = vec![[u0, tw], [u1, tw], [u1, v1], [u0, v0]]; + out.push((k, if s < 0.0 { ring } else { vec![ring[1], ring[0], ring[3], ring[2]] })); + } + } + out + } + + /// Fenster-System in der Stirn: Mitte der Öffnung auf der Aussenseite, `ew` Breite, `eh` = oben, + /// `n` = nach aussen. + pub fn window_frame(&self, o: &Opening) -> Option { + let (w, h) = (o.width, o.height); + let hw = self.width / 2.0 - self.wall_thickness; + let off = if o.position.is_finite() { o.position } else { 0.0 }; + let sill = if o.sill_height.is_finite() { o.sill_height.max(0.0) } else { 0.0 }; + if !(finite_pos(w) && finite_pos(h)) || off.abs() + w / 2.0 > hw + 1e-9 { + return None; + } + let zc = self.frame.z_m0 + sill + h / 2.0; + if zc + h / 2.0 > self.under(off - w / 2.0, 0.0).min(self.under(off + w / 2.0, 0.0)) + 1e-9 { + return None; + } + let c = self.frame.world(off, 0.0, zc); + let f = &self.frame; + Some(crate::opening_shape::HostFrame { + c, + ew: [f.ew[0], f.ew[1], 0.0], + eh: [0.0, 0.0, 1.0], + n: [f.h[0], f.h[1], 0.0], + thickness: self.wall_thickness, + plane: None, + host: 0, + dormer: true, + }) + } +} + +/// Gaube `dormer_id` im Dach `roof_id` (Index des Dachs, Gaube). +pub fn find<'a>(p: &'a Project, roof_id: &str, dormer_id: &str) -> Option<(usize, &'a Roof, &'a Dormer)> { + let (ri, roof) = p.roofs.as_deref()?.iter().enumerate().find(|(_, r)| r.id == roof_id)?; + let d = roof.dormers.as_deref()?.iter().find(|d| d.id == dormer_id)?; + Some((ri, roof, d)) +} + +/// Fenster in den Gauben eines Dachs (Index): (Öffnung, Gaube, System). +pub fn dormer_openings(p: &Project, roof_index: usize) -> Vec<(&Opening, &Dormer, crate::opening_shape::HostFrame)> { + let Some(roof) = p.roofs.as_deref().and_then(|r| r.get(roof_index)) else { return Vec::new() }; + let mut out = Vec::new(); + for o in p.openings.as_deref().unwrap_or(&[]) { + if o.host_roof_id.as_deref() != Some(roof.id.as_str()) { + continue; + } + let Some(did) = o.host_dormer_id.as_deref() else { continue }; + let Some(d) = roof.dormers.as_deref().and_then(|v| v.iter().find(|d| d.id == did)) else { continue }; + if let Some(mut f) = geometry(p, roof, d).and_then(|g| g.window_frame(o)) { + f.host = roof_index; + out.push((o, d, f)); + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + pub(crate) fn gable_project() -> Project { + serde_json::from_value(serde_json::json!({ + "id": "p", "name": "t", "lineStyles": [], "hatches": [], "components": [], "wallTypes": [], + "drawingLevels": [], "layers": [], "walls": [], "drawings2d": [], + "roofs": [{ + "id": "R1", "type": "roof", "floorId": "F", "categoryCode": "35", + "outline": [{"x": 0, "y": 0}, {"x": 10, "y": 0}, {"x": 10, "y": 8}, {"x": 0, "y": 8}], + "shape": "sattel", "pitchDeg": 45, "overhang": 0.5, "ridgeAxis": "x", "baseElevation": 3.0, "thickness": 0.3, + "dormers": [{"id": "D1", "kind": "sattel", "position": {"x": 3, "y": 1.0}, "width": 2.4, "frontHeight": 1.6}] + }] + })) + .unwrap() + } + + #[test] + fn frame_and_hole_on_gable_roof() { + let p = gable_project(); + let roof = &p.roofs.as_ref().unwrap()[0]; + let d = &roof.dormers.as_ref().unwrap()[0]; + let g = geometry(&p, roof, d).expect("Gaube"); + // Südseite (y klein) fällt nach −y: h = (0, −1) + assert!((g.frame.h[1] + 1.0).abs() < 1e-9 && g.frame.h[0].abs() < 1e-9); + assert!((g.frame.tan_main - 1.0).abs() < 1e-9); + // Hauptdach-Oberkante an der Stirn: Traufe 3.0 bei y = 0 (Überstand 0.5 ⇒ Rand bei −0.5). + let zm = g.frame.z_m0; + assert!(zm > 3.9 && zm < 4.6, "{zm}"); + // Lochrand an den Wangen = Stirnhöhe / tan P, am First weiter hinten. + assert!((g.hole_v(1.2) - 1.6).abs() < 1e-9); + assert!(g.hole_v(0.0) > g.hole_v(1.2)); + assert_eq!(g.hole().len(), 5); + assert!(g.wall_pieces().len() == 3, "Stirn + zwei Wangen"); + assert_eq!(g.planes().len(), 2); + // lokal ↔ Grundriss + let q = g.frame.plan(0.5, 1.0); + let l = g.frame.local(q[0], q[1]); + assert!((l[0] - 0.5).abs() < 1e-12 && (l[1] - 1.0).abs() < 1e-12); + } + + #[test] + fn rejects_bad_parameters() { + let mut p = gable_project(); + let set = |p: &mut Project, f: &dyn Fn(&mut Dormer)| f(&mut p.roofs.as_mut().unwrap()[0].dormers.as_mut().unwrap()[0]); + set(&mut p, &|d| d.width = f64::NAN); + let ok = |p: &Project| { + let r = &p.roofs.as_ref().unwrap()[0]; + geometry(p, r, &r.dormers.as_ref().unwrap()[0]).is_some() + }; + assert!(!ok(&p)); + set(&mut p, &|d| { + d.width = 2.0; + d.kind = DormerKind::Schlepp; + d.pitch_deg = Some(50.0); + }); + assert!(!ok(&p), "Schleppgaube steiler als das Hauptdach"); + set(&mut p, &|d| d.pitch_deg = Some(15.0)); + assert!(ok(&p)); + set(&mut p, &|d| d.position = Vec2 { x: 50.0, y: 50.0 }); + assert!(!ok(&p), "ausserhalb"); + } +} diff --git a/src-tauri/core/src/export_schedule.rs b/src-tauri/core/src/export_schedule.rs index 8338acdf..203a4d04 100644 --- a/src-tauri/core/src/export_schedule.rs +++ b/src-tauri/core/src/export_schedule.rs @@ -127,6 +127,22 @@ pub fn schedule_rows(p: &Project) -> Vec { thickness: Some(r.thickness), area: Some(polygon_area(&r.outline)), }); + // Gauben ([G5]): Breite, Stirnhöhe, Wanddicke, Grundfläche des Ausschnitts im Hauptdach. + for d in r.dormers.as_deref().unwrap_or(&[]) { + let Some(g) = crate::dormer::geometry(p, r, d) else { continue }; + let hole: Vec = g.hole().iter().map(|q| Vec2 { x: q[0], y: q[1] }).collect(); + rows.push(ScheduleRow { + kind: "Gaube", + id: d.id.clone(), + type_name: dormer_kind_name(d.kind).into(), + floor: floor_name(p, &r.floor_id), + floor_id: Some(r.floor_id.clone()), + length: Some(d.width), + height_m: Some(d.front_height), + thickness: Some(g.wall_thickness), + area: Some(polygon_area(&hole)), + }); + } } for c in p.columns.as_deref().unwrap_or(&[]) { let (type_name, length, thickness) = match &c.profile { @@ -148,6 +164,15 @@ pub fn schedule_rows(p: &Project) -> Vec { rows } +fn dormer_kind_name(k: DormerKind) -> &'static str { + match k { + DormerKind::Schlepp => "Schleppgaube", + DormerKind::Sattel | DormerKind::Unknown => "Satteldachgaube", + DormerKind::Flach => "Flachdachgaube", + DormerKind::Walm => "Walmgaube", + } +} + fn shape_name(s: RoofShape) -> &'static str { match s { RoofShape::Flach => "flach", diff --git a/src-tauri/core/src/grips.rs b/src-tauri/core/src/grips.rs index 1122a5b7..4649456c 100644 --- a/src-tauri/core/src/grips.rs +++ b/src-tauri/core/src/grips.rs @@ -932,8 +932,77 @@ fn resize_geom(g: &Value, w: f64, h: f64, fx: f64, fy: f64) -> Option { // ── Dach, Polylinien-Punkte, Dicken ────────────────────────────────────────── +/// Gauben-Griffe ([G5]) im Dach-Griff: Index = Basis + 10 × Gaube + k; k = 0/1 Breite (links/rechts, +/// symmetrisch um die Stirnmitte), k = 2 Tiefe (Schleppgaube; die Neigung folgt daraus). +pub const DORMER_GRIP_BASE: f64 = 1000.0; + +fn dormer_grip(r: &Value, local: f64, x: f64, y: f64) -> Option { + if !(local.is_finite() && local >= 0.0 && x.is_finite() && y.is_finite()) { + return None; + } + let (di, k) = ((local / 10.0).floor() as usize, local as i64 % 10); + let dormers = field(r, "dormers")?.as_array()?; + let d = dormers.get(di)?; + let roof: crate::model::Roof = serde_json::from_value(r.clone()).ok()?; + let (px, py) = xy(field(d, "position")?); + let g = crate::roof::roof_geometry(&roof.params(), 0.0); + let pl = g.planes.iter().find(|pl| pl.len() >= 3 && crate::dormer::point_in_xy(px, py, pl))?; + let n = crate::model3d::plane_normal_up(pl); + let hl = hypot2(n[0], n[1]); + if !(hl > 0.05) { + return None; + } + let h = (n[0] / hl, n[1] / hl); + let (dx, dy) = (x - px, y - py); + let nd = match k { + 0 | 1 => { + let w = 2.0 * (dx * -h.1 + dy * h.0).abs(); + with(d, "width", js_num(jsnum::max(0.8, w))) + } + 2 => { + let depth = -(dx * h.0 + dy * h.1); + let mut nd = with(d, "depth", js_num(jsnum::max(0.3, depth))); + if let Some(o) = nd.as_object_mut() { + o.remove("pitchDeg"); + } + nd + } + _ => return None, + }; + let mut list = dormers.clone(); + list[di] = nd; + Some(with(r, "dormers", Value::Array(list))) +} + +#[cfg(test)] +mod dormer_grip_tests { + use super::*; + + #[test] + fn breite_und_tiefe() { + let r = serde_json::json!({ + "id": "R", "type": "roof", "floorId": "F", "categoryCode": "35", + "outline": [{"x": 0, "y": 0}, {"x": 10, "y": 0}, {"x": 10, "y": 8}, {"x": 0, "y": 8}], + "shape": "sattel", "pitchDeg": 45, "overhang": 0.3, "ridgeAxis": "x", "thickness": 0.3, + "dormers": [{"id": "D", "kind": "schlepp", "position": {"x": 4, "y": 1}, "width": 2, "frontHeight": 1.5, "pitchDeg": 15}] + }); + // Breite: Punkt 1.5 rechts der Mitte (Südseite: ew = +x) ⇒ 3.0 + let w = roof_grip(&r, DORMER_GRIP_BASE + 1.0, 5.5, 1.0).unwrap(); + assert_eq!(w["dormers"][0]["width"], 3.0); + // Tiefe: 2 m das Gefälle hinauf (+y) ⇒ depth 2, Neigung entfällt + let d = roof_grip(&r, DORMER_GRIP_BASE + 2.0, 4.0, 3.0).unwrap(); + assert_eq!(d["dormers"][0]["depth"], 2.0); + assert!(d["dormers"][0].get("pitchDeg").is_none()); + assert!(roof_grip(&r, DORMER_GRIP_BASE + 10.0, 4.0, 3.0).is_none(), "keine zweite Gaube"); + assert!(roof_grip(&r, DORMER_GRIP_BASE + 2.0, f64::NAN, 3.0).is_none()); + } +} + /// Dach-Eckgriff: die gegenüberliegende Ecke bleibt fix, der Umriss bleibt ein achsparalleles Rechteck. fn roof_grip(r: &Value, index: f64, x: f64, y: f64) -> Option { + if index >= DORMER_GRIP_BASE { + return dormer_grip(r, index - DORMER_GRIP_BASE, x, y); + } let outline = field(r, "outline")?.as_array()?; let n = outline.len(); if n < 4 { diff --git a/src-tauri/core/src/ifc_data.rs b/src-tauri/core/src/ifc_data.rs index 98eb060e..c67c3b63 100644 --- a/src-tauri/core/src/ifc_data.rs +++ b/src-tauri/core/src/ifc_data.rs @@ -1050,8 +1050,9 @@ pub fn ifc_export_data(src: &Project, opt: &IfcOptions) -> Result let structure = structure_of(&roof.floor_id); let base = base_of(structure); classified.push((format!("roof/{}", roof.id), Kind::Roof, roof.category_code.clone())); - p.roofs = Some(vec![roof.clone()]); - let meshes = model3d::emit_roofs(&p, None)?; + // Alle Dächer im Projekt lassen (Verschneidung [G5] braucht die Nachbarn), nur dieses ausgeben. + p.roofs = roofs.clone(); + let meshes = model3d::emit_roofs(&p, Some(&roof.id))?; let (mut positions, mut indices) = (Vec::::new(), Vec::::new()); for m in &meshes { let at = (positions.len() / 3) as u32; @@ -1094,7 +1095,7 @@ pub fn ifc_export_data(src: &Project, opt: &IfcOptions) -> Result // ── Dach-/Deckenfenster ([103]): IfcOpeningElement im Dach bzw. in der Decke, IfcWindow/IfcDoor darin ── for o in openings.iter() { let Some(fr) = crate::opening_shape::host_frame(&p, o) else { continue }; - let (host_key, floor_id) = if fr.plane.is_some() { + let (host_key, floor_id) = if fr.plane.is_some() || fr.dormer { let r = &p.roofs.as_deref().unwrap_or(&[])[fr.host]; (format!("roof/{}", r.id), r.floor_id.clone()) } else { diff --git a/src-tauri/core/src/lib.rs b/src-tauri/core/src/lib.rs index 26fb0f59..8c4ca38e 100644 --- a/src-tauri/core/src/lib.rs +++ b/src-tauri/core/src/lib.rs @@ -79,6 +79,9 @@ pub mod ifc_quantities; pub mod ifc_stairs; pub mod ifc_data; pub mod mesh_data; +pub mod solid_bool; +pub mod dormer; +pub mod roof_assembly; pub mod groups; pub mod layers; pub mod levels; diff --git a/src-tauri/core/src/model/generated.rs b/src-tauri/core/src/model/generated.rs index a4e68d11..5db4655d 100644 --- a/src-tauri/core/src/model/generated.rs +++ b/src-tauri/core/src/model/generated.rs @@ -2435,6 +2435,73 @@ pub struct Roof { #[serde(rename = "surfacePatternOffset", default, skip_serializing_if = "Option::is_none")] #[ts(optional)] pub surface_pattern_offset: Option, + /// Gauben/Lukarnen ([G5]) in den Dachflächen dieses Dachs. Fehlt ⇒ keine. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub dormers: Option>, + #[serde(flatten)] + #[ts(skip)] + pub extra: Extra, +} + +/// Gaubenart ([G5]). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize, TS)] +pub enum DormerKind { + /// Schleppgaube: eine Dachfläche, flacher als das Hauptdach. + #[default] + #[serde(rename = "schlepp")] + Schlepp, + /// Satteldachgaube (Giebelgaube): First quer zur Traufe des Hauptdachs. + #[serde(rename = "sattel")] + Sattel, + /// Flachdachgaube. + #[serde(rename = "flach")] + Flach, + /// Walmgaube: Satteldachgaube mit abgewalmter Stirn. + #[serde(rename = "walm")] + Walm, + #[serde(other)] + #[ts(skip)] + Unknown, +} + +/// Gaube/Lukarne ([G5]) in einer Dachfläche: Stirnwand parallel zur Traufe, Wangen bis an das +/// Hauptdach, eigenes Dach mit dem Hauptdach verschnitten; das Hauptdach ist an der Gaube in allen +/// Schichten ausgeschnitten. Das Fenster in der Stirn ist eine `Opening` mit `hostDormerId`. +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, TS)] +#[serde(default)] +pub struct Dormer { + pub id: String, + pub kind: DormerKind, + /// Mitte der Stirnwand-Aussenseite im Grundriss (Meter); legt auch die Dachfläche fest. + pub position: Vec2, + /// Aussenbreite (Wange aussen bis Wange aussen, Meter). + pub width: f64, + /// Stirnhöhe: von der Dach-Oberkante an der Stirn bis Unterkante Gaubendach (Meter). + #[serde(rename = "frontHeight")] + pub front_height: f64, + /// Neigung des Gaubendachs in Grad (Sattel/Walm/Schlepp); fehlt ⇒ Sattel/Walm 40°, Schlepp aus der + /// Tiefe bzw. 15°, Flach 0. + #[serde(rename = "pitchDeg", default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub pitch_deg: Option, + /// Nur Schleppgaube: waagrechte Tiefe von der Stirn bis zum Anschluss an das Hauptdach (Meter); + /// gesetzt ⇒ die Neigung folgt daraus. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub depth: Option, + /// Dachüberstand an Stirn und Seiten (Meter); fehlt ⇒ 0.15. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub overhang: Option, + /// Wandtyp für Wangen und Stirn; fehlt ⇒ einschichtig 0.15 m. + #[serde(rename = "wallTypeId", default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub wall_type_id: Option, + /// Dachtyp des Gaubendachs; fehlt ⇒ der des Hauptdachs. + #[serde(rename = "roofTypeId", default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub roof_type_id: Option, #[serde(flatten)] #[ts(skip)] pub extra: Extra, @@ -2773,6 +2840,12 @@ pub struct Opening { #[serde(rename = "hostAngle", default, skip_serializing_if = "Option::is_none")] #[ts(optional)] pub host_angle: Option, + /// Wirt Gaube ([G5]): Fenster in der Stirnwand der Gaube `hostDormerId` des Dachs `hostRoofId`. + /// `position` = Versatz der Fenstermitte von der Stirnmitte (Meter, + nach rechts von aussen), + /// `sillHeight` = Brüstung über der Dach-Oberkante an der Stirn. + #[serde(rename = "hostDormerId", default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub host_dormer_id: Option, /// Übersteuert das Rahmen-Detail des Typs feldweise für diese Öffnung ([105]). #[serde(rename = "frameDetail", default, skip_serializing_if = "Option::is_none")] #[ts(optional)] diff --git a/src-tauri/core/src/model3d.rs b/src-tauri/core/src/model3d.rs index 73534c14..872ef573 100644 --- a/src-tauri/core/src/model3d.rs +++ b/src-tauri/core/src/model3d.rs @@ -316,6 +316,13 @@ pub fn material_color_maps(p: &Project, only_roof: Option<&str>) -> Vec consider(&l.component_id); } } + for d in r.dormers.as_deref().unwrap_or(&[]) { + for l in crate::dormer::wall_layers(p, d).iter().chain(crate::dormer::roof_layers(p, r, d).iter()) { + if !l.component_id.is_empty() { + consider(&l.component_id); + } + } + } } list } @@ -1445,6 +1452,22 @@ fn push_roof_slab_between(positions: &mut Vec, indices: &mut Vec, top: } } +/// Je Dachfläche ein geschlossenes Prisma der Schicht `d0`–`d1` unter der Oberkante (alle Seiten, auch +/// die gemeinsamen) — Eingabe der Körper-Booleans ([G5], `roof_assembly`). +pub(crate) fn roof_plane_prisms(planes: &[Vec], d0: f64, d1: f64) -> Vec { + let mitre = Mitre::new(planes); + let mut out = Vec::new(); + for (i, plane) in planes.iter().enumerate() { + if plane.len() < 3 { + continue; + } + let (mut positions, mut indices) = (Vec::new(), Vec::new()); + push_roof_slab_between(&mut positions, &mut indices, &mitre.at(i, d0), &mitre.at(i, d1), &vec![false; plane.len()]); + out.push(crate::solid_bool::Mesh { positions, indices }); + } + out +} + /// Dachfenster-Loch in einer Dachfläche ([103]): Ecken auf der Dach-Oberkante (Gegenuhrzeigersinn um /// `n`) und die Normale. pub(crate) struct RoofHoleRect { @@ -1594,9 +1617,24 @@ pub fn emit_roofs(p: &Project, only_roof: Option<&str>) -> Result, St let maps = material_color_maps(p, only_roof); let mut out = Vec::new(); for (ri, roof) in p.roofs.as_deref().unwrap_or(&[]).iter().enumerate().filter(|(_, r)| only_roof.is_none_or(|id| r.id == id)) { + let override_color = roof.color.as_deref().filter(|c| !c.is_empty()).map(|c| hex_to_rgb(c, ROOF_RGB)); + // Verschnittene Dächer und Gauben ([G5]): Körper aus `roof_assembly`. + if let Some(solids) = crate::roof_assembly::roof_solids(p, ri) { + for part in &solids.parts { + let wall = part.role == crate::roof_assembly::Role::DormerWall; + let color = if wall { + p.component(&part.component_id).map_or(WALL_RGB, |c| hex_to_rgb(&c.color, WALL_RGB)) + } else { + roof_color(p, override_color, &part.component_id)? + }; + let material_index = if (wall || override_color.is_none()) && !part.component_id.is_empty() { material_layer(p, &maps, &part.component_id) } else { None }; + let (positions, indices) = crate::roof_assembly::unshared(&part.mesh); + out.push(RMesh { positions, indices, kind: "extrusion", color, vertex_colors: None, material_index }); + } + continue; + } let eaves_z = p.roof_base_elevation(roof); let g = crate::roof::roof_geometry(&roof.params(), eaves_z); - let override_color = roof.color.as_deref().filter(|c| !c.is_empty()).map(|c| hex_to_rgb(c, ROOF_RGB)); let mitre = Mitre::new(&g.planes); let holes = roof_holes_by_plane(p, ri, g.planes.len()); let mut offset_above = 0.0; diff --git a/src-tauri/core/src/opening_shape.rs b/src-tauri/core/src/opening_shape.rs index e941aa7e..20ce9772 100644 --- a/src-tauri/core/src/opening_shape.rs +++ b/src-tauri/core/src/opening_shape.rs @@ -237,6 +237,8 @@ pub struct HostFrame { pub plane: Option, /// Index des Wirts in `Project::roofs` bzw. `Project::ceilings`. pub host: usize, + /// Fenster in der Stirnwand einer Gaube ([G5]): `host` = Dach, `n` waagrecht nach aussen. + pub dormer: bool, } impl HostFrame { @@ -292,6 +294,9 @@ pub fn is_surface_hosted(o: &Opening) -> bool { /// Öffnungs-System eines Dach-/Deckenwirts; `None` ohne Wirt, Lage ausserhalb oder Unsinn. pub fn host_frame(p: &Project, o: &Opening) -> Option { + if o.host_dormer_id.as_deref().is_some_and(|s| !s.is_empty()) { + return dormer_frame(p, o); + } let hp = o.host_point?; if !(hp.x.is_finite() && hp.y.is_finite() && o.width > MIN && o.height > MIN) { return None; @@ -308,14 +313,22 @@ pub fn host_frame(p: &Project, o: &Opening) -> Option { let z = pts[0][2] - (n[0] * (hp.x - pts[0][0]) + n[1] * (hp.y - pts[0][1])) / n[2]; let thickness = p.roof_layers(roof).iter().fold(0.0, |s, l| s + l.thickness.max(0.0)); let (ew, eh) = axes(n, angle); - return Some(HostFrame { c: [hp.x, hp.y, z], ew, eh, n, thickness, plane: Some(plane), host }); + return Some(HostFrame { c: [hp.x, hp.y, z], ew, eh, n, thickness, plane: Some(plane), host, dormer: false }); } let id = o.host_ceiling_id.as_deref().filter(|s| !s.is_empty())?; let (host, c) = p.ceilings.as_deref()?.iter().enumerate().find(|(_, c)| c.id == id)?; let (zb, zt) = p.ceiling_vertical_extent(c); let n = [0.0, 0.0, 1.0]; let (ew, eh) = axes(n, angle); - Some(HostFrame { c: [hp.x, hp.y, zt], ew, eh, n, thickness: (zt - zb).max(0.0), plane: None, host }) + Some(HostFrame { c: [hp.x, hp.y, zt], ew, eh, n, thickness: (zt - zb).max(0.0), plane: None, host, dormer: false }) +} + +fn dormer_frame(p: &Project, o: &Opening) -> Option { + let did = o.host_dormer_id.as_deref()?; + let (ri, roof, d) = crate::dormer::find(p, o.host_roof_id.as_deref()?, did)?; + let mut f = crate::dormer::geometry(p, roof, d)?.window_frame(o)?; + f.host = ri; + Some(f) } /// Rechteck der Öffnung im Grundriss (Oberfläche, Gegenuhrzeigersinn). @@ -344,7 +357,7 @@ pub fn roof_openings(p: &Project, roof_index: usize) -> Vec<(&Opening, HostFrame .as_deref() .unwrap_or(&[]) .iter() - .filter(|o| o.host_roof_id.as_deref() == Some(roof.id.as_str())) + .filter(|o| o.host_roof_id.as_deref() == Some(roof.id.as_str()) && o.host_dormer_id.as_deref().is_none_or(str::is_empty)) .filter_map(|o| host_frame(p, o).map(|f| (o, f))) .collect() } @@ -375,7 +388,7 @@ pub fn surface_window_boxes(p: &Project, o: &Opening, f: &HostFrame) -> Vec<(u8, out.push((0, quad_box(&q, top - 0.03, top - 0.01, &map))); } } - if o.host_roof_id.is_some() { + if o.host_roof_id.is_some() && !f.dormer { let flash = [[-0.06, -0.06], [w + 0.06, -0.06], [w + 0.06, h + 0.06], [-0.06, h + 0.06]]; for q in ring_quads(&flash, &outer) { out.push((2, quad_box(&q, 0.0, 0.03, &map))); diff --git a/src-tauri/core/src/plan/domains.rs b/src-tauri/core/src/plan/domains.rs index 60eb5bbf..977fcd91 100644 --- a/src-tauri/core/src/plan/domains.rs +++ b/src-tauri/core/src/plan/domains.rs @@ -385,6 +385,25 @@ fn roofs(c: &Ctx, out: &mut Vec, bounds: &mut Bounds) { } } } + // Verschnittene Dächer und Gauben ([G5]): Dachaufsicht aus den Körpern (Traufen, Firste, + // Grate/Kehlen, verdeckte Teile weg). + let ri = p.roofs.as_deref().and_then(|r| r.iter().position(|x| x.id == roof.id)); + if let Some(ri) = ri.filter(|&ri| crate::roof_assembly::is_assembled(p, ri)) { + use crate::roof_assembly::EdgeKind; + for (owner, a, b, kind) in crate::roof_assembly::assembly_edges(p).iter() { + if *owner != ri { + continue; + } + let (cls, w) = match kind { + EdgeKind::Eaves => ("roof-eaves", ROOF_EAVES_MM), + EdgeKind::Ridge => ("roof-ridge", ROOF_RIDGE_MM), + EdgeKind::Hip => ("roof-hip", ROOF_HIP_MM), + }; + out.push(line(pv(*a), pv(*b), cls, w, None, stroke, greyed)); + } + roof_windows(c, out, roof); + continue; + } for ring in std::iter::once(&geo.eaves).chain(geo.eaves_holes.iter()) { let pts: Vec = ring.iter().map(|q| pv(*q)).collect(); let n = pts.len(); diff --git a/src-tauri/core/src/plan/elevation.rs b/src-tauri/core/src/plan/elevation.rs index 5f635897..419adddf 100644 --- a/src-tauri/core/src/plan/elevation.rs +++ b/src-tauri/core/src/plan/elevation.rs @@ -177,7 +177,7 @@ pub(crate) fn corner_shifts(x: &RWall) -> [f64; 4] { /// `collectRoofFaces`. fn collect_roof_faces(p: &Project, frame: &[f64; 9]) -> Result, String> { let mut roofs = Vec::new(); - for roof in p.roofs.as_deref().unwrap_or(&[]) { + for (ri, roof) in p.roofs.as_deref().unwrap_or(&[]).iter().enumerate() { let g = crate::roof::roof_geometry(&roof.params(), p.roof_base_elevation(roof)); let layers = p.roof_layers(roof); let outer = layers.first(); @@ -189,6 +189,35 @@ fn collect_roof_faces(p: &Project, frame: &[f64; 9]) -> Result, String None => ROOF_RGB_FALLBACK, }, }; + // Verschnittene Dächer und Gauben ([G5]): sichtbare Dreiecke der Aussenhaut, Gaubenwände in + // ihrer Bauteilfarbe. + if let Some(solids) = crate::roof_assembly::roof_solids(p, ri) { + let fn_ = [frame[3], frame[4], frame[5]]; + // Zugewandte Dreiecke (Ansichtswelt x, Höhe, y wie `surface_openings`). + let front = |m: &crate::solid_bool::Mesh| -> Vec { + (0..m.indices.len() / 3) + .filter(|&ti| { + let q = |i: u32| { + let j = i as usize * 3; + [m.positions[j], m.positions[j + 1], m.positions[j + 2]] + }; + let t = &m.indices[ti * 3..ti * 3 + 3]; + let tri = [q(t[0]), q(t[1]), q(t[2])]; + let n = crate::opening_shape::cross([tri[1][0] - tri[0][0], tri[1][1] - tri[0][1], tri[1][2] - tri[0][2]], [tri[2][0] - tri[0][0], tri[2][1] - tri[0][1], tri[2][2] - tri[0][2]]); + fn_[0] * n[0] + fn_[1] * n[2] + fn_[2] * n[1] < -1e-12 + }) + .collect() + }; + // Wie die übrigen Dächer: Oberfläche der Eindeckung (Dach + Gaubendächer), dazu die Gaubenwände. + roofs.push(RoofIn { id: roof.id.clone(), fill, planes: crate::roof_assembly::planar_faces(&solids.top, &front(&solids.top)), gables: g.gables.clone() }); + let wall_comp = solids.parts.iter().find(|pt| pt.role == crate::roof_assembly::Role::DormerWall && pt.layer == 0).and_then(|pt| p.component(&pt.component_id)); + let wf = wall_comp.map_or([0.85, 0.83, 0.8], |c| hex_to_rgb(&c.color, [0.85, 0.83, 0.8])); + let wall_faces = crate::roof_assembly::planar_faces(&solids.walls, &front(&solids.walls)); + if !wall_faces.is_empty() { + roofs.push(RoofIn { id: roof.id.clone(), fill: wf, planes: wall_faces, gables: Vec::new() }); + } + continue; + } roofs.push(RoofIn { id: roof.id.clone(), fill, planes: g.planes.clone(), gables: g.gables.clone() }); } Ok(project_faces(frame, &[], &[], &roofs)) @@ -542,7 +571,7 @@ fn surface_openings(p: &Project, frame: &[f64; 9], out: &mut Vec) { }; for o in p.openings.as_deref().unwrap_or(&[]) { let Some(f) = crate::opening_shape::host_frame(p, o) else { continue }; - if f.plane.is_none() || fnrm[0] * f.n[0] + fnrm[1] * f.n[2] + fnrm[2] * f.n[1] >= -1e-4 { + if (f.plane.is_none() && !f.dormer) || fnrm[0] * f.n[0] + fnrm[1] * f.n[2] + fnrm[2] * f.n[1] >= -1e-4 { continue; } let (w, h) = (o.width, o.height); @@ -701,6 +730,7 @@ pub fn elevation_primitives(p: &Project, level: &LevelSpec, shadows: bool, mono: let mut seq = 0usize; let mut pending: Vec = Vec::new(); + let assembled: std::collections::HashSet<&str> = p.roofs.as_deref().unwrap_or(&[]).iter().enumerate().filter(|(i, _)| crate::roof_assembly::is_assembled(p, *i)).map(|(_, r)| r.id.as_str()).collect(); let mut roof_edges: HashMap> = HashMap::new(); for (fi, f) in faces.iter().enumerate() { if f.role != Role::Roof || f.id.is_empty() { @@ -715,12 +745,34 @@ pub fn elevation_primitives(p: &Project, level: &LevelSpec, shadows: bool, mono: if f.role != Role::Roof || f.id.is_empty() { return false; } - roof_edges.get(&edge_key(a, b)).is_some_and(|list| { - list.iter().any(|&oi| { - let o = &faces[oi]; - oi != fi && o.id == f.id && f.normal[0] * o.normal[0] + f.normal[1] * o.normal[1] + f.normal[2] * o.normal[2] > 1.0 - 1e-9 + let same = |oi: usize| { + let o = &faces[oi]; + oi != fi && o.id == f.id && f.normal[0] * o.normal[0] + f.normal[1] * o.normal[1] + f.normal[2] * o.normal[2] > 1.0 - 1e-7 + }; + if roof_edges.get(&edge_key(a, b)).is_some_and(|list| list.iter().any(|&oi| same(oi))) { + return true; + } + // Verschnittene Dächer ([G5]): Fugen zwischen Streifen derselben Fläche mit T-Stoss — die Kante + // liegt (an Stichproben) auf Kanten koplanarer Nachbarflächen. + if !assembled.contains(f.id.as_str()) { + return false; + } + let near = |s: Pt| { + faces.iter().enumerate().filter(|(oi, _)| same(*oi)).any(|(_, o)| { + (0..o.pts.len()).any(|k| { + let (c, d) = (o.pts[k], o.pts[(k + 1) % o.pts.len()]); + let (dx, dy) = (d[0] - c[0], d[1] - c[1]); + let l2 = dx * dx + dy * dy; + if l2 < 1e-18 { + return false; + } + let t = ((s[0] - c[0]) * dx + (s[1] - c[1]) * dy) / l2; + let (qx, qy) = (c[0] + dx * t, c[1] + dy * t); + (-1e-9..=1.0 + 1e-9).contains(&t) && (s[0] - qx).powi(2) + (s[1] - qy).powi(2) < 1e-12 + }) }) - }) + }; + [0.1, 0.3, 0.5, 0.7, 0.9].iter().all(|&t| near([a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t])) }; // [T2] Bogenwände: Stossfugen der Sehnen-Teilkörper nicht als Kante zeichnen (die Fläche wirkt // gekrümmt statt facettiert). Eine senkrechte Kante gilt als Fuge, wenn eine andere Fläche derselben @@ -787,7 +839,11 @@ pub fn elevation_primitives(p: &Project, level: &LevelSpec, shadows: bool, mono: pending.push(Pending::Line { a, b, depth: f.depth_min - EPS * 5.0, style: None, paint: None }); } } - let mut prim = polygon(pts, &fill_for(f.fill), "none", 0.0, no_hatch()); + // Verschnittene Dächer ([G5]) kommen teils als Dreiecke: ein Hauch Kontur in der Füllfarbe deckt + // die Haarfugen zwischen ihnen. + let fill = fill_for(f.fill); + let seam = is_roof && assembled.contains(f.id.as_str()); + let mut prim = if seam { polygon(pts, &fill, &fill, 0.05, no_hatch()) } else { polygon(pts, &fill, "none", 0.0, no_hatch()) }; if let Primitive::Polygon { greyed: g, wall_id, ceiling_id, roof_id, .. } = &mut prim { *g = Some(greyed(f)); if !f.id.is_empty() { diff --git a/src-tauri/core/src/plan/section.rs b/src-tauri/core/src/plan/section.rs index 47a3cc35..be7bd87a 100644 --- a/src-tauri/core/src/plan/section.rs +++ b/src-tauri/core/src/plan/section.rs @@ -940,6 +940,21 @@ fn shaped_wall_cuts(cuts: &mut [Cut], p: &Project, walls_r: &[RWall], base: (f64 } } +/// Neigung (Grad) der längsten Kante eines Schnitt-Rings, auf −90…90 gefaltet. +fn ring_slope_deg(pts: &[[f64; 2]]) -> f64 { + let n = pts.len(); + let mut best = (0.0, 0.0); + for i in 0..n { + let (a, b) = (pts[i], pts[(i + 1) % n]); + let (dx, dy) = (b[0] - a[0], b[1] - a[1]); + let l = dx * dx + dy * dy; + if l > best.0 { + best = (l, if dx < 0.0 { atan2(-dy, -dx) } else { atan2(dy, dx) }); + } + } + best.1 * 180.0 / std::f64::consts::PI +} + /// Formöffnungen ([G3]) hinter der Schnittebene: die Wand trägt im Modell das Rechteck-Loch, die /// Projektion zeigt aber den Umriss — Kanten der Wand im Loch-Rechteck fallen weg, der Umriss auf der /// zugewandten Wandfläche kommt dazu. @@ -1010,6 +1025,28 @@ fn append_roof_sections(cuts: &mut Vec, p: &Project, plane: &Plane) { let (bx, by) = plane.base(); let (ux, uy) = plane.u_model(); for (index, roof) in roofs.iter().enumerate() { + // Verschnittene Dächer und Gauben ([G5]): Schnitt durch die Körper je Schicht. + if let Some(solids) = crate::roof_assembly::roof_solids(p, index) { + for part in &solids.parts { + let rings = crate::roof_assembly::section_rings(&part.mesh, (bx, by), (ux, uy)); + if rings.is_empty() { + continue; + } + let wall = part.role == crate::roof_assembly::Role::DormerWall; + for pts in rings { + // Muster der Dachschichten entlang der Neigung (Richtung der längsten Kante). + let slope = if wall { None } else { Some(ring_slope_deg(&pts)) }; + let hatch = if part.component_id.is_empty() { None } else { p.component(&part.component_id).and_then(|comp| resolve_hatch(p, &comp.hatch_id, slope, None, None)) }; + let mut c = Cut::new(Kind::Roof, index, pts); + if let Some(h) = &hatch { + c.fill = Some(poche_fill(h.pattern).to_string()); + c.hatch = Some(h.clone()); + } + cuts.push(c); + } + } + continue; + } let eaves = p.roof_base_elevation(roof); let geo = crate::roof::roof_geometry(&roof.params(), eaves); let layers = p.roof_layers(roof); diff --git a/src-tauri/core/src/roof_assembly.rs b/src-tauri/core/src/roof_assembly.rs new file mode 100644 index 00000000..d334784f --- /dev/null +++ b/src-tauri/core/src/roof_assembly.rs @@ -0,0 +1,860 @@ +//! Dach-Verschneidung und Gauben als Körper ([G5], Booleans über [`crate::solid_bool`]). +//! +//! **Wann:** Ein Dach ist „verschnitten", wenn sich sein Traufumriss mit dem eines anderen Dachs +//! überdeckt (L-/T-Dächer, Anbauten auf gleicher Höhe) oder wenn es Gauben trägt. Nur dann rechnen +//! 3D, Schnitt, Ansicht und Grundriss mit den Körpern hier; alle übrigen Dächer bleiben auf dem +//! bisherigen (analytischen) Weg. +//! +//! **Regel Dach ↔ Dach** (je Schicht k mit Tiefe d0…d1 unter der Oberkante): `S_X(d)` = Raum unter der +//! um `d` gesenkten Oberfläche von Dach X (lotrechte Prismen über den Dachflächen bis unter dessen +//! tiefste Unterkante). Das frühere Dach A (Reihenfolge in `Project::roofs`) verliert, was unter der +//! Schicht-Unterkante von B liegt: `A_k − S_B(d1)`; das spätere B verliert, was unter der Schicht-Oberkante +//! von A liegt: `B_k − S_A(d0)`. Zusammen ergibt das je Schicht genau die Schicht der oberen Hülle beider +//! Dächer (Kehlen, Grate, im anderen Dach steckende Giebel fallen weg), ohne Überlappung. +//! +//! **Gaube** (`dormer.rs`): Hauptdach − Loch (alle Schichten); Gaubendach-Schichten − `S_Haupt(0)` +//! (liegt auf der Eindeckung auf); Wangen/Stirn je Wandschicht − `S_Haupt(Dicke)` (stehen auf der +//! Unterkante) − Raum über der Gaubendach-Unterkante − Fensterlöcher. +//! +//! **Cache:** je Dach (Schlüssel `roof-solids/`), Inhalts-Hash über das Dach, die verschnittenen +//! Nachbarn, Typen und Öffnungen. Schlägt ein Boolean fehl, bleibt der Teil unverschnitten (gezählt in +//! `failed`), nie Panik. + +use std::rc::Rc; + +use crate::dormer::DormerGeom; +use crate::model::*; +use crate::opening_shape::V3; +use crate::solid_bool::{cached, ContentHash, Mesh, Solid}; + +/// Art eines Teils. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Role { + /// Schicht des Dachs selbst. + RoofLayer, + /// Schicht eines Gaubendachs. + DormerRoof, + /// Wandschicht (Wange/Stirn) einer Gaube. + DormerWall, +} + +#[derive(Clone, Debug)] +pub struct Part { + pub role: Role, + /// Schicht-Index (Dach- bzw. Wandaufbau, aussen zuerst). + pub layer: usize, + pub component_id: String, + /// Geschlossenes, verschweisstes Netz (Modell-Meter, z = Höhe). + pub mesh: Mesh, + pub dormer: Option, +} + +#[derive(Clone, Default)] +pub struct RoofSolids { + pub parts: Vec, + /// Vereinigung aller Teile (Aussenhaut für Ansicht/Grundriss). + pub skin: Mesh, + /// Vereinigung der äussersten Dachschichten (Eindeckung von Dach und Gaubendächern): Dachaufsicht. + pub top: Mesh, + /// Vereinigung der Gaubenwände (Ansicht). + pub walls: Mesh, + /// Teile, deren Boolean scheiterte (unverschnitten übernommen). + pub failed: usize, +} + +const LOW: f64 = 0.05; + +/// Dachflächen und Schichten eines Dachs. +struct RoofIn { + planes: Vec>, + layers: Vec, + total: f64, + eaves: Vec<[f64; 2]>, + z_lo: f64, + z_hi: f64, +} + +fn roof_in(p: &Project, r: &Roof) -> RoofIn { + let g = crate::roof::roof_geometry(&r.params(), p.roof_base_elevation(r)); + let layers: Vec = p.roof_layers(r); + let total: f64 = layers.iter().map(|l| l.thickness.max(0.0)).sum(); + let mut z_lo = f64::INFINITY; + let mut z_hi = f64::NEG_INFINITY; + let mut min_nz: f64 = 1.0; + for pl in &g.planes { + let n = crate::model3d::plane_normal_up(pl); + if n[2] > 1e-3 { + min_nz = min_nz.min(n[2]); + } + for q in pl { + z_lo = z_lo.min(q[2]); + z_hi = z_hi.max(q[2]); + } + } + RoofIn { planes: g.planes, layers, total, eaves: g.eaves, z_lo: z_lo - total / min_nz.max(0.05) - LOW, z_hi } +} + +/// Raum unter der um `d` (senkrecht zur Fläche) gesenkten Oberfläche, bis unter die tiefste Unterkante. +fn below_surface(r: &RoofIn, d: f64) -> Vec { + let mut out = Vec::new(); + for pl in &r.planes { + if pl.len() < 3 { + continue; + } + let n = crate::model3d::plane_normal_up(pl); + if n[2] < 1e-3 { + continue; + } + let o = pl[0]; + let top = move |x: f64, y: f64| o[2] - (n[0] * (x - o[0]) + n[1] * (y - o[1])) / n[2] - d / n[2]; + let ring: Vec<[f64; 2]> = pl.iter().map(|q| [q[0], q[1]]).collect(); + let zl = r.z_lo; + let m = Mesh::prism_between(&ring, &move |_, _| zl, &top); + if !m.is_empty() { + out.push(m); + } + } + out +} + +fn solid_union(meshes: &[Mesh], failed: &mut usize) -> Solid { + let (s, bad) = Solid::union_all(meshes); + *failed += bad; + s +} + +fn area2(ring: &[[f64; 2]]) -> f64 { + let n = ring.len(); + (0..n).map(|i| ring[i][0] * ring[(i + 1) % n][1] - ring[(i + 1) % n][0] * ring[i][1]).sum::() / 2.0 +} + +/// Überdecken sich die Traufumrisse zweier Dächer (Fläche > 1e-4 m²) und ihre Höhenbereiche? +fn overlaps(a: &RoofIn, b: &RoofIn) -> bool { + if a.eaves.len() < 3 || b.eaves.len() < 3 || a.z_hi < b.z_lo || b.z_hi < a.z_lo { + return false; + } + let pa = vec![vec![a.eaves.clone()]]; + let pb = vec![vec![b.eaves.clone()]]; + let i = crate::polygon_bool::intersection(&pa, &pb); + i.iter().map(|poly| poly.iter().enumerate().map(|(k, r)| if k == 0 { area2(r).abs() } else { -area2(r).abs() }).sum::()).sum::() > 1e-4 +} + +/// Je Dach: verschnitten (Nachbarn überdecken sich oder Gauben)? Und mit welchen Nachbarn. +pub fn neighbors(p: &Project) -> Vec> { + let roofs = p.roofs.as_deref().unwrap_or(&[]); + let mut h = ContentHash::default(); + for r in roofs { + h.json(&r.outline).json(&r.holes).json(&r.edge_pitch_deg).str(&format!("{:?}{:?}", r.shape, r.ridge_axis)).f64(r.pitch_deg).f64(r.overhang).f64(r.overhang_gable.unwrap_or(-1.0)).f64(r.thickness).f64(p.roof_base_elevation(r)); + h.json(&r.pitch_upper_deg).json(&r.mansard_type).json(&r.mansard_knee_ratio).json(&r.half_hip_ratio).json(&r.roof_type_id); + } + h.json(&p.roof_types); + (*cached("roof-solids/neighbors", h.finish(), || neighbors_uncached(p, roofs))).clone() +} + +fn neighbors_uncached(p: &Project, roofs: &[Roof]) -> Vec> { + let ins: Vec = roofs.iter().map(|r| roof_in(p, r)).collect(); + let mut out = vec![Vec::new(); roofs.len()]; + for i in 0..roofs.len() { + for j in i + 1..roofs.len() { + if overlaps(&ins[i], &ins[j]) { + out[i].push(j); + out[j].push(i); + } + } + } + out +} + +fn has_dormers(r: &Roof) -> bool { + r.dormers.as_deref().is_some_and(|d| !d.is_empty()) +} + +/// Ist das Dach `ri` verschnitten (Körper-Weg)? +pub fn is_assembled(p: &Project, ri: usize) -> bool { + let Some(r) = p.roofs.as_deref().and_then(|v| v.get(ri)) else { return false }; + has_dormers(r) || !neighbors(p).get(ri).is_none_or(Vec::is_empty) +} + +/// Körper des Dachs `ri`, falls verschnitten (sonst `None`), aus dem Cache. +pub fn roof_solids(p: &Project, ri: usize) -> Option> { + let roofs = p.roofs.as_deref()?; + let roof = roofs.get(ri)?; + let nb = neighbors(p).swap_remove(ri); + if nb.is_empty() && !has_dormers(roof) { + return None; + } + let mut h = ContentHash::default(); + h.json(roof).f64(p.roof_base_elevation(roof)).json(&p.roof_types); + for &j in &nb { + h.u64(j as u64).json(&roofs[j]).f64(p.roof_base_elevation(&roofs[j])); + } + if has_dormers(roof) { + h.json(&p.wall_types); + } + for o in p.openings.as_deref().unwrap_or(&[]).iter().filter(|o| o.host_roof_id.as_deref() == Some(roof.id.as_str())) { + h.json(o); + } + let r = cached(&format!("roof-solids/{}", roof.id), h.finish(), || build(p, ri, &nb)); + Some(r) +} + +fn build(p: &Project, ri: usize, nb: &[usize]) -> RoofSolids { + let roofs = p.roofs.as_deref().unwrap_or(&[]); + let roof = &roofs[ri]; + let me = roof_in(p, roof); + let others: Vec<(usize, RoofIn)> = nb.iter().map(|&j| (j, roof_in(p, &roofs[j]))).collect(); + let mut failed = 0usize; + let mut parts = Vec::new(); + + // Löcher: Dachfenster (Quader senkrecht zur Fläche) und Gauben (lotrechte Prismen). + let mut holes: Vec = Vec::new(); + for (o, f) in crate::opening_shape::roof_openings(p, ri) { + holes.push(hex_of(&crate::opening_shape::surface_hole_box(o, &f))); + } + let dormers: Vec<(&Dormer, DormerGeom)> = roof.dormers.as_deref().unwrap_or(&[]).iter().filter_map(|d| crate::dormer::geometry(p, roof, d).map(|g| (d, g))).collect(); + for (_, g) in &dormers { + let ring: Vec<[f64; 2]> = g.hole().iter().map(|q| g.frame.plan(q[0], q[1])).collect(); + holes.push(Mesh::prism(&ring, me.z_lo - 1.0, me.z_hi + 1.0)); + } + let hole_solid = solid_union(&holes, &mut failed); + + let mut d0 = 0.0; + for (k, layer) in me.layers.iter().enumerate() { + let t = layer.thickness.max(0.0); + if t <= 1e-6 { + continue; + } + let d1 = d0 + t; + let prisms = crate::model3d::roof_plane_prisms(&me.planes, d0, d1); + let mut slab = solid_union(&prisms, &mut failed); + let raw = slab.clone(); + let mut ok = true; + if let Ok(s) = slab.difference(&hole_solid) { + slab = s; + } else { + ok = false; + } + for (j, other) in &others { + let d = if *j > ri { d1 } else { d0 }; + let cut = solid_union(&below_surface(other, d), &mut failed); + match slab.difference(&cut) { + Ok(s) => slab = s, + Err(_) => ok = false, + } + } + if !ok { + failed += 1; + slab = raw; + } + let mesh = slab.to_mesh(); + if !mesh.is_empty() { + parts.push(Part { role: Role::RoofLayer, layer: k, component_id: layer.component_id.clone(), mesh, dormer: None }); + } + d0 = d1; + } + + // Gauben. + if !dormers.is_empty() { + let main_top = solid_union(&below_surface(&me, 0.0), &mut failed); + let main_under = solid_union(&below_surface(&me, me.total), &mut failed); + let windows = crate::dormer::dormer_openings(p, ri); + for (d, g) in &dormers { + dormer_parts(d, g, &main_top, &main_under, &windows, &mut parts, &mut failed); + } + } + + let mut skin = Solid::empty(); + for pt in &parts { + match Solid::new_exact(&pt.mesh).and_then(|s| skin.union(&s)) { + Ok(s) => skin = s, + Err(_e) => { + #[cfg(test)] + eprintln!("skin: {_e}"); + failed += 1 + } + } + } + // Ohne `simplify`: das Zusammenlegen kippte an Schichtgrenzen einzelne Dreiecke aus der Dachebene + // (Scheinkanten in Aufsicht/Ansicht). + let skin = skin.to_mesh_raw(); + let mut top = Solid::empty(); + for pt in parts.iter().filter(|pt| pt.layer == 0 && pt.role != Role::DormerWall) { + if let Ok(s) = Solid::new_exact(&pt.mesh).and_then(|s| top.union(&s)) { + top = s; + } + } + let top = top.to_mesh_raw(); + let mut walls = Solid::empty(); + for pt in parts.iter().filter(|pt| pt.role == Role::DormerWall) { + if let Ok(s) = Solid::new_exact(&pt.mesh).and_then(|s| walls.union(&s)) { + walls = s; + } + } + let walls = walls.to_mesh_raw(); + RoofSolids { parts, skin, top, walls, failed } +} + +fn hex_of(b: &[f64; 24]) -> Mesh { + // `quad_box`: Ecke i nach Bits (0/1: Viereck in Bit-Reihenfolge 0,1,3,2; Bit 2: Seite). + let c: [[f64; 3]; 8] = std::array::from_fn(|k| { + let i = [0, 1, 3, 2, 4, 5, 7, 6][k]; + [b[i * 3], b[i * 3 + 1], b[i * 3 + 2]] + }); + Mesh::hexahedron(&c) +} + +fn dormer_parts( + d: &Dormer, + g: &DormerGeom, + main_top: &Solid, + main_under: &Solid, + windows: &[(&Opening, &Dormer, crate::opening_shape::HostFrame)], + parts: &mut Vec, + failed: &mut usize, +) { + let f = &g.frame; + let planes = g.planes(); + let z_hi = g.z_max() + 1.0; + let world_ring = |ring: &[[f64; 2]]| -> Vec<[f64; 2]> { ring.iter().map(|q| f.plan(q[0], q[1])).collect() }; + // Höhe einer lokalen Ebene an einem Grundrisspunkt. + let zf = |pl: &crate::dormer::DormerPlane, x: f64, y: f64| { + let l = f.local(x, y); + pl.z(l[0], l[1]) + }; + // Gaubendach je Schicht. + let mut d0 = 0.0; + for (k, layer) in g.roof_layers.iter().enumerate() { + let d1 = d0 + layer.thickness; + let mut pieces = Vec::new(); + for pl in &planes { + let c = pl.cos(); + let (a, b) = (d0 / c, d1 / c); + let pl2 = pl.clone(); + let pl3 = pl.clone(); + pieces.push(Mesh::prism_between(&world_ring(&pl.ring), &move |x, y| zf(&pl2, x, y) - b, &move |x, y| zf(&pl3, x, y) - a)); + } + let s = solid_union(&pieces, failed); + let s = s.difference(main_top).unwrap_or_else(|_e| { + #[cfg(test)] + eprintln!("dormer roof: {_e}"); + *failed += 1; + s.clone() + }); + let mesh = s.to_mesh(); + if !mesh.is_empty() { + parts.push(Part { role: Role::DormerRoof, layer: k, component_id: layer.component_id.clone(), mesh, dormer: Some(d.id.clone()) }); + } + d0 = d1; + } + // Raum über der Gaubendach-Unterkante. + let rv = g.roof_thickness; + let above: Vec = planes + .iter() + .map(|pl| { + let b = rv / pl.cos(); + let pl2 = pl.clone(); + Mesh::prism_between(&world_ring(&pl.ring), &move |x, y| zf(&pl2, x, y) - b, &move |_, _| z_hi + 1.0) + }) + .collect(); + let above = solid_union(&above, failed); + let win: Vec = windows.iter().filter(|(_, wd, _)| wd.id == d.id).map(|(o, _, fr)| hex_of(&crate::opening_shape::surface_hole_box(o, fr))).collect(); + let win = solid_union(&win, failed); + let z_lo = f.z_m0 - g.main_thickness * (1.0 + f.tan_main * f.tan_main).sqrt() - 0.005; + for (k, ring) in g.wall_pieces() { + let m = Mesh::prism(&world_ring(&ring), z_lo, z_hi); + let Ok(s) = Solid::new(&m) else { + #[cfg(test)] + eprintln!("wall prism"); + *failed += 1; + continue; + }; + let r = s.difference(main_under).and_then(|s| s.difference(&above)).and_then(|s| s.difference(&win)); + let s = match r { + Ok(s) => s, + Err(_e) => { + #[cfg(test)] + eprintln!("wall: {_e}"); + *failed += 1; + continue; + } + }; + let mesh = s.to_mesh(); + if !mesh.is_empty() { + parts.push(Part { role: Role::DormerWall, layer: k, component_id: g.wall_layers[k].component_id.clone(), mesh, dormer: Some(d.id.clone()) }); + } + } +} + +// ── Auswertung für Grundriss, Schnitt, Ansicht, 3D ─────────────────────────── + +/// Netz mit eigenen Ecken je Dreieck (flache Schattierung im 3D). +pub fn unshared(m: &Mesh) -> (Vec, Vec) { + let mut positions = Vec::with_capacity(m.indices.len() * 3); + for &i in &m.indices { + let j = i as usize * 3; + positions.extend_from_slice(&m.positions[j..j + 3]); + } + let indices = (0..m.indices.len() as u32).collect(); + (positions, indices) +} + +fn tri(m: &Mesh, t: &[u32]) -> [V3; 3] { + let v = |i: u32| { + let j = i as usize * 3; + [m.positions[j], m.positions[j + 1], m.positions[j + 2]] + }; + [v(t[0]), v(t[1]), v(t[2])] +} + +fn normal(t: &[V3; 3]) -> V3 { + let (a, b) = ([t[1][0] - t[0][0], t[1][1] - t[0][1], t[1][2] - t[0][2]], [t[2][0] - t[0][0], t[2][1] - t[0][1], t[2][2] - t[0][2]]); + let c = crate::opening_shape::cross(a, b); + let l = crate::opening_shape::dot(c, c).sqrt(); + if l > 1e-15 { [c[0] / l, c[1] / l, c[2] / l] } else { [0.0, 0.0, 0.0] } +} + +/// Koplanare, über Kanten zusammenhängende Dreiecke gruppieren (Indizes `tris` in `m`): Gruppe je +/// Dreieck und Normale je Gruppe (die des grössten Dreiecks). Schmale Dreiecke (ungenaue Normale) zählen +/// zur Ebene ihres Nachbarn, wenn ihre Ecken darin liegen. +fn plane_groups(m: &Mesh, tris: &[usize], canon: &[u32]) -> (Vec, Vec) { + use std::collections::HashMap; + let geo: Vec<[V3; 3]> = tris.iter().map(|&t| tri(m, &m.indices[t * 3..t * 3 + 3])).collect(); + let area: Vec = geo + .iter() + .map(|t| { + let c = crate::opening_shape::cross([t[1][0] - t[0][0], t[1][1] - t[0][1], t[1][2] - t[0][2]], [t[2][0] - t[0][0], t[2][1] - t[0][1], t[2][2] - t[0][2]]); + crate::opening_shape::dot(c, c).sqrt() / 2.0 + }) + .collect(); + let nrm: Vec = geo.iter().map(normal).collect(); + let coplanar = |a: usize, b: usize| { + let (big, small) = if area[a] >= area[b] { (a, b) } else { (b, a) }; + let o = crate::opening_shape::dot(nrm[big], geo[big][0]); + let on = geo[small].iter().all(|v| (crate::opening_shape::dot(nrm[big], *v) - o).abs() < 1e-4); + (on && (area[small] < 1e-4 || crate::opening_shape::dot(nrm[a], nrm[b]) > 0.99)) || crate::opening_shape::dot(nrm[a], nrm[b]) > 0.9995 + }; + let mut parent: Vec = (0..tris.len()).collect(); + fn root(p: &mut [usize], mut i: usize) -> usize { + while p[i] != i { + p[i] = p[p[i]]; + i = p[i]; + } + i + } + let mut by_edge: HashMap<(u32, u32), Vec> = HashMap::new(); + for (k, &t) in tris.iter().enumerate() { + for e in 0..3 { + let (a, b) = (canon[m.indices[t * 3 + e] as usize], canon[m.indices[t * 3 + (e + 1) % 3] as usize]); + by_edge.entry((a.min(b), a.max(b))).or_default().push(k); + } + } + let mut keys: Vec<&(u32, u32)> = by_edge.keys().collect(); + keys.sort_unstable(); + for e in keys { + if let [a, b] = by_edge[e].as_slice() { + if coplanar(*a, *b) { + let (ra, rb) = (root(&mut parent, *a), root(&mut parent, *b)); + parent[ra] = rb; + } + } + } + let mut gid: HashMap = HashMap::new(); + let mut group = vec![0; tris.len()]; + let mut best: Vec<(f64, V3)> = Vec::new(); + for k in 0..tris.len() { + let r = root(&mut parent, k); + let g = *gid.entry(r).or_insert_with(|| { + best.push((-1.0, [0.0; 3])); + best.len() - 1 + }); + group[k] = g; + if area[k] > best[g].0 { + best[g] = (area[k], nrm[k]); + } + } + (group, best.into_iter().map(|b| b.1).collect()) +} + +/// Ecken-Ids: Manifold-Netze sind nach Indizes mannigfaltig — gleiche Lage verschiedener Ecken nicht +/// vereinen (gerundete Schlüssel trennten nahe Ecken an Rundungsgrenzen und erzeugten Scheinkanten). +fn canon_ids(m: &Mesh) -> Vec { + (0..(m.positions.len() / 3) as u32).collect() +} + +/// Dreiecke `tris` (Indizes in `m`) zu ebenen Flächen zusammenfassen: zusammenhängende, koplanare +/// Dreiecke bilden eine Gruppe; hat sie genau einen Rand-Ring, wird sie zu diesem Polygon (kollineare +/// Ecken entfernt), sonst (Löcher) bleiben ihre Dreiecke. Für die Ansicht (eine Fläche statt vieler +/// Dreiecke: keine Haarfugen, keine Scheinkanten). +pub fn planar_faces(m: &Mesh, tris: &[usize]) -> Vec> { + use std::collections::HashMap; + let canon = canon_ids(m); + let tv: Vec<[u32; 3]> = tris.iter().map(|&t| [canon[m.indices[t * 3] as usize], canon[m.indices[t * 3 + 1] as usize], canon[m.indices[t * 3 + 2] as usize]]).collect(); + let geo: Vec<[V3; 3]> = tris.iter().map(|&t| tri(m, &m.indices[t * 3..t * 3 + 3])).collect(); + let (group, _) = plane_groups(m, tris, &canon); + let mut groups: HashMap> = HashMap::new(); + for (k, &g) in group.iter().enumerate() { + groups.entry(g).or_default().push(k); + } + let pos = |i: u32| { + let j = i as usize * 3; + [m.positions[j], m.positions[j + 1], m.positions[j + 2]] + }; + let mut keys: Vec = groups.keys().copied().collect(); + keys.sort_unstable(); + let mut out = Vec::new(); + for g in keys { + let list = &groups[&g]; + // Gerichtete Randkanten: Kante ohne Gegenkante in der Gruppe. + let mut directed: HashMap<(u32, u32), usize> = HashMap::new(); + for &k in list { + for e in 0..3 { + *directed.entry((tv[k][e], tv[k][(e + 1) % 3])).or_default() += 1; + } + } + let boundary: Vec<(u32, u32)> = directed.keys().copied().filter(|&(a, b)| !directed.contains_key(&(b, a))).collect(); + let mut next: HashMap = HashMap::new(); + let mut simple = true; + for &(a, b) in &boundary { + if next.insert(a, b).is_some() { + simple = false; + } + } + let ring = simple.then(|| { + let start = boundary.first()?.0; + let mut ring = vec![start]; + let mut cur = *next.get(&start)?; + while cur != start { + if ring.len() > boundary.len() { + return None; + } + ring.push(cur); + cur = *next.get(&cur)?; + } + (ring.len() == boundary.len()).then_some(ring) + }); + match ring.flatten() { + Some(r) => { + let pts: Vec = r.iter().map(|&i| pos(i)).collect(); + // Kollineare Ecken weg. + let n = pts.len(); + let keep: Vec = (0..n) + .filter(|&i| { + let (a, b, c) = (pts[(i + n - 1) % n], pts[i], pts[(i + 1) % n]); + let cr = crate::opening_shape::cross([b[0] - a[0], b[1] - a[1], b[2] - a[2]], [c[0] - b[0], c[1] - b[1], c[2] - b[2]]); + crate::opening_shape::dot(cr, cr).sqrt() > 1e-10 + }) + .map(|i| pts[i]) + .collect(); + if keep.len() >= 3 { + out.push(keep); + } + } + // Fläche mit Löchern: ihre Dreiecke (grosse Flächen stören die Maler-Reihenfolge der Ansicht vor + // den Gauben; die Dreieckskanten blendet die Ansicht als koplanare Nähte aus). + None => out.extend(list.iter().map(|&k| geo[k].to_vec())), + } + } + out +} + +/// Liegt `c` auf der Oberfläche von `m` (Abstand < 1e-6 zu einem Dreieck)? +pub fn on_surface(m: &Mesh, c: V3) -> bool { + m.indices.chunks_exact(3).any(|t| { + let tr = tri(m, t); + let n = normal(&tr); + let d = (c[0] - tr[0][0]) * n[0] + (c[1] - tr[0][1]) * n[1] + (c[2] - tr[0][2]) * n[2]; + if d.abs() > 1e-6 { + return false; + } + // Baryzentrisch in der Ebene. + let e = |a: V3, b: V3| crate::opening_shape::dot(crate::opening_shape::cross([b[0] - a[0], b[1] - a[1], b[2] - a[2]], [c[0] - a[0], c[1] - a[1], c[2] - a[2]]), n); + e(tr[0], tr[1]) >= -1e-9 && e(tr[1], tr[2]) >= -1e-9 && e(tr[2], tr[0]) >= -1e-9 + }) +} + +/// Linienart der Dachaufsicht. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum EdgeKind { + Eaves, + Ridge, + Hip, +} + +/// Dachaufsicht: sichtbare Kanten der nach oben zeigenden Flächen von `skin` (Rand gegen +/// nicht-aufwärts gerichtete Flächen = Traufe/Ortgang, zwischen zwei Ebenen = First (waagrecht) bzw. +/// Grat/Kehle), verdeckt durch alle `occluders` (Aufwärts-Flächen darüber) weggeschnitten. +pub fn top_view_edges(skin: &Mesh, occluders: &[&Mesh]) -> Vec<([f64; 2], [f64; 2], EdgeKind)> { + use std::collections::HashMap; + let canon = canon_ids(skin); + let all: Vec = (0..skin.indices.len() / 3).collect(); + let (group, gn) = plane_groups(skin, &all, &canon); + let mut edges: HashMap<(u32, u32), Vec> = HashMap::new(); + for (ti, t) in skin.indices.chunks_exact(3).enumerate() { + for k in 0..3 { + let (a, b) = (canon[t[k] as usize], canon[t[(k + 1) % 3] as usize]); + edges.entry((a.min(b), a.max(b))).or_default().push(ti); + } + } + let is_up = |ti: usize| gn[group[ti]][2] > 1e-4; + let same_plane = |a: usize, b: usize| group[a] == group[b]; + // Verdecker: alle aufwärts zeigenden Dreiecke aller Häute. + let occ: Vec<[V3; 3]> = occluders + .iter() + .flat_map(|m| m.indices.chunks_exact(3).map(|t| tri(m, t)).filter(|t| normal(t)[2] > 1e-4).collect::>()) + .collect(); + let hidden = |x: f64, y: f64, z: f64| { + occ.iter().any(|t| { + let (a, b, c) = (t[0], t[1], t[2]); + let d = (b[1] - c[1]) * (a[0] - c[0]) + (c[0] - b[0]) * (a[1] - c[1]); + if d.abs() < 1e-15 { + return false; + } + let l1 = ((b[1] - c[1]) * (x - c[0]) + (c[0] - b[0]) * (y - c[1])) / d; + let l2 = ((c[1] - a[1]) * (x - c[0]) + (a[0] - c[0]) * (y - c[1])) / d; + let l3 = 1.0 - l1 - l2; + let e = 1e-9; + l1 > e && l2 > e && l3 > e && l1 * a[2] + l2 * b[2] + l3 * c[2] > z + 1e-4 + }) + }; + let mut out = Vec::new(); + for (&(a, b), list) in &edges { + let ups: Vec = list.iter().copied().filter(|&t| is_up(t)).collect(); + let kind = match ups.as_slice() { + [] => continue, + [_] => EdgeKind::Eaves, + [x, y] if same_plane(*x, *y) => continue, + _ => EdgeKind::Hip, + }; + let pa = [skin.positions[a as usize * 3], skin.positions[a as usize * 3 + 1], skin.positions[a as usize * 3 + 2]]; + let pb = [skin.positions[b as usize * 3], skin.positions[b as usize * 3 + 1], skin.positions[b as usize * 3 + 2]]; + let kind = if kind == EdgeKind::Hip && (pa[2] - pb[2]).abs() < 1e-6 { EdgeKind::Ridge } else { kind }; + let len = ((pb[0] - pa[0]).powi(2) + (pb[1] - pa[1]).powi(2)).sqrt(); + if len < 1e-6 { + continue; + } + // In Stücke teilen, verdeckte weglassen, sichtbare zusammenhängende Stücke vereinen. + let n = ((len / 0.05).ceil() as usize).clamp(1, 400); + let at = |s: f64| [pa[0] + (pb[0] - pa[0]) * s, pa[1] + (pb[1] - pa[1]) * s, pa[2] + (pb[2] - pa[2]) * s]; + let mut start: Option = None; + for i in 0..=n { + let vis = i < n && { + let m = at((i as f64 + 0.5) / n as f64); + !hidden(m[0], m[1], m[2]) + }; + match (vis, start) { + (true, None) => start = Some(i), + (false, Some(s)) => { + let (q0, q1) = (at(s as f64 / n as f64), at(i as f64 / n as f64)); + out.push(([q0[0], q0[1]], [q1[0], q1[1]], kind)); + start = None; + } + _ => {} + } + } + } + out.sort_by(|a, b| a.0[0].total_cmp(&b.0[0]).then(a.0[1].total_cmp(&b.0[1])).then(a.1[0].total_cmp(&b.1[0])).then(a.1[1].total_cmp(&b.1[1]))); + out +} + +/// Dachaufsicht aller verschnittenen Dächer zusammen (Kehlen zwischen zwei Dächern werden so als +/// Grat/Kehle erkannt): (Dach-Index, a, b, Art). Zuordnung einer Kante zum Dach mit der höchsten +/// Oberkante an ihrer Mitte. +pub fn assembly_edges(p: &Project) -> Rc> { + let n = p.roofs.as_deref().map_or(0, |r| r.len()); + let solids: Vec<(usize, Rc)> = (0..n).filter_map(|i| roof_solids(p, i).map(|s| (i, s))).collect(); + let mut h = ContentHash::default(); + for (i, s) in &solids { + h.u64(*i as u64).f64s(&s.top.positions).u64(s.top.indices.len() as u64); + } + cached("roof-solids/edges", h.finish(), || { + // Je Dach seine eigene Aufsicht (eine Vereinigung aller Dächer triangulierte neu und erzeugte + // Scheinkanten), verdeckt durch alle; Traufkanten, die auf einer Traufkante eines anderen Dachs + // liegen, sind Kehlen/Grate zwischen zwei Dächern (nur einmal, beim früheren Dach). + let tops: Vec<&Mesh> = solids.iter().map(|(_, s)| &s.top).collect(); + let per: Vec> = solids.iter().map(|(_, s)| top_view_edges(&s.top, &tops)).collect(); + let on_seg = |q: [f64; 2], a: [f64; 2], b: [f64; 2]| { + let (dx, dy) = (b[0] - a[0], b[1] - a[1]); + let l2 = dx * dx + dy * dy; + if l2 < 1e-18 { + return false; + } + let t = ((q[0] - a[0]) * dx + (q[1] - a[1]) * dy) / l2; + let (px, py) = (a[0] + dx * t, a[1] + dy * t); + (-1e-6..=1.0 + 1e-6).contains(&t) && (q[0] - px).powi(2) + (q[1] - py).powi(2) < 1e-10 + }; + let shared = |k: usize, a: [f64; 2], b: [f64; 2]| -> Option { + let m = [(a[0] + b[0]) / 2.0, (a[1] + b[1]) / 2.0]; + (0..per.len()).filter(|&o| o != k).find(|&o| per[o].iter().any(|e| e.2 == EdgeKind::Eaves && on_seg(m, e.0, e.1) && on_seg(a, e.0, e.1) || e.2 == EdgeKind::Eaves && on_seg(m, e.0, e.1) && on_seg(b, e.0, e.1))) + }; + let mut out = Vec::new(); + for (k, edges) in per.iter().enumerate() { + for &(a, b, kind) in edges { + if kind == EdgeKind::Eaves { + if let Some(o) = shared(k, a, b) { + if o < k { + continue; + } + out.push((solids[k].0, a, b, EdgeKind::Hip)); + continue; + } + } + out.push((solids[k].0, a, b, kind)); + } + } + out + }) +} + +/// Senkrechter Schnitt eines Körpers durch `base` in Richtung `u` (Grundriss): Ringe in +/// Schnitt-Koordinaten (t entlang `u`, z). +pub fn section_rings(m: &Mesh, base: (f64, f64), u: (f64, f64)) -> Vec> { + let idx: Vec = m.indices.iter().map(|&i| i as f64).collect(); + let r = crate::mesh_section::cut(&m.positions, &idx, &[0.0, base.0, base.1, u.0, u.1]); + let mut out = Vec::new(); + let Some(&n) = r.first() else { return out }; + let mut i = 1; + for _ in 0..n as usize { + let Some(&k) = r.get(i) else { break }; + let k = k as usize; + if i + 1 + 2 * k > r.len() { + break; + } + out.push((0..k).map(|j| [r[i + 1 + 2 * j], r[i + 2 + 2 * j]]).collect()); + i += 1 + 2 * k; + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + fn base_project(roofs: serde_json::Value) -> Project { + serde_json::from_value(serde_json::json!({ + "id": "p", "name": "t", "lineStyles": [], "hatches": [], "components": [], "wallTypes": [], + "drawingLevels": [], "layers": [], "walls": [], "drawings2d": [], "roofs": roofs + })) + .unwrap() + } + + fn sattel(id: &str, outline: [[f64; 2]; 2], axis: &str) -> serde_json::Value { + let [a, b] = outline; + serde_json::json!({ + "id": id, "type": "roof", "floorId": "F", "categoryCode": "35", + "outline": [{"x": a[0], "y": a[1]}, {"x": b[0], "y": a[1]}, {"x": b[0], "y": b[1]}, {"x": a[0], "y": b[1]}], + "shape": "sattel", "pitchDeg": 40, "overhang": 0.0, "ridgeAxis": axis, "baseElevation": 3.0, "thickness": 0.25 + }) + } + + fn total_volume(p: &Project) -> f64 { + (0..p.roofs.as_ref().unwrap().len()).filter_map(|i| roof_solids(p, i)).flat_map(|s| s.parts.iter().map(|pt| pt.mesh.volume()).collect::>()).sum() + } + + /// L-Dach: zwei Satteldächer gleicher Traufhöhe und Breite, das zweite stösst an das erste. + #[test] + fn l_roof_without_overlap_and_watertight() { + let p = base_project(serde_json::json!([sattel("A", [[0.0, 0.0], [12.0, 8.0]], "x"), sattel("B", [[0.0, 0.0], [8.0, 14.0]], "y")])); + let nb = neighbors(&p); + assert_eq!(nb, vec![vec![1], vec![0]]); + let a = roof_solids(&p, 0).unwrap(); + let b = roof_solids(&p, 1).unwrap(); + assert_eq!(a.failed + b.failed, 0); + for s in [&a, &b] { + for pt in &s.parts { + assert!(pt.mesh.is_closed_exact(), "Teil geschlossen"); + assert!(pt.mesh.volume() > 0.0); + } + } + // Keine Überlappung: Schnitt der beiden Dachkörper leer. + let sa = Solid::new_exact(&a.parts[0].mesh).unwrap(); + let sb = Solid::new_exact(&b.parts[0].mesh).unwrap(); + assert!(sa.intersection(&sb).unwrap().volume() < 1e-9); + // Vereinigt = Hülle: kleiner als die Summe der unverschnittenen Dächer. + let raw: f64 = ["A", "B"].iter().map(|_| 0.0).sum::(); + let _ = raw; + let vol = total_volume(&p); + let single = |r: &Roof| crate::model3d::roof_plane_prisms(&crate::roof::roof_geometry(&r.params(), 3.0).planes, 0.0, 0.25).iter().map(|m| m.volume()).sum::(); + let rs = p.roofs.as_ref().unwrap(); + let sum = single(&rs[0]) + single(&rs[1]); + assert!(vol < sum - 0.5, "überlappendes Volumen entfernt: {vol} vs {sum}"); + // Aufsicht: Kehle(n) als Grat-Linien vorhanden. + let edges = assembly_edges(&p); + let hips = edges.iter().filter(|e| e.3 == EdgeKind::Hip).count(); + assert!(hips >= 1, "Kehle sichtbar: {edges:?}"); + assert!(edges.iter().any(|e| e.0 == 0) && edges.iter().any(|e| e.0 == 1)); + } + + #[test] + fn separate_roofs_are_not_assembled() { + let p = base_project(serde_json::json!([sattel("A", [[0.0, 0.0], [5.0, 5.0]], "x"), sattel("B", [[10.0, 0.0], [15.0, 5.0]], "x")])); + assert!(roof_solids(&p, 0).is_none() && roof_solids(&p, 1).is_none()); + } + + #[test] + fn dormers_cut_main_roof_and_are_closed() { + for kind in ["sattel", "schlepp", "flach", "walm"] { + let mut r = sattel("R", [[0.0, 0.0], [10.0, 8.0]], "x"); + r["pitchDeg"] = 45.into(); + r["overhang"] = 0.4.into(); + r["dormers"] = serde_json::json!([{"id": "D", "kind": kind, "position": {"x": 4.0, "y": 1.2}, "width": 2.4, "frontHeight": 1.5}]); + let p = base_project(serde_json::json!([r])); + let s = roof_solids(&p, 0).expect("verschnitten"); + assert_eq!(s.failed, 0, "{kind}"); + let roles = |role: Role| s.parts.iter().filter(|pt| pt.role == role).count(); + assert_eq!(roles(Role::RoofLayer), 1, "{kind}"); + assert_eq!(roles(Role::DormerRoof), 1, "{kind}"); + assert_eq!(roles(Role::DormerWall), 3, "{kind}: Stirn + 2 Wangen"); + for pt in &s.parts { + assert!(pt.mesh.is_closed_exact(), "{kind} {:?}", pt.role); + assert!(pt.mesh.volume() > 1e-4, "{kind} {:?}", pt.role); + } + // Gaubendach und Hauptdach überlappen nicht. + let main = Solid::new_exact(&s.parts[0].mesh).unwrap(); + for pt in &s.parts[1..] { + let v = main.intersection(&Solid::new_exact(&pt.mesh).unwrap()).unwrap().volume(); + assert!(v < 1e-7, "{kind} {:?}: {v}", pt.role); + } + // Hauptdach hat ein Loch: Volumen kleiner als ohne Gaube. + let roof = &p.roofs.as_ref().unwrap()[0]; + let full: f64 = crate::model3d::roof_plane_prisms(&crate::roof::roof_geometry(&roof.params(), 3.0).planes, 0.0, 0.25).iter().map(|m| m.volume()).sum(); + assert!(s.parts[0].mesh.volume() < full - 0.5, "{kind}"); + assert!(s.skin.is_closed_exact()); + } + } + + /// Ansicht: koplanare Dreiecke zu Flächen (mit Loch ⇒ Dreiecke); Fläche bleibt gleich. + #[test] + fn planar_faces_keep_area() { + let mut r = sattel("R", [[0.0, 0.0], [10.0, 8.0]], "x"); + r["dormers"] = serde_json::json!([{"id": "D", "kind": "sattel", "position": {"x": 4.0, "y": 1.2}, "width": 2.4, "frontHeight": 1.3}]); + let p = base_project(serde_json::json!([r])); + let s = roof_solids(&p, 0).unwrap(); + let all: Vec = (0..s.skin.indices.len() / 3).collect(); + let area3 = |pts: &[V3]| { + let mut a = [0.0; 3]; + for k in 1..pts.len() - 1 { + let c = crate::opening_shape::cross([pts[k][0] - pts[0][0], pts[k][1] - pts[0][1], pts[k][2] - pts[0][2]], [pts[k + 1][0] - pts[0][0], pts[k + 1][1] - pts[0][1], pts[k + 1][2] - pts[0][2]]); + for i in 0..3 { + a[i] += c[i] / 2.0; + } + } + crate::opening_shape::dot(a, a).sqrt() + }; + let tri_area: f64 = all.iter().map(|&t| area3(&tri(&s.skin, &s.skin.indices[t * 3..t * 3 + 3]))).sum(); + let faces = planar_faces(&s.skin, &all); + let face_area: f64 = faces.iter().map(|f| area3(f)).sum(); + assert!((tri_area - face_area).abs() < 1e-6 * tri_area, "{tri_area} vs {face_area}"); + assert!(faces.len() * 2 < all.len(), "zusammengefasst: {} Flächen aus {} Dreiecken", faces.len(), all.len()); + } + + #[test] + fn section_through_dormer_hits_all_parts() { + let mut r = sattel("R", [[0.0, 0.0], [10.0, 8.0]], "x"); + r["dormers"] = serde_json::json!([{"id": "D", "kind": "sattel", "position": {"x": 4.0, "y": 1.2}, "width": 2.4, "frontHeight": 1.5}]); + let p = base_project(serde_json::json!([r])); + let s = roof_solids(&p, 0).unwrap(); + // Schnitt längs y durch die Gaubenmitte (x = 4). + let n: usize = s.parts.iter().map(|pt| section_rings(&pt.mesh, (4.0, -5.0), (0.0, 1.0)).len()).sum(); + assert!(n >= 4, "Hauptdach (2 Seiten), Gaubendach, Stirn: {n}"); + } +} diff --git a/src-tauri/core/src/selection_info.rs b/src-tauri/core/src/selection_info.rs index 80d76163..7dffbdb8 100644 --- a/src-tauri/core/src/selection_info.rs +++ b/src-tauri/core/src/selection_info.rs @@ -656,6 +656,7 @@ fn roof_selection(root: &Map, r: &Value) -> Result { .v("edges", roof_edges(r)) .v("holes", J::arr(holes)) .v("hasEdgePitch", Value::Bool(field(r, "edgePitchDeg").is_some())) + .raw("dormers", r, "dormers") .done(); Ok(O::default() .s("kind", "roof") diff --git a/src-tauri/core/src/solid_bool.rs b/src-tauri/core/src/solid_bool.rs new file mode 100644 index 00000000..c11c752b --- /dev/null +++ b/src-tauri/core/src/solid_bool.rs @@ -0,0 +1,788 @@ +//! Körper-Booleans im Kern ([107] Schritt 2, für [G5]): `manifold-rust` (exakter Modus) für synchrone +//! Ableitungen (Dach-Verschneidung, Gauben, Wand an Dach). Messung und Entscheid: TODO.md [107]. +//! +//! **Panik-Schutz.** Auf wasm32-unknown-unknown gibt es kein `catch_unwind`; eine Panik legt den ganzen +//! Kern lahm. Daher geht nur ein vorher geprüftes Netz an Manifold ([`Solid::new`]): Dreier-Gruppen, +//! Indizes im Bereich, endliche Koordinaten mit |x| < 1e7 m, Obergrenze Dreiecke, Ecken verschweisst +//! (Toleranz [`WELD`]), geschlossen und mannigfaltig (jede gerichtete Kante genau einmal, ihre Gegenkante +//! auch), Volumen ≠ 0; innen nach aussen gedrehte Körper (Volumen < 0) werden umgedreht (Manifold nähme +//! sie still an und rechnete falsch). Nach jeder Operation wird `status()` geprüft. Der Fuzz-Test +//! (`tests::fuzz_*`) wirft zufällige und kaputte Netze hinein und verlangt Fehler statt Panik. +//! +//! **Kodierung** (WASM-Grenze, `web/solid_bool.rs`): `[n_verts, x, y, z, …, n_tris, i0, i1, i2, …]`. +//! +//! **Cache** ([`cached`]): Ergebnis je Element (Schlüssel) mit Inhalts-Hash; ändert sich der Hash, wird +//! neu gerechnet und der alte Eintrag ersetzt — der Cache wächst nur mit der Zahl der Elemente. + +use std::any::Any; +use std::cell::RefCell; +use std::collections::HashMap; +use std::rc::Rc; + +use manifold_rust::manifold::Manifold; +use manifold_rust::types::{BooleanEngine, Error, MeshGL64}; + +/// Obergrenze Dreiecke je Eingabe (Speicher/Zeit im WASM). +pub const MAX_TRIANGLES: usize = 200_000; +/// Koordinaten-Obergrenze (Meter): grösser ist Unsinn (Welt-Koordinaten sind lokal rebasiert). +pub const MAX_COORD: f64 = 1e7; +/// Verschweiss-Toleranz (Meter): Ecken näher als das gelten als gleich. +pub const WELD: f64 = 1e-7; + +/// Dreiecksnetz (Modell-Meter, f64). +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Mesh { + pub positions: Vec, + pub indices: Vec, +} + +impl Mesh { + pub fn is_empty(&self) -> bool { + self.indices.is_empty() + } + + /// Hängt `other` an (ohne Verschweissen). + pub fn append(&mut self, other: &Mesh) { + let base = (self.positions.len() / 3) as u32; + self.positions.extend_from_slice(&other.positions); + self.indices.extend(other.indices.iter().map(|i| i + base)); + } + + /// Volumen (Divergenzsatz, relativ zur ersten Ecke). + pub fn volume(&self) -> f64 { + let p = &self.positions; + if p.len() < 3 { + return 0.0; + } + let o = [p[0], p[1], p[2]]; + let v = |i: u32| { + let j = i as usize * 3; + [p[j] - o[0], p[j + 1] - o[1], p[j + 2] - o[2]] + }; + let mut vol = 0.0; + for t in self.indices.chunks_exact(3) { + let (a, b, c) = (v(t[0]), v(t[1]), v(t[2])); + vol += a[0] * (b[1] * c[2] - b[2] * c[1]) - a[1] * (b[0] * c[2] - b[2] * c[0]) + a[2] * (b[0] * c[1] - b[1] * c[0]); + } + vol / 6.0 + } + + /// Geschlossen: jede gerichtete Kante (nach Verschweissen) genau einmal mit Gegenkante. + pub fn is_closed(&self) -> bool { + weld_and_check(&self.positions, &self.indices).is_ok() + } + + /// Geschlossen nach Indizes (ohne Verschweissen): für Manifold-Ergebnisse. + pub fn is_closed_exact(&self) -> bool { + let mut edges: HashMap<(u32, u32), u32> = HashMap::new(); + for t in self.indices.chunks_exact(3) { + for k in 0..3 { + *edges.entry((t[k], t[(k + 1) % 3])).or_default() += 1; + } + } + !edges.is_empty() && edges.iter().all(|(&(a, b), &c)| c == 1 && edges.get(&(b, a)) == Some(&1)) + } + + /// Achsparallele Hülle `[min, max]`; leer ⇒ `None`. + pub fn bounds(&self) -> Option<([f64; 3], [f64; 3])> { + let mut lo = [f64::INFINITY; 3]; + let mut hi = [f64::NEG_INFINITY; 3]; + for q in self.positions.chunks_exact(3) { + for k in 0..3 { + lo[k] = lo[k].min(q[k]); + hi[k] = hi[k].max(q[k]); + } + } + (lo[0] <= hi[0]).then_some((lo, hi)) + } + + /// Geschlossener Quader aus 8 Ecken (Reihenfolge wie `opening_shape::quad_box`: 4 unten, 4 oben, + /// je im selben Drehsinn); Orientierung egal (wird beim Prüfen gerichtet). + pub fn hexahedron(c: &[[f64; 3]; 8]) -> Mesh { + let mut positions = Vec::with_capacity(24); + for q in c { + positions.extend_from_slice(q); + } + let indices = vec![0, 2, 1, 0, 3, 2, 4, 5, 6, 4, 6, 7, 0, 1, 5, 0, 5, 4, 1, 2, 6, 1, 6, 5, 2, 3, 7, 2, 7, 6, 3, 0, 4, 3, 4, 7]; + Mesh { positions, indices } + } + + /// Senkrechtes Prisma über einem einfachen Polygon (Grundriss, beliebiger Drehsinn) von `z0` bis + /// `z1`; Deckel über Ohrenschnitt. Entartet ⇒ leer. + pub fn prism(ring: &[[f64; 2]], z0: f64, z1: f64) -> Mesh { + Self::prism_between(ring, &|_, _| z0, &|_, _| z1) + } + + /// Prisma über `ring` mit Boden `bottom(x, y)` und Deckel `top(x, y)` (je Ecke; ebene Funktionen + /// ergeben ebene Flächen). + pub fn prism_between(ring: &[[f64; 2]], bottom: &dyn Fn(f64, f64) -> f64, top: &dyn Fn(f64, f64) -> f64) -> Mesh { + let n = ring.len(); + if n < 3 { + return Mesh::default(); + } + let area: f64 = (0..n).map(|i| ring[i][0] * ring[(i + 1) % n][1] - ring[(i + 1) % n][0] * ring[i][1]).sum::() / 2.0; + if !(area.abs() > 1e-12) { + return Mesh::default(); + } + let ccw: Vec<[f64; 2]> = if area > 0.0 { ring.to_vec() } else { ring.iter().rev().copied().collect() }; + let tris = ear_clip(&ccw); + if tris.is_empty() { + return Mesh::default(); + } + let mut positions = Vec::with_capacity(n * 6); + for q in &ccw { + positions.extend([q[0], q[1], bottom(q[0], q[1])]); + } + for q in &ccw { + positions.extend([q[0], q[1], top(q[0], q[1])]); + } + let nn = n as u32; + let mut indices = Vec::new(); + for t in &tris { + indices.extend([t[0] as u32, t[2] as u32, t[1] as u32]); + indices.extend([t[0] as u32 + nn, t[1] as u32 + nn, t[2] as u32 + nn]); + } + for i in 0..nn { + let j = (i + 1) % nn; + indices.extend([i, j, j + nn, i, j + nn, i + nn]); + } + Mesh { positions, indices } + } +} + +/// Ohrenschnitt eines einfachen Polygons im Gegenuhrzeigersinn (Indizes). +pub fn ear_clip(ring: &[[f64; 2]]) -> Vec<[usize; 3]> { + let n = ring.len(); + let mut idx: Vec = (0..n).collect(); + let mut out = Vec::new(); + let cross = |a: [f64; 2], b: [f64; 2], c: [f64; 2]| (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]); + let mut guard = 0; + while idx.len() > 3 && guard < 4 * n * n + 8 { + guard += 1; + let m = idx.len(); + let mut found = false; + for k in 0..m { + let (ia, ib, ic) = (idx[(k + m - 1) % m], idx[k], idx[(k + 1) % m]); + let (a, b, c) = (ring[ia], ring[ib], ring[ic]); + let cr = cross(a, b, c); + if cr <= 1e-14 { + // Kollineare Ecke ohne Fläche: entfernen. + if cr.abs() <= 1e-14 { + idx.remove(k); + found = true; + break; + } + continue; + } + let inside = idx.iter().any(|&j| { + if j == ia || j == ib || j == ic { + return false; + } + let p = ring[j]; + cross(a, b, p) >= -1e-14 && cross(b, c, p) >= -1e-14 && cross(c, a, p) >= -1e-14 + }); + if !inside { + out.push([ia, ib, ic]); + idx.remove(k); + found = true; + break; + } + } + if !found { + break; + } + } + if idx.len() == 3 && cross(ring[idx[0]], ring[idx[1]], ring[idx[2]]) > 1e-14 { + out.push([idx[0], idx[1], idx[2]]); + } + out +} + +/// Prüft und verschweisst; liefert nach aussen orientierte Ecken/Dreiecke oder einen Fehlertext. +fn weld_and_check(positions: &[f64], indices: &[u32]) -> Result<(Vec, Vec), String> { + weld_and_check_tol(positions, indices, WELD) +} + +fn weld_and_check_tol(positions: &[f64], indices: &[u32], tol: f64) -> Result<(Vec, Vec), String> { + if positions.len() % 3 != 0 || indices.len() % 3 != 0 { + return Err("Positionen/Indizes keine Dreier-Gruppen".into()); + } + if indices.is_empty() { + return Err("leeres Netz".into()); + } + if indices.len() / 3 > MAX_TRIANGLES { + return Err(format!("zu viele Dreiecke (> {MAX_TRIANGLES})")); + } + if positions.iter().any(|x| !x.is_finite() || x.abs() > MAX_COORD) { + return Err("Koordinaten nicht endlich oder zu gross".into()); + } + let n_in = positions.len() / 3; + let weld = tol >= 0.0; + let tol = tol.max(0.0); + // Raster ≥ 1e-9 m: |x| ≤ 1e7 ⇒ Zellnummern ≤ 1e16, ±1 läuft nicht über. + let cell = |v: f64| (v / tol.max(1e-9)).floor() as i64; + let mut grid: HashMap<(i64, i64, i64), Vec> = HashMap::new(); + let mut verts: Vec = Vec::new(); + let mut map: Vec = Vec::with_capacity(n_in); + for c in positions.chunks_exact(3) { + let key = (cell(c[0]), cell(c[1]), cell(c[2])); + let mut hit = None; + 'search: for dx in if weld { -1..=1 } else { 1..=0 } { + for dy in -1..=1 { + for dz in -1..=1 { + if let Some(list) = grid.get(&(key.0 + dx, key.1 + dy, key.2 + dz)) { + for &id in list { + let j = id as usize * 3; + if (verts[j] - c[0]).abs() <= tol && (verts[j + 1] - c[1]).abs() <= tol && (verts[j + 2] - c[2]).abs() <= tol { + hit = Some(id); + break 'search; + } + } + } + } + } + } + let id = hit.unwrap_or_else(|| { + let id = (verts.len() / 3) as u32; + verts.extend_from_slice(&[c[0] + 0.0, c[1] + 0.0, c[2] + 0.0]); + grid.entry(key).or_default().push(id); + id + }); + map.push(id); + } + let mut tris: Vec = Vec::with_capacity(indices.len()); + for t in indices.chunks_exact(3) { + let mut m = [0u32; 3]; + for k in 0..3 { + let i = t[k] as usize; + if i >= n_in { + return Err(format!("Index {i} ausserhalb")); + } + m[k] = map[i]; + } + if m[0] == m[1] || m[1] == m[2] || m[0] == m[2] { + continue; + } + tris.extend_from_slice(&m); + } + if tris.len() < 12 { + return Err("weniger als vier Dreiecke".into()); + } + let mut edges: HashMap<(u32, u32), u32> = HashMap::with_capacity(tris.len()); + for t in tris.chunks_exact(3) { + for k in 0..3 { + *edges.entry((t[k], t[(k + 1) % 3])).or_default() += 1; + } + } + for (&(a, b), &c) in &edges { + if c != 1 || edges.get(&(b, a)).copied() != Some(1) { + return Err("Netz nicht geschlossen/mannigfaltig".into()); + } + } + let m = Mesh { positions: verts, indices: tris }; + let vol = m.volume(); + let ext = m.bounds().map_or(0.0, |(lo, hi)| (0..3).map(|k| hi[k] - lo[k]).fold(0.0, f64::max)); + if !vol.is_finite() || vol.abs() <= 1e-15 * ext.powi(3).max(1e-12) { + return Err("Volumen 0".into()); + } + let Mesh { positions: verts, indices: mut tris } = m; + if vol < 0.0 { + tris.chunks_exact_mut(3).for_each(|t| t.swap(1, 2)); + } + Ok((verts, tris)) +} + +/// Geprüfter Körper (Manifold). Leer ist erlaubt (Ergebnis einer Differenz). +#[derive(Clone)] +pub struct Solid(Manifold); + +impl Solid { + /// Prüft das Netz (s. Modulkopf) und baut den Körper; Fehler statt Panik. + pub fn new(mesh: &Mesh) -> Result { + Self::with_tolerance(mesh, WELD) + } + + /// Wie [`Solid::new`], ohne Verschweissen (Indizes wie gegeben): für Netze, die schon aus Manifold + /// kommen (dort können Ecken gleicher Lage getrennt geführt sein). + pub fn new_exact(mesh: &Mesh) -> Result { + Self::with_tolerance(mesh, -1.0) + } + + fn with_tolerance(mesh: &Mesh, tol: f64) -> Result { + let (verts, tris) = weld_and_check_tol(&mesh.positions, &mesh.indices, tol)?; + let mut g = MeshGL64::default(); + g.num_prop = 3; + g.vert_properties = verts; + g.tri_verts = tris.iter().map(|&i| i as u64).collect(); + let m = Manifold::from_mesh_gl64(&g); + if m.status() != Error::NoError { + return Err(format!("kein gültiger Körper ({:?})", m.status())); + } + Ok(Solid(m)) + } + + pub fn empty() -> Solid { + Solid(Manifold::empty()) + } + + pub fn is_empty(&self) -> bool { + self.0.is_empty() + } + + pub fn volume(&self) -> f64 { + self.0.volume() + } + + fn checked(m: Manifold) -> Result { + if m.status() != Error::NoError { + return Err(format!("Boolean fehlgeschlagen ({:?})", m.status())); + } + Ok(Solid(m)) + } + + pub fn union(&self, o: &Solid) -> Result { + if o.is_empty() { + return Ok(self.clone()); + } + if self.is_empty() { + return Ok(o.clone()); + } + Self::checked(self.0.union_with_engine(&o.0, BooleanEngine::Exact)) + } + + pub fn difference(&self, o: &Solid) -> Result { + if o.is_empty() || self.is_empty() { + return Ok(self.clone()); + } + Self::checked(self.0.difference_with_engine(&o.0, BooleanEngine::Exact)) + } + + pub fn intersection(&self, o: &Solid) -> Result { + if o.is_empty() || self.is_empty() { + return Ok(Solid::empty()); + } + Self::checked(self.0.intersection_with_engine(&o.0, BooleanEngine::Exact)) + } + + /// Vereinigung vieler Körper (ungültige Teile werden übergangen und gezählt). + pub fn union_all(meshes: &[Mesh]) -> (Solid, usize) { + let mut acc = Solid::empty(); + let mut bad = 0; + for m in meshes { + match Solid::new(m).and_then(|s| acc.union(&s)) { + Ok(s) => acc = s, + Err(_e) => { + #[cfg(test)] + eprintln!("union_all: {_e} {:?}", m.bounds()); + bad += 1 + } + } + } + (acc, bad) + } + + /// Netz mit zusammengefassten koplanaren Dreiecken (`simplify`). + pub fn to_mesh(&self) -> Mesh { + self.mesh_of(true) + } + + /// Netz ohne `simplify` (alle Dreiecke wie berechnet; `simplify` kann Kanten so zusammenlegen, dass + /// einzelne Dreiecke leicht aus ihrer Ebene kippen — für die Aufsicht/Ansicht unerwünscht). + pub fn to_mesh_raw(&self) -> Mesh { + self.mesh_of(false) + } + + fn mesh_of(&self, simplify: bool) -> Mesh { + if self.is_empty() { + return Mesh::default(); + } + let g = if simplify { self.0.simplify(0.0).get_mesh_gl64(-1) } else { self.0.get_mesh_gl64(-1) }; + let np = (g.num_prop as usize).max(3); + let positions: Vec = g.vert_properties.chunks_exact(np).flat_map(|v| [v[0], v[1], v[2]]).collect(); + // Manifold führt Ecken an Grenzen zwischen Eingabe-Körpern doppelt (`merge_*_vert`): zusammenführen, + // damit das Netz auch nach Indizes geschlossen ist. + let nv = positions.len() / 3; + let mut map: Vec = (0..nv as u32).collect(); + for (f, t) in g.merge_from_vert.iter().zip(g.merge_to_vert.iter()) { + let (f, t) = (*f as usize, *t as usize); + if f < nv && t < nv { + map[f] = t as u32; + } + } + let indices: Vec = g.tri_verts.iter().map(|&i| map.get(i as usize).copied().unwrap_or(0)).collect(); + Mesh { positions, indices } + } +} + +/// Zwei Netze verknüpfen ("union" | "difference" | "intersection"). +pub fn boolean(a: &Mesh, b: &Mesh, op: &str) -> Result { + let (sa, sb) = (Solid::new(a)?, Solid::new(b)?); + let r = match op { + "union" => sa.union(&sb)?, + "difference" => sa.difference(&sb)?, + "intersection" => sa.intersection(&sb)?, + _ => return Err(format!("unbekannte Operation {op}")), + }; + Ok(r.to_mesh()) +} + +// ── Flache Kodierung ──────────────────────────────────────────────────────── + +/// `[n_verts, x, y, z, …, n_tris, i0, i1, i2, …]` → Netz; kaputt ⇒ `None`. +pub fn decode_mesh(buf: &[f64]) -> Option { + let count = |v: f64| (v.is_finite() && v >= 0.0 && v.fract() == 0.0 && v < 1e8).then_some(v as usize); + let nv = count(*buf.first()?)?; + let pend = 1usize.checked_add(nv.checked_mul(3)?)?; + let positions = buf.get(1..pend)?.to_vec(); + let nt = count(*buf.get(pend)?)?; + let iend = (pend + 1).checked_add(nt.checked_mul(3)?)?; + let raw = buf.get(pend + 1..iend)?; + if iend != buf.len() { + return None; + } + let mut indices = Vec::with_capacity(raw.len()); + for &v in raw { + let i = count(v)?; + if i >= nv { + return None; + } + indices.push(i as u32); + } + Some(Mesh { positions, indices }) +} + +pub fn encode_mesh(m: &Mesh) -> Vec { + let mut out = Vec::with_capacity(2 + m.positions.len() + m.indices.len()); + out.push((m.positions.len() / 3) as f64); + out.extend_from_slice(&m.positions); + out.push((m.indices.len() / 3) as f64); + out.extend(m.indices.iter().map(|&i| i as f64)); + out +} + +/// Flache Eingabe: `[op, …mesh a, …mesh b]` mit op 0 = Vereinigung, 1 = Differenz, 2 = Schnitt. +/// Kaputte Eingaben oder Fehler ⇒ leerer Puffer (nie Panik). +pub fn boolean_flat(op: f64, a: &[f64], b: &[f64]) -> Vec { + let name = match op as i64 { + 0 if op == 0.0 => "union", + 1 if op == 1.0 => "difference", + 2 if op == 2.0 => "intersection", + _ => return Vec::new(), + }; + let (Some(a), Some(b)) = (decode_mesh(a), decode_mesh(b)) else { return Vec::new() }; + boolean(&a, &b, name).map(|m| encode_mesh(&m)).unwrap_or_default() +} + +// ── Inhalts-Hash und Cache je Element ─────────────────────────────────────── + +/// FNV-1a über Zahlen/Texte (stabil, ohne Zufalls-Seed). +#[derive(Clone, Copy)] +pub struct ContentHash(u64); + +impl Default for ContentHash { + fn default() -> Self { + ContentHash(0xcbf2_9ce4_8422_2325) + } +} + +impl ContentHash { + fn byte(&mut self, b: u8) { + self.0 ^= b as u64; + self.0 = self.0.wrapping_mul(0x0100_0000_01b3); + } + pub fn u64(&mut self, v: u64) -> &mut Self { + for b in v.to_le_bytes() { + self.byte(b); + } + self + } + pub fn f64(&mut self, v: f64) -> &mut Self { + self.u64((v + 0.0).to_bits()) + } + pub fn f64s(&mut self, v: &[f64]) -> &mut Self { + self.u64(v.len() as u64); + for &x in v { + self.f64(x); + } + self + } + pub fn str(&mut self, s: &str) -> &mut Self { + self.u64(s.len() as u64); + for b in s.bytes() { + self.byte(b); + } + self + } + /// Beliebiges serialisierbares Element (JSON-Text; für Modell-Elemente). + pub fn json(&mut self, v: &T) -> &mut Self { + let s = serde_json::to_string(v).unwrap_or_default(); + self.str(&s) + } + pub fn finish(&self) -> u64 { + self.0 + } +} + +const CACHE_MAX: usize = 4096; + +thread_local! { + static CACHE: RefCell)>> = RefCell::new(HashMap::new()); +} + +/// Ergebnis je Element `key` mit Inhalts-Hash `hash`: gleicher Hash ⇒ gespeichertes Ergebnis, sonst +/// `f()` rechnen und den Eintrag des Elements ersetzen. +pub fn cached(key: &str, hash: u64, f: impl FnOnce() -> T) -> Rc { + let hit = CACHE.with(|c| c.borrow().get(key).filter(|(h, _)| *h == hash).and_then(|(_, v)| v.clone().downcast::().ok())); + if let Some(v) = hit { + return v; + } + let v = Rc::new(f()); + CACHE.with(|c| { + let mut c = c.borrow_mut(); + if c.len() >= CACHE_MAX && !c.contains_key(key) { + c.clear(); + } + c.insert(key.to_string(), (hash, v.clone() as Rc)); + }); + v +} + +/// Anzahl Cache-Einträge (Tests). +pub fn cache_len() -> usize { + CACHE.with(|c| c.borrow().len()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn cuboid(x: f64, y: f64, z: f64, w: f64, l: f64, h: f64) -> Mesh { + Mesh::prism(&[[x, y], [x + w, y], [x + w, y + l], [x, y + l]], z, z + h) + } + + #[test] + fn prism_is_closed_with_volume() { + let m = cuboid(0.0, 0.0, 0.0, 2.0, 3.0, 4.0); + assert!(m.is_closed()); + assert!((m.volume() - 24.0).abs() < 1e-12); + // L-Grundriss (nicht konvex) + let l = Mesh::prism(&[[0.0, 0.0], [4.0, 0.0], [4.0, 1.0], [1.0, 1.0], [1.0, 3.0], [0.0, 3.0]], 0.0, 1.0); + assert!(l.is_closed()); + assert!((l.volume() - 6.0).abs() < 1e-12); + } + + #[test] + fn flush_difference_and_union_exact() { + let a = cuboid(0.0, 0.0, 0.0, 2.0, 2.0, 2.0); + let b = cuboid(1.0, 0.0, 0.0, 1.0, 2.0, 2.0); + let d = boolean(&a, &b, "difference").unwrap(); + assert!(d.is_closed()); + assert!((d.volume() - 4.0).abs() < 1e-9); + let u = boolean(&a, &cuboid(2.0, 0.0, 0.0, 1.0, 2.0, 2.0), "union").unwrap(); + assert!((u.volume() - 12.0).abs() < 1e-9); + assert!(u.indices.len() / 3 <= 24, "simplify fasst koplanare Dreiecke zusammen: {}", u.indices.len() / 3); + let i = boolean(&a, &b, "intersection").unwrap(); + assert!((i.volume() - 4.0).abs() < 1e-9); + } + + #[test] + fn inside_out_input_is_flipped() { + let mut a = cuboid(0.0, 0.0, 0.0, 2.0, 2.0, 2.0); + a.indices.chunks_exact_mut(3).for_each(|t| t.swap(1, 2)); + assert!(a.volume() < 0.0); + let d = boolean(&a, &cuboid(1.0, 0.0, 0.0, 1.0, 2.0, 2.0), "difference").unwrap(); + assert!((d.volume() - 4.0).abs() < 1e-9); + } + + #[test] + fn nearly_equal_vertices_are_welded() { + // Zwei Hälften mit um 1e-9 versetzten gemeinsamen Ecken (wie Gehrungs-Ecken der Dachflächen). + let mut m = cuboid(0.0, 0.0, 0.0, 1.0, 1.0, 1.0); + for v in m.positions.iter_mut().step_by(5) { + *v += 1e-9; + } + assert!(Solid::new(&m).is_ok()); + } + + #[test] + fn rejects_broken_inputs() { + let good = cuboid(0.0, 0.0, 0.0, 1.0, 1.0, 1.0); + let mut open = good.clone(); + open.indices.truncate(open.indices.len() - 3); + assert!(Solid::new(&open).is_err()); + let mut nan = good.clone(); + nan.positions[4] = f64::NAN; + assert!(Solid::new(&nan).is_err()); + let mut far = good.clone(); + far.positions[0] = 1e9; + assert!(Solid::new(&far).is_err()); + let mut idx = good.clone(); + idx.indices[0] = 999; + assert!(Solid::new(&idx).is_err()); + assert!(Solid::new(&Mesh::default()).is_err()); + let flat = Mesh::prism(&[[0.0, 0.0], [1.0, 0.0], [1.0, 1.0]], 0.0, 0.0); + assert!(Solid::new(&flat).is_err(), "Volumen 0"); + // doppelte Fläche: nicht mannigfaltig + let mut dbl = good.clone(); + let extra: Vec = dbl.indices[0..3].to_vec(); + dbl.indices.extend(extra); + assert!(Solid::new(&dbl).is_err()); + } + + #[test] + fn flat_codec_roundtrip_and_garbage() { + let a = cuboid(0.0, 0.0, 0.0, 2.0, 2.0, 2.0); + let b = cuboid(1.0, 1.0, 1.0, 2.0, 2.0, 2.0); + assert_eq!(decode_mesh(&encode_mesh(&a)), Some(a.clone())); + let r = boolean_flat(1.0, &encode_mesh(&a), &encode_mesh(&b)); + let m = decode_mesh(&r).unwrap(); + assert!((m.volume() - 7.0).abs() < 1e-9); + for bad in [vec![], vec![f64::NAN], vec![1.0, 0.0], vec![-1.0], vec![1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 5.0], vec![1e300]] { + assert!(decode_mesh(&bad).is_none(), "{bad:?}"); + assert!(boolean_flat(0.0, &bad, &encode_mesh(&a)).is_empty()); + } + assert!(boolean_flat(7.0, &encode_mesh(&a), &encode_mesh(&b)).is_empty()); + assert!(boolean_flat(f64::NAN, &encode_mesh(&a), &encode_mesh(&b)).is_empty()); + assert!(boolean_flat(0.5, &encode_mesh(&a), &encode_mesh(&b)).is_empty()); + } + + #[test] + fn cache_per_element() { + let n0 = cache_len(); + let mut calls = 0; + let a = cached("test/e1", 1, || { + calls += 1; + 5 + }); + let b = cached("test/e1", 1, || { + calls += 1; + 6 + }); + assert_eq!((*a, *b, calls), (5, 5, 1)); + let c = cached("test/e1", 2, || 7); + assert_eq!(*c, 7); + assert_eq!(cache_len(), n0 + 1, "Eintrag ersetzt, nicht angehängt"); + let mut h1 = ContentHash::default(); + h1.f64s(&[1.0, 2.0]).str("x"); + let mut h2 = ContentHash::default(); + h2.f64s(&[1.0, 2.0]).str("y"); + assert_ne!(h1.finish(), h2.finish()); + } + + /// Kleiner deterministischer Zufallsgenerator (xorshift). + struct Rng(u64); + impl Rng { + fn next(&mut self) -> u64 { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + self.0 + } + fn f(&mut self) -> f64 { + (self.next() >> 11) as f64 / (1u64 << 53) as f64 + } + fn pick(&mut self, v: &[T]) -> T { + v[(self.next() % v.len() as u64) as usize] + } + } + + /// Fuzz: zufällige und kaputte Netze ⇒ Ergebnis oder Fehler, nie Panik; gültige Ergebnisse + /// sind geschlossen und haben plausible Volumen. + #[test] + fn fuzz_random_and_corrupt_meshes_never_panic() { + let mut rng = Rng(0x9e37_79b9_7f4a_7c15); + let specials = [0.0, -0.0, 1e-12, 1e-7, 1e-6, 1.0, 1e6, 1e8, f64::NAN, f64::INFINITY, f64::NEG_INFINITY, f64::MIN_POSITIVE, -1e-300]; + let mut ok = 0; + for round in 0..400 { + let mut a = cuboid(rng.f() * 2.0, rng.f() * 2.0, rng.f() * 2.0, 0.1 + rng.f() * 3.0, 0.1 + rng.f() * 3.0, 0.1 + rng.f() * 3.0); + let mut b = if round % 3 == 0 { + // bündig zu a + let (lo, hi) = a.bounds().unwrap(); + cuboid(lo[0] + (hi[0] - lo[0]) * 0.5, lo[1], lo[2], hi[0] - lo[0], hi[1] - lo[1], (hi[2] - lo[2]) * rng.f()) + } else { + Mesh::prism(&[[rng.f() * 3.0, rng.f()], [3.0 + rng.f(), rng.f() * 3.0], [rng.f() * 3.0, 3.0 + rng.f()], [-rng.f(), 1.0 + rng.f()]], rng.f(), 1.0 + rng.f() * 2.0) + }; + // Korruption: Koordinaten, Indizes, Abschneiden, Duplikate, Entartung. + let target = if rng.next() % 2 == 0 { &mut a } else { &mut b }; + match rng.next() % 9 { + 0 => { + let i = (rng.next() as usize) % target.positions.len().max(1); + if let Some(v) = target.positions.get_mut(i) { + *v = rng.pick(&specials); + } + } + 1 => { + let i = (rng.next() as usize) % target.indices.len().max(1); + if let Some(v) = target.indices.get_mut(i) { + *v = (rng.next() % 64) as u32; + } + } + 2 => { + let k = (rng.next() as usize) % (target.indices.len() + 1); + target.indices.truncate(k); + } + 3 => { + let k = (rng.next() as usize) % (target.positions.len() + 1); + target.positions.truncate(k); + } + 4 => { + let t: Vec = target.indices.iter().take(6).copied().collect(); + target.indices.extend(t); + } + 5 => { + // alles auf eine Ebene drücken + for v in target.positions.iter_mut().skip(2).step_by(3) { + *v = 0.0; + } + } + 6 => { + // Ecke minimal verschieben (Splitter) + let s = rng.pick(&[1e-10, 1e-8, 1e-6, 1e-3]); + for v in target.positions.iter_mut().take(3) { + *v += s; + } + } + 7 => target.indices.chunks_exact_mut(3).for_each(|t| t.swap(1, 2)), + _ => {} + } + let op = rng.pick(&["union", "difference", "intersection"]); + let r = std::panic::catch_unwind(|| boolean(&a, &b, op)); + let r = r.unwrap_or_else(|_| panic!("Panik in Runde {round} ({op})")); + if let Ok(m) = r { + ok += 1; + if !m.is_empty() { + assert!(m.is_closed_exact(), "Runde {round}: Ergebnis offen"); + assert!(m.volume() > -1e-9 && m.volume().is_finite()); + } + } + } + assert!(ok > 100, "genug gültige Fälle: {ok}"); + } + + /// Fuzz über die flache Kodierung (Bytes wie aus TS): zufällige Puffer. + #[test] + fn fuzz_flat_buffers_never_panic() { + let mut rng = Rng(12345); + let a = encode_mesh(&cuboid(0.0, 0.0, 0.0, 1.0, 1.0, 1.0)); + for _ in 0..2000 { + let mut buf = a.clone(); + for _ in 0..(rng.next() % 4) { + let i = (rng.next() as usize) % buf.len(); + buf[i] = match rng.next() % 5 { + 0 => f64::NAN, + 1 => -(rng.f() * 10.0), + 2 => (rng.next() % 40) as f64, + 3 => rng.f() * 1e12, + _ => rng.f(), + }; + } + if rng.next() % 4 == 0 { + let k = (rng.next() as usize) % (buf.len() + 1); + buf.truncate(k); + } + let op = (rng.next() % 4) as f64; + let r = std::panic::catch_unwind(|| boolean_flat(op, &buf, &a)); + assert!(r.is_ok(), "Panik bei {buf:?}"); + } + } +} diff --git a/src-tauri/core/src/web/mod.rs b/src-tauri/core/src/web/mod.rs index 079837e5..4036319a 100644 --- a/src-tauri/core/src/web/mod.rs +++ b/src-tauri/core/src/web/mod.rs @@ -45,6 +45,7 @@ mod area_report; mod rich_text; mod geo_mesh; mod opening_presets; +mod solid_bool; use wasm_bindgen::prelude::wasm_bindgen; diff --git a/src-tauri/core/src/web/solid_bool.rs b/src-tauri/core/src/web/solid_bool.rs new file mode 100644 index 00000000..4f65e37f --- /dev/null +++ b/src-tauri/core/src/web/solid_bool.rs @@ -0,0 +1,10 @@ +//! Bindung der Körper-Booleans (`crate::solid_bool`, [107] Schritt 2): Netze flach +//! `[n_verts, x, y, z, …, n_tris, i0, i1, i2, …]`, `op` 0 = Vereinigung, 1 = Differenz, 2 = Schnitt. +//! Kaputte Eingaben oder Fehler ⇒ leerer Puffer (nie Panik). + +use wasm_bindgen::prelude::wasm_bindgen; + +#[wasm_bindgen] +pub fn solid_boolean(op: f64, a: &[f64], b: &[f64]) -> Vec { + crate::solid_bool::boolean_flat(op, a, b) +} diff --git a/src/commands/cmds/dormer.ts b/src/commands/cmds/dormer.ts new file mode 100644 index 00000000..8f18af3e --- /dev/null +++ b/src/commands/cmds/dormer.ts @@ -0,0 +1,55 @@ +// Gaube/Lukarne ([G5]) als Engine-Befehl: ein Klick in eine geneigte Dachfläche setzt die Gaube mit der +// Mitte ihrer Stirn an den Punkt (Breite 2.4 m, Stirnhöhe 1.5 m) und ein Fenster in die Stirn. Art als +// Inline-Option (Schlepp/Sattel/Flach/Walm). Kern: `cmd_solid.rs::dormer_ops`, Geometrie `dormer.rs`, +// Verschneidung mit dem Hauptdach `roof_assembly.rs`. + +import { createMutation, xy } from "../createCore"; +import type { CmdOption, Command, CommandResult, CommandState } from "../types"; + +const KIND_OPTIONS: CmdOption[] = [ + { id: "schlepp", labelKey: "cmd.dormer.opt.schlepp" }, + { id: "sattel", labelKey: "cmd.dormer.opt.sattel" }, + { id: "flach", labelKey: "cmd.dormer.opt.flach" }, + { id: "walm", labelKey: "cmd.dormer.opt.walm" }, +]; +const KIND_IDS = new Set(KIND_OPTIONS.map((o) => o.id)); + +interface DormerState extends CommandState { + phase: "start"; + kind: string; +} + +const idle = (kind = "schlepp"): [CommandState, CommandResult] => [ + { phase: "start", kind, lastPoint: null } as DormerState, + { draft: null, done: true }, +]; + +export const dormerCommand: Command = { + name: "dormer", + labelKey: "cmd.dormer.label", + floorOnly: true, + prompt: () => "cmd.dormer.start", + accepts: () => ["point", "option"], + options: () => KIND_OPTIONS, + init: (): DormerState => ({ phase: "start", kind: "schlepp", lastPoint: null }), + + onInput: (state, input, ctx): [CommandState, CommandResult] => { + const s = state as DormerState; + if (input.kind === "option" && KIND_IDS.has(input.id)) { + return [{ ...s, kind: input.id } as DormerState, { draft: null }]; + } + if (input.kind !== "point") return [s, { draft: null }]; + return [ + { ...s, lastPoint: input.point } as DormerState, + { draft: null, commit: createMutation(ctx, { cmd: "dormer", p: xy(input.point), kind: s.kind }) }, + ]; + }, + + onMove: (state, point): [CommandState, CommandResult] => [ + state, + { draft: { preview: [{ kind: "poly", pts: [point], closed: false }], vertices: [point] } }, + ], + + onConfirm: (state): [CommandState, CommandResult] => idle((state as DormerState).kind), + onCancel: (state): [CommandState, CommandResult] => idle((state as DormerState).kind), +}; diff --git a/src/commands/registry.ts b/src/commands/registry.ts index e4535cea..26ffa3dd 100644 --- a/src/commands/registry.ts +++ b/src/commands/registry.ts @@ -19,6 +19,7 @@ import { solidBoolCommand } from "./cmds/solidbool"; import { voidBoxCommand } from "./cmds/voidbox"; import { ceilingOpeningCommand } from "./cmds/ceilingOpening"; import { roofWindowCommand } from "./cmds/roofWindow"; +import { dormerCommand } from "./cmds/dormer"; import { roofHoleCommand } from "./cmds/roofHole"; import { roomCommand } from "./cmds/room"; import { rectCommand } from "./cmds/rect"; @@ -80,6 +81,7 @@ export const COMMANDS: Record = { voidbox: voidBoxCommand, ceilingopening: ceilingOpeningCommand, roofwindow: roofWindowCommand, + dormer: dormerCommand, roofhole: roofHoleCommand, room: roomCommand, line: lineCommand, @@ -165,6 +167,8 @@ export const ALIASES: Record = { aussparung: "ceilingopening", dachfenster: "roofwindow", oberlicht: "roofwindow", + gaube: "dormer", + lukarne: "dormer", dachhof: "roofhole", lichthof: "roofhole", rf: "roof", diff --git a/src/core/robustness.test.ts b/src/core/robustness.test.ts index 5733eba2..5f76129a 100644 --- a/src/core/robustness.test.ts +++ b/src/core/robustness.test.ts @@ -235,6 +235,23 @@ function corruptions(base: Project, seed: number): [string, Project][] { } } }); + add("Gauben kaputt ([G5])", (p) => { + const roofs = list(p, "roofs"); + const bad = [NaN, -1, 0, 1e9, Infinity]; + if (!Array.isArray(p.openings)) p.openings = []; + for (const [i, rf] of roofs.entries()) { + const o = rf.outline as { x: number; y: number }[] | undefined; + const c = Array.isArray(o) && o[0] ? { x: o[0].x + 1, y: o[0].y + 1 } : { x: 1, y: 1 }; + rf.dormers = [ + { id: `GD${i}a`, kind: "sattel", position: c, width: 2, frontHeight: 1.2 }, + { id: `GD${i}b`, kind: "unbekannt", position: { x: NaN, y: 0 }, width: bad[i % bad.length], frontHeight: bad[(i + 1) % bad.length] }, + { id: `GD${i}c`, kind: "schlepp", position: c, width: 1e-9, frontHeight: 1, depth: -5, pitchDeg: 89, overhang: NaN, wallTypeId: "fehlt", roofTypeId: "fehlt" }, + { id: `GD${i}d`, kind: "walm", position: c, width: 3, frontHeight: 1, overhang: 1e6 }, + ]; + list(p, "openings").push({ id: `GW${i}`, type: "opening", hostWallId: "", hostRoofId: rf.id, hostDormerId: `GD${i}a`, categoryCode: "21", kind: "window", position: NaN, width: 0.8, height: 0.8, sillHeight: 0.1 }); + list(p, "openings").push({ id: `GX${i}`, type: "opening", hostWallId: "", hostRoofId: rf.id, hostDormerId: "fehlt", categoryCode: "21", kind: "window", position: 0, width: 0.8, height: 0.8, sillHeight: 0 }); + } + }); add("Baurecht/Sonne kaputt", (p) => { p.siteRules = { parcel: [{ x: 0, y: 0 }, { x: NaN, y: 1 }, { x: 1, y: 1 }], setbacks: [NaN, -1], defaultSetback: NaN, buildingLines: [{ a: { x: 0, y: 0 }, b: { x: 0, y: 0 } }], maxHeight: NaN, show: true }; p.sunStudy = { when: "kein Datum", show: true }; diff --git a/src/geometry/solidBool.test.ts b/src/geometry/solidBool.test.ts new file mode 100644 index 00000000..de234a08 --- /dev/null +++ b/src/geometry/solidBool.test.ts @@ -0,0 +1,73 @@ +import { describe, expect, it } from "vitest"; +import { solidBoolean, type SolidMesh } from "./solidBool"; + +function box(x: number, y: number, z: number, w: number, l: number, h: number): SolidMesh { + const p = [ + [x, y, z], + [x + w, y, z], + [x + w, y + l, z], + [x, y + l, z], + [x, y, z + h], + [x + w, y, z + h], + [x + w, y + l, z + h], + [x, y + l, z + h], + ]; + const indices = [0, 2, 1, 0, 3, 2, 4, 5, 6, 4, 6, 7, 0, 1, 5, 0, 5, 4, 1, 2, 6, 1, 6, 5, 2, 3, 7, 2, 7, 6, 3, 0, 4, 3, 4, 7]; + return { positions: p.flat(), indices }; +} + +function volume(m: { positions: ArrayLike; indices: ArrayLike }): number { + let v = 0; + const P = m.positions; + for (let t = 0; t < m.indices.length; t += 3) { + const [a, b, c] = [m.indices[t] * 3, m.indices[t + 1] * 3, m.indices[t + 2] * 3]; + v += + P[a] * (P[b + 1] * P[c + 2] - P[b + 2] * P[c + 1]) - + P[a + 1] * (P[b] * P[c + 2] - P[b + 2] * P[c]) + + P[a + 2] * (P[b] * P[c + 1] - P[b + 1] * P[c]); + } + return v / 6; +} + +describe("solidBoolean (Kern, Manifold)", () => { + it("bündige Differenz exakt", () => { + const r = solidBoolean(box(0, 0, 0, 2, 2, 2), box(1, 0, 0, 1, 2, 2), "difference"); + expect(r).not.toBeNull(); + expect(volume(r!)).toBeCloseTo(4, 9); + }); + + it("Schnitt ohne Überdeckung: leer, nicht null", () => { + const r = solidBoolean(box(0, 0, 0, 1, 1, 1), box(5, 5, 5, 1, 1, 1), "intersection"); + expect(r).not.toBeNull(); + expect(r!.indices.length).toBe(0); + }); + + it("kaputte Netze: null statt Ausnahme (Fuzz)", () => { + let seed = 7; + const rnd = () => ((seed = (seed * 1103515245 + 12345) % 2147483648) / 2147483648); + const specials = [NaN, Infinity, -Infinity, 1e300, -0, 1e-12]; + for (let k = 0; k < 300; k++) { + const a = box(rnd(), rnd(), rnd(), 0.5 + rnd(), 0.5 + rnd(), 0.5 + rnd()); + const pos = Array.from(a.positions); + const idx = Array.from(a.indices); + switch (k % 5) { + case 0: + pos[Math.floor(rnd() * pos.length)] = specials[k % specials.length]; + break; + case 1: + idx[Math.floor(rnd() * idx.length)] = Math.floor(rnd() * 50) - 5; + break; + case 2: + idx.length = Math.floor(rnd() * idx.length); + break; + case 3: + idx.push(...idx.slice(0, 3)); + break; + default: + break; + } + const ops = ["union", "difference", "intersection"] as const; + expect(() => solidBoolean({ positions: pos, indices: idx }, box(0.3, 0.3, 0.3, 1, 1, 1), ops[k % 3])).not.toThrow(); + } + }); +}); diff --git a/src/geometry/solidBool.ts b/src/geometry/solidBool.ts new file mode 100644 index 00000000..ebd7452b --- /dev/null +++ b/src/geometry/solidBool.ts @@ -0,0 +1,38 @@ +// Körper-Booleans des Rust-Kerns ([107] Schritt 2, `src-tauri/core/src/solid_bool.rs`, Manifold-Port +// `manifold-rust`, exakter Modus): synchron, Netze als flache Positionen/Indizes (Modell-Meter). +// Ungültige Eingaben (offen, nicht endlich, Volumen 0, zu viele Dreiecke) ergeben `null` statt einer +// Ausnahme; innen nach aussen gedrehte Körper werden gedreht. + +import { core } from "../engine/coreWasm"; + +export interface SolidMesh { + positions: ArrayLike; + indices: ArrayLike; +} + +export type SolidOp = "union" | "difference" | "intersection"; + +const OPS: Record = { union: 0, difference: 1, intersection: 2 }; + +function encode(m: SolidMesh): Float64Array { + const nv = Math.floor(m.positions.length / 3); + const nt = Math.floor(m.indices.length / 3); + const out = new Float64Array(2 + nv * 3 + nt * 3); + out[0] = nv; + for (let i = 0; i < nv * 3; i++) out[1 + i] = m.positions[i]; + out[1 + nv * 3] = nt; + for (let i = 0; i < nt * 3; i++) out[2 + nv * 3 + i] = m.indices[i]; + return out; +} + +/** `a op b`; `null` bei ungültiger Eingabe. Ein leeres Ergebnis (z. B. Schnitt ohne Überdeckung) hat + * leere Listen. */ +export function solidBoolean(a: SolidMesh, b: SolidMesh, op: SolidOp): { positions: Float64Array; indices: Uint32Array } | null { + const r = core().solid_boolean(OPS[op], encode(a), encode(b)); + if (r.length < 2) return null; + const nv = r[0]; + const positions = r.slice(1, 1 + nv * 3); + const nt = r[1 + nv * 3]; + const indices = Uint32Array.from(r.subarray(2 + nv * 3, 2 + nv * 3 + nt * 3)); + return { positions, indices }; +} diff --git a/src/i18n/de.ts b/src/i18n/de.ts index 27940ab3..848c7367 100644 --- a/src/i18n/de.ts +++ b/src/i18n/de.ts @@ -488,6 +488,24 @@ export const de = { "objinfo.roof.courtRemove": "Hof entfernen", "objinfo.roof.courtAdd": "Hof hinzufügen: Befehl „Dachhof“ (Kontur zeichnen)", "objinfo.roof.courtAddBtn": "Hof zeichnen …", + "objinfo.dormer.section": "Gauben", + "objinfo.dormer.kind": "Gaubenart", + "objinfo.dormer.kind.schlepp": "Schleppgaube", + "objinfo.dormer.kind.sattel": "Satteldachgaube", + "objinfo.dormer.kind.flach": "Flachdachgaube", + "objinfo.dormer.kind.walm": "Walmgaube", + "objinfo.dormer.remove": "Gaube entfernen", + "objinfo.dormer.width": "Breite (aussen)", + "objinfo.dormer.frontHeight": "Stirnhöhe", + "objinfo.dormer.pitch": "Neigung Gaubendach", + "objinfo.dormer.depth": "Tiefe (Schleppgaube)", + "objinfo.dormer.overhang": "Überstand", + "objinfo.dormer.wallType": "Wandaufbau", + "objinfo.dormer.wallType.default": "einschichtig 15 cm", + "objinfo.dormer.roofType": "Dachaufbau", + "objinfo.dormer.roofType.host": "wie Hauptdach", + "objinfo.dormer.add": "Gaube in eine Dachfläche setzen", + "objinfo.dormer.addBtn": "Gaube setzen …", // ── Stützen-Attribute (Object-Info-Panel) ─────────────────────────────── "objinfo.column.section": "Stütze", "objinfo.column.profile": "Profil", @@ -1541,6 +1559,12 @@ export const de = { "cmd.roof.corner": "Gegenecke:", "cmd.roofWindow.label": "Dachfenster", "cmd.roofWindow.start": "Mitte des Dachfensters (in einer Dachfläche, sonst Oberlicht in der Decke):", + "cmd.dormer.label": "Gaube", + "cmd.dormer.start": "Mitte der Gaubenstirn in einer geneigten Dachfläche:", + "cmd.dormer.opt.schlepp": "Schlepp", + "cmd.dormer.opt.sattel": "Sattel", + "cmd.dormer.opt.flach": "Flach", + "cmd.dormer.opt.walm": "Walm", "cmd.ceilingOpening.label": "Deckenloch", "cmd.ceilingOpening.start": "Erste Ecke der Aussparung (in einer Decke):", "cmd.ceilingOpening.corner": "Gegenecke:", @@ -2782,6 +2806,7 @@ export const de = { "history.cmd.break": "Auftrennen", "history.cmd.ceiling": "Decke zeichnen", "history.cmd.roofWindow": "Dachfenster", + "history.cmd.dormer": "Gaube", "history.cmd.ceilingOpening": "Deckenöffnung", "history.cmd.chamfer": "Fase", "history.cmd.circle": "Kreis zeichnen", diff --git a/src/i18n/en.ts b/src/i18n/en.ts index e25e878f..c9bddf33 100644 --- a/src/i18n/en.ts +++ b/src/i18n/en.ts @@ -486,6 +486,24 @@ export const en: Record = { "objinfo.roof.courtRemove": "Remove courtyard", "objinfo.roof.courtAdd": "Add a courtyard: command \"Roof court\" (draw the contour)", "objinfo.roof.courtAddBtn": "Draw courtyard …", + "objinfo.dormer.section": "Dormers", + "objinfo.dormer.kind": "Dormer type", + "objinfo.dormer.kind.schlepp": "Shed dormer", + "objinfo.dormer.kind.sattel": "Gable dormer", + "objinfo.dormer.kind.flach": "Flat-roof dormer", + "objinfo.dormer.kind.walm": "Hipped dormer", + "objinfo.dormer.remove": "Remove dormer", + "objinfo.dormer.width": "Width (outside)", + "objinfo.dormer.frontHeight": "Front height", + "objinfo.dormer.pitch": "Dormer roof pitch", + "objinfo.dormer.depth": "Depth (shed dormer)", + "objinfo.dormer.overhang": "Overhang", + "objinfo.dormer.wallType": "Wall build-up", + "objinfo.dormer.wallType.default": "single layer 15 cm", + "objinfo.dormer.roofType": "Roof build-up", + "objinfo.dormer.roofType.host": "as main roof", + "objinfo.dormer.add": "Place a dormer in a roof face", + "objinfo.dormer.addBtn": "Place dormer …", // ── Column attributes (object info panel) ──────────────────────────────── "objinfo.column.section": "Column", "objinfo.column.profile": "Profile", @@ -1530,6 +1548,12 @@ export const en: Record = { "cmd.roof.corner": "Opposite corner:", "cmd.roofWindow.label": "Roof window", "cmd.roofWindow.start": "Centre of the roof window (in a roof face, otherwise skylight in the ceiling):", + "cmd.dormer.label": "Dormer", + "cmd.dormer.start": "Centre of the dormer front in a sloped roof face:", + "cmd.dormer.opt.schlepp": "Shed", + "cmd.dormer.opt.sattel": "Gable", + "cmd.dormer.opt.flach": "Flat", + "cmd.dormer.opt.walm": "Hipped", "cmd.ceilingOpening.label": "Slab opening", "cmd.ceilingOpening.start": "First corner of the opening (inside a slab):", "cmd.ceilingOpening.corner": "Opposite corner:", @@ -2768,6 +2792,7 @@ export const en: Record = { "history.cmd.break": "Break", "history.cmd.ceiling": "Draw ceiling", "history.cmd.roofWindow": "Roof window", + "history.cmd.dormer": "Dormer", "history.cmd.ceilingOpening": "Ceiling opening", "history.cmd.chamfer": "Chamfer", "history.cmd.circle": "Draw circle", diff --git a/src/model/types.generated.ts b/src/model/types.generated.ts index a7fc93b8..bc12ac00 100644 --- a/src/model/types.generated.ts +++ b/src/model/types.generated.ts @@ -631,6 +631,41 @@ export type DoorType = { doorFrame?: DoorFrameDetail; }; +/** + * Gaube/Lukarne ([G5]) in einer Dachfläche: Stirnwand parallel zur Traufe, Wangen bis an das + * Hauptdach, eigenes Dach mit dem Hauptdach verschnitten; das Hauptdach ist an der Gaube in allen + * Schichten ausgeschnitten. Das Fenster in der Stirn ist eine `Opening` mit `hostDormerId`. + */ +export type Dormer = { + id: string; + kind: DormerKind; + /** Mitte der Stirnwand-Aussenseite im Grundriss (Meter); legt auch die Dachfläche fest. */ + position: Vec2; + /** Aussenbreite (Wange aussen bis Wange aussen, Meter). */ + width: number; + /** Stirnhöhe: von der Dach-Oberkante an der Stirn bis Unterkante Gaubendach (Meter). */ + frontHeight: number; + /** + * Neigung des Gaubendachs in Grad (Sattel/Walm/Schlepp); fehlt ⇒ Sattel/Walm 40°, Schlepp aus der + * Tiefe bzw. 15°, Flach 0. + */ + pitchDeg?: number; + /** + * Nur Schleppgaube: waagrechte Tiefe von der Stirn bis zum Anschluss an das Hauptdach (Meter); + * gesetzt ⇒ die Neigung folgt daraus. + */ + depth?: number; + /** Dachüberstand an Stirn und Seiten (Meter); fehlt ⇒ 0.15. */ + overhang?: number; + /** Wandtyp für Wangen und Stirn; fehlt ⇒ einschichtig 0.15 m. */ + wallTypeId?: string; + /** Dachtyp des Gaubendachs; fehlt ⇒ der des Hauptdachs. */ + roofTypeId?: string; +}; + +/** Gaubenart ([G5]). */ +export type DormerKind = "schlepp" | "sattel" | "flach" | "walm"; + /** Ein freies 2D-Zeichenelement auf einer Zeichnungsebene. */ export type Drawing2D = { id: string; @@ -1802,6 +1837,12 @@ export type Opening = { * Traufe aus. Fehlt ⇒ 0 (x-Achse). */ hostAngle?: number; + /** + * Wirt Gaube ([G5]): Fenster in der Stirnwand der Gaube `hostDormerId` des Dachs `hostRoofId`. + * `position` = Versatz der Fenstermitte von der Stirnmitte (Meter, + nach rechts von aussen), + * `sillHeight` = Brüstung über der Dach-Oberkante an der Stirn. + */ + hostDormerId?: string; /** Übersteuert das Rahmen-Detail des Typs feldweise für diese Öffnung ([105]). */ frameDetail?: FrameDetail; /** Ersetzt den Schichteinzug des Typs für diese Öffnung ([106]). */ @@ -2309,6 +2350,8 @@ export type Roof = { * der Elementkante. */ surfacePatternOffset?: Vec2; + /** Gauben/Lukarnen ([G5]) in den Dachflächen dieses Dachs. Fehlt ⇒ keine. */ + dormers?: Array; }; /** diff --git a/src/panels/ObjectInfoPanel.tsx b/src/panels/ObjectInfoPanel.tsx index e7247236..4ad0aa26 100644 --- a/src/panels/ObjectInfoPanel.tsx +++ b/src/panels/ObjectInfoPanel.tsx @@ -27,6 +27,8 @@ import { t } from "../i18n"; import type { TranslationKey } from "../i18n"; import { flattenCategories, formatM } from "../model/types"; import type { + Dormer, + DormerKind, DrawingLevel, RoofShape, SiaCategory, @@ -922,6 +924,103 @@ function rectOutline(x0: number, y0: number, w: number, d: number) { ]; } +/** Gauben ([G5]) des Dachs: Art, Masse, Neigung, Aufbau je Gaube; Hinzufügen über den Befehl „Gaube". */ +function DormersSection({ roof, host }: { roof: RoofInfo; host: ReturnType }) { + const dormers = roof.dormers ?? []; + const patch = (i: number, p: Partial) => + host.onSetRoofPatch({ dormers: dormers.map((d, k) => (k === i ? { ...d, ...p } : d)) }, `dormer-${i}`); + const num = (labelKey: TranslationKey, value: number, step: number, apply: (v: number) => void) => ( +

+ {t(labelKey)} + { + const v = Number(e.target.value); + if (Number.isFinite(v)) apply(v); + }} + title={t(labelKey)} + /> +
+ ); + return ( + <> +
+
{t("objinfo.dormer.section")}
+ {dormers.map((d, i) => ( +
+
+ {t("objinfo.dormer.kind")} + patch(i, { kind: v as DormerKind })} + options={[ + { value: "schlepp", label: t("objinfo.dormer.kind.schlepp") }, + { value: "sattel", label: t("objinfo.dormer.kind.sattel") }, + { value: "flach", label: t("objinfo.dormer.kind.flach") }, + { value: "walm", label: t("objinfo.dormer.kind.walm") }, + ]} + title={t("objinfo.dormer.kind")} + width={130} + /> + +
+ {num("objinfo.dormer.width", d.width, 0.1, (v) => patch(i, { width: Math.max(0.8, v) }))} + {num("objinfo.dormer.frontHeight", d.frontHeight, 0.05, (v) => patch(i, { frontHeight: Math.max(0.5, v) }))} + {d.kind !== "flach" && + num("objinfo.dormer.pitch", d.pitchDeg ?? (d.kind === "schlepp" ? 15 : 40), 1, (v) => + patch(i, { pitchDeg: Math.max(0, Math.min(75, v)), depth: undefined }), + )} + {d.kind === "schlepp" && + num("objinfo.dormer.depth", d.depth ?? 0, 0.1, (v) => patch(i, { depth: v > 0.1 ? v : undefined }))} + {num("objinfo.dormer.overhang", d.overhang ?? 0.15, 0.05, (v) => patch(i, { overhang: Math.max(0, v) }))} +
+ {t("objinfo.dormer.wallType")} + patch(i, { wallTypeId: v || undefined })} + options={[ + { value: "", label: t("objinfo.dormer.wallType.default") }, + ...host.project.wallTypes.map((wt) => ({ value: wt.id, label: wt.name })), + ]} + title={t("objinfo.dormer.wallType")} + width={130} + /> +
+
+ {t("objinfo.dormer.roofType")} + patch(i, { roofTypeId: v || undefined })} + options={[ + { value: "", label: t("objinfo.dormer.roofType.host") }, + ...(host.project.roofTypes ?? []).map((rt) => ({ value: rt.id, label: rt.name })), + ]} + title={t("objinfo.dormer.roofType")} + width={130} + /> +
+
+ ))} +
+ +
+ + ); +} + /** Dach-Abschnitt: Form, Neigung(en), Überstand, Firstrichtung, Dicke. */ export function RoofSection({ roof, @@ -1092,6 +1191,7 @@ export function RoofSection({ )} {/* Innenhöfe: Liste mit Entfernen, Hinzufügen über den Befehl „Dachhof“. */} + {roof.shape !== "pult" && ( <>
diff --git a/src/panels/ToolsPanel.tsx b/src/panels/ToolsPanel.tsx index defb12af..4fc8c5c6 100644 --- a/src/panels/ToolsPanel.tsx +++ b/src/panels/ToolsPanel.tsx @@ -355,7 +355,7 @@ const TOOLS_2D: ToolId[] = [ "image", ]; const TOOLS_3D: ToolId[] = ["wall", "ceiling", "window", "door", "stair", "room"]; -const COMMANDS_3D = ["column", "ceilingopening", "roof", "roofhole", "roofwindow", "extrude", "solid", "solidbool", "sectionline", "viewline", "autodim"]; +const COMMANDS_3D = ["column", "ceilingopening", "roof", "roofhole", "roofwindow", "dormer", "extrude", "solid", "solidbool", "sectionline", "viewline", "autodim"]; const COMMANDS_EDIT = ["move", "copy", "array", "rotate", "mirror", "offset", "multiline", "trim", "break", "extend", "fillet", "chamfer", "join", "defblock", "measure"]; type ToolsView = "list" | "icons"; diff --git a/src/state/selectionInfo.ts b/src/state/selectionInfo.ts index 39577f59..676d2a8c 100644 --- a/src/state/selectionInfo.ts +++ b/src/state/selectionInfo.ts @@ -88,6 +88,8 @@ export interface RoofInfo { minY: number; /** Kanten (Umriss, dann Höfe) mit Neigungsvorgabe ([26], `roofEdgeList`). */ edges: RoofEdge[]; + /** Gauben ([G5]) des Dachs, wie gespeichert. */ + dormers?: import("../model/types").Dormer[]; /** Innenhöfe: Fläche (m²) und Punktzahl je Hof, in der Reihenfolge von `Roof.holes`. */ holes: { area: number; points: number }[]; /** Ob `edgePitchDeg` gesetzt ist. */ diff --git a/src/ui/ribbon/CommandIcon.tsx b/src/ui/ribbon/CommandIcon.tsx index 3131179f..84e16c37 100644 --- a/src/ui/ribbon/CommandIcon.tsx +++ b/src/ui/ribbon/CommandIcon.tsx @@ -190,6 +190,15 @@ export function CommandIcon({ name }: { name: string }) { ); + case "dormer": + // Gaube: Dachfläche mit Satteldach-Gaube und Fenster in der Stirn. + return ( + + + + + + ); case "roofwindow": // Dachfenster: Dachfläche mit Fensterrahmen und Glas. return ( diff --git a/src/viewport/Wasm3DViewport.tsx b/src/viewport/Wasm3DViewport.tsx index a15572d6..1e386e74 100644 --- a/src/viewport/Wasm3DViewport.tsx +++ b/src/viewport/Wasm3DViewport.tsx @@ -129,6 +129,44 @@ interface Grip { pos: Vec3; } +/** Gauben-Griffe: erster Index (Kern `grips.rs::DORMER_GRIP_BASE`). */ +const DORMER_GRIP_BASE = 1000; + +/** System einer Gaube: Dachfläche über `p` (Normale → `h` nach aussen, `ew` Breite), Höhe dort. */ +function dormerGripFrame( + planes: readonly { pts: readonly (readonly [number, number, number])[] }[], + p: Vec2, +): { h: [number, number]; ew: [number, number]; z: number; tanMain: number } | null { + for (const pl of planes) { + const pts = pl.pts; + if (pts.length < 3) continue; + let inside = false; + for (let i = 0, j = pts.length - 1; i < pts.length; j = i++) { + const a = pts[i]; + const b = pts[j]; + if (a[1] > p.y !== b[1] > p.y && p.x < ((b[0] - a[0]) * (p.y - a[1])) / (b[1] - a[1]) + a[0]) inside = !inside; + } + if (!inside) continue; + let nx = 0; + let ny = 0; + let nz = 0; + for (let i = 0; i < pts.length; i++) { + const c = pts[i]; + const d = pts[(i + 1) % pts.length]; + nx += (c[1] - d[1]) * (c[2] + d[2]); + ny += (c[2] - d[2]) * (c[0] + d[0]); + nz += (c[0] - d[0]) * (c[1] + d[1]); + } + if (nz < 0) [nx, ny, nz] = [-nx, -ny, -nz]; + const hl = Math.hypot(nx, ny); + if (!(hl > 1e-9 && nz > 1e-9)) return null; + const h: [number, number] = [nx / hl, ny / hl]; + const z = pts[0][2] - (nx * (p.x - pts[0][0]) + ny * (p.y - pts[0][1])) / nz; + return { h, ew: [-h[1], h[0]], z, tanMain: hl / nz }; + } + return null; +} + /** * Alle Griffe der gewählten Wände + 2D-Zeichnungen: pro Wand zwei Endpunkte * (UK), ein Höhen-Griff (Achsmitte, OK) und ein Verschiebe-Griff (Achsmitte, @@ -217,6 +255,25 @@ function computeGrips( // g-Punkte sind MODELL [x, y, z=Höhe] → world [x, Höhe, y]. if (apex) out.push({ kind: "roofpitch", target, index: -1, pos: [apex[0], apex[2], apex[1]] }); } + // Gauben ([G5]): Breiten-Griffe links/rechts der Stirn, Tiefen-Griff (Schleppgaube) hinten; Index ab + // DORMER_GRIP_BASE (Kern `grips.rs::dormer_grip`). + (roof.dormers ?? []).forEach((d, di) => { + const f = dormerGripFrame(g.planes, d.position); + if (!f) return; + const z = f.z + d.frontHeight; + const at = (u: number, v: number, zz: number): Vec3 => [ + d.position.x + f.ew[0] * u - f.h[0] * v, + zz, + d.position.y + f.ew[1] * u - f.h[1] * v, + ]; + const base = DORMER_GRIP_BASE + di * 10; + out.push({ kind: "vertex", target, index: base, pos: at(-d.width / 2, 0, z) }); + out.push({ kind: "vertex", target, index: base + 1, pos: at(d.width / 2, 0, z) }); + if (d.kind === "schlepp") { + const depth = d.depth ?? d.frontHeight / Math.max(0.05, f.tanMain - Math.tan(((d.pitchDeg ?? 15) * Math.PI) / 180)); + out.push({ kind: "vertex", target, index: base + 2, pos: at(0, depth, f.z + depth * f.tanMain) }); + } + }); } return out; }