From 3a3ed7f74ff17ab9ed206e0ead5234200ef08c3b Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 22:27:19 +0000 Subject: [PATCH] [K2] Oeffnungen in 3D und Wand-Loch-Mesh nach Rust (openings3d.rs, wall_mesh_cut.rs) Glas/Mehrfachverglasung, Tuerblatt/Kassette, Blend- und Fluegelrahmen je Eckstoss, Sprossen, SIA-Symbole, Baenke, Zarge, Schwelle und Rollladenkasten rechnet der Kern; toWalls3d/openings.ts sammelt nur noch aus dem Project und uebergibt alle Waende in einem Aufruf (emitOpeningMeshes), Farbe je Bauteil-Klasse bleibt TS. wallMeshCut.ts ist Fassade (wallCutMeshes fuer viele Baender, solidSubrects, isWatertight); STL/OBJ/IFC holen die Loch-Meshes gesammelt. TS-Rechenlogik geloescht. Ergebnis bitgleich (Beispiel + 40 Zufallsprojekte x 4 Detailgrade, 6586 Baender, IFC-Datei identisch). projectToModel3d (1500 Waende) 193 -> 126 ms. --- TODO.md | 8 + src-tauri/core/src/joins.rs | 2 +- src-tauri/core/src/lib.rs | 2 + src-tauri/core/src/openings3d.rs | 1246 +++++++++++++++++++++++ src-tauri/core/src/wall_mesh_cut.rs | 399 ++++++++ src-tauri/core/src/web/mod.rs | 2 + src-tauri/core/src/web/openings3d.rs | 15 + src-tauri/core/src/web/wall_mesh_cut.rs | 21 + src/export/exportIfc.ts | 11 +- src/export/exportMesh.ts | 25 +- src/plan/toWalls3d.ts | 8 +- src/plan/toWalls3d/bands.ts | 2 +- src/plan/toWalls3d/openings.ts | 1235 +++------------------- src/plan/wallMeshCut.ts | 392 ++----- 14 files changed, 1943 insertions(+), 1425 deletions(-) create mode 100644 src-tauri/core/src/openings3d.rs create mode 100644 src-tauri/core/src/wall_mesh_cut.rs create mode 100644 src-tauri/core/src/web/openings3d.rs create mode 100644 src-tauri/core/src/web/wall_mesh_cut.rs diff --git a/TODO.md b/TODO.md index 800223fe..d140b2cc 100644 --- a/TODO.md +++ b/TODO.md @@ -40,6 +40,14 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern `model/joins.ts` und `toWalls3d/bands.ts` sammeln nur noch aus dem `Project` und übergeben flach (Decken/Dächer einmal je Geschoss). Ergebnis bitgleich (Vergleich über 27 Projekte inkl. Zufallsgrundrisse), `computeJoins` ~10×, `projectToWalls3d` (1296 Wände) ~4× schneller. + - ✅ (27.10.) Öffnungen in 3D und Wand-Loch-Mesh in Rust (`openings3d.rs`, `wall_mesh_cut.rs`): Glas/ + Mehrfachverglasung, Türblatt/Kassette, Blend-/Flügelrahmen je Eckstoss, Sprossen, SIA-Symbole, Bänke, + Zarge, Schwelle, Rollladenkasten; Loch-Mesh für STL/OBJ/IFC, `isWatertight`. `toWalls3d/openings.ts` + sammelt nur noch (alle Wände in einem Aufruf, `emitOpeningMeshes`), `wallMeshCut.ts` ist Fassade + (`wallCutMeshes` für viele Bänder). Bitgleich (Beispiel + 40 Zufallsprojekte × 4 Detailgrade, 152k + Quader; 6586 Bänder; IFC-Datei identisch). Öffnungen ~4–7×, Loch-Mesh ~1,6× schneller, + `projectToModel3d` (1500 Wände) 193 → 126 ms; `isWatertight` allein ~4× langsamer (Übergabe der + `number[]`, je Mesh < 3 µs), IFC-Export gesamt unverändert. - ○ **[K3] Plan, Schnitt, Ansicht in Rust**, Primitive direkt an render2d (ohne TS-Umweg). · L - ○ **[K4] Modell und Ops in Rust** [2]; TS bekommt die Typen generiert (z. B. `ts-rs`). · XL - **Fertig wenn** (je Etappe): TS-Fassung gelöscht, `npm run check` grün, App/CLI/IFC unverändert. diff --git a/src-tauri/core/src/joins.rs b/src-tauri/core/src/joins.rs index 3e092e0a..27dc68ba 100644 --- a/src-tauri/core/src/joins.rs +++ b/src-tauri/core/src/joins.rs @@ -189,7 +189,7 @@ pub fn normalize(a: Vec2) -> Vec2 { } /// `Math.round` (halbe Werte nach +∞). -fn js_round(x: f64) -> f64 { +pub fn js_round(x: f64) -> f64 { if !x.is_finite() { return x; } diff --git a/src-tauri/core/src/lib.rs b/src-tauri/core/src/lib.rs index 685a4148..4fd9a907 100644 --- a/src-tauri/core/src/lib.rs +++ b/src-tauri/core/src/lib.rs @@ -20,6 +20,8 @@ pub mod wall_bands; pub mod room_area; pub mod room_boundary; pub mod polygon_holes; +pub mod openings3d; +pub mod wall_mesh_cut; #[cfg(feature = "web")] mod web; diff --git a/src-tauri/core/src/openings3d.rs b/src-tauri/core/src/openings3d.rs new file mode 100644 index 00000000..3acba463 --- /dev/null +++ b/src-tauri/core/src/openings3d.rs @@ -0,0 +1,1246 @@ +//! Öffnungen in 3D: Glasscheibe(n)/Türblatt, Rahmen-/Sprossen-Riegel (Zarge/Blendrahmen/Kämpfer/ +//! Mittelpfosten/Flügelrahmen + SIA-Symbole), Fensterbänke, Zargen-Umgriff, Schwellenprofil und +//! Rollladen-/Sonnenschutzkasten typisierter Tür-/Fensteröffnungen — das 3D-Pendant zu +//! `generatePlan/openings.ts`. Portiert aus `src/plan/toWalls3d/openings.ts`; dort bleiben das +//! Sammeln aus dem `Project` (Typ-Auflösung, Flügeltabelle, Öffnungs-Intervall/-Höhe) und die +//! Farbzuordnung je Bauteil-Klasse ([`Part`]). +//! +//! Die Wand-Löcher selbst (Laibung, Sturz, Brüstung) schneidet [`crate::wall_bands`] aus den +//! Wandbändern; hier entstehen nur die Einbauteile IN der Öffnung. +//! +//! Jedes Teil ist ein geschlossener Quader (8 Ecken, Topologie `OPENING_BOX_TRIS` in TS) in +//! Modell-Metern (x, y, z = Höhe). Rechnung bitgleich zur früheren TS-Fassung (gleiche +//! Operationsreihenfolge, `Math.hypot`/`Math.round`/`Math.max`/`Math.min` nachgebildet). + +use crate::flat_read::Reader; +use crate::joins::{js_hypot, js_round}; +use crate::wall_bands::EPS; + +/// Halbe Dicke EINER Fensterscheibe (8 mm je Scheibe). +const GLASS_HALF_THICK: f64 = 0.004; +/// Luftraum zwischen zwei Scheiben einer Mehrfachverglasung. +const GLASS_PANE_GAP: f64 = 0.006; +/// Halbe Breite der Symbol-Diagonalen (~5 mm Gesamtbreite). +const SYMBOL_HALF_WIDTH: f64 = 0.0025; +/// Türblatt-Dicke quer zur Wand. +const DOOR_LEAF_THICK: f64 = 0.04; +/// Default-Ansichtsbreite des Rahmenprofils, wenn der Typ keine nennt. +const DEFAULT_FRAME_WIDTH: f64 = 0.06; +/// Default-Rahmentiefe (deckt sich mit `geometry/opening.ts::DEFAULT_FRAME_DEPTH`, 2D = 3D). +const DEFAULT_FRAME_DEPTH: f64 = 0.07; +/// Stegbreite der Kassetten-Füllstäbe. +const PANEL_STILE_WIDTH: f64 = 0.06; +/// Vertiefung der Kassetten-Füllung gegenüber den Stegen (je Seite). +const PANEL_RECESS: f64 = 0.012; +/// Obergrenze für Zählwerte (Flügel, Sprossen, Kassetten, Scheiben) gegen Unsinn-Eingaben. +const MAX_COUNT: f64 = 4096.0; + +/// Bauteil-Klasse eines Quaders (TS ordnet die Farbe zu). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Part { + Glass = 0, + Frame = 1, + Shading = 2, + Sill = 3, + Symbol = 4, + DoorLeaf = 5, +} + +/// Ein Quader: Bauteil-Klasse und 8 Ecken (x, y, z), Ecken-Bits wie `OPENING_BOX_TRIS`. +#[derive(Clone, Debug, PartialEq)] +pub struct BoxMesh { + pub part: Part, + pub positions: [f64; 24], +} + +/// Rahmen-Querschnitt in der Öffnungsebene (u, h): (from,UK), (to,UK), (from,OK), (to,OK). +pub type Quad = [[f64; 2]; 4]; + +/// Eckverbindung von Blend- und Flügelrahmen (`FrameCornerJoin`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum CornerJoin { + Vertical, + Horizontal, + Mitre, +} + +/// Detailgrad (`DetailLevel`); `Other` = unbekannter Wert (weder fein noch mittel, aber Rahmen). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Detail { + Coarse, + Medium, + Fine, + Other, +} + +/// Öffnungsart eines Flügels (`SashDef.opening`); `None` = fehlt/leer. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SashOpening { + None, + Turn, + Tilt, + TurnTilt, + Fixed, + Slide, + Other, +} + +/// Art eines Eintrags der Flügeltabelle (`SashDef.kind`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SashKind { + Sash, + Post, + Other, +} + +/// Ein Eintrag der Flügeltabelle. `width`/`post_width`: NaN = fehlt. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct SashIn { + pub kind: SashKind, + /// `autoWidth === false` (feste Breite). + pub fixed_width: bool, + pub width: f64, + pub post_width: f64, + pub opening: SashOpening, + pub hinge_left: bool, +} + +/// Blatt-Ausführung einer Tür (`DoorType.leafStyle`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum LeafStyle { + Plain, + Glass, + Panelled, +} + +/// Fensterbank-Wahl (`WindowType.sillBoard`); `Outer` = "aussen" oder fehlt. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SillBoard { + Outer, + None, + Inner, + Both, +} + +/// Tür-spezifische Typwerte (NaN = fehlt). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct DoorTypeIn { + pub threshold: bool, + pub leaf_count: f64, + pub leaf_style: LeafStyle, + pub glazing_ratio: f64, + /// `(frameKind ?? "zarge") === "zarge"`. + pub zarge: bool, + pub panel_cols: f64, + pub panel_rows: f64, +} + +/// Fenster-spezifische Typwerte (NaN = fehlt). +#[derive(Clone, Debug, PartialEq)] +pub struct WindowTypeIn { + /// `glazingPanesOf(wt)`. + pub glazing_panes: f64, + pub mullion_rows: f64, + pub mullion_cols: f64, + pub sill_board: SillBoard, + /// Explizite Flügeltabelle (leer ⇒ gleichmässig aus `default_wing_count`). + pub sashes: Vec, + /// `op.wingCount ?? wt.wingCount ?? 1`. + pub default_wing_count: f64, + /// `wt.kind` (Öffnungsart der gleichmässigen Flügel). + pub default_opening: SashOpening, + /// Rollladenkasten (Breite, Höhe, Tiefe), nur bei `shading.create`. + pub shading: Option<[f64; 3]>, +} + +#[derive(Clone, Debug, PartialEq)] +pub enum KindIn { + Door(DoorTypeIn), + Window(WindowTypeIn), +} + +/// Aufgelöster Tür-/Fenstertyp einer Öffnung (gemeinsame Werte, NaN = fehlt). +#[derive(Clone, Debug, PartialEq)] +pub struct TypeIn { + pub frame_depth: f64, + pub inset_from_face: f64, + /// `(insetFace ?? "aussen") === "innen"`. + pub inset_inner: bool, + pub corner_join: CornerJoin, + pub frame_width: f64, + pub transom_height: f64, + pub kind: KindIn, +} + +/// Eine Öffnung: Achs-Intervall (ab Wandstart), absolute Höhen, Tür/Fenster, Wanddicke und Typ. +#[derive(Clone, Debug, PartialEq)] +pub struct OpeningIn { + pub from: f64, + pub to: f64, + pub z_bottom: f64, + pub z_top: f64, + pub door: bool, + pub wall_thickness: f64, + pub ty: Option, +} + +/// Eine Wand mit ihren Öffnungen (in Projekt-Reihenfolge). +#[derive(Clone, Debug, PartialEq)] +pub struct WallIn { + pub start: [f64; 2], + pub end: [f64; 2], + pub openings: Vec, +} + +/// `Math.max(a, b)` (NaN gewinnt, +0 vor −0). +pub(crate) fn jmax(a: f64, b: f64) -> f64 { + if a.is_nan() || b.is_nan() { + f64::NAN + } else if a > b { + a + } else if b > a { + b + } else if a.is_sign_positive() { + a + } else { + b + } +} + +/// `Math.min(a, b)` (NaN gewinnt, −0 vor +0). +pub(crate) fn jmin(a: f64, b: f64) -> f64 { + if a.is_nan() || b.is_nan() { + f64::NAN + } else if a < b { + a + } else if b < a { + b + } else if a.is_sign_negative() { + a + } else { + b + } +} + +/// `v ?? d` (fehlend = NaN). +fn or(v: f64, d: f64) -> f64 { + if v.is_nan() { + d + } else { + v + } +} + +/// Klemmt `v` auf `[lo, hi]` wie `clampRange` (`Math.max(lo, Math.min(hi, v))`). +fn clamp_range(v: f64, lo: f64, hi: f64) -> f64 { + jmax(lo, jmin(hi, v)) +} + +/// Wandachse: Start, Richtung u und rechte Normale (uy, −ux) — die Dicken-Achse der Öffnungs- +/// Quader (bewusst NICHT die linke Normale; zusammen mit dem Vorzeichen in +/// [`frame_normal_range`] liegt "aussen" physisch richtig). +#[derive(Clone, Copy)] +struct Axis { + sx: f64, + sy: f64, + ux: f64, + uy: f64, + nx: f64, + ny: f64, +} + +impl Axis { + fn of(start: [f64; 2], end: [f64; 2]) -> Option { + let dx = end[0] - start[0]; + let dy = end[1] - start[1]; + let len = js_hypot(dx, dy); + if len < 1e-9 { + return None; + } + let ux = dx / len; + let uy = dy / len; + Some(Axis { sx: start[0], sy: start[1], ux, uy, nx: uy, ny: -ux }) + } + + fn point(&self, s: f64, t: f64, z: f64, out: &mut [f64; 24], i: usize) { + out[i * 3] = self.sx + self.ux * s + self.nx * t; + out[i * 3 + 1] = self.sy + self.uy * s + self.ny * t; + out[i * 3 + 2] = z; + } +} + +/// Sammelt die Quader einer Wand (Achse fehlt ⇒ nichts). +struct Emitter<'a> { + axis: Option, + out: &'a mut Vec, +} + +impl Emitter<'_> { + /// Achsen-Quader `[from,to] × [z_bottom,z_top] × [n_min,n_max]` (`openingAxisBox`). + #[allow(clippy::too_many_arguments)] + fn axis_box(&mut self, from: f64, to: f64, z_bottom: f64, z_top: f64, n_min: f64, n_max: f64, part: Part) { + if to - from <= EPS || z_top - z_bottom <= EPS || (n_max - n_min).abs() <= EPS { + return; + } + let Some(a) = self.axis else { return }; + let mut p = [0.0; 24]; + for i in 0..8 { + let s = if i & 1 != 0 { to } else { from }; + let z = if i & 2 != 0 { z_top } else { z_bottom }; + let t = if i & 4 != 0 { n_max } else { n_min }; + a.point(s, t, z, &mut p, i); + } + self.out.push(BoxMesh { part, positions: p }); + } + + /// Prisma mit Viereck-Querschnitt `q` in der Öffnungsebene (`openingPlaneQuad`). + fn plane_quad(&mut self, q: &Quad, n_min: f64, n_max: f64, part: Part) { + if (n_max - n_min).abs() <= EPS { + return; + } + let Some(a) = self.axis else { return }; + let mut p = [0.0; 24]; + for i in 0..8 { + let [s, z] = q[i & 3]; + let t = if i & 4 != 0 { n_max } else { n_min }; + a.point(s, t, z, &mut p, i); + } + self.out.push(BoxMesh { part, positions: p }); + } + + /// Dünnes Prisma mit schräger Längsachse `(u0,h0)→(u1,h1)` in der Öffnungsebene + /// (`openingPlaneBox`, SIA-Symbole). + #[allow(clippy::too_many_arguments)] + fn plane_box(&mut self, u0: f64, h0: f64, u1: f64, h1: f64, half_width: f64, n_front: f64, n_back: f64, part: Part) { + let du = u1 - u0; + let dh = h1 - h0; + let seg_len = js_hypot(du, dh); + if seg_len < EPS { + return; + } + let Some(a) = self.axis else { return }; + let pu = -dh / seg_len; + let ph = du / seg_len; + let mut p = [0.0; 24]; + for i in 0..8 { + let ui = if i & 1 != 0 { u1 } else { u0 }; + let hi = if i & 1 != 0 { h1 } else { h0 }; + let s = if i & 2 != 0 { 1.0 } else { -1.0 }; + let t = if i & 4 != 0 { n_front } else { n_back }; + let u = ui + s * half_width * pu; + let h = hi + s * half_width * ph; + a.point(u, t, h, &mut p, i); + } + self.out.push(BoxMesh { part, positions: p }); + } +} + +/// Rahmen-Ring über `[from,to] × [z_b,z_t]` mit Profilbreite `w` ohne überlappende Profile +/// (`frameRingQuads`): `join` bestimmt, welche Glieder an den Ecken durchlaufen. +pub fn frame_ring_quads(from: f64, to: f64, z_b: f64, z_t: f64, w: f64, join: CornerJoin, bottom: bool) -> Vec { + let bx = |u0: f64, u1: f64, h0: f64, h1: f64| -> Quad { [[u0, h0], [u1, h0], [u0, h1], [u1, h1]] }; + let mut out = Vec::with_capacity(4); + if to - from <= 2.0 * w + EPS || z_t - z_b <= (if bottom { 2.0 } else { 1.0 }) * w + EPS { + // Zu klein für einen Ring: ein Vollprofil. + out.push(bx(from, to, z_b, z_t)); + return out; + } + let bz = if bottom { z_b + w } else { z_b }; + match join { + CornerJoin::Horizontal => { + out.push(bx(from, to, z_t - w, z_t)); + if bottom { + out.push(bx(from, to, z_b, z_b + w)); + } + out.push(bx(from, from + w, bz, z_t - w)); + out.push(bx(to - w, to, bz, z_t - w)); + } + CornerJoin::Mitre => { + out.push([[from + w, z_t - w], [to - w, z_t - w], [from, z_t], [to, z_t]]); + if bottom { + out.push([[from, z_b], [to, z_b], [from + w, z_b + w], [to - w, z_b + w]]); + } + out.push([[from, z_b], [from + w, bz], [from, z_t], [from + w, z_t - w]]); + out.push([[to - w, bz], [to, z_b], [to - w, z_t - w], [to, z_t]]); + } + CornerJoin::Vertical => { + out.push(bx(from, from + w, z_b, z_t)); + out.push(bx(to - w, to, z_b, z_t)); + out.push(bx(from + w, to - w, z_t - w, z_t)); + if bottom { + out.push(bx(from + w, to - w, z_b, z_b + w)); + } + } + } + out +} + +/// Aufgelöste Rahmen-/Sprossen-Parameter einer Öffnung (`OpeningFrameParams` in TS). +struct FrameParams<'a> { + frame_width: f64, + n_min: f64, + n_max: f64, + transom_height: f64, + has_sill: bool, + wing_count: f64, + mullion_rows: f64, + mullion_cols: f64, + glazed: bool, + glazing_panes: f64, + glazed_fraction: f64, + sashes: std::borrow::Cow<'a, [SashIn]>, + half_thickness: f64, + draw_sill: bool, + draw_interior_sill: bool, + zarge_cladding: bool, + draw_threshold_profile: bool, + panelled: bool, + panel_cols: f64, + panel_rows: f64, + corner_join: CornerJoin, +} + +/// Rahmentiefe quer zur Wand: `frame_depth` (> EPS) oder Default, auf die Wanddicke geklemmt. +fn across_wall_depth(frame_depth: f64, wall_thickness: f64) -> f64 { + let depth = if frame_depth > EPS { frame_depth } else { DEFAULT_FRAME_DEPTH }; + jmin(depth, wall_thickness) +} + +/// Quer-Versatz `[n_min, n_max]` des Rahmenkörpers: Vorderkante bündig mit der gewählten +/// Wandfläche (minus Schichteinzug), `depth` zur Wandmitte hin, auf die halbe Dicke geklemmt. +fn frame_normal_range(half: f64, depth: f64, inset: f64, inner: bool) -> (f64, f64) { + let sign = if inner { -1.0 } else { 1.0 }; + let front = sign * (half - inset); + let back = front - sign * depth; + let a = clamp_range(front, -half, half); + let b = clamp_range(back, -half, half); + (jmin(a, b), jmax(a, b)) +} + +fn resolve_frame(o: &OpeningIn) -> Option> { + let ty = o.ty.as_ref()?; + let half = o.wall_thickness / 2.0; + let depth = across_wall_depth(ty.frame_depth, o.wall_thickness); + let (n_min, n_max) = frame_normal_range(half, depth, or(ty.inset_from_face, 0.0), ty.inset_inner); + let frame_width = or(ty.frame_width, DEFAULT_FRAME_WIDTH); + let transom_height = jmax(0.0, or(ty.transom_height, 0.0)); + Some(match &ty.kind { + KindIn::Door(d) => FrameParams { + corner_join: ty.corner_join, + frame_width, + n_min, + n_max, + transom_height, + has_sill: d.threshold, + wing_count: jmax(1.0, js_round(or(d.leaf_count, 1.0))), + mullion_rows: 1.0, + mullion_cols: 1.0, + glazed: d.leaf_style == LeafStyle::Glass, + glazing_panes: 1.0, + glazed_fraction: jmax(0.05, jmin(1.0, or(d.glazing_ratio, 1.0))), + sashes: std::borrow::Cow::Borrowed(&[]), + half_thickness: half, + draw_sill: false, + draw_interior_sill: false, + zarge_cladding: d.zarge, + draw_threshold_profile: d.threshold, + panelled: d.leaf_style == LeafStyle::Panelled, + panel_cols: jmax(1.0, js_round(or(d.panel_cols, 2.0))), + panel_rows: jmax(1.0, js_round(or(d.panel_rows, 3.0))), + }, + KindIn::Window(w) => { + // Flügeltabelle: explizite gewinnt; sonst gleichmässig aus der effektiven Flügelzahl. + let sashes: std::borrow::Cow<'_, [SashIn]> = if !w.sashes.is_empty() { + std::borrow::Cow::Borrowed(&w.sashes) + } else { + let n = jmax(1.0, js_round(w.default_wing_count)); + // `Array.from({ length: NaN })` ist leer. + let n = if n.is_nan() { 0 } else { n.min(MAX_COUNT) as usize }; + std::borrow::Cow::Owned( + (0..n) + .map(|i| SashIn { + kind: SashKind::Sash, + fixed_width: false, + width: f64::NAN, + post_width: f64::NAN, + opening: w.default_opening, + hinge_left: i % 2 == 0, + }) + .collect(), + ) + }; + let wings = sashes.iter().filter(|s| s.kind == SashKind::Sash).count() as f64; + FrameParams { + corner_join: ty.corner_join, + frame_width, + n_min, + n_max, + transom_height, + has_sill: true, + wing_count: jmax(1.0, wings), + mullion_rows: jmax(1.0, js_round(or(w.mullion_rows, 1.0))), + mullion_cols: jmax(1.0, js_round(or(w.mullion_cols, 1.0))), + glazed: true, + glazing_panes: w.glazing_panes, + glazed_fraction: 1.0, + sashes, + half_thickness: half, + draw_sill: w.sill_board != SillBoard::None && w.sill_board != SillBoard::Inner, + draw_interior_sill: w.sill_board == SillBoard::Inner || w.sill_board == SillBoard::Both, + zarge_cladding: false, + draw_threshold_profile: false, + panelled: false, + panel_cols: 1.0, + panel_rows: 1.0, + } + } + }) +} + +/// Flügeleinteilung auf `[from, to]`: feste Breiten exakt, der Rest gleichmässig. +fn sash_spans(sashes: &[SashIn], from: f64, to: f64) -> Vec<(SashIn, f64, f64)> { + let width = jmax(0.0, to - from); + let mut fixed_sum = 0.0; + let mut auto_count = 0.0; + let fixed = |s: &SashIn| -> Option { + if s.kind == SashKind::Post { + Some(jmax(0.0, or(s.post_width, 0.06))) + } else if s.fixed_width { + Some(jmax(0.0, or(s.width, 0.0))) + } else { + None + } + }; + for s in sashes { + match fixed(s) { + Some(w) => fixed_sum += w, + None => auto_count += 1.0, + } + } + let auto_w = if auto_count > 0.0 { jmax(0.0, (width - fixed_sum) / auto_count) } else { 0.0 }; + let mut cursor = from; + sashes + .iter() + .map(|s| { + let w = fixed(s).unwrap_or(auto_w); + let seg = (*s, cursor, cursor + w); + cursor += w; + seg + }) + .collect() +} + +/// Rahmen-/Sprossen-Riegel, Flügelrahmen, SIA-Symbole, Bänke, Schwelle und Zargen-Umgriff einer +/// Öffnung (`frameMeshesForOpening`). +fn frame_meshes(em: &mut Emitter, o: &OpeningIn, p: &FrameParams, detail: Detail) { + let fine = detail == Detail::Fine; + let medium = detail == Detail::Medium; + let sashes_on = fine || medium; + let detail_bodies = fine || medium; + let fw = p.frame_width; + let (from0, to0, zb0, zt0) = (o.from, o.to, o.z_bottom, o.z_top); + for q in frame_ring_quads(from0, to0, zb0, zt0, fw, p.corner_join, p.has_sill) { + em.plane_quad(&q, p.n_min, p.n_max, Part::Frame); + } + // Schwellenprofil über die ganze Wanddicke. + if detail_bodies && p.draw_threshold_profile { + let strip_h = 0.02; + em.axis_box(from0 + fw, to0 - fw, zb0, zb0 + strip_h, -p.half_thickness, p.half_thickness, Part::Sill); + } + let sash_from = from0 + fw; + let sash_to = to0 - fw; + let sash_bottom = zb0 + if p.has_sill { fw } else { 0.0 }; + let mut sash_top = zt0 - fw; + if p.transom_height > EPS { + let split_z = clamp_range(zt0 - p.transom_height, sash_bottom, sash_top); + em.axis_box(sash_from, sash_to, split_z - fw / 2.0, split_z + fw / 2.0, p.n_min, p.n_max, Part::Frame); + sash_top = split_z - fw / 2.0; + } + if fine { + // Senkrechte Teiler laufen durch, waagrechte Kämpfer-Zeilen dazwischen unterbrochen. + let mut posts: Vec = Vec::new(); + let add_posts = |count: f64, posts: &mut Vec| { + if count <= 1.0 || sash_to - sash_from <= EPS { + return; + } + let cell = (sash_to - sash_from) / count; + let mut i = 1.0; + while i < count.min(MAX_COUNT) { + let center = sash_from + i * cell; + if !posts.iter().any(|c| (c - center).abs() < 1e-4) { + posts.push(center); + } + i += 1.0; + } + }; + add_posts(p.wing_count, &mut posts); + add_posts(p.mullion_cols, &mut posts); + posts.sort_by(|x, y| x.partial_cmp(y).unwrap_or(std::cmp::Ordering::Equal)); + for ¢er in &posts { + em.axis_box(center - fw / 2.0, center + fw / 2.0, sash_bottom, sash_top, p.n_min, p.n_max, Part::Frame); + } + if p.mullion_rows > 1.0 && sash_top - sash_bottom > EPS { + let cell = (sash_top - sash_bottom) / p.mullion_rows; + let mut i = 1.0; + while i < p.mullion_rows.min(MAX_COUNT) { + let center = sash_bottom + i * cell; + let mut from = sash_from; + for post in posts.iter().copied().chain(std::iter::once(sash_to + fw / 2.0)) { + let to = jmin(sash_to, post - fw / 2.0); + if to - from > EPS { + em.axis_box(from, to, center - fw / 2.0, center + fw / 2.0, p.n_min, p.n_max, Part::Frame); + } + from = post + fw / 2.0; + } + i += 1.0; + } + } + } + // Flügelrahmen je öffenbarem Flügel (zurückgesetztes, flacheres Quer-Band) + SIA-Symbole. + if sashes_on && !p.sashes.is_empty() && sash_to - sash_from > EPS && sash_top - sash_bottom > EPS { + let segs = sash_spans(&p.sashes, sash_from, sash_to); + let sfw = fw * 0.7; + let sash_front_n = p.n_max - 0.005; + let sash_back_n = jmax(p.n_min, p.n_max - 0.055); + let glass_front_n = p.n_max - 0.02; + let sym_back_n = glass_front_n; + let sym_front_n = glass_front_n + 0.003; + let symbol = |em: &mut Emitter, u0: f64, h0: f64, u1: f64, h1: f64| { + em.plane_box(u0, h0, u1, h1, SYMBOL_HALF_WIDTH, sym_front_n, sym_back_n, Part::Symbol); + }; + for (s, cf, ct) in segs { + if s.kind != SashKind::Sash || s.opening == SashOpening::None || s.opening == SashOpening::Fixed { + continue; + } + let bz = sash_bottom; + let tz = sash_top; + if ct - cf <= EPS || tz - bz <= EPS { + continue; + } + for q in frame_ring_quads(cf, ct, bz, tz, sfw, p.corner_join, true) { + em.plane_quad(&q, sash_back_n, sash_front_n, Part::Frame); + } + if !fine { + continue; + } + let g_a = cf + sfw; + let g_b = ct - sfw; + let gbz = bz + sfw; + let gtz = tz - sfw; + if g_b - g_a <= EPS || gtz - gbz <= EPS { + continue; + } + let kind = s.opening; + if kind == SashOpening::Turn || kind == SashOpening::TurnTilt { + let apex_u = if s.hinge_left { g_a } else { g_b }; + let apex_h = (gbz + gtz) / 2.0; + let far_u = if s.hinge_left { g_b } else { g_a }; + symbol(em, far_u, gbz, apex_u, apex_h); + symbol(em, far_u, gtz, apex_u, apex_h); + } + if kind == SashOpening::Tilt || kind == SashOpening::TurnTilt { + let apex_u = (g_a + g_b) / 2.0; + symbol(em, g_a, gbz, apex_u, gtz); + symbol(em, g_b, gbz, apex_u, gtz); + } + if kind == SashOpening::Slide { + let zc = (gbz + gtz) / 2.0; + let tail = if s.hinge_left { g_a } else { g_b }; + let head = if s.hinge_left { g_b } else { g_a }; + let barb = (head - tail) * 0.22; + symbol(em, tail, zc, head, zc); + symbol(em, head - barb, gbz + (gtz - gbz) * 0.32, head, zc); + symbol(em, head - barb, gbz + (gtz - gbz) * 0.68, head, zc); + } + } + } + // Fensterbank aussen (Bank + Tropfkante). + if detail_bodies && p.draw_sill { + let (ov, proj, under, bank_h, drip_h, drip_w) = (0.03, 0.04, 0.02, 0.04, 0.02, 0.02); + let outer_n = p.half_thickness; + let bank_top = zb0; + let bank_bottom = bank_top - bank_h; + em.axis_box(from0 - ov, to0 + ov, bank_bottom, bank_top, outer_n - under, outer_n + proj, Part::Sill); + em.axis_box(from0 - ov, to0 + ov, bank_bottom - drip_h, bank_bottom, outer_n + proj - drip_w, outer_n + proj, Part::Sill); + } + // Innen-Fensterbank (ohne Tropfkante). + if detail_bodies && p.draw_interior_sill { + let (ov, proj, under, bank_h) = (0.03, 0.04, 0.02, 0.04); + let inner_n = -p.half_thickness; + let bank_top = zb0; + let bank_bottom = bank_top - bank_h; + em.axis_box(from0 - ov, to0 + ov, bank_bottom, bank_top, inner_n - proj, inner_n + under, Part::Sill); + } + // Tür-Zarge mit Umgriff vor beiden Wandflächen. + if detail_bodies && p.zarge_cladding { + let (proud, ext, cas_w) = (0.013, 0.02, fw); + for sign in [1.0, -1.0] { + let face_n = sign * p.half_thickness; + let n_a = face_n; + let n_b = face_n + sign * proud; + em.axis_box(from0 - ext, from0 + cas_w, zb0, zt0 + ext, n_a, n_b, Part::Frame); + em.axis_box(to0 - cas_w, to0 + ext, zb0, zt0 + ext, n_a, n_b, Part::Frame); + em.axis_box(from0 - ext, to0 + ext, zt0 - cas_w, zt0 + ext, n_a, n_b, Part::Frame); + } + } +} + +/// Glasscheibe(n) einer typisierten Öffnung je Z-Band (Hauptfeld, Oberlicht), nahe der +/// Aussenfläche, Mehrfachverglasung mit Luftraum nach innen (`glassPanesForOpening`). +fn glass_panes(em: &mut Emitter, o: &OpeningIn, p: &FrameParams) { + let fw = p.frame_width; + let sash_from = o.from + fw; + let sash_to = o.to - fw; + let sash_bottom = o.z_bottom + if p.has_sill { fw } else { 0.0 }; + let sash_top_full = o.z_top - fw; + let glass_thick = GLASS_HALF_THICK * 2.0; + let panes = jmax(1.0, jmin(3.0, js_round(p.glazing_panes))); + let push = |em: &mut Emitter, z_bottom: f64, z_top: f64| { + let mut n1 = p.n_max - 0.02; + let mut k = 0.0; + while k < panes { + let n0 = jmax(p.n_min, n1 - glass_thick); + if n1 - n0 <= EPS { + break; + } + em.axis_box(sash_from, sash_to, z_bottom, z_top, n0, n1, Part::Glass); + n1 = n0 - GLASS_PANE_GAP; + if n1 <= p.n_min { + break; + } + k += 1.0; + } + }; + let frac = jmax(0.05, jmin(1.0, p.glazed_fraction)); + let glazed_bottom = |b: f64, t: f64| t - frac * (t - b); + if p.transom_height > EPS { + let split_z = clamp_range(o.z_top - p.transom_height, sash_bottom, sash_top_full); + let main_top = split_z - fw / 2.0; + if p.glazed { + push(em, glazed_bottom(sash_bottom, main_top), main_top); + } + push(em, split_z + fw / 2.0, sash_top_full); + } else if p.glazed { + push(em, glazed_bottom(sash_bottom, sash_top_full), sash_top_full); + } +} + +/// Türblatt im Hauptfeld (Vollblatt bzw. blinder Rest unter der Teilverglasung, `doorLeafPanels`). +fn door_leaf(em: &mut Emitter, o: &OpeningIn, p: &FrameParams) { + let fw = p.frame_width; + let leaf_from = o.from + fw; + let leaf_to = o.to - fw; + let leaf_bottom = o.z_bottom + if p.has_sill { fw } else { 0.0 }; + let mut field_top = o.z_top - fw; + if p.transom_height > EPS { + let split_z = clamp_range(o.z_top - p.transom_height, leaf_bottom, field_top); + field_top = split_z - fw / 2.0; + } + let frac = if p.glazed { jmax(0.05, jmin(1.0, p.glazed_fraction)) } else { 0.0 }; + let leaf_top = field_top - frac * (field_top - leaf_bottom); + if leaf_top - leaf_bottom <= EPS || leaf_to - leaf_from <= EPS { + return; + } + let n1 = p.n_max - 0.02 + DOOR_LEAF_THICK / 2.0; + let n0 = jmax(p.n_min, n1 - DOOR_LEAF_THICK); + if p.panelled { + kassette(em, leaf_from, leaf_to, leaf_bottom, leaf_top, n0, n1, p); + return; + } + em.axis_box(leaf_from, leaf_to, leaf_bottom, leaf_top, n0, n1, Part::DoorLeaf); +} + +/// Kassettentür-Blatt: Rahmen + Trennstege in voller Blattdicke, Felder dünner und vertieft. +#[allow(clippy::too_many_arguments)] +fn kassette(em: &mut Emitter, leaf_from: f64, leaf_to: f64, leaf_bottom: f64, leaf_top: f64, n0: f64, n1: f64, p: &FrameParams) { + let push = |em: &mut Emitter, from: f64, to: f64, zb: f64, zt: f64, a: f64, b: f64| { + em.axis_box(from, to, zb, zt, a, b, Part::DoorLeaf); + }; + let cols = p.panel_cols; + let rows = p.panel_rows; + let sw = jmin(jmin(PANEL_STILE_WIDTH, (leaf_to - leaf_from) / (2.0 * cols)), (leaf_top - leaf_bottom) / (2.0 * rows)); + if sw <= EPS { + push(em, leaf_from, leaf_to, leaf_bottom, leaf_top, n0, n1); + return; + } + push(em, leaf_from, leaf_to, leaf_bottom, leaf_bottom + sw, n0, n1); + push(em, leaf_from, leaf_to, leaf_top - sw, leaf_top, n0, n1); + push(em, leaf_from, leaf_from + sw, leaf_bottom, leaf_top, n0, n1); + push(em, leaf_to - sw, leaf_to, leaf_bottom, leaf_top, n0, n1); + let cell_w = (leaf_to - leaf_from) / cols; + let cell_h = (leaf_top - leaf_bottom) / rows; + let n_cols = cols.min(MAX_COUNT); + let n_rows = rows.min(MAX_COUNT); + let mut c = 1.0; + while c < n_cols { + let x = leaf_from + c * cell_w; + push(em, x - sw / 2.0, x + sw / 2.0, leaf_bottom, leaf_top, n0, n1); + c += 1.0; + } + let mut r = 1.0; + while r < n_rows { + let y = leaf_bottom + r * cell_h; + push(em, leaf_from, leaf_to, y - sw / 2.0, y + sw / 2.0, n0, n1); + r += 1.0; + } + let n0p = n0 + PANEL_RECESS; + let n1p = jmax(n0p + 0.004, n1 - PANEL_RECESS); + let mut r = 0.0; + while r < n_rows { + let mut c = 0.0; + while c < n_cols { + let fx0 = leaf_from + c * cell_w + sw / 2.0; + let fx1 = leaf_from + (c + 1.0) * cell_w - sw / 2.0; + let fy0 = leaf_bottom + r * cell_h + sw / 2.0; + let fy1 = leaf_bottom + (r + 1.0) * cell_h - sw / 2.0; + if !(fx1 - fx0 <= EPS || fy1 - fy0 <= EPS) { + push(em, fx0, fx1, fy0, fy1, n0p, n1p); + } + c += 1.0; + } + r += 1.0; + } +} + +/// Alle Öffnungs-Quader der Wände in der Reihenfolge der früheren TS-Fassung: erst Glas/Blätter +/// aller Wände (`emitOpeningGlass`), dann Rahmen (`emitOpeningFrames`, nicht bei grob), dann +/// Rollladenkästen (`emitOpeningShading`, nicht bei grob). +pub fn opening_meshes(walls: &[WallIn], detail: Detail) -> Vec { + let mut out = Vec::new(); + let open = |o: &OpeningIn| !(o.z_top - o.z_bottom <= EPS); + for w in walls { + let mut em = Emitter { axis: Axis::of(w.start, w.end), out: &mut out }; + for o in w.openings.iter().filter(|o| open(o)) { + let params = resolve_frame(o); + if !o.door { + match params { + // Kein Typ: Alt-Verhalten (eine Vollscheibe mittig in der Wand). + None => em.axis_box(o.from, o.to, o.z_bottom, o.z_top, -GLASS_HALF_THICK, GLASS_HALF_THICK, Part::Glass), + Some(p) => glass_panes(&mut em, o, &p), + } + } else if let Some(p) = params { + door_leaf(&mut em, o, &p); + glass_panes(&mut em, o, &p); + } + } + } + if detail == Detail::Coarse { + return out; + } + for w in walls { + let mut em = Emitter { axis: Axis::of(w.start, w.end), out: &mut out }; + for o in w.openings.iter().filter(|o| open(o)) { + if let Some(p) = resolve_frame(o) { + frame_meshes(&mut em, o, &p, detail); + } + } + } + for w in walls { + let mut em = Emitter { axis: Axis::of(w.start, w.end), out: &mut out }; + for o in w.openings.iter().filter(|o| open(o)) { + let Some(TypeIn { kind: KindIn::Window(wt), .. }) = &o.ty else { continue }; + let Some([bw, bh, bd]) = wt.shading else { continue }; + let Some(p) = resolve_frame(o) else { continue }; + let h = jmax(0.0, bh); + let d = jmax(0.0, bd); + if h <= EPS || d <= EPS { + continue; + } + let span = if bw > 0.0 { bw } else { o.to - o.from }; + let center = (o.from + o.to) / 2.0; + let from = center - span / 2.0; + let to = center + span / 2.0; + let n_outer = p.n_max; + em.axis_box(from, to, o.z_top, o.z_top + h, n_outer, n_outer + d, Part::Shading); + } + } + out +} + +// ── Flache Kodierung ───────────────────────────────────────────────────────── +// +// Eingabe: `[detail (0 grob, 1 mittel, 2 fein, sonst andere), nWände, Wand…]` +// Wand = `sx, sy, ex, ey, nÖffnungen, Öffnung…` +// Öffnung = `from, to, zBottom, zTop, istTür, Wanddicke, typisiert (0/1)[, Typ]` +// Typ = `frameDepth, insetFromFace, insetInnen, Eckstoss (0 vertikal, 1 horizontal, 2 Gehrung), +// frameWidth, transomHeight,` dann +// Tür: `threshold, leafCount, leafStyle (0 glatt, 1 glas, 2 kassette), glazingRatio, zarge, +// panelCols, panelRows` +// Fenster: `glazingPanes, mullionRows, mullionCols, sillBoard (0 aussen/fehlt, 1 keine, +// 2 innen, 3 beide), Rollladen (0/1), Breite, Höhe, Tiefe, Flügelzahl-Default, +// Öffnungsart-Default, nFlügel, Flügel…` +// Flügel = `Art (0 Flügel, 1 Pfosten, 2 andere), festeBreite, width, postWidth, Öffnungsart, +// BandLinks` +// Öffnungsart: 0 fehlt, 1 dreh, 2 kipp, 3 drehkipp, 4 fest, 5 schiebe, 6 andere. NaN = fehlt. +// Ausgabe: `[nQuader, (Bauteil-Klasse, 24 Koordinaten)…]`. Kaputte Eingabe ⇒ `[0]`. + +fn opening_kind(v: f64) -> SashOpening { + match v as i64 { + 0 if v == 0.0 => SashOpening::None, + 1 => SashOpening::Turn, + 2 => SashOpening::Tilt, + 3 => SashOpening::TurnTilt, + 4 => SashOpening::Fixed, + 5 => SashOpening::Slide, + _ if v.is_nan() => SashOpening::None, + _ => SashOpening::Other, + } +} + +fn flag(r: &mut Reader) -> Option { + Some(r.num()? != 0.0) +} + +fn decode_type(r: &mut Reader, door: bool) -> Option { + let frame_depth = r.num()?; + let inset_from_face = r.num()?; + let inset_inner = flag(r)?; + let corner_join = match r.num()? as i64 { + 1 => CornerJoin::Horizontal, + 2 => CornerJoin::Mitre, + _ => CornerJoin::Vertical, + }; + let frame_width = r.num()?; + let transom_height = r.num()?; + let kind = if door { + KindIn::Door(DoorTypeIn { + threshold: flag(r)?, + leaf_count: r.num()?, + leaf_style: match r.num()? as i64 { + 1 => LeafStyle::Glass, + 2 => LeafStyle::Panelled, + _ => LeafStyle::Plain, + }, + glazing_ratio: r.num()?, + zarge: flag(r)?, + panel_cols: r.num()?, + panel_rows: r.num()?, + }) + } else { + let glazing_panes = r.num()?; + let mullion_rows = r.num()?; + let mullion_cols = r.num()?; + let sill_board = match r.num()? as i64 { + 1 => SillBoard::None, + 2 => SillBoard::Inner, + 3 => SillBoard::Both, + _ => SillBoard::Outer, + }; + let create = flag(r)?; + let shading_box = [r.num()?, r.num()?, r.num()?]; + let default_wing_count = r.num()?; + let default_opening = opening_kind(r.num()?); + let n = r.count()?; + let mut sashes = Vec::with_capacity(n.min(1024)); + for _ in 0..n { + sashes.push(SashIn { + kind: match r.num()? as i64 { + 0 => SashKind::Sash, + 1 => SashKind::Post, + _ => SashKind::Other, + }, + fixed_width: flag(r)?, + width: r.num()?, + post_width: r.num()?, + opening: opening_kind(r.num()?), + hinge_left: flag(r)?, + }); + } + KindIn::Window(WindowTypeIn { + glazing_panes, + mullion_rows, + mullion_cols, + sill_board, + sashes, + default_wing_count, + default_opening, + shading: if create { Some(shading_box) } else { None }, + }) + }; + Some(TypeIn { frame_depth, inset_from_face, inset_inner, corner_join, frame_width, transom_height, kind }) +} + +fn decode(buf: &[f64]) -> Option<(Vec, Detail)> { + let mut r = Reader::new(buf); + let detail = match r.num()? { + d if d == 0.0 => Detail::Coarse, + d if d == 1.0 => Detail::Medium, + d if d == 2.0 => Detail::Fine, + _ => Detail::Other, + }; + let n = r.count()?; + let mut walls = Vec::with_capacity(n.min(1 << 16)); + for _ in 0..n { + let start = [r.num()?, r.num()?]; + let end = [r.num()?, r.num()?]; + let n_ops = r.count()?; + let mut openings = Vec::with_capacity(n_ops.min(1024)); + for _ in 0..n_ops { + let (from, to, z_bottom, z_top) = (r.num()?, r.num()?, r.num()?, r.num()?); + let door = flag(&mut r)?; + let wall_thickness = r.num()?; + let ty = if flag(&mut r)? { Some(decode_type(&mut r, door)?) } else { None }; + // Unsinn (NaN/∞ in Lage oder Wanddicke): Öffnung auslassen. + if [from, to, z_bottom, z_top, wall_thickness].iter().all(|v| v.is_finite()) { + openings.push(OpeningIn { from, to, z_bottom, z_top, door, wall_thickness, ty }); + } + } + if [start[0], start[1], end[0], end[1]].iter().all(|v| v.is_finite()) { + walls.push(WallIn { start, end, openings }); + } + } + Some((walls, detail)) +} + +/// Flache Bindung (Kodierung s. oben); nie ein Panic. +pub fn opening_meshes_flat(buf: &[f64]) -> Vec { + let Some((walls, detail)) = decode(buf) else { return vec![0.0] }; + let meshes = opening_meshes(&walls, detail); + let mut out = Vec::with_capacity(1 + meshes.len() * 25); + out.push(meshes.len() as f64); + for m in &meshes { + out.push(m.part as i32 as f64); + out.extend_from_slice(&m.positions); + } + out +} + +/// Flache Bindung von [`frame_ring_quads`]: `[n, (u, h) × 4 …]`; Eckstoss wie oben. +pub fn frame_ring_quads_flat(from: f64, to: f64, z_b: f64, z_t: f64, w: f64, join: f64, bottom: bool) -> Vec { + let join = match join as i64 { + 1 => CornerJoin::Horizontal, + 2 => CornerJoin::Mitre, + _ => CornerJoin::Vertical, + }; + let qs = frame_ring_quads(from, to, z_b, z_t, w, join, bottom); + let mut out = vec![qs.len() as f64]; + for q in qs { + for [u, h] in q { + out.push(u); + out.push(h); + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + fn close(a: f64, b: f64) -> bool { + (a - b).abs() < 1e-9 + } + + fn window_type(sill: SillBoard) -> TypeIn { + TypeIn { + frame_depth: f64::NAN, + inset_from_face: f64::NAN, + inset_inner: false, + corner_join: CornerJoin::Vertical, + frame_width: f64::NAN, + transom_height: f64::NAN, + kind: KindIn::Window(WindowTypeIn { + glazing_panes: 1.0, + mullion_rows: f64::NAN, + mullion_cols: f64::NAN, + sill_board: sill, + sashes: vec![], + default_wing_count: 1.0, + default_opening: SashOpening::TurnTilt, + shading: None, + }), + } + } + + fn door_type(style: LeafStyle) -> TypeIn { + TypeIn { + frame_depth: f64::NAN, + inset_from_face: f64::NAN, + inset_inner: false, + corner_join: CornerJoin::Vertical, + frame_width: f64::NAN, + transom_height: f64::NAN, + kind: KindIn::Door(DoorTypeIn { + threshold: false, + leaf_count: 1.0, + leaf_style: style, + glazing_ratio: f64::NAN, + zarge: true, + panel_cols: f64::NAN, + panel_rows: f64::NAN, + }), + } + } + + fn wall(op: OpeningIn) -> WallIn { + WallIn { start: [0.0, 0.0], end: [5.0, 0.0], openings: vec![op] } + } + + fn op(door: bool, ty: Option) -> OpeningIn { + OpeningIn { from: 1.0, to: 2.2, z_bottom: if door { 0.0 } else { 0.9 }, z_top: 2.1, door, wall_thickness: 0.3, ty } + } + + fn count(ms: &[BoxMesh], part: Part) -> usize { + ms.iter().filter(|m| m.part == part).count() + } + + fn bbox(m: &BoxMesh) -> [f64; 6] { + let mut b = [f64::INFINITY, f64::INFINITY, f64::INFINITY, -f64::INFINITY, -f64::INFINITY, -f64::INFINITY]; + for i in 0..8 { + for k in 0..3 { + b[k] = b[k].min(m.positions[i * 3 + k]); + b[k + 3] = b[k + 3].max(m.positions[i * 3 + k]); + } + } + b + } + + #[test] + fn rahmenring_je_eckstoss_ohne_ueberlappung() { + let area = |q: &Quad| { + let r = [q[0], q[1], q[3], q[2]]; + let mut a = 0.0; + for i in 0..4 { + a += r[i][0] * r[(i + 1) % 4][1] - r[(i + 1) % 4][0] * r[i][1]; + } + a.abs() / 2.0 + }; + for join in [CornerJoin::Vertical, CornerJoin::Horizontal, CornerJoin::Mitre] { + let qs = frame_ring_quads(0.0, 1.2, 0.9, 2.1, 0.06, join, true); + assert_eq!(qs.len(), 4); + let total: f64 = qs.iter().map(area).sum(); + assert!(close(total, 1.2 * 1.2 - 1.08 * 1.08)); + assert_eq!(frame_ring_quads(0.0, 1.0, 0.0, 2.1, 0.06, join, false).len(), 3); + } + // Zu klein: ein Vollprofil. + assert_eq!(frame_ring_quads(0.0, 0.1, 0.0, 1.0, 0.06, CornerJoin::Vertical, true).len(), 1); + } + + #[test] + fn untypisiertes_fenster_eine_scheibe_mittig() { + let ms = opening_meshes(&[wall(op(false, None))], Detail::Fine); + assert_eq!(ms.len(), 1); + assert_eq!(ms[0].part, Part::Glass); + let b = bbox(&ms[0]); + assert!(close(b[0], 1.0) && close(b[3], 2.2)); + assert!(close(b[1], -0.004) && close(b[4], 0.004)); + assert!(close(b[2], 0.9) && close(b[5], 2.1)); + // Untypisierte Tür: offenes Loch. + assert!(opening_meshes(&[wall(op(true, None))], Detail::Fine).is_empty()); + } + + #[test] + fn typisiertes_fenster_je_detailgrad() { + let w = [wall(op(false, Some(window_type(SillBoard::Outer))))]; + let grob = opening_meshes(&w, Detail::Coarse); + assert_eq!(grob.len(), 1); + assert_eq!(count(&grob, Part::Glass), 1); + let mittel = opening_meshes(&w, Detail::Medium); + // Glas + 4 Blendrahmen + 4 Flügelrahmen + Bank + Tropfkante. + assert_eq!(count(&mittel, Part::Frame), 8); + assert_eq!(count(&mittel, Part::Sill), 2); + assert_eq!(count(&mittel, Part::Symbol), 0); + let fein = opening_meshes(&w, Detail::Fine); + // Dreh-Kipp: 2 + 2 Symbol-Diagonalen. + assert_eq!(count(&fein, Part::Symbol), 4); + // Scheibe nahe der Aussenfläche: Rahmen n ∈ [0.08, 0.15], Glas n ∈ [0.122, 0.13]; + // rechte Normale (0, −1) ⇒ y = −n. + let g = bbox(&fein[0]); + assert!(close(g[1], -0.13) && close(g[4], -0.122)); + } + + #[test] + fn mehrfachverglasung_und_innenbank() { + let mut t = window_type(SillBoard::Both); + if let KindIn::Window(w) = &mut t.kind { + w.glazing_panes = 3.0; + w.shading = Some([0.0, 0.25, 0.2]); + } + let ms = opening_meshes(&[wall(op(false, Some(t)))], Detail::Fine); + assert_eq!(count(&ms, Part::Glass), 3); + assert_eq!(count(&ms, Part::Sill), 3); + assert_eq!(count(&ms, Part::Shading), 1); + let s = bbox(ms.iter().find(|m| m.part == Part::Shading).unwrap()); + assert!(close(s[0], 1.0) && close(s[3], 2.2) && close(s[2], 2.1) && close(s[5], 2.35)); + // Rollladen nie bei grob. + let mut t2 = window_type(SillBoard::Outer); + if let KindIn::Window(w) = &mut t2.kind { + w.shading = Some([0.0, 0.25, 0.2]); + } + assert_eq!(count(&opening_meshes(&[wall(op(false, Some(t2)))], Detail::Coarse), Part::Shading), 0); + } + + #[test] + fn tueren_blatt_kassette_und_zarge() { + let glatt = opening_meshes(&[wall(op(true, Some(door_type(LeafStyle::Plain))))], Detail::Fine); + assert_eq!(count(&glatt, Part::DoorLeaf), 1); + assert_eq!(count(&glatt, Part::Glass), 0); + // Zarge: 3 Ringglieder + 6 Bekleidungen. + assert_eq!(count(&glatt, Part::Frame), 9); + let kas = opening_meshes(&[wall(op(true, Some(door_type(LeafStyle::Panelled))))], Detail::Fine); + // 4 Rahmen + 1 Steg senkrecht + 2 waagrecht + 2×3 Felder. + assert_eq!(count(&kas, Part::DoorLeaf), 13); + let glas = opening_meshes(&[wall(op(true, Some(door_type(LeafStyle::Glass))))], Detail::Fine); + assert_eq!(count(&glas, Part::Glass), 1); + assert_eq!(count(&glas, Part::DoorLeaf), 0); + } + + #[test] + fn fluegeltabelle_mit_pfosten_und_schiebe() { + let mut t = window_type(SillBoard::None); + if let KindIn::Window(w) = &mut t.kind { + let s = |kind, opening, hinge_left| SashIn { kind, fixed_width: false, width: f64::NAN, post_width: f64::NAN, opening, hinge_left }; + w.sashes = vec![s(SashKind::Sash, SashOpening::Slide, false), s(SashKind::Post, SashOpening::None, true), s(SashKind::Sash, SashOpening::Fixed, true)]; + } + let ms = opening_meshes(&[wall(op(false, Some(t)))], Detail::Fine); + // Schiebe-Pfeil: 3 Striche; fester Flügel ohne Flügelrahmen. + assert_eq!(count(&ms, Part::Symbol), 3); + assert_eq!(count(&ms, Part::Sill), 0); + let spans = sash_spans(&[SashIn { kind: SashKind::Post, fixed_width: false, width: f64::NAN, post_width: f64::NAN, opening: SashOpening::None, hinge_left: true }], 0.0, 1.0); + assert!(close(spans[0].2 - spans[0].1, 0.06)); + } + + #[test] + fn bitgleiche_hilfen() { + assert!(jmax(-0.0, 0.0).is_sign_positive()); + assert!(jmin(0.0, -0.0).is_sign_negative()); + assert!(jmax(1.0, f64::NAN).is_nan()); + assert_eq!(clamp_range(5.0, 0.0, 1.0), 1.0); + let (a, b) = frame_normal_range(0.15, 0.07, 0.0, false); + assert!(close(a, 0.08) && close(b, 0.15)); + let (a, b) = frame_normal_range(0.15, 0.07, 0.0, true); + assert!(close(a, -0.15) && close(b, -0.08)); + } + + #[test] + fn flach_hin_und_zurueck() { + // Fenster ohne Typ in Wand (0,0)→(5,0), fein. + let buf = [2.0, 1.0, 0.0, 0.0, 5.0, 0.0, 1.0, 1.0, 2.2, 0.9, 2.1, 0.0, 0.3, 0.0]; + let out = opening_meshes_flat(&buf); + assert_eq!(out.len(), 1 + 25); + assert_eq!(out[0], 1.0); + assert_eq!(out[1], Part::Glass as i32 as f64); + let ring = frame_ring_quads_flat(0.0, 1.0, 0.0, 1.0, 0.1, 0.0, true); + assert_eq!(ring[0], 4.0); + assert_eq!(&ring[1..9], &[0.0, 0.0, 0.1, 0.0, 0.0, 1.0, 0.1, 1.0]); + } + + #[test] + fn unsinn_ohne_panic() { + assert_eq!(opening_meshes_flat(&[]), vec![0.0]); + assert_eq!(opening_meshes_flat(&[f64::NAN]), vec![0.0]); + assert_eq!(opening_meshes_flat(&[2.0, 1e300]), vec![0.0]); + assert_eq!(opening_meshes_flat(&[2.0, 1.0, 0.0, 0.0, 5.0]), vec![0.0]); + // Nullwand, NaN-Lagen, riesige Zählwerte, negative Masse. + let mut buf = vec![2.0, 2.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 2.0, 0.0, 2.0, 0.0, 0.3, 0.0]; + buf.extend([f64::NAN, 0.0, 0.0, 0.0, 1.0, 1.0, 2.0, 0.0, 2.0, 0.0, 0.3, 1.0]); + // Fenster-Typ mit Unsinn: riesige Sprossen-/Flügelzahlen, negative Rahmenbreite. + buf.extend([1e9, -5.0, 0.0, 7.0, -0.5, f64::INFINITY, 1e12, 1e12, 1e12, 9.0, 1.0, f64::NAN, -1.0, 1.0, 1e15, 3.0, 0.0]); + let out = opening_meshes_flat(&buf); + assert!(out[0] >= 0.0); + let mut big = vec![2.0, 1.0, 0.0, 0.0, 5.0, 0.0, 1.0, 1.0, 4.0, 0.0, 2.0, 1.0, 0.3, 1.0]; + big.extend([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1e12, 2.0, f64::NAN, 1.0, 1e12, 1e12]); + assert!(opening_meshes_flat(&big)[0] >= 0.0); + let _ = frame_ring_quads_flat(f64::NAN, f64::INFINITY, -1.0, 1.0, -3.0, 9.0, false); + } +} diff --git a/src-tauri/core/src/wall_mesh_cut.rs b/src-tauri/core/src/wall_mesh_cut.rs new file mode 100644 index 00000000..0514fd44 --- /dev/null +++ b/src-tauri/core/src/wall_mesh_cut.rs @@ -0,0 +1,399 @@ +//! Wand-Mesh MIT echtem Loch-Ausschnitt (Fenster/Türen) für die Datei-Exporte (STL/OBJ/IFC): +//! aus EINEM Wandband (`RWall`: Achse, Dicke, UK, Höhe, rechteckige Löcher) entsteht das +//! Dreiecksnetz mit ausgestanzten Öffnungen samt Laibungsflächen — dieselbe Zerlegung wie +//! `render3d/src/mesh.rs::extrude_layer_segment_with_holes`, aber ohne Gehrung (die Bänder aus +//! [`crate::wall_bands`] sind an den Enden schon gekürzt). Portiert aus `src/plan/wallMeshCut.ts`. +//! +//! Achsen: Modell (x, y) → Welt (x, Höhe, y), Y-up. Jedes Dreieck hat drei eigene Ecken; die +//! Indizes sind daher fortlaufend `0, 1, 2, …` und werden nicht übertragen. +//! +//! Bitgleich zur früheren TS-Fassung (gleiche Operationsreihenfolge, `Math.hypot` wie V8). + +use crate::flat_read::Reader; +use crate::joins::js_hypot; +use crate::openings3d::{jmax, jmin}; +use kernel2d::{add, left_normal, scale, Vec2}; + +/// Rundungs-/Entartungsschwelle (wie `openings::MIN_SPAN` in render3d). +const MIN_SPAN: f64 = 1e-4; + +type V3 = [f64; 3]; + +/// Ein Wandband mit Löchern `[from, to, zBottom, zTop]` (Achs-Meter ab Start, absolute Höhen). +#[derive(Clone, Debug, PartialEq)] +pub struct CutWall { + pub start: [f64; 2], + pub end: [f64; 2], + pub thickness: f64, + pub base_elevation: f64, + pub height: f64, + pub holes: Vec<[f64; 4]>, +} + +/// `Math.hypot(x, y, z)` wie V8 (Skalierung mit dem Maximum, kompensierte Summe). +fn js_hypot3(x: f64, y: f64, z: f64) -> f64 { + let v = [x.abs(), y.abs(), z.abs()]; + if v.iter().any(|a| a.is_infinite()) { + return f64::INFINITY; + } + if v.iter().any(|a| a.is_nan()) { + return f64::NAN; + } + let max = v[0].max(v[1]).max(v[2]); + if max == 0.0 { + return 0.0; + } + let mut sum = 0.0; + let mut comp = 0.0; + for a in v { + let n = a / max; + let summand = n * n - comp; + let pre = sum + summand; + comp = (pre - sum) - summand; + sum = pre; + } + sum.sqrt() * max +} + +fn cross(a: V3, b: V3) -> V3 { + [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]] +} + +fn sub3(a: V3, b: V3) -> V3 { + [a[0] - b[0], a[1] - b[1], a[2] - b[2]] +} + +/// Aussen-Normale eines planaren Quads über die Ecken a, b, d (`mesh.rs::quad_normal`). +fn quad_normal(a: V3, b: V3, d: V3) -> V3 { + let c = cross(sub3(b, a), sub3(d, a)); + let l = js_hypot3(c[0], c[1], c[2]); + // `Math.max(len, 1e-9)` (NaN bleibt NaN). + let l = if l.is_nan() { l } else { l.max(1e-9) }; + [c[0] / l, c[1] / l, c[2] / l] +} + +/// Dreieck mit Wicklung nach `want` (`mesh.rs::push_tri_oriented`). +fn push_tri(out: &mut Vec, a: V3, b: V3, c: V3, want: V3) { + let g = cross(sub3(b, a), sub3(c, a)); + let dot = g[0] * want[0] + g[1] * want[1] + g[2] * want[2]; + let (v1, v2) = if dot < 0.0 { (c, b) } else { (b, c) }; + out.extend_from_slice(&[a[0], a[1], a[2], v1[0], v1[1], v1[2], v2[0], v2[1], v2[2]]); +} + +fn push_quad(out: &mut Vec, a: V3, b: V3, c: V3, d: V3, want: V3) { + push_tri(out, a, b, c, want); + push_tri(out, a, c, d, want); +} + +fn by_value(a: &f64, b: &f64) -> std::cmp::Ordering { + a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal) +} + +/// Rechteck `[u_lo,u_hi] × [z_lo,z_hi]` MINUS `holes` als disjunkte Teilrechtecke +/// (Koordinaten-Kompression, `mesh.rs::solid_subrects`). +pub fn solid_subrects(u_lo: f64, u_hi: f64, z_lo: f64, z_hi: f64, holes: &[[f64; 4]]) -> Vec<[f64; 4]> { + let sort_dedup = |mut v: Vec| -> Vec { + v.sort_by(by_value); + let mut out: Vec = Vec::with_capacity(v.len()); + for x in v { + match out.last() { + Some(&l) if !((x - l).abs() > MIN_SPAN) => {} + _ => out.push(x), + } + } + out + }; + let mut us = vec![u_lo, u_hi]; + let mut zs = vec![z_lo, z_hi]; + for h in holes { + us.extend([h[0], h[1]]); + zs.extend([h[2], h[3]]); + } + let us = sort_dedup(us); + let zs = sort_dedup(zs); + let mut out = Vec::new(); + for i in 0..us.len().saturating_sub(1) { + let (ua, ub) = (us[i], us[i + 1]); + if ub - ua <= MIN_SPAN { + continue; + } + for j in 0..zs.len().saturating_sub(1) { + let (za, zb) = (zs[j], zs[j + 1]); + if zb - za <= MIN_SPAN { + continue; + } + let cu = (ua + ub) * 0.5; + let cz = (za + zb) * 0.5; + let in_hole = holes.iter().any(|h| cu > h[0] && cu < h[1] && cz > h[2] && cz < h[3]); + if !in_hole { + out.push([ua, ub, za, zb]); + } + } + } + out +} + +/// `[lo, hi]` minus die (ggf. überlappenden) `gaps` (`mesh.rs::subtract_intervals`). Bewusst +/// nicht `wall_bands::subtract_spans`: andere Randregeln, das Ergebnis soll bitgleich bleiben. +fn subtract_intervals(lo: f64, hi: f64, gaps: &[[f64; 2]]) -> Vec<[f64; 2]> { + let mut gs: Vec<[f64; 2]> = gaps.iter().map(|&[a, b]| [jmax(a, lo), jmin(b, hi)]).filter(|&[a, b]| b - a > MIN_SPAN).collect(); + gs.sort_by(|p, q| by_value(&p[0], &q[0])); + let mut out = Vec::new(); + let mut cursor = lo; + for [a, b] in gs { + if a > cursor + MIN_SPAN { + out.push([cursor, a]); + } + cursor = jmax(cursor, b); + } + if hi > cursor + MIN_SPAN { + out.push([cursor, hi]); + } + out +} + +/// Wand-Mesh eines Bandes mit echten Loch-Ausschnitten: Langseiten (Gitter minus Löcher), Deckel/ +/// Boden und Stirnkappen minus randständiger Löcher, Laibungen je Loch. Liefert die Weltpunkte +/// (x, Höhe, y) je Dreieck; entartetes Band ⇒ leer. +pub fn wall_cut_mesh(w: &CutWall) -> Vec { + let mut out = Vec::new(); + let [sx, sy] = w.start; + let dx = w.end[0] - sx; + let dy = w.end[1] - sy; + let length = js_hypot(dx, dy); + if length < 1e-9 || w.height <= 1e-9 || w.thickness <= 1e-9 { + return out; + } + let ux = dx / length; + let uy = dy / length; + let n = left_normal(Vec2 { x: ux, y: uy }); + let y0 = w.base_elevation; + let y1 = w.base_elevation + w.height; + let off_a = w.thickness / 2.0; + let off_b = -w.thickness / 2.0; + // Planpunkt bei Achsen-Position `a` und Dicken-Versatz `o`, in die Welt (x, y, Planz). + let at = |a: f64, o: f64, y: f64| -> V3 { + let g = add(Vec2 { x: sx + ux * a, y: sy + uy * a }, scale(n, o)); + [g.x, y, g.y] + }; + + let hs: Vec<[f64; 4]> = w + .holes + .iter() + .map(|h| [jmax(h[0], 0.0), jmin(h[1], length), jmax(h[2], y0), jmin(h[3], y1)]) + .filter(|h| h[1] - h[0] > MIN_SPAN && h[3] - h[2] > MIN_SPAN) + .collect(); + + // Langseiten (+n / −n). + let np = [n.x, 0.0, n.y]; + let nn = [-n.x, 0.0, -n.y]; + for [ua, ub, za, zb] in solid_subrects(0.0, length, y0, y1, &hs) { + push_quad(&mut out, at(ua, off_a, za), at(ub, off_a, za), at(ub, off_a, zb), at(ua, off_a, zb), np); + push_quad(&mut out, at(ua, off_b, za), at(ub, off_b, za), at(ub, off_b, zb), at(ua, off_b, zb), nn); + } + + // Deckel / Boden. + let top_gaps: Vec<[f64; 2]> = hs.iter().filter(|h| h[3] >= y1 - MIN_SPAN).map(|h| [h[0], h[1]]).collect(); + for [ua, ub] in subtract_intervals(0.0, length, &top_gaps) { + push_quad(&mut out, at(ua, off_a, y1), at(ub, off_a, y1), at(ub, off_b, y1), at(ua, off_b, y1), [0.0, 1.0, 0.0]); + } + let bot_gaps: Vec<[f64; 2]> = hs.iter().filter(|h| h[2] <= y0 + MIN_SPAN).map(|h| [h[0], h[1]]).collect(); + for [ua, ub] in subtract_intervals(0.0, length, &bot_gaps) { + push_quad(&mut out, at(ua, off_a, y0), at(ub, off_a, y0), at(ub, off_b, y0), at(ua, off_b, y0), [0.0, -1.0, 0.0]); + } + + // Stirnkappen. + let start_normal = quad_normal(at(0.0, off_b, y0), at(0.0, off_a, y0), at(0.0, off_b, y1)); + let start_gaps: Vec<[f64; 2]> = hs.iter().filter(|h| h[0] <= MIN_SPAN).map(|h| [h[2], h[3]]).collect(); + for [za, zb] in subtract_intervals(y0, y1, &start_gaps) { + push_quad(&mut out, at(0.0, off_b, za), at(0.0, off_a, za), at(0.0, off_a, zb), at(0.0, off_b, zb), start_normal); + } + let end_normal = quad_normal(at(length, off_a, y0), at(length, off_b, y0), at(length, off_a, y1)); + let end_gaps: Vec<[f64; 2]> = hs.iter().filter(|h| h[1] >= length - MIN_SPAN).map(|h| [h[2], h[3]]).collect(); + for [za, zb] in subtract_intervals(y0, y1, &end_gaps) { + push_quad(&mut out, at(length, off_a, za), at(length, off_b, za), at(length, off_b, zb), at(length, off_a, zb), end_normal); + } + + // Laibungen je Loch (nur die im Wand-Inneren liegenden Seiten). + for &[a0, a1, zb, zt] in &hs { + if a0 > MIN_SPAN { + push_quad(&mut out, at(a0, off_a, zb), at(a0, off_b, zb), at(a0, off_b, zt), at(a0, off_a, zt), [ux, 0.0, uy]); + } + if a1 < length - MIN_SPAN { + push_quad(&mut out, at(a1, off_a, zb), at(a1, off_b, zb), at(a1, off_b, zt), at(a1, off_a, zt), [-ux, 0.0, -uy]); + } + if zb > y0 + MIN_SPAN { + push_quad(&mut out, at(a0, off_a, zb), at(a1, off_a, zb), at(a1, off_b, zb), at(a0, off_b, zb), [0.0, 1.0, 0.0]); + } + if zt < y1 - MIN_SPAN { + push_quad(&mut out, at(a0, off_a, zt), at(a1, off_a, zt), at(a1, off_b, zt), at(a0, off_b, zt), [0.0, -1.0, 0.0]); + } + } + out +} + +/// Geschlossen und nach aussen gewunden? Gauss-Kriterium: Σ (v1−v0)×(v2−v0) = 0 (keine Lücke, +/// T-Stoss-robust) und signiertes Volumen > 0. Index ausserhalb ⇒ `false`. +pub fn is_watertight(positions: &[f64], indices: &[u32], eps: f64) -> bool { + let p = positions; + let (mut ax, mut ay, mut az, mut vol6) = (0.0, 0.0, 0.0, 0.0); + for t in indices.chunks(3) { + if t.len() < 3 { + // TS liest dann `undefined` ⇒ NaN ⇒ nicht dicht. + return false; + } + // In u64 rechnen: auf wasm32 liefe `u32 * 3` als usize sonst über. + let (j0, j1, j2) = (t[0] as u64 * 3, t[1] as u64 * 3, t[2] as u64 * 3); + if j0.max(j1).max(j2) + 2 >= p.len() as u64 { + return false; + } + let (i0, i1, i2) = (j0 as usize, j1 as usize, j2 as usize); + let e1 = sub3([p[i1], p[i1 + 1], p[i1 + 2]], [p[i0], p[i0 + 1], p[i0 + 2]]); + let e2 = sub3([p[i2], p[i2 + 1], p[i2 + 2]], [p[i0], p[i0 + 1], p[i0 + 2]]); + let c = cross(e1, e2); + ax += c[0]; + ay += c[1]; + az += c[2]; + vol6 += p[i0] * c[0] + p[i0 + 1] * c[1] + p[i0 + 2] * c[2]; + } + js_hypot3(ax, ay, az) < eps && vol6 > eps +} + +// ── Flache Kodierung ───────────────────────────────────────────────────────── +// +// Eingabe: `[nBänder, (sx, sy, ex, ey, Dicke, UK, Höhe, nLöcher, (from, to, zb, zt)…)…]`. +// Ausgabe: `[nBänder, (nZahlen, x, Höhe, y, …)…]` — je Band die Weltpunkte, drei je Dreiecksecke. +// Kaputte Eingabe ⇒ `[0]`; ein Band mit NaN/∞ ⇒ leeres Mesh. + +fn decode(buf: &[f64]) -> Option> { + let mut r = Reader::new(buf); + let n = r.count()?; + let mut out = Vec::with_capacity(n.min(1 << 16)); + for _ in 0..n { + let start = [r.num()?, r.num()?]; + let end = [r.num()?, r.num()?]; + let (thickness, base_elevation, height) = (r.num()?, r.num()?, r.num()?); + let nh = r.count()?; + let mut holes = Vec::with_capacity(nh.min(1024)); + for _ in 0..nh { + holes.push([r.num()?, r.num()?, r.num()?, r.num()?]); + } + out.push(CutWall { start, end, thickness, base_elevation, height, holes }); + } + Some(out) +} + +fn finite(w: &CutWall) -> bool { + [w.start[0], w.start[1], w.end[0], w.end[1], w.thickness, w.base_elevation, w.height].iter().all(|v| v.is_finite()) + && w.holes.iter().flatten().all(|v| v.is_finite()) +} + +/// Flache Bindung für viele Bänder auf einmal; nie ein Panic. +pub fn wall_cut_meshes_flat(buf: &[f64]) -> Vec { + let Some(walls) = decode(buf) else { return vec![0.0] }; + let mut out = vec![walls.len() as f64]; + for w in &walls { + let m = if finite(w) { wall_cut_mesh(w) } else { Vec::new() }; + out.push(m.len() as f64); + out.extend_from_slice(&m); + } + out +} + +/// Flache Bindung von [`solid_subrects`]: `holes` als `[from, to, zb, zt, …]`; Ausgabe ebenso. +pub fn solid_subrects_flat(u_lo: f64, u_hi: f64, z_lo: f64, z_hi: f64, holes: &[f64]) -> Vec { + let hs: Vec<[f64; 4]> = holes.chunks_exact(4).map(|c| [c[0], c[1], c[2], c[3]]).collect(); + solid_subrects(u_lo, u_hi, z_lo, z_hi, &hs).into_iter().flatten().collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn band(holes: Vec<[f64; 4]>) -> CutWall { + CutWall { start: [0.0, 0.0], end: [5.0, 0.0], thickness: 0.4, base_elevation: 0.0, height: 2.6, holes } + } + + fn tight(pos: &[f64]) -> bool { + let idx: Vec = (0..(pos.len() / 3) as u32).collect(); + is_watertight(pos, &idx, 1e-6) + } + + #[test] + fn zerlegung_wie_render3d() { + assert_eq!(solid_subrects(0.0, 5.0, 0.0, 2.6, &[]), vec![[0.0, 5.0, 0.0, 2.6]]); + assert_eq!(solid_subrects(0.0, 5.0, 0.0, 2.6, &[[2.0, 3.0, 0.9, 2.4]]).len(), 8); + assert_eq!(solid_subrects(0.0, 5.0, 0.0, 2.6, &[[2.0, 3.0, 0.0, 2.1]]).len(), 5); + assert_eq!(subtract_intervals(0.0, 5.0, &[[1.0, 2.0], [1.5, 3.0]]), vec![[0.0, 1.0], [3.0, 5.0]]); + } + + #[test] + fn volle_box_ohne_loch() { + let m = wall_cut_mesh(&band(vec![])); + // 2 Langseiten + Deckel + Boden + 2 Kappen = 6 Quads = 12 Dreiecke. + assert_eq!(m.len(), 12 * 9); + assert!(tight(&m)); + } + + #[test] + fn fenster_und_tuer_bleiben_dicht() { + let fenster = wall_cut_mesh(&band(vec![[2.0, 3.0, 0.9, 2.1]])); + // 8 Teilrechtecke × 2 Seiten + Deckel + Boden + 2 Kappen + 4 Laibungen = 24 Quads. + assert_eq!(fenster.len(), 24 * 2 * 9); + assert!(tight(&fenster)); + let tuer = wall_cut_mesh(&band(vec![[2.0, 3.0, 0.0, 2.1]])); + assert!(tight(&tuer)); + // Loch am Wandende und über die ganze Höhe. + let rand = wall_cut_mesh(&band(vec![[4.0, 6.0, 0.5, 2.0], [0.0, 1.0, -1.0, 9.0]])); + assert!(tight(&rand)); + } + + #[test] + fn dichtheit_erkennt_luecken_und_wicklung() { + let m = wall_cut_mesh(&band(vec![])); + assert!(!tight(&m[..m.len() - 9])); + let mut flipped = m.clone(); + for t in flipped.chunks_mut(9) { + let (a, b) = t.split_at_mut(6); + a[3..6].swap_with_slice(&mut b[0..3]); + } + assert!(!tight(&flipped)); + assert!(!is_watertight(&m, &[0, 1, 99], 1e-6)); + assert!(!is_watertight(&m, &[0, 1], 1e-6)); + assert!(!is_watertight(&m, &[u32::MAX, 0, 1], 1e-6)); + assert!(!is_watertight(&[], &[], 1e-6)); + } + + #[test] + fn hypot3_wie_js() { + assert_eq!(js_hypot3(3.0, 4.0, 12.0), 13.0); + assert_eq!(js_hypot3(0.0, 0.0, 0.0), 0.0); + assert!(js_hypot3(f64::NAN, 1.0, 0.0).is_nan()); + assert_eq!(js_hypot3(f64::NAN, f64::INFINITY, 0.0), f64::INFINITY); + } + + #[test] + fn flach_viele_baender() { + let buf = [2.0, 0.0, 0.0, 5.0, 0.0, 0.4, 0.0, 2.6, 0.0, 0.0, 0.0, 0.0, 0.0, 0.4, 0.0, 2.6, 1.0, 1.0, 2.0, 0.0, 2.0]; + let out = wall_cut_meshes_flat(&buf); + assert_eq!(out[0], 2.0); + assert_eq!(out[1], 108.0); + assert_eq!(out[2 + 108], 0.0); // Nullwand ⇒ leer + assert_eq!(solid_subrects_flat(0.0, 5.0, 0.0, 2.6, &[2.0, 3.0, 0.0, 2.1, 9.0]).len(), 5 * 4); + } + + #[test] + fn unsinn_ohne_panic() { + assert_eq!(wall_cut_meshes_flat(&[]), vec![0.0]); + assert_eq!(wall_cut_meshes_flat(&[f64::NAN]), vec![0.0]); + assert_eq!(wall_cut_meshes_flat(&[1e300]), vec![0.0]); + assert_eq!(wall_cut_meshes_flat(&[1.0, 0.0, 0.0, 5.0]), vec![0.0]); + let out = wall_cut_meshes_flat(&[1.0, 0.0, 0.0, f64::NAN, 0.0, 0.4, 0.0, 2.6, 0.0]); + assert_eq!(out, vec![1.0, 0.0]); + // Löcher verkehrt herum, riesig, negativ. + let w = band(vec![[3.0, 1.0, 2.0, 0.5], [-1e9, 1e9, -1e9, 1e9], [f64::NAN, 1.0, 0.0, 1.0]]); + let _ = wall_cut_mesh(&w); + let _ = solid_subrects(f64::NAN, 1.0, 0.0, f64::INFINITY, &[[f64::NAN; 4]]); + let _ = solid_subrects_flat(0.0, 1.0, 0.0, 1.0, &[1.0, 2.0]); + } +} diff --git a/src-tauri/core/src/web/mod.rs b/src-tauri/core/src/web/mod.rs index a7e7d954..e0fdb68c 100644 --- a/src-tauri/core/src/web/mod.rs +++ b/src-tauri/core/src/web/mod.rs @@ -17,6 +17,8 @@ mod wall_bands; mod room_area; mod room_boundary; mod polygon_holes; +mod openings3d; +mod wall_mesh_cut; use wasm_bindgen::prelude::wasm_bindgen; diff --git a/src-tauri/core/src/web/openings3d.rs b/src-tauri/core/src/web/openings3d.rs new file mode 100644 index 00000000..45ccc8fc --- /dev/null +++ b/src-tauri/core/src/web/openings3d.rs @@ -0,0 +1,15 @@ +//! Bindungen der Öffnungs-Einbauteile in 3D (`crate::openings3d`). Kodierung s. dort. + +use wasm_bindgen::prelude::wasm_bindgen; + +/// Wände mit Öffnungen (+ Detailgrad) flach → Quader (Bauteil-Klasse, 8 Ecken) flach; nie ein Panic. +#[wasm_bindgen] +pub fn opening_meshes_flat(buf: &[f64]) -> Vec { + crate::openings3d::opening_meshes_flat(buf) +} + +/// Rahmen-Ring als Vierecke (u, h) flach: `[n, (u, h) × 4 …]`. +#[wasm_bindgen] +pub fn frame_ring_quads_flat(from: f64, to: f64, z_b: f64, z_t: f64, w: f64, join: f64, bottom: bool) -> Vec { + crate::openings3d::frame_ring_quads_flat(from, to, z_b, z_t, w, join, bottom) +} diff --git a/src-tauri/core/src/web/wall_mesh_cut.rs b/src-tauri/core/src/web/wall_mesh_cut.rs new file mode 100644 index 00000000..d58aba82 --- /dev/null +++ b/src-tauri/core/src/web/wall_mesh_cut.rs @@ -0,0 +1,21 @@ +//! Bindungen des Wand-Loch-Mesh (`crate::wall_mesh_cut`). Kodierung s. dort. + +use wasm_bindgen::prelude::wasm_bindgen; + +/// Viele Wandbänder flach → je Band die Weltpunkte der Dreiecke; nie ein Panic. +#[wasm_bindgen] +pub fn wall_cut_meshes_flat(buf: &[f64]) -> Vec { + crate::wall_mesh_cut::wall_cut_meshes_flat(buf) +} + +/// Rechteck minus Löcher als Teilrechtecke (`[u0, u1, z0, z1, …]`). +#[wasm_bindgen] +pub fn solid_subrects_flat(u_lo: f64, u_hi: f64, z_lo: f64, z_hi: f64, holes: &[f64]) -> Vec { + crate::wall_mesh_cut::solid_subrects_flat(u_lo, u_hi, z_lo, z_hi, holes) +} + +/// Geschlossenes, nach aussen gewundenes Mesh? (Gauss-Kriterium.) +#[wasm_bindgen] +pub fn is_watertight_flat(positions: &[f64], indices: &[u32], eps: f64) -> bool { + crate::wall_mesh_cut::is_watertight(positions, indices, eps) +} diff --git a/src/export/exportIfc.ts b/src/export/exportIfc.ts index cb398862..8a671042 100644 --- a/src/export/exportIfc.ts +++ b/src/export/exportIfc.ts @@ -73,7 +73,7 @@ import { } from "../model/wall"; import { pickGeometry } from "../plan/toWalls3d"; import type { RWall } from "../plan/toWalls3d"; -import { isWatertight, wallCutMesh } from "../plan/wallMeshCut"; +import { isWatertight, wallCutMeshes, type CutMesh } from "../plan/wallMeshCut"; import { evaluateRoom } from "../geometry/roomArea"; import { columnFootprint } from "../geometry/column"; import { emitRoofs } from "../plan/toWalls3d/roofs"; @@ -607,7 +607,11 @@ export function exportIfcSpf(projectIn: Project): string { // aussen bleiben. Watertightness (isWatertight) misst das anschliessend am // fertigen IFC-Mesh → treibt das Closed-Flag des Face-Sets. const bandsByWallId = new Map(); - for (const band of pickGeometry(project).walls) { + const allBands = pickGeometry(project).walls; + // Loch-Ausschnitte aller Bänder in EINEM Kern-Aufruf. + const cutOf = new Map(); + wallCutMeshes(allBands).forEach((m, i) => cutOf.set(allBands[i], m)); + for (const band of allBands) { const list = bandsByWallId.get(band.wallId); if (list) list.push(band); else bandsByWallId.set(band.wallId, [band]); @@ -620,7 +624,8 @@ export function exportIfcSpf(projectIn: Project): string { const positions: number[] = []; const indices: number[] = []; for (const band of bands) { - const cut = wallCutMesh(band); + const cut = cutOf.get(band); + if (!cut) continue; const base = positions.length / 3; for (let i = 0; i < cut.positions.length; i += 3) { positions.push( diff --git a/src/export/exportMesh.ts b/src/export/exportMesh.ts index 37c0a826..f6844be2 100644 --- a/src/export/exportMesh.ts +++ b/src/export/exportMesh.ts @@ -8,7 +8,7 @@ // die auch der 3D-Viewer zeichnet (EIN RWall je Materiallage/Achsen- // Teilstück, bereits mit End-Cuts/Gehrungen/Decken-Dominanz aufgelöst). // Bänder mit Öffnungs-`holes` werden über den gemeinsamen Loch-Ausschnitt- -// Generator (`plan/wallMeshCut.ts`, TS-Port von render3ds Gitter-Zerlegung +// Generator (`plan/wallMeshCut.ts` → Rust-Kern, Gitter-Zerlegung wie render3ds // `extrude_layer_segment_with_holes`) ÖFFNUNGSGENAU trianguliert — die // Fenster/Türen sind sichtbar ausgestanzt inkl. Laibungsflächen, genau wie // im 3D-Viewer. Lochlose Bänder bleiben die klassische geteilte 8-Ecken-Box. @@ -39,7 +39,7 @@ import type { Project, Vec2 } from "../model/types"; import { getFloor } from "../model/types"; import { pickGeometry } from "../plan/toWalls3d"; import type { RWall } from "../plan/toWalls3d"; -import { wallCutMesh } from "../plan/wallMeshCut"; +import { wallCutMeshes, type CutMesh } from "../plan/wallMeshCut"; import { triangulate } from "../plan/glPlan/glPlanCompile"; /** @@ -67,7 +67,7 @@ function sanitizeName(id: string): string { /** * Die 6 Quader-Seiten als Eckpunkt-Quadrupel (Index-Bits: bit0=Achse −/+, - * bit1=Höhe −/+, bit2=Dicke −/+ — dieselbe Konvention wie `emitOpeningGlass`/ + * bit1=Höhe −/+, bit2=Dicke −/+ — dieselbe Konvention wie `emitOpeningMeshes`/ * `selectionHighlightLines` in toWalls3d.ts), in nach AUSSEN gewundener * Reihenfolge (für ein rechtshändiges Dreibein Achse×Höhe=Dicke-Normale, wie * es die Wandbox-Konstruktion unten aufspannt). Jedes Quadrupel wird zu 2 @@ -85,14 +85,13 @@ const BOX_QUADS: Array<[number, number, number, number]> = [ /** * Hängt EIN Wand-Schicht-Band (`RWall`, siehe toWalls3d.ts) an eine Mesh-Gruppe * an: hat das Band echte Öffnungs-`holes`, wird das öffnungsgenaue Loch-Ausschnitt- - * Mesh (siehe {@link wallCutMesh}) verwendet — die Fenster/Türen sind sichtbar - * ausgestanzt inkl. Laibungen, exakt wie im 3D-Viewer. Ohne Löcher bleibt es die - * klassische, geteilte 8-Ecken-Box ({@link pushWallBox}) — bitgleich zum - * bisherigen Verhalten (Joins/Gehrungen stecken schon in `start`/`end`). + * Mesh `cut` (vorab für alle Bänder über {@link wallCutMeshes}) verwendet — die + * Fenster/Türen sind sichtbar ausgestanzt inkl. Laibungen, exakt wie im 3D-Viewer. + * Ohne Löcher bleibt es die klassische, geteilte 8-Ecken-Box ({@link pushWallBox}) + * (Joins/Gehrungen stecken schon in `start`/`end`). */ -function pushWall(group: MeshGroup, w: RWall): void { - if (w.holes && w.holes.length > 0) { - const cut = wallCutMesh(w); +function pushWall(group: MeshGroup, w: RWall, cut: CutMesh | undefined): void { + if (cut) { const base = group.positions.length / 3; for (const p of cut.positions) group.positions.push(p); for (const idx of cut.indices) group.indices.push(base + idx); @@ -221,6 +220,10 @@ function buildGroups(project: Project): MeshGroup[] { // Wände: alle Schicht-Bänder DERSELBEN Wand-Id in EINE Gruppe (mehrere // Materiallagen ergeben mehrere Boxen im selben Bauteil-Vorkommen). const wallGroups = new Map(); + // Loch-Ausschnitte aller gelochten Bänder in EINEM Kern-Aufruf. + const holed = walls.filter((w) => w.holes && w.holes.length > 0); + const cuts = new Map(); + wallCutMeshes(holed).forEach((m, i) => cuts.set(holed[i], m)); for (const w of walls) { let g = wallGroups.get(w.wallId); if (!g) { @@ -228,7 +231,7 @@ function buildGroups(project: Project): MeshGroup[] { wallGroups.set(w.wallId, g); groups.push(g); } - pushWall(g, w); + pushWall(g, w, cuts.get(w)); } // Decken: ein Prisma je Decke. diff --git a/src/plan/toWalls3d.ts b/src/plan/toWalls3d.ts index 76a8f95d..05267559 100644 --- a/src/plan/toWalls3d.ts +++ b/src/plan/toWalls3d.ts @@ -71,7 +71,7 @@ import { applyVoids3d } from "./toWalls3d/voids3d"; import { emitDrawingLineVerts, pickDrawingSegs } from "./toWalls3d/drawing2d"; import { emitColumns } from "./toWalls3d/columns"; import { emitRoofCutLayers, emitRoofs } from "./toWalls3d/roofs"; -import { emitOpeningFrames, emitOpeningGlass, emitOpeningShading } from "./toWalls3d/openings"; +import { emitOpeningMeshes } from "./toWalls3d/openings"; // Re-Export des gemeinsamen Vokabulars — externe Konsumenten (viewport/, // export/, toSection.ts, nativeSync.ts, …) importieren weiterhin @@ -217,15 +217,13 @@ export function projectToModel3d(project: Project, opts: Model3dOptions = {}): R slabs: [...emitSlabs(project), ...emitStairs(project, { forSection: opts.forSection })], // Kontext-Meshes (Terrain/Import) + Fenster-/Tür-Glasscheiben (eigenes Mesh // je Scheibe) + Rahmen-/Sprossen-Riegel typisierter Öffnungen (Zarge/ - // Blendrahmen/Kämpfer/Mittelpfosten, s. emitOpeningFrames) + glatte Beton- + // Blendrahmen/Kämpfer/Mittelpfosten, s. emitOpeningMeshes) + glatte Beton- // Laufplatten (gerade Betontreppen als Mesh) + Dachflächen/-giebel // (s. emitRoofs) — pickGeometry/Highlight nutzen `meshes` bewusst NICHT (man // wählt Wand/Öffnung/Treppe; Treppen-Pick läuft über die pickGeometry-Boxen). meshes: [ ...emitMeshes(project), - ...emitOpeningGlass(project), - ...emitOpeningFrames(project, detail), - ...emitOpeningShading(project, detail), + ...emitOpeningMeshes(project, detail), ...emitStairMeshes(project), ...emitStairRailings(project), ...emitRoofs(project), diff --git a/src/plan/toWalls3d/bands.ts b/src/plan/toWalls3d/bands.ts index 3598f434..5edeecf3 100644 --- a/src/plan/toWalls3d/bands.ts +++ b/src/plan/toWalls3d/bands.ts @@ -181,7 +181,7 @@ function withTopAngle(h: RHatch, dx: number, dy: number): RHatch { * Dicke einer Wand für die grobe Grundriss-Hülle (Decken-Vorfilter im Kern): * Summe der WallType-Schichtdicken, sonst der Fallback-Grundton-Dicke aus * {@link resolveWallBands} (0.2 m), falls kein WallType auflösbar ist. Auch von - * `../openings.ts::resolveOpeningFrame` genutzt (Rahmen-Tiefe auf die Wanddicke + * `openings.ts::emitOpeningMeshes` genutzt (Rahmen-Tiefe auf die Wanddicke * klemmen). */ export function wallThicknessSafe(project: Project, wall: Wall): number { diff --git a/src/plan/toWalls3d/openings.ts b/src/plan/toWalls3d/openings.ts index 91256d12..9cdf3591 100644 --- a/src/plan/toWalls3d/openings.ts +++ b/src/plan/toWalls3d/openings.ts @@ -1,171 +1,182 @@ // Öffnungs-Domäne der 3D-Ableitung: Glasscheibe(n)/Türblatt, Rahmen-/Sprossen- -// Riegel (Zarge/Blendrahmen/Kämpfer/Mittelpfosten/Flügelrahmen + SIA-Symbole) -// und der Rollladen-/Sonnenschutzkasten typisierter Tür-/Fensteröffnungen — das -// 3D-Pendant zu `generatePlan/openings.ts`. +// Riegel (Zarge/Blendrahmen/Kämpfer/Mittelpfosten/Flügelrahmen + SIA-Symbole), +// Fensterbänke, Zargen-Umgriff, Schwellenprofil und der Rollladen-/Sonnenschutz- +// kasten typisierter Tür-/Fensteröffnungen — das 3D-Pendant zu +// `generatePlan/openings.ts`. +// +// Gerechnet wird im Rust-Kern (`src-tauri/core/src/openings3d.rs`, Kodierung +// dort); hier bleiben das Sammeln aus dem `Project` (Tür-/Fenstertyp, Flügel- +// tabelle, Öffnungs-Intervall und -Höhe, Wanddicke), die flache Übergabe aller +// Wände in EINEM Kern-Aufruf und die Farbe je Bauteil-Klasse. +// +// Die Quader liegen in MODELL-Metern (x, y, z = Höhe); render3d bildet sie nach +// world ab und rendert sie doppelseitig (Winding egal). `kind: "extrusion"` +// (NICHT "imported"): die Nord-Achsen-Negation in `append_context_mesh` gilt nur +// für echte Import-Rohdaten, Öffnungs-Quader entstehen orientierungserhaltend aus +// der Wandachse (Fund 2026-09-27). -import type { FrameCornerJoin, Opening, Project, SashDef, Wall } from "../../model/types"; -import { getDoorType, getWindowType, glazingPanesOf, openingsOfWall } from "../../model/types"; +import type { DoorType, FrameCornerJoin, Opening, Project, WindowType } from "../../model/types"; +import { getDoorType, getWindowType, glazingPanesOf } from "../../model/types"; import { openingInterval, openingVerticalExtent } from "../../geometry/opening"; import type { DetailLevel } from "../../model/viewTypes"; -import { EPS, type RMesh, type RRgb } from "./shared"; +import { FlatReader, FlatWriter } from "../../geometry/coreFlat"; +import { core } from "../../engine/coreWasm"; +import type { RMesh, RRgb } from "./shared"; import { wallThicknessSafe } from "./bands"; -/** Helles, leicht bläuliches Fenster-Glas (Scheibe in der Öffnung). */ -const GLASS_RGB: RRgb = [0.62, 0.76, 0.85]; /** - * Halbe Dicke EINER Fensterscheibe (Meter, Mehrfachverglasungs-Pfad). Kompakt - * gehalten (8 mm Gesamtdicke je Scheibe, wie ein reales Einzelglas), damit - * z. B. eine Dreifachverglasung noch in den realistisch schlanken Default- - * Rahmen ({@link DEFAULT_FRAME_DEPTH}, ~70 mm) passt — bei der früheren - * "volle Wanddicke"-Rahmentiefe gab es dafür reichlich Platz, im schlanken - * Rahmen nicht mehr. + * Farbe je Bauteil-Klasse (Index = `Part` in `openings3d.rs`): Glas (hell, + * bläulich), Rahmen (helles, warmes Grau), Rollladenkasten, Fensterbank/ + * Schwelle (Stein-Grau), SIA-Symbole (dunkle Linien auf dem Glas), Türblatt + * (warm, hell). */ -const GLASS_HALF_THICK = 0.004; -/** - * Helles, warmes Rahmen-Grau (Zarge/Blendrahmen/Kämpfer/Sprossen) — bewusst - * deutlich heller als Wand und klar von der bläulichen Scheibe ({@link GLASS_RGB}) - * unterscheidbar, damit der Rahmen im 3D als eigenes Bauteil lesbar ist - * (s. {@link emitOpeningFrames}). - */ -const FRAME_RGB: RRgb = [0.85, 0.85, 0.83]; -/** Heller Grauton für den Rollladen-/Sonnenschutzkasten (s. {@link emitOpeningShading}). */ -const SHADING_RGB: RRgb = [0.88, 0.88, 0.9]; -/** - * Heller Stein-/Beton-Grauton der Fensterbank (Sims/Tropfkante) — bewusst etwas - * dunkler/kühler als der Rahmen ({@link FRAME_RGB}), damit die Bank im 3D als - * eigenes Bauteil (nicht als Rahmenfortsatz) liest (s. Sims-Zweig in - * {@link frameMeshesForOpening}). - */ -const SILL_RGB: RRgb = [0.8, 0.8, 0.78]; -/** - * Dunkles Grau der SIA-Öffnungssymbole (dünne Diagonalen AUF dem Glas, wie in der - * 2D-Ansicht) — feine dunkle Linien auf der Scheibe (s. Symbol-Zweig in - * {@link frameMeshesForOpening}). Als sehr dünne, in der Öffnungsebene gedrehte - * Prismen ({@link openingPlaneBox}) knapp vor der Glasebene. - */ -const SYMBOL_RGB: RRgb = [0.25, 0.27, 0.3]; -/** Halbe Breite der Symbol-Diagonalen (Meter) — ~5 mm Gesamtbreite, feine Linie. */ -const SYMBOL_HALF_WIDTH = 0.0025; -/** - * Warmer, heller Türblatt-Ton — bewusst wärmer/heller als der Rahmen - * ({@link FRAME_RGB}), damit das Blatt im 3D als eigene Füllung liest - * (s. {@link doorLeafPanels}). - */ -const DOOR_LEAF_RGB: RRgb = [0.93, 0.9, 0.85]; -/** Türblatt-Dicke quer zur Wand (Meter). */ -const DOOR_LEAF_THICK = 0.04; -/** Default-Ansichtsbreite des Rahmenprofils (Meter), wenn `TYPE.frameWidth` fehlt. */ -const DEFAULT_FRAME_WIDTH = 0.06; -/** - * Default-Rahmentiefe (Meter), wenn ein Typ keine `frameDepth` nennt: reale - * Fensterrahmen sind ~70–90 mm tief (Holz/PVC/Alu), UNABHÄNGIG von der - * Wanddicke — ein schlanker Rahmen mit sichtbarer Laibung ringsum, nicht ein - * massiver Block über die volle Wandtiefe. Deckt sich mit - * `geometry/opening.ts::DEFAULT_FRAME_DEPTH` (2D=3D). - */ -const DEFAULT_FRAME_DEPTH = 0.07; +const PART_RGB: readonly RRgb[] = [ + [0.62, 0.76, 0.85], + [0.85, 0.85, 0.83], + [0.88, 0.88, 0.9], + [0.8, 0.8, 0.78], + [0.25, 0.27, 0.3], + [0.93, 0.9, 0.85], +]; -// Faces eines Boxen-Quaders als Dreiecks-Indizes (Ecken-Index-Bits: bit0 = -// Achse from/to, bit1 = Höhe UK/OK, bit2 = Quer-Versatz nMin/nMax). Doppelseitig -// gerendert (append_context_mesh) ⇒ Winding egal; je Fläche 2 Dreiecke, 6 -// Flächen = 12 Dreiecke. Gemeinsame Topologie für Glasscheiben UND Rahmen-/ -// Sprossen-Riegel (s. {@link openingAxisBox}). -const OPENING_BOX_TRIS: number[] = [ - 0, 1, 3, 0, 3, 2, // Quer-Versatz nMin - 4, 5, 7, 4, 7, 6, // Quer-Versatz nMax +/** Dreiecke eines Öffnungs-Quaders (Ecken-Bits: bit0 = Achse, bit1 = Höhe, bit2 = quer). */ +const OPENING_BOX_TRIS: readonly number[] = [ + 0, 1, 3, 0, 3, 2, // quer nMin + 4, 5, 7, 4, 7, 6, // quer nMax 0, 1, 5, 0, 5, 4, // UK 2, 3, 7, 2, 7, 6, // OK 0, 2, 6, 0, 6, 4, // from 1, 3, 7, 1, 7, 5, // to ]; -/** - * Baut EINEN geschlossenen Achsen-Quader (8 Ecken, 12 Dreiecke) für eine - * Öffnung — die gemeinsame Basis von {@link emitOpeningGlass} (Scheiben) und - * {@link emitOpeningFrames} (Rahmen-/Sprossen-Riegel). Achsen-Intervall - * `[from,to]` (Meter ab `wall.start`, entlang der Wandrichtung u), Höhen- - * Intervall `[zBottom,zTop]` (absolute Weltmeter) und Quer-Versatz-Intervall - * `[nMin,nMax]` (Meter entlang der Grundriss-Normalen n=(uy,−ux), dieselbe - * Konvention wie die bisherige Glas-Box — `nMin`/`nMax` MÜSSEN nicht sortiert - * übergeben werden, die Box spannt zwischen beiden Werten). `positions` in - * MODELL-Metern (x, y, z=Höhe). Liefert `null` bei entarteten Massen (Achse/ - * Höhe/Dicke ≤ EPS) statt eines Nullquaders. - */ -function openingAxisBox( - wall: Wall, - from: number, - to: number, - zBottom: number, - zTop: number, - nMin: number, - nMax: number, - color: RRgb, -): RMesh | null { - if (to - from <= EPS) return null; - if (zTop - zBottom <= EPS) return null; - if (Math.abs(nMax - nMin) <= EPS) return null; - const dx = wall.end.x - wall.start.x; - const dy = wall.end.y - wall.start.y; - const len = Math.hypot(dx, dy); - if (len < 1e-9) return null; - const ux = dx / len; - const uy = dy / len; - // Grundriss-Normale (Dicken-Achse) — RECHTE Normale (uy,−ux), bewusst NICHT - // leftNormal (anders als pushSegment/windowSymbol) — kombiniert mit dem - // (ebenfalls gespiegelten) Vorzeichen in resolveFrameNormalRange ergibt sich - // daraus physisch die korrekte aussen/innen-Seite (s. dortigen Kommentar). - const nx = uy; - const ny = -ux; - const positions: number[] = []; - for (let i = 0; i < 8; i++) { - const s = i & 1 ? to : from; - const z = i & 2 ? zTop : zBottom; - const t = i & 4 ? nMax : nMin; - positions.push(wall.start.x + ux * s + nx * t, wall.start.y + uy * s + ny * t, z); +const DETAIL_CODE: Record = { grob: 0, mittel: 1, fein: 2 }; +const JOIN_CODE: Record = { horizontal: 1, gehrung: 2 }; +const OPENING_KIND_CODE: Record = { dreh: 1, kipp: 2, drehkipp: 3, fest: 4, schiebe: 5 }; +const SILL_BOARD_CODE: Record = { keine: 1, innen: 2, beide: 3 }; + +/** Fehlender Wert → NaN (der Kern setzt dort den Default). */ +const opt = (v: number | null | undefined): number => v ?? Number.NaN; +const flag = (b: boolean): number => (b ? 1 : 0); +const openingKindCode = (k: string | undefined): number => (k ? OPENING_KIND_CODE[k] ?? 6 : 0); + +/** Gemeinsame Typwerte (Kodierung `openings3d.rs`). */ +function writeCommon(w: FlatWriter, t: DoorType | WindowType): void { + w.num( + opt(t.frameDepth), + opt(t.insetFromFace), + flag((t.insetFace ?? "aussen") === "innen"), + JOIN_CODE[t.frameCornerJoin ?? ""] ?? 0, + opt(t.frameWidth), + opt(t.transomHeight), + ); +} + +function writeOpening(w: FlatWriter, project: Project, op: Opening): void { + if (op.kind === "window") { + const wt = getWindowType(project, op); + if (!wt) { + w.num(0); + return; + } + w.num(1); + writeCommon(w, wt); + const shading = wt.shading?.create ? wt.shading.box : undefined; + w.num( + glazingPanesOf(wt), + opt(wt.mullionRows), + opt(wt.mullionCols), + SILL_BOARD_CODE[wt.sillBoard ?? ""] ?? 0, + flag(!!shading), + shading?.width ?? 0, + shading?.height ?? 0, + shading?.depth ?? 0, + op.wingCount ?? wt.wingCount ?? 1, + openingKindCode(wt.kind), + ); + const sashes = wt.sashes ?? []; + w.num(sashes.length); + for (const s of sashes) { + w.num( + s.kind === "fluegel" ? 0 : s.kind === "pfosten" ? 1 : 2, + flag(s.autoWidth === false), + opt(s.width), + opt(s.postWidth), + openingKindCode(s.opening), + flag((s.hingeSide ?? "left") === "left"), + ); + } + return; } - // "extrusion", NICHT "imported" — s. Moduldoc an emitOpeningGlass (Nord- - // Achsen-Negation in append_context_mesh gilt nur für echte Import-Kinds). - return { positions, indices: [...OPENING_BOX_TRIS], kind: "extrusion", color }; + const dt = getDoorType(project, op); + if (!dt) { + w.num(0); + return; + } + w.num(1); + writeCommon(w, dt); + w.num( + flag(dt.threshold === true), + opt(dt.leafCount), + dt.leafStyle === "glas" ? 1 : dt.leafStyle === "kassette" ? 2 : 0, + opt(dt.glazingRatio), + flag((dt.frameKind ?? "zarge") === "zarge"), + opt(dt.panelCols), + opt(dt.panelRows), + ); } /** - * Prisma mit beliebigem konvexem VIERECK als Ansichts-Querschnitt (in der - * Öffnungsebene: u entlang der Wand, h = Welthöhe), extrudiert über - * `[nMin,nMax]` quer zur Wand — für Gehrungs-Stösse (Trapez-Profile). Eckenfolge - * wie {@link OPENING_BOX_TRIS}: q[0]=(from,UK), q[1]=(to,UK), q[2]=(from,OK), - * q[3]=(to,OK) im Sinne der Topologie. + * Alle Öffnungs-Einbauteile eines Projekts als rohe Quader-Meshes, in EINEM + * Kern-Aufruf. Reihenfolge wie früher: erst Glas/Türblätter aller Wände, dann + * Rahmen/Sprossen/Bänke/Zargen (nicht bei „grob"), dann Rollladenkästen (nicht + * bei „grob"). + * + * • Ohne auflösbaren Typ: Fenster = EINE Vollscheibe mittig in der Wand, Tür = + * offenes Loch, kein Rahmen (Rückwärtskompatibilität). + * • „mittel": Blendrahmen + Oberlicht-Kämpfer + Flügelrahmen + Fensterbank/ + * Zargen-Umgriff/Schwellenprofil, keine Sprossen, keine SIA-Symbole. + * • „fein": zusätzlich Flügel-Mittelpfosten, Kämpfer-Zeilen und SIA-Symbole. */ -function openingPlaneQuad( - wall: Wall, - q: [[number, number], [number, number], [number, number], [number, number]], - nMin: number, - nMax: number, - color: RRgb, -): RMesh | null { - if (Math.abs(nMax - nMin) <= EPS) return null; - const dx = wall.end.x - wall.start.x; - const dy = wall.end.y - wall.start.y; - const len = Math.hypot(dx, dy); - if (len < 1e-9) return null; - const ux = dx / len; - const uy = dy / len; - const nx = uy; // dieselbe (rechte) Normale wie openingAxisBox - const ny = -ux; - const positions: number[] = []; - for (let i = 0; i < 8; i++) { - const [s, z] = q[i & 3]; - const t = i & 4 ? nMax : nMin; - positions.push(wall.start.x + ux * s + nx * t, wall.start.y + uy * s + ny * t, z); +export function emitOpeningMeshes(project: Project, detail: DetailLevel = "fein"): RMesh[] { + const byWall = new Map(); + for (const op of project.openings ?? []) { + const list = byWall.get(op.hostWallId); + if (list) list.push(op); + else byWall.set(op.hostWallId, [op]); } - return { positions, indices: [...OPENING_BOX_TRIS], kind: "extrusion", color }; + const w = new FlatWriter().num(DETAIL_CODE[detail] ?? 3, project.walls.length); + for (const wall of project.walls) { + w.num(wall.start.x, wall.start.y, wall.end.x, wall.end.y); + const slot = w.slot(); + let count = 0; + let thickness: number | undefined; + for (const op of byWall.get(wall.id) ?? []) { + const iv = openingInterval(wall, op); + if (!iv) continue; + const vert = openingVerticalExtent(project, wall, op); + thickness ??= wallThicknessSafe(project, wall); + w.num(iv.from, iv.to, vert.zBottom, vert.zTop, flag(op.kind !== "window"), thickness); + writeOpening(w, project, op); + count++; + } + w.set(slot, count); + } + const buf = core().opening_meshes_flat(w.done()); + const out: RMesh[] = []; + const n = new FlatReader(buf).count(); + for (let k = 0, i = 1; k < n && i + 25 <= buf.length; k++, i += 25) { + const positions = new Array(24); + for (let j = 0; j < 24; j++) positions[j] = buf[i + 1 + j]; + out.push({ positions, indices: [...OPENING_BOX_TRIS], kind: "extrusion", color: PART_RGB[buf[i]] ?? PART_RGB[1] }); + } + return out; } /** * Rahmen-Ring (Pfosten links/rechts, Riegel oben, Riegel unten nur bei - * `bottom`) über das Feld `[from,to]×[zB,zT]` mit Profilbreite `w`, OHNE - * überlappende Profile: `join` entscheidet, welche Glieder an den Ecken - * durchlaufen ("vertikal"/"horizontal") oder ob auf Gehrung gestossen wird. - * Liefert die Glieder als (u,h)-Vierecke (Reihenfolge s. {@link openingPlaneQuad}). + * `bottom`) über das Feld `[from,to]×[zB,zT]` mit Profilbreite `w`, ohne + * überlappende Profile; `join` bestimmt die durchlaufenden Glieder. Glieder als + * (u,h)-Vierecke: (from,UK), (to,UK), (from,OK), (to,OK). Rechnet im Kern. */ export function frameRingQuads( from: number, @@ -176,935 +187,15 @@ export function frameRingQuads( join: FrameCornerJoin, bottom: boolean, ): Array<[[number, number], [number, number], [number, number], [number, number]]> { - type Q = [[number, number], [number, number], [number, number], [number, number]]; - const box = (u0: number, u1: number, h0: number, h1: number): Q => [[u0, h0], [u1, h0], [u0, h1], [u1, h1]]; - const out: Q[] = []; - if (to - from <= 2 * w + EPS || zT - zB <= (bottom ? 2 : 1) * w + EPS) { - // Zu klein für einen Ring: ein Vollprofil. - out.push(box(from, to, zB, zT)); - return out; - } - const bz = bottom ? zB + w : zB; // Unterkante des Innenfelds - if (join === "horizontal") { - out.push(box(from, to, zT - w, zT)); // Sturz-Riegel durchlaufend - if (bottom) out.push(box(from, to, zB, zB + w)); - out.push(box(from, from + w, bz, zT - w)); - out.push(box(to - w, to, bz, zT - w)); - } else if (join === "gehrung") { - // Oben: Trapez, Innenkante um w eingerückt. - out.push([[from + w, zT - w], [to - w, zT - w], [from, zT], [to, zT]]); - if (bottom) out.push([[from, zB], [to, zB], [from + w, zB + w], [to - w, zB + w]]); - // Pfosten: aussen volle Höhe, innen bis an die Gehrung. - out.push([[from, zB], [from + w, bz], [from, zT], [from + w, zT - w]]); - out.push([[to - w, bz], [to, zB], [to - w, zT - w], [to, zT]]); - } else { - out.push(box(from, from + w, zB, zT)); // Pfosten durchlaufend (Default) - out.push(box(to - w, to, zB, zT)); - out.push(box(from + w, to - w, zT - w, zT)); - if (bottom) out.push(box(from + w, to - w, zB, zB + w)); - } - return out; -} - -/** - * Baut EIN sehr dünnes Prisma mit FREI orientierter Längsachse IN der Öffnungs- - * ebene — die diagonale Schwester von {@link openingAxisBox}. Die Längsachse - * verläuft vom Punkt `(u0,h0)` zum Punkt `(u1,h1)`, beide in Öffnungsebenen- - * koordinaten: `u` = Meter entlang der Wandrichtung (ab `wall.start`), `h` = - * absolute Welthöhe (Meter). Der Querschnitt spannt `±halfWidth` senkrecht zur - * Längsachse INNERHALB der Ebene (gedreht mit) und `[nBack,nFront]` entlang der - * Grundriss-Normalen (quer zur Wand, Tiefe). Damit lassen sich die schrägen - * SIA-Öffnungssymbole (Dreh-/Kipp-Diagonalen) als dünne, gedrehte dunkle Riegel - * AUF dem Glas erzeugen — der Renderer kennt nur Dreiecks-Meshes, keine Linien. - * `null` bei entarteter Länge (≤ EPS). 8 Ecken, dieselbe {@link OPENING_BOX_TRIS}- - * Topologie (doppelseitig gerendert ⇒ Winding egal; die drei Bits parametrisieren - * hier Endpunkt/Quer-Versatz/Tiefe). - */ -function openingPlaneBox( - wall: Wall, - u0: number, - h0: number, - u1: number, - h1: number, - halfWidth: number, - nFront: number, - nBack: number, - color: RRgb, -): RMesh | null { - const du = u1 - u0; - const dh = h1 - h0; - const segLen = Math.hypot(du, dh); - if (segLen < EPS) return null; - const dx = wall.end.x - wall.start.x; - const dy = wall.end.y - wall.start.y; - const wlen = Math.hypot(dx, dy); - if (wlen < 1e-9) return null; - const ux = dx / wlen; - const uy = dy / wlen; - // Grundriss-Normale (Dicken-Achse) — dieselbe Konvention wie openingAxisBox. - const nx = uy; - const ny = -ux; - // In der Ebene senkrecht zur Längsachse (u entlang Wand, h = Welthöhe): - // Rotation der normierten Richtung um 90°. `pu` wirkt auf die u-Achse (Wand), - // `ph` auf die Höhe — beide in Metern, orthonormal ⇒ echte `halfWidth`-Breite. - const pu = -dh / segLen; - const ph = du / segLen; - const positions: number[] = []; - for (let i = 0; i < 8; i++) { - const ui = i & 1 ? u1 : u0; - const hi = i & 1 ? h1 : h0; - const s = i & 2 ? 1 : -1; - const t = i & 4 ? nFront : nBack; - const u = ui + s * halfWidth * pu; - const h = hi + s * halfWidth * ph; - positions.push(wall.start.x + ux * u + nx * t, wall.start.y + uy * u + ny * t, h); - } - // "extrusion", NICHT "imported" — s. Moduldoc an emitOpeningGlass. - return { positions, indices: [...OPENING_BOX_TRIS], kind: "extrusion", color }; -} - -/** Klemmt `v` auf `[lo,hi]`. */ -function clampRange(v: number, lo: number, hi: number): number { - return Math.max(lo, Math.min(hi, v)); -} - -/** - * Rahmen-Tiefe quer zur Wand (Meter): explizite `frameDepth` des Typs, sonst - * {@link DEFAULT_FRAME_DEPTH} (auf die Wanddicke geklemmt, falls die Wand - * dünner als der Default-Rahmen ist). - */ -function resolveAcrossWallDepth( - frameDepth: number | undefined, - wallThickness: number, -): number { - const depth = frameDepth !== undefined && frameDepth > EPS ? frameDepth : DEFAULT_FRAME_DEPTH; - return Math.min(depth, wallThickness); -} - -/** - * Quer-Versatz-Intervall `[nMin,nMax]` (Meter entlang der Wand-Normalen, s. - * {@link openingAxisBox}) des Rahmenkörpers — der 3D-Niederschlag des - * Schichteinzugs (`insetFromFace`/`insetFace`): die Rahmen-VORDERKANTE liegt - * bündig mit der gewählten Wandfläche, zurückversetzt um `insetFromFace` - * (0/fehlt ⇒ bündig), der Rahmenkörper erstreckt sich von dort aus `depth` - * Meter zur Wandmitte hin. "aussen" liegt an der POSITIVEN Normalen-Seite - * (kleinster Schicht-Offset in `../bands.ts::pushSegment`, s. dessen Kommentar - * zur Aussenseiten-Konvention via `leftNormal`), "innen" an der negativen. Das - * Ergebnis wird auf die halbe Wanddicke geklemmt — ein Schichteinzug darf den - * Rahmen nie aus der Wand hinausschieben. - */ -function resolveFrameNormalRange( - halfThickness: number, - depth: number, - insetFromFace: number, - face: "aussen" | "innen", -): { nMin: number; nMax: number } { - const sign = face === "innen" ? -1 : 1; - const front = sign * (halfThickness - insetFromFace); - const back = front - sign * depth; - const a = clampRange(front, -halfThickness, halfThickness); - const b = clampRange(back, -halfThickness, halfThickness); - return { nMin: Math.min(a, b), nMax: Math.max(a, b) }; -} - -/** - * Aufgelöste Rahmen-/Sprossen-Parameter EINER Öffnung (Tür oder Fenster) aus - * ihrem `DoorType`/`WindowType` (via `getDoorType`/`getWindowType`). `null`, - * wenn kein Typ auflösbar ist (`Opening.typeId` fehlt/verwaist) — DANN - * emittieren weder {@link emitOpeningFrames} noch die Rahmen-/Sprossen-Logik in - * {@link emitOpeningGlass} irgendetwas (Rückwärtskompatibilität: unveränderte - * Alt-Darstellung, s. Moduldoc-Kommentar in `../../toWalls3d.ts`). - */ -interface OpeningFrameParams { - /** Sichtbare Rahmen-/Flügelprofil-Breite in der Öffnungsebene (Meter). */ - frameWidth: number; - /** Rahmen-Tiefe quer zur Wand (Meter, informativ — steckt bereits in nMin/nMax). */ - acrossWallDepth: number; - /** Quer-Versatz-Intervall des Rahmenkörpers (s. {@link resolveFrameNormalRange}). */ - nMin: number; - nMax: number; - /** Oberlicht-Höhe (Meter); 0 = kein Oberlicht/Kämpfer. */ - transomHeight: number; - /** Schwelle/Sohlbank zeichnen: Fenster immer, Tür nur mit `threshold`. */ - hasSill: boolean; - /** Flügelzahl (vertikale Mittelpfosten = wingCount−1); Türen immer 1. */ - wingCount: number; - /** Kämpfer-Zeilen (horizontale Teilung = mullionRows−1); Türen immer 1. */ - mullionRows: number; - /** Sprossen-Spalten (vertikale Teilung = mullionCols−1); Türen immer 1. */ - mullionCols: number; - /** Ob eine Glasscheibe gezeichnet wird (Fenster immer, Tür nur `leafStyle: "glas"`). */ - glazed: boolean; - /** - * Verglasungs-Scheibenzahl (1–3), render-wirksam (`glazingPanesOf`). Türen: - * immer 1 (keine typisierte Mehrfachverglasung). Steuert die Anzahl dünner, - * in Wandrichtung leicht versetzter Glasflächen in {@link glassPanesForOpening}. - */ - glazingPanes: 1 | 2 | 3; - /** - * Verglasungs-Anteil des HAUPTFELDS (0..1, von OBEN gemessen): 1 = voll - * verglast (Fenster, Ganzglastür), < 1 = nur der obere Anteil ist Glas, unten - * bleibt ein blindes Feld (z. B. Tür mit Oberglas, `DoorType.glazingRatio`). - * Fenster: immer 1. - */ - glazedFraction: number; - /** - * Flügeleinteilung (`sashesOfWindowType`) — je ÖFFENBAREM Flügel wird im - * 3D ein Flügelrahmen (Rahmen-Riegel innerhalb des Blendrahmens) erzeugt - * (Schachtelung Blendrahmen → Flügelrahmen → Glas). Türen: leer. - */ - sashes: SashDef[]; - /** Halbe Wanddicke (Meter) — Bezug der Wand-Aussenfläche (+n) für Bank/Zargen-Umgriff. */ - halfThickness: number; - /** - * Fensterbank (Sims) zeichnen: nur Fenster mit `sillBoard` ≠ "keine"/"innen" - * (fehlt ⇒ zeichnen, wie in der 2D-Ansicht). Türen: nie. - */ - drawSill: boolean; - /** - * Innen-Fensterbank zeichnen: nur Fenster mit `sillBoard` === "innen"/"beide". - * Gegenstück zu {@link drawSill} auf der Wand-Innenfläche (kein Überstand/ - * keine Tropfkante — das ist eine reine Innenausbau-Ablage, keine - * Witterungskante). Türen: nie. - */ - drawInteriorSill: boolean; - /** - * Zargen-Umgriff (Bekleidung VOR beiden Wandflächen) zeichnen: nur Türen mit - * `frameKind === "zarge"`. Blockrahmen bleibt bündig (false). - */ - zargeCladding: boolean; - /** - * Echtes Schwellenprofil (dünne, farblich abgesetzte Leiste über die GANZE - * Wanddicke am Fussboden, analog zur Fensterbank-Leiste) zeichnen: nur - * Türen mit `threshold === true`. Zusätzlich zum bisherigen, strukturellen - * Blendrahmen-Riegel ({@link hasSill}) — der bleibt unverändert (steuert - * weiterhin, wo der Flügel-/Blatt-Bereich beginnt), das Profil kommt als - * eigenständiges, sichtbar unterscheidbares Bauteil obendrauf, nicht als - * dessen Ersatz. Fenster: nie (ihre Schwelle ist die `hasSill`-Sohlbank, - * kein Bodenanschlag). - */ - drawThresholdProfile: boolean; - /** - * Kassettentür-Blatt (Rahmen aus Stegen/Pfosten + vertiefte Felder statt - * einer glatten Platte) zeichnen: nur Türen mit `leafStyle === "kassette"`. - * Fenster: nie. - */ - panelled: boolean; - /** Kassetten-Raster horizontal/vertikal (nur bei {@link panelled} relevant). */ - panelCols: number; - panelRows: number; - /** Eckverbindung von Blend- und Flügelrahmen (s. `WindowType.frameCornerJoin`). */ - cornerJoin: FrameCornerJoin; -} - -function resolveOpeningFrame(project: Project, wall: Wall, op: Opening): OpeningFrameParams | null { - const wallThickness = wallThicknessSafe(project, wall); - const halfThickness = wallThickness / 2; - if (op.kind === "door") { - const dt = getDoorType(project, op); - if (!dt) return null; - const acrossWallDepth = resolveAcrossWallDepth(dt.frameDepth, wallThickness); - const { nMin, nMax } = resolveFrameNormalRange( - halfThickness, - acrossWallDepth, - dt.insetFromFace ?? 0, - dt.insetFace ?? "aussen", - ); - return { - cornerJoin: dt.frameCornerJoin ?? "vertikal", - frameWidth: dt.frameWidth ?? DEFAULT_FRAME_WIDTH, - acrossWallDepth, - nMin, - nMax, - transomHeight: Math.max(0, dt.transomHeight ?? 0), - hasSill: dt.threshold === true, - // Zweiflüglige Tür ⇒ 2 Flügel = ein mittiger Anschlagpfosten (Stulp) im 3D. - wingCount: Math.max(1, Math.round(dt.leafCount ?? 1)), - mullionRows: 1, - mullionCols: 1, - glazed: dt.leafStyle === "glas", - glazingPanes: 1, - // Teilverglasung: glazingRatio (Glasanteil oben) bei Glasblatt; sonst voll. - glazedFraction: Math.max(0.05, Math.min(1, dt.glazingRatio ?? 1)), - sashes: [], - halfThickness, - drawSill: false, - drawInteriorSill: false, - // Zarge umgreift die Wand (Bekleidung auf beiden Flächen); Blockrahmen bleibt bündig. - zargeCladding: (dt.frameKind ?? "zarge") === "zarge", - drawThresholdProfile: dt.threshold === true, - panelled: dt.leafStyle === "kassette", - panelCols: Math.max(1, Math.round(dt.panelCols ?? 2)), - panelRows: Math.max(1, Math.round(dt.panelRows ?? 3)), - }; - } - const wt = getWindowType(project, op); - if (!wt) return null; - const acrossWallDepth = resolveAcrossWallDepth(wt.frameDepth, wallThickness); - const { nMin, nMax } = resolveFrameNormalRange( - halfThickness, - acrossWallDepth, - wt.insetFromFace ?? 0, - wt.insetFace ?? "aussen", - ); - // Flügeltabelle: explizite `wt.sashes` gewinnen; sonst gleichmäßig aus dem - // effektiven Flügelzahl-Wert (Instanz-Override `op.wingCount` vor Typ-Default). - // wingCount wird DARAUS abgeleitet, damit Mittelpfosten (wingCount−1) und - // Flügelrahmen (je Flügel) konsistent bleiben. - let sashes = wt.sashes && wt.sashes.length > 0 ? wt.sashes : undefined; - if (!sashes) { - const n = Math.max(1, Math.round(op.wingCount ?? wt.wingCount ?? 1)); - const opening = wt.kind === "fest" ? "fest" : wt.kind; - sashes = Array.from({ length: n }, (_, i) => ({ - kind: "fluegel" as const, - autoWidth: true, - opening, - hingeSide: (i % 2 === 0 ? "left" : "right") as "left" | "right", - })); - } - const wingCount = Math.max(1, sashes.filter((s) => s.kind === "fluegel").length); - return { - cornerJoin: wt.frameCornerJoin ?? "vertikal", - frameWidth: wt.frameWidth ?? DEFAULT_FRAME_WIDTH, - acrossWallDepth, - nMin, - nMax, - transomHeight: Math.max(0, wt.transomHeight ?? 0), - hasSill: true, - wingCount, - mullionRows: Math.max(1, Math.round(wt.mullionRows ?? 1)), - mullionCols: Math.max(1, Math.round(wt.mullionCols ?? 1)), - glazed: true, - glazingPanes: glazingPanesOf(wt), - glazedFraction: 1, - sashes, - halfThickness, - // Fensterbank zeichnen, ausser explizit "keine"/"innen" (fehlt ⇒ zeichnen). - drawSill: wt.sillBoard !== "keine" && wt.sillBoard !== "innen", - // Innen-Fensterbank nur bei explizit "innen"/"beide". - drawInteriorSill: wt.sillBoard === "innen" || wt.sillBoard === "beide", - zargeCladding: false, - drawThresholdProfile: false, - panelled: false, - panelCols: 1, - panelRows: 1, - }; -} - -/** - * Rahmen-/Sprossen-Riegel EINER Öffnung: Pfosten (links/rechts, volle - * Öffnungshöhe), Sturz (oben), Schwelle (nur wenn `params.hasSill`), optional - * ein Kämpfer-Riegel (Oberlicht-Trennung, `transomHeight>0`) sowie die - * Flügel-Mittelpfosten (`wingCount−1`, vertikal) und Kämpfer-Zeilen - * (`mullionRows−1`, horizontal) im Flügel-Bereich zwischen Schwelle/Sturz - * bzw. Schwelle/Kämpfer. Alle Rahmen-Riegel in {@link FRAME_RGB}. - * - * DetailLevel-Staffelung (VW-Detailgrad „fein" als Referenz): - * • „grob" — wird gar nicht aufgerufen (s. {@link emitOpeningFrames}). - * • „mittel"— Blendrahmen + Oberlicht-Kämpfer + Flügelrahmen (verschachtelt) + - * Fensterbank/Zargen-Umgriff, aber KEINE Sprossen und KEINE SIA-Symbole. - * • „fein" — zusätzlich Flügel-Mittelpfosten + Kämpfer-Zeilen (Sprossen) und - * die SIA-Öffnungssymbole (`openingPlaneBox`) auf dem Glas. - */ -function frameMeshesForOpening( - wall: Wall, - iv: { from: number; to: number }, - vert: { zBottom: number; zTop: number }, - params: OpeningFrameParams, - detail: DetailLevel = "fein", -): RMesh[] { - const out: RMesh[] = []; - const fine = detail === "fein"; - const medium = detail === "mittel"; - const sashesOn = fine || medium; // Flügelrahmen: mittel + fein - const detailBodies = fine || medium; // Bank + Zargen-Umgriff: mittel + fein - const fw = params.frameWidth; - // Generischer Riegel mit frei wählbarem Quer-Band [nA,nB] und Farbe. - const pushC = ( - from: number, - to: number, - zBottom: number, - zTop: number, - nA: number, - nB: number, - color: RRgb, - ): void => { - const mesh = openingAxisBox(wall, from, to, zBottom, zTop, nA, nB, color); - if (mesh) out.push(mesh); - }; - // Blendrahmen-Riegel (volles Rahmen-Quer-Band nMin..nMax, Rahmenfarbe). - const push = (from: number, to: number, zBottom: number, zTop: number): void => - pushC(from, to, zBottom, zTop, params.nMin, params.nMax, FRAME_RGB); - // Blendrahmen-Ring: Pfosten (Laibungsseiten), Sturz und — Fenster immer, Tür - // nur mit Bodenanschlag (threshold) — Schwelle; Eckstoss je `cornerJoin`. - for (const q of frameRingQuads(iv.from, iv.to, vert.zBottom, vert.zTop, fw, params.cornerJoin, params.hasSill)) { - const mesh = openingPlaneQuad(wall, q, params.nMin, params.nMax, FRAME_RGB); - if (mesh) out.push(mesh); - } - // Echtes Schwellenprofil (Tür, `threshold`): eine dünne, farblich abgesetzte - // Leiste ÜBER DIE GANZE WANDDICKE am Fussboden (nicht nur die Rahmentiefe - // wie der Blendrahmen-Riegel oben) — analog zur Fensterbank-Leiste - // (SILL_RGB statt FRAME_RGB), zeigt den realen Bodenanschlag (Stein/Metall- - // Streifen) statt eines rahmenfarbenen Riegels. Zusätzlich zum bestehenden - // Riegel, nicht dessen Ersatz (der bleibt für die Flügel-/Blatt-Z-Basis unten). - if (detailBodies && params.drawThresholdProfile) { - const stripH = 0.02; // Schwellen-Dicke - pushC( - iv.from + fw, - iv.to - fw, - vert.zBottom, - vert.zBottom + stripH, - -params.halfThickness, - params.halfThickness, - SILL_RGB, - ); - } - - // Flügel-/Sash-Bereich zwischen Schwelle und Sturz, ggf. durch den Kämpfer - // (Oberlicht-Trennung) oben beschnitten. - const sashFrom = iv.from + fw; - const sashTo = iv.to - fw; - const sashBottom = vert.zBottom + (params.hasSill ? fw : 0); - let sashTop = vert.zTop - fw; - if (params.transomHeight > EPS) { - const splitZ = clampRange(vert.zTop - params.transomHeight, sashBottom, sashTop); - push(sashFrom, sashTo, splitZ - fw / 2, splitZ + fw / 2); // Kämpfer-Riegel - sashTop = splitZ - fw / 2; - } - // Flügel-Mittelpfosten + Kämpfer-Zeilen (Sprossen) nur bei FEINEM Detailgrad — - // bei „mittel" bleibt es beim reinen Rahmen (+ Oberlicht-Kämpfer oben). - if (fine) { - // Senkrechte Teiler (Flügel-Mittelpfosten + Sprossen-Spalten) laufen durch; - // die waagrechten Kämpfer-Zeilen werden dazwischen unterbrochen, damit sich - // die Profile an den Kreuzungen nicht überlappen. Gleiche Lage nur einmal. - const posts: number[] = []; - const addPosts = (count: number): void => { - if (count <= 1 || sashTo - sashFrom <= EPS) return; - const cell = (sashTo - sashFrom) / count; - for (let i = 1; i < count; i++) { - const center = sashFrom + i * cell; - if (!posts.some((c) => Math.abs(c - center) < 1e-4)) posts.push(center); - } - }; - addPosts(params.wingCount); - addPosts(params.mullionCols); - posts.sort((x, y) => x - y); - for (const center of posts) push(center - fw / 2, center + fw / 2, sashBottom, sashTop); - // Kämpfer-Zeilen (horizontal, mullionRows−1) im Sash-Bereich. - if (params.mullionRows > 1 && sashTop - sashBottom > EPS) { - const cell = (sashTop - sashBottom) / params.mullionRows; - for (let i = 1; i < params.mullionRows; i++) { - const center = sashBottom + i * cell; - let from = sashFrom; - for (const post of [...posts, sashTo + fw / 2]) { - const to = Math.min(sashTo, post - fw / 2); - if (to - from > EPS) push(from, to, center - fw / 2, center + fw / 2); - from = post + fw / 2; - } - } - } - } - // Flügelrahmen je ÖFFENBAREM Flügel: ein eigener Rahmen-Riegel-Ring (links/ - // rechts/oben/unten), der DIREKT am Blendrahmen ansetzt (kein Spalt — sonst - // schiene die Vollfeld-Glasscheibe als Streifen zwischen Blend- und Flügel- - // rahmen durch). Die Schachtelung Blendrahmen → Flügelrahmen → Glas liest sich - // über die Tiefe: der Flügelrahmen sitzt in einem EIGENEN, leicht ZURÜCK- - // GESETZTEN und flacheren Quer-Band (`sashBackN..sashFrontN`) hinter der - // Blendrahmen-Vorderkante — eine plastische Stufe nach innen (VW „fein"), - // ohne vor die Fassade auszukragen. Zusätzlich (nur „fein") die SIA-Öffnungs- - // symbole auf dem Glas. Feste Flügel bekommen weder Flügelrahmen noch Symbol. - if (sashesOn && params.sashes.length > 0 && sashTo - sashFrom > EPS && sashTop - sashBottom > EPS) { - const segs = resolveSashSpans(params.sashes, sashFrom, sashTo); - const sfw = fw * 0.7; - // Verschachteltes Flügelrahmen-Band: ~5 mm HINTER der Blendrahmen-Vorderkante - // (nMax = Aussenseite) und nur ~50 mm tief — abgesetzte Stufe nach innen, - // die Glas-Vorderkante (nMax − 0.02, Falzmass) liegt INNERHALB dieses Bands. - const sashFrontN = params.nMax - 0.005; - const sashBackN = Math.max(params.nMin, params.nMax - 0.055); - // Glas-Vorderkante (s. glassPanesForOpening: n1 = nMax − 0.02); die Symbole - // liegen als ~2.5 mm dünne dunkle Prismen KNAPP davor (weiter aussen). - const glassFrontN = params.nMax - 0.02; - const symBackN = glassFrontN; - const symFrontN = glassFrontN + 0.003; - const pushSymbol = (u0: number, h0: number, u1: number, h1: number): void => { - const mesh = openingPlaneBox(wall, u0, h0, u1, h1, SYMBOL_HALF_WIDTH, symFrontN, symBackN, SYMBOL_RGB); - if (mesh) out.push(mesh); - }; - for (const seg of segs) { - const s = seg.sash; - if (s.kind !== "fluegel" || !s.opening || s.opening === "fest") continue; - // Bündig am Blendrahmen/Segmentrand ansetzen — die Stufe kommt aus der - // Tiefe (sashBackN..sashFrontN), nicht aus einem sichtbaren Glas-Spalt. - const cf = seg.from; - const ct = seg.to; - const bz = sashBottom; - const tz = sashTop; - if (ct - cf <= EPS || tz - bz <= EPS) continue; - // Flügelrahmen-Ring (Holme + Riegel) ohne Überlappung an den Ecken — - // vorher liefen Holme UND Riegel über die volle Länge (doppelte Kanten). - for (const q of frameRingQuads(cf, ct, bz, tz, sfw, params.cornerJoin, true)) { - const mesh = openingPlaneQuad(wall, q, sashBackN, sashFrontN, FRAME_RGB); - if (mesh) out.push(mesh); - } - // SIA-Öffnungssymbole (nur „fein") auf dem Glasfeld INNERHALB des Flügel- - // rahmens — exakt wie in der 2D-Ansicht (s. toElevation): Dreh = V mit - // Spitze am Bandseiten-Mittel des Glasfelds, Kipp = V mit Spitze oben Mitte. - if (!fine) continue; - const gA = cf + sfw; - const gB = ct - sfw; - const gbz = bz + sfw; - const gtz = tz - sfw; - if (gB - gA <= EPS || gtz - gbz <= EPS) continue; - const kind = s.opening; - if (kind === "dreh" || kind === "drehkipp") { - const hingeLeft = (s.hingeSide ?? "left") === "left"; - const apexU = hingeLeft ? gA : gB; - const apexH = (gbz + gtz) / 2; - const farU = hingeLeft ? gB : gA; - pushSymbol(farU, gbz, apexU, apexH); - pushSymbol(farU, gtz, apexU, apexH); - } - if (kind === "kipp" || kind === "drehkipp") { - const apexU = (gA + gB) / 2; - pushSymbol(gA, gbz, apexU, gtz); - pushSymbol(gB, gbz, apexU, gtz); - } - if (kind === "schiebe") { - // Schiebe: horizontaler Pfeil in Laufrichtung (Griff links ⇒ nach rechts). - const zc = (gbz + gtz) / 2; - const toRight = (s.hingeSide ?? "left") === "left"; - const tail = toRight ? gA : gB; - const head = toRight ? gB : gA; - const barb = (head - tail) * 0.22; - pushSymbol(tail, zc, head, zc); // Schaft - pushSymbol(head - barb, gbz + (gtz - gbz) * 0.32, head, zc); // obere Spitze - pushSymbol(head - barb, gbz + (gtz - gbz) * 0.68, head, zc); // untere Spitze - } - } - } - - // Fensterbank (Sims, VW „fein"/„mittel"): Bank-Quader unter der Öffnung, - // seitlich ~3 cm überstehend, nach aussen (Wand-Aussenfläche +halfThickness) - // auskragend, mit einer zweiten, dünneren Tropfkanten-Stufe an der Aussenkante - // darunter. Nur Fenster mit `params.drawSill` (sillBoard ≠ "keine"/"innen"). - if (detailBodies && params.drawSill) { - const ov = 0.03; // seitlicher Überstand je Seite - const proj = 0.04; // Auskragung nach aussen (vor die Wandfläche) - const under = 0.02; // Einbindung unter den Rahmen (in den Reveal) - const bankH = 0.04; // Bankdicke - const dripH = 0.02; // Höhe der Tropfkanten-Stufe - const dripW = 0.02; // Tiefe der Tropfkante an der Aussenkante - const outerN = params.halfThickness; // Wand-Aussenfläche - const bankTop = vert.zBottom; - const bankBottom = bankTop - bankH; - // Bank - pushC(iv.from - ov, iv.to + ov, bankBottom, bankTop, outerN - under, outerN + proj, SILL_RGB); - // Tropfkante (dünnere Stufe darunter, an der Aussenkante) - pushC(iv.from - ov, iv.to + ov, bankBottom - dripH, bankBottom, outerN + proj - dripW, outerN + proj, SILL_RGB); - } - - // Innen-Fensterbank (Ablage, VW „fein"/„mittel"): wie die Aussenbank - // gespiegelt auf die Wand-INNENfläche, aber ohne Tropfkante (reine - // Innenausbau-Ablage, keine Witterungskante) — `params.drawInteriorSill` - // (sillBoard "innen"/"beide"). - if (detailBodies && params.drawInteriorSill) { - const ov = 0.03; - const proj = 0.04; - const under = 0.02; - const bankH = 0.04; - const innerN = -params.halfThickness; // Wand-Innenfläche - const bankTop = vert.zBottom; - const bankBottom = bankTop - bankH; - pushC(iv.from - ov, iv.to + ov, bankBottom, bankTop, innerN - proj, innerN + under, SILL_RGB); - } - - // Tür-Zarge mit Umgriff (VW): die Zarge umgreift die Wand — eine schmale - // Bekleidungs-Platte VOR beiden Wandflächen, als Ring (Pfosten links/rechts + - // Sturz) rund um die Öffnung, ~1.3 cm vor die Fläche vorstehend. Nur - // `frameKind === "zarge"`; Blockrahmen bleibt bündig (params.zargeCladding false). - if (detailBodies && params.zargeCladding) { - const proud = 0.013; // Vorstand vor die Wandfläche - const ext = 0.02; // Überstand auf die Wandfläche (über die Laibungskante hinaus) - const casW = fw; // Bekleidungsbreite (= Rahmenprofil) - for (const sign of [1, -1] as const) { - const faceN = sign * params.halfThickness; - const nA = faceN; - const nB = faceN + sign * proud; - pushC(iv.from - ext, iv.from + casW, vert.zBottom, vert.zTop + ext, nA, nB, FRAME_RGB); // Pfosten links - pushC(iv.to - casW, iv.to + ext, vert.zBottom, vert.zTop + ext, nA, nB, FRAME_RGB); // Pfosten rechts - pushC(iv.from - ext, iv.to + ext, vert.zTop - casW, vert.zTop + ext, nA, nB, FRAME_RGB); // Sturz - } - } - return out; -} - -/** - * Löst die Flügeleinteilung auf das konkrete Achsintervall `[from,to]` (Meter) - * auf — feste Breiten (`kind:"pfosten"`/`autoWidth:false`) exakt, der Rest - * gleichmäßig auf die Restbreite. Pendant zu `sashSegments` in `opening.ts` - * (2D), aber direkt in Öffnungs-Achskoordinaten (3D). - */ -function resolveSashSpans( - sashes: SashDef[], - from: number, - to: number, -): { sash: SashDef; from: number; to: number }[] { - const width = Math.max(0, to - from); - let fixedSum = 0; - let autoCount = 0; - for (const s of sashes) { - if (s.kind === "pfosten") fixedSum += Math.max(0, s.postWidth ?? 0.06); - else if (s.autoWidth === false) fixedSum += Math.max(0, s.width ?? 0); - else autoCount++; - } - const autoW = autoCount > 0 ? Math.max(0, (width - fixedSum) / autoCount) : 0; - const out: { sash: SashDef; from: number; to: number }[] = []; - let cursor = from; - for (const s of sashes) { - const w = - s.kind === "pfosten" - ? Math.max(0, s.postWidth ?? 0.06) - : s.autoWidth === false - ? Math.max(0, s.width ?? 0) - : autoW; - out.push({ sash: s, from: cursor, to: cursor + w }); - cursor += w; - } - return out; -} - -/** Luftraum zwischen zwei Scheiben einer Mehrfachverglasung (Meter, informativ). */ -const GLASS_PANE_GAP = 0.006; - -/** - * Glasscheibe(n) EINER typisierten Öffnung (Fenster immer, Tür nur bei - * `params.glazed`): je Z-Band (Hauptfeld zwischen Schwelle und Sturz bzw. - * Kämpfer, plus — bei `transomHeight>0` — ein zweites Oberlicht-Band) werden - * `params.glazingPanes` dünne, in Wandrichtung (quer zur Wand, n-Achse) leicht - * versetzte Scheiben mit Luftraum dazwischen erzeugt (Isolierverglasung: - * 1 = Einfach-, 2 = Zweifach-, 3 = Dreifachverglasung). Bei `glazingPanes: 1` - * (Alt-Verhalten/Default) entsteht exakt EINE Scheibe an derselben Position wie - * bisher. Die Sprossen/Mittelpfosten aus {@link frameMeshesForOpening} liegen - * VOR diesen Scheiben (keine Pro-Feld-Aufteilung — bewusst einfach gehalten). - */ -function glassPanesForOpening( - wall: Wall, - iv: { from: number; to: number }, - vert: { zBottom: number; zTop: number }, - params: OpeningFrameParams, -): RMesh[] { - const out: RMesh[] = []; - const fw = params.frameWidth; - const sashFrom = iv.from + fw; - const sashTo = iv.to - fw; - const sashBottom = vert.zBottom + (params.hasSill ? fw : 0); - const sashTopFull = vert.zTop - fw; - // Die Scheibe(n) sitzen als DÜNNE Tafeln NAHE der Aussenfläche (nMax = +n- - // Seite, s. resolveFrameNormalRange) — mittig tief im Reveal wirkte das - // schwach/kaum sichtbar. Direkt hinter der Aussenkante (Falzmass ~2 cm, s. - // Fensterbau-Recherche) liest sich das Fenster klar, die Laibung/Reveal- - // Tiefe zeigt nach innen. Bei mehreren Scheiben rücken die weiteren mit - // `GLASS_PANE_GAP` Luftraum dazwischen weiter nach innen (Richtung `nMin`). - const glassThick = GLASS_HALF_THICK * 2; - const panes = Math.max(1, Math.min(3, Math.round(params.glazingPanes))); - const push = (zBottom: number, zTop: number): void => { - let n1 = params.nMax - 0.02; - for (let p = 0; p < panes; p++) { - const n0 = Math.max(params.nMin, n1 - glassThick); - if (n1 - n0 <= EPS) break; - const mesh = openingAxisBox(wall, sashFrom, sashTo, zBottom, zTop, n0, n1, GLASS_RGB); - if (mesh) out.push(mesh); - n1 = n0 - GLASS_PANE_GAP; - if (n1 <= params.nMin) break; - } - }; - // Teilverglasung (Türen mit glazingRatio < 1): das HAUPTFELD ist nur im oberen - // `glazedFraction`-Anteil Glas; darunter bleibt ein blindes Blattfeld. Von der - // OBERKANTE des Hauptbands gemessen. Fenster: glazedFraction = 1 (voll). - const frac = Math.max(0.05, Math.min(1, params.glazedFraction)); - const glazedBottom = (bBottom: number, bTop: number) => - bTop - frac * (bTop - bBottom); - if (params.transomHeight > EPS) { - const splitZ = clampRange(vert.zTop - params.transomHeight, sashBottom, sashTopFull); - const mainTop = splitZ - fw / 2; - if (params.glazed) push(glazedBottom(sashBottom, mainTop), mainTop); // Hauptglas (ggf. nur oben). - push(splitZ + fw / 2, sashTopFull); // Oberlicht-Scheibe (immer voll, auch Vollblatt-Tür). - } else if (params.glazed) { - push(glazedBottom(sashBottom, sashTopFull), sashTopFull); - } - return out; -} - -/** - * Türblatt EINER typisierten Tür als Füllung im Hauptfeld (zwischen den - * Rahmen-Pfosten, über Schwelle bis Sturz bzw. Kämpfer): Vollblatt - * (`leafStyle` ∈ {"glatt","kassette"}) füllt das ganze Feld, Teilverglasung - * (`glazingRatio` < 1 bei `leafStyle: "glas"`) nur den blinden UNTEREN Rest - * unter dem Glasanteil (Anteil von OBEN gemessen, s. {@link - * glassPanesForOpening}). Bei `leafStyle === "kassette"` ist das Feld selbst - * kein glatter Quader, sondern ein Rahmen-Raster mit vertieften Feldern (s. - * {@link kassettePanels}). Das Blatt liegt mittig um die Glasebene - * (nMax − 0.03), ~4 cm dick ({@link DOOR_LEAF_THICK}), in - * {@link DOOR_LEAF_RGB} — damit Türen im 3D als Türen lesbar sind statt als - * offene Löcher mit Rahmen. Fenster: nie (glazedFraction = 1 ⇒ kein Blatt). - */ -function doorLeafPanels( - wall: Wall, - iv: { from: number; to: number }, - vert: { zBottom: number; zTop: number }, - params: OpeningFrameParams, -): RMesh[] { - const out: RMesh[] = []; - const fw = params.frameWidth; - const leafFrom = iv.from + fw; - const leafTo = iv.to - fw; - const leafBottom = vert.zBottom + (params.hasSill ? fw : 0); - let fieldTop = vert.zTop - fw; - if (params.transomHeight > EPS) { - const splitZ = clampRange(vert.zTop - params.transomHeight, leafBottom, fieldTop); - fieldTop = splitZ - fw / 2; // Hauptfeld endet am Kämpfer, Oberlicht bleibt Glas. - } - // Blinder Blattanteil: alles unterhalb des (von oben gemessenen) Glasanteils. - const frac = params.glazed ? Math.max(0.05, Math.min(1, params.glazedFraction)) : 0; - const leafTop = fieldTop - frac * (fieldTop - leafBottom); - if (leafTop - leafBottom <= EPS || leafTo - leafFrom <= EPS) return out; - const n1 = params.nMax - 0.02 + DOOR_LEAF_THICK / 2; - const n0 = Math.max(params.nMin, n1 - DOOR_LEAF_THICK); - if (params.panelled) { - return kassettePanels(wall, leafFrom, leafTo, leafBottom, leafTop, n0, n1, params); - } - const mesh = openingAxisBox(wall, leafFrom, leafTo, leafBottom, leafTop, n0, n1, DOOR_LEAF_RGB); - if (mesh) out.push(mesh); - return out; -} - -/** Stegbreite der Kassetten-Füllstäbe (Rahmen ums Feld + Trennstege), Meter. */ -const PANEL_STILE_WIDTH = 0.06; -/** - * Vertiefung der Kassetten-Füllung gegenüber den Stegen (je Seite, Meter) — - * dieselbe „Tiefenstufe"-Technik wie die Flügelrahmen-Verschachtelung bei - * Fenstern ({@link frameMeshesForOpening}s `sashFrontN`/`sashBackN`): ein - * zweiter, dünnerer Quader mittig im Blatt sitzt um {@link PANEL_RECESS} - * zurückversetzt ⇒ wirkt von beiden Seiten vertieft. - */ -const PANEL_RECESS = 0.012; - -/** - * Kassettentür-Blatt (`DoorType.leafStyle === "kassette"`): statt einer - * glatten Blatt-Tafel ({@link doorLeafPanels}) ein Raster aus - * `panelRows × panelCols` Feldern — äusserer Rahmen + Trennstege in voller - * Blattdicke ({@link DOOR_LEAF_THICK}, dieselbe Technik wie die Sprossen- - * Raster-Riegel bei Fenstern, `mullionRows`/`mullionCols` in - * {@link frameMeshesForOpening}), die Felder selbst dünner und um - * {@link PANEL_RECESS} zurückversetzt (vertiefter Kassetten-Look). Steg- und - * Feld-Quader überlappen an den Rändern geringfügig (das vertiefte Feld - * verschwindet dort einfach hinter dem dickeren Steg) — bewusst in Kauf - * genommen statt pixelgenauer Spaltberechnung, rein dekorative Geometrie - * ohne Boolean-Anspruch. - */ -function kassettePanels( - wall: Wall, - leafFrom: number, - leafTo: number, - leafBottom: number, - leafTop: number, - n0: number, - n1: number, - params: OpeningFrameParams, -): RMesh[] { - const out: RMesh[] = []; - const push = (from: number, to: number, zB: number, zT: number, a: number, b: number) => { - const m = openingAxisBox(wall, from, to, zB, zT, a, b, DOOR_LEAF_RGB); - if (m) out.push(m); - }; - const cols = params.panelCols; - const rows = params.panelRows; - const sw = Math.min( - PANEL_STILE_WIDTH, - (leafTo - leafFrom) / (2 * cols), - (leafTop - leafBottom) / (2 * rows), - ); - if (sw <= EPS) { - // Blatt zu schmal fürs Raster (Mini-Tür/Degenerat) — Fallback Vollblatt. - push(leafFrom, leafTo, leafBottom, leafTop, n0, n1); - return out; - } - // Äusserer Rahmen (Stile/Riegel) — volle Blattdicke. - push(leafFrom, leafTo, leafBottom, leafBottom + sw, n0, n1); // unterer Riegel - push(leafFrom, leafTo, leafTop - sw, leafTop, n0, n1); // oberer Riegel - push(leafFrom, leafFrom + sw, leafBottom, leafTop, n0, n1); // linker Pfosten - push(leafTo - sw, leafTo, leafBottom, leafTop, n0, n1); // rechter Pfosten - const cellW = (leafTo - leafFrom) / cols; - const cellH = (leafTop - leafBottom) / rows; - // Trennstege zwischen den Feldern — volle Blattdicke. - for (let c = 1; c < cols; c++) { - const x = leafFrom + c * cellW; - push(x - sw / 2, x + sw / 2, leafBottom, leafTop, n0, n1); - } - for (let r = 1; r < rows; r++) { - const y = leafBottom + r * cellH; - push(leafFrom, leafTo, y - sw / 2, y + sw / 2, n0, n1); - } - // Vertiefte Kassetten-Felder — dünner, mittig zurückversetzt. - const n0p = n0 + PANEL_RECESS; - const n1p = Math.max(n0p + 0.004, n1 - PANEL_RECESS); - for (let r = 0; r < rows; r++) { - for (let c = 0; c < cols; c++) { - const fx0 = leafFrom + c * cellW + sw / 2; - const fx1 = leafFrom + (c + 1) * cellW - sw / 2; - const fy0 = leafBottom + r * cellH + sw / 2; - const fy1 = leafBottom + (r + 1) * cellH - sw / 2; - if (fx1 - fx0 <= EPS || fy1 - fy0 <= EPS) continue; - push(fx0, fx1, fy0, fy1, n0p, n1p); - } - } - return out; -} - -/** - * Emittiert je Fensteröffnung eine Glasscheibe und je Türöffnung die Füllung - * (Blatt-Tafel, s. {@link doorLeafPanels}, plus Scheibe bei Glasanteil/ - * Oberlicht) als rohe Quader-Meshes — damit Fenster/Türen im 3D lesbar sind - * statt als blosse Löcher in der Wand. - * - * OHNE auflösbaren Typ (`getWindowType`/`getDoorType` liefert `undefined`, - * z. B. `Opening.typeId` fehlt): unverändertes ALT-Verhalten — EINE Vollscheibe - * über die geklemmte Öffnungs-Achse (`openingInterval`) und -Höhe - * (`openingVerticalExtent`), quer ±{@link GLASS_HALF_THICK} mittig in der - * Wand (Rückwärtskompatibilität, s. Moduldoc-Kommentar). - * - * MIT Typ: die Scheibe(n) sitzen im Flügel-Bereich INNERHALB des Rahmens (s. - * {@link glassPanesForOpening}), quer entlang des über den Schichteinzug - * bestimmten Rahmen-Versatzes (s. {@link resolveFrameNormalRange}) statt fix - * mittig — bei Oberlicht (`transomHeight>0`) kommt eine zweite Scheibe im - * Oberlicht-Band dazu. Die zugehörigen Rahmen-/Sprossen-Riegel emittiert - * separat {@link emitOpeningFrames} (eigene Farbe, eigene Funktion — leichter - * einzeln zu testen/filtern als eine gemeinsame Emission). - * - * `positions` liegen — wie bei den übrigen Meshes — in MODELL-Metern als - * flaches (x, y, z=Höhe)-Array; render3d bildet sie selbst nach world - * (x, Höhe, y) ab und rendert die Meshes doppelseitig (append_context_mesh), - * daher ist die Winding-Reihenfolge der Dreiecke unerheblich. `kind: - * "extrusion"` (NICHT "imported"!) mit gesetzter `color` ⇒ render3d zeichnet - * die Scheibe in GLASS_RGB — "extrusion" ist zugleich die Weiche gegen die - * Nord-Achsen-Negation, die `append_context_mesh` NUR für `"imported"`/ - * `"terrain"` anwendet (echte, unabhängige Import-Rohdaten); Öffnungs-Boxen - * entstehen dagegen orientierungserhaltend aus der Wandachse wie eine Wand - * selbst (Fund 2026-09-27: mit `kind:"imported"` wäre die Scheibe/der Rahmen - * für jede Wand ausserhalb y=0 an der falschen Stelle gerendert worden — - * s. PENDENZEN.md). - */ -export function emitOpeningGlass(project: Project): RMesh[] { - const out: RMesh[] = []; - for (const wall of project.walls) { - for (const op of openingsOfWall(project, wall.id)) { - const iv = openingInterval(wall, op); - if (!iv) continue; - const vert = openingVerticalExtent(project, wall, op); - if (vert.zTop - vert.zBottom <= EPS) continue; - if (op.kind === "window") { - const params = resolveOpeningFrame(project, wall, op); - if (!params) { - // Kein Typ auflösbar -> Alt-Verhalten (fixe Vollscheibe, mittig). - const mesh = openingAxisBox( - wall, - iv.from, - iv.to, - vert.zBottom, - vert.zTop, - -GLASS_HALF_THICK, - GLASS_HALF_THICK, - GLASS_RGB, - ); - if (mesh) out.push(mesh); - continue; - } - out.push(...glassPanesForOpening(wall, iv, vert, params)); - } else { - // Tür: Blatt-Tafel (Vollblatt bzw. blinder Rest unter der Teilverglasung) - // + Scheibe(n) für Glasanteil/Oberlicht. Ohne auflösbaren Typ: nichts - // (Alt-Verhalten: offenes Loch). - const params = resolveOpeningFrame(project, wall, op); - if (params) { - out.push(...doorLeafPanels(wall, iv, vert, params)); - out.push(...glassPanesForOpening(wall, iv, vert, params)); - } - } - } - } - return out; -} - -/** - * Emittiert je Öffnung MIT auflösbarem Typ (`getDoorType`/`getWindowType`) die - * Rahmen-/Sprossen-Riegel (Zarge/Blendrahmen, Sturz, Schwelle, Kämpfer, - * Mittelpfosten — s. {@link frameMeshesForOpening}) als rohe Quader-Meshes in - * {@link FRAME_RGB}. Öffnungen OHNE auflösbaren Typ (`typeId` fehlt/verwaist) - * bekommen KEINEN Rahmen — exakt das Alt-Verhalten vor der Typ-Vertiefung - * (Rückwärtskompatibilität). - */ -export function emitOpeningFrames(project: Project, detail: DetailLevel = "fein"): RMesh[] { - // Grob: keine Rahmen/Sprossen — die Öffnung bleibt Loch + Scheibe (schlank). - if (detail === "grob") return []; - const out: RMesh[] = []; - for (const wall of project.walls) { - for (const op of openingsOfWall(project, wall.id)) { - const iv = openingInterval(wall, op); - if (!iv) continue; - const vert = openingVerticalExtent(project, wall, op); - if (vert.zTop - vert.zBottom <= EPS) continue; - const params = resolveOpeningFrame(project, wall, op); - if (!params) continue; - out.push(...frameMeshesForOpening(wall, iv, vert, params, detail)); - } - } - return out; -} - -/** - * Rollladen-/Sonnenschutzkasten als 3D-Box über der Öffnung (nur Fenster mit - * `WindowType.shading.create`, nur mittel/fein). Ein heller Quader, aussen an - * der Aussenfläche (params.nMax) ansetzend und um `box.depth` nach aussen - * ragend, von der Öffnungs-OK um `box.height` nach oben. Breite = `box.width` - * (0/fehlt ⇒ Öffnungsbreite), mittig über der Öffnung. Pendant zur 2D-Kontur - * (`window-shading` in generatePlan/openings.ts). - */ -export function emitOpeningShading(project: Project, detail: DetailLevel = "fein"): RMesh[] { - if (detail === "grob") return []; - const out: RMesh[] = []; - for (const wall of project.walls) { - for (const op of openingsOfWall(project, wall.id)) { - if (op.kind !== "window") continue; - const wt = getWindowType(project, op); - if (!wt?.shading?.create) continue; - const iv = openingInterval(wall, op); - if (!iv) continue; - const vert = openingVerticalExtent(project, wall, op); - if (vert.zTop - vert.zBottom <= EPS) continue; - const params = resolveOpeningFrame(project, wall, op); - if (!params) continue; - const box = wt.shading.box; - const h = Math.max(0, box.height); - const d = Math.max(0, box.depth); - if (h <= EPS || d <= EPS) continue; - const span = box.width > 0 ? box.width : iv.to - iv.from; - const center = (iv.from + iv.to) / 2; - const from = center - span / 2; - const to = center + span / 2; - // Aussen an der Aussenfläche (nMax) ansetzen und um die Kastentiefe hinaus. - const nOuter = params.nMax; - const mesh = openingAxisBox( - wall, - from, - to, - vert.zTop, - vert.zTop + h, - nOuter, - nOuter + d, - SHADING_RGB, - ); - if (mesh) out.push(mesh); - } + const r = new FlatReader(core().frame_ring_quads_flat(from, to, zB, zT, w, JOIN_CODE[join] ?? 0, bottom)); + const out: Array<[[number, number], [number, number], [number, number], [number, number]]> = []; + for (let n = r.count(); n > 0; n--) { + out.push([ + [r.num(), r.num()], + [r.num(), r.num()], + [r.num(), r.num()], + [r.num(), r.num()], + ]); } return out; } diff --git a/src/plan/wallMeshCut.ts b/src/plan/wallMeshCut.ts index d04563f9..aaf03a7e 100644 --- a/src/plan/wallMeshCut.ts +++ b/src/plan/wallMeshCut.ts @@ -1,35 +1,19 @@ -// Gemeinsamer Wand-Mesh-Generator MIT echtem Loch-Ausschnitt (Fenster/Türen). +// Wand-Mesh MIT echtem Loch-Ausschnitt (Fenster/Türen) für die Datei-Exporte +// (STL/OBJ/IFC): aus einem RWall-Band (Achse `start→end`, `thickness`, +// `baseElevation`, `height` + rechteckige `holes`) entsteht das Dreiecks-Mesh mit +// ausgestanzten Öffnungen inkl. Laibungen — so sehen die Exporte aus wie die +// 3D-Ansicht. Gerechnet wird im Rust-Kern (`src-tauri/core/src/wall_mesh_cut.rs`, +// dieselbe Zerlegung wie `render3d/src/mesh.rs::extrude_layer_segment_with_holes`, +// ohne Gehrung: die Bänder sind an den Enden schon gekürzt). Hier bleibt die +// flache Übergabe. // -// Portierung der Rust-Referenz `render3d/src/mesh.rs::extrude_layer_segment_ -// with_holes` nach TS: aus EINEM RWall-Band (Achse `start→end`, `thickness`, -// `baseElevation`, `height` + rechteckige `holes`) wird das Dreiecks-Mesh -// erzeugt, das die Öffnungen ECHT ausschneidet (statt der vollen Box). Damit -// sehen die Datei-Exporte (STL/OBJ/IFC) genauso aus wie die 3D-Ansicht: die -// Löcher sind sichtbar ausgestanzt, inklusive der Laibungs-/Jamb-Flächen. -// -// WICHTIG — WARUM KEINE GEHRUNG HIER: Die RWall-Bänder aus -// `toWalls3d.ts::pickGeometry` sind bereits an ihren Achsenden auf die -// Gehrungs-/Anschluss-Schnittlinie GEKÜRZT (die Box endet aber achsparallel, -// keine gekippte Stirnfläche — siehe `bandCutDistance` in toWalls3d.ts). Die -// Ecken-Verschneidung (Joins) steckt also schon in `start`/`end` jedes Bandes. -// Deshalb entfällt hier die `start_cut`/`end_cut`-Gehrungslogik der Rust-Funktion -// (im Rust-Pfad wird sie nur gebraucht, weil dort EIN ungekürztes Band mit -// Gehrungslinien extrudiert wird). Das Ergebnis: dieselbe Rechteck-Zerlegung der -// Langseiten + dieselben 4 Laibungsquads je Loch wie in Rust, nur mit rechten -// (ungekippten) Stirnkappen — exakt die Geometrie, die der Viewer schon zeigt. -// -// ACHSEN: Modell (x, y) → Welt (x, Höhe, y), Y-UP — identisch zu exportMesh.ts / -// selectionHighlightLines / dem 3D-Viewer. Ein Weltvertex (vx,vy,vz) ist also -// (Modell-x, Meter-Höhe, Modell-y). +// ACHSEN: Modell (x, y) → Welt (x, Höhe, y), Y-UP — wie exportMesh.ts und der +// 3D-Viewer. +import { core } from "../engine/coreWasm"; +import { FlatWriter } from "../geometry/coreFlat"; import type { RWall } from "./toWalls3d"; -/** Rundungs-/Entartungsschwelle (1e-4 m), 1:1 wie `openings::MIN_SPAN` in Rust. */ -const MIN_SPAN = 1e-4; - -/** Ein Weltpunkt (x, Höhe, y). */ -type V3 = [number, number, number]; - /** * Ein Dreiecks-Mesh in LOKALEN (0-basierten) Indizes: `positions` flach * (x,y,z, …) in Weltmetern (Y-up), `indices` je 3 = ein Dreieck. @@ -39,54 +23,10 @@ export interface CutMesh { indices: number[]; } -/** - * Aussen-Normale eines planaren, CCW-von-aussen georderten Quads über die ersten - * drei Ecken: `normalize(cross(b-a, d-a))` — 1:1 wie `mesh.rs::quad_normal`. - * Nulllange Flächen liefern den Nullvektor (Aufrufer nutzt sie dann nicht). - */ -function quadNormal(a: V3, b: V3, d: V3): V3 { - const ab: V3 = [b[0] - a[0], b[1] - a[1], b[2] - a[2]]; - const ad: V3 = [d[0] - a[0], d[1] - a[1], d[2] - a[2]]; - const c: V3 = [ - ab[1] * ad[2] - ab[2] * ad[1], - ab[2] * ad[0] - ab[0] * ad[2], - ab[0] * ad[1] - ab[1] * ad[0], - ]; - const len = Math.max(Math.hypot(c[0], c[1], c[2]), 1e-9); - return [c[0] / len, c[1] / len, c[2] / len]; -} - -/** - * Hängt ein Dreieck an `mesh` an, dessen Winding an `wantNormal` ausgerichtet - * wird (robust gegen die Eck-Reihenfolge) — 1:1 wie `mesh.rs::push_tri_oriented`. - */ -function pushTriOriented(mesh: CutMesh, a: V3, b: V3, c: V3, wantNormal: V3): void { - const ab: V3 = [b[0] - a[0], b[1] - a[1], b[2] - a[2]]; - const ac: V3 = [c[0] - a[0], c[1] - a[1], c[2] - a[2]]; - const gn: V3 = [ - ab[1] * ac[2] - ab[2] * ac[1], - ab[2] * ac[0] - ab[0] * ac[2], - ab[0] * ac[1] - ab[1] * ac[0], - ]; - const dot = gn[0] * wantNormal[0] + gn[1] * wantNormal[1] + gn[2] * wantNormal[2]; - const [v0, v1, v2] = dot < 0 ? [a, c, b] : [a, b, c]; - const base = mesh.positions.length / 3; - mesh.positions.push(v0[0], v0[1], v0[2], v1[0], v1[1], v1[2], v2[0], v2[1], v2[2]); - mesh.indices.push(base, base + 1, base + 2); -} - -/** Hängt ein Quad (vier Ecken als Ring) als zwei orientierte Dreiecke an. */ -function pushQuadOriented(mesh: CutMesh, a: V3, b: V3, c: V3, d: V3, wantNormal: V3): void { - pushTriOriented(mesh, a, b, c, wantNormal); - pushTriOriented(mesh, a, c, d, wantNormal); -} - /** * Zerlegt das Rechteck `[uLo,uHi]×[zLo,zHi]` MINUS `holes` (`[u0,u1,z0,z1]`) in - * achsparallele, disjunkte SOLIDE Teilrechtecke — Koordinaten-Kompression, 1:1 - * wie `mesh.rs::solid_subrects` (jede Gitterzelle, deren Mittelpunkt in keinem - * Loch liegt, ist ein solides Teilrechteck). Exportiert für die Zerlegungs-Tests - * (gleiche Rechteck-Anzahl wie die Rust-Zerlegung). + * achsparallele, disjunkte solide Teilrechtecke (Koordinaten-Kompression wie + * `mesh.rs::solid_subrects`). */ export function solidSubrects( uLo: number, @@ -95,276 +35,64 @@ export function solidSubrects( zHi: number, holes: Array<[number, number, number, number]>, ): Array<[number, number, number, number]> { - const sortDedup = (v: number[]): number[] => { - const s = [...v].sort((a, b) => a - b); - const out: number[] = []; - for (const x of s) { - if (out.length === 0 || Math.abs(x - out[out.length - 1]) > MIN_SPAN) out.push(x); - } - return out; - }; - const usRaw = [uLo, uHi]; - const zsRaw = [zLo, zHi]; - for (const [a0, a1, hb, ht] of holes) { - usRaw.push(a0, a1); - zsRaw.push(hb, ht); - } - const us = sortDedup(usRaw); - const zs = sortDedup(zsRaw); + const flat = new Float64Array(holes.length * 4); + holes.forEach((h, i) => flat.set(h, i * 4)); + const r = core().solid_subrects_flat(uLo, uHi, zLo, zHi, flat); const out: Array<[number, number, number, number]> = []; - for (let i = 0; i < us.length - 1; i++) { - const ua = us[i]; - const ub = us[i + 1]; - if (ub - ua <= MIN_SPAN) continue; - for (let j = 0; j < zs.length - 1; j++) { - const za = zs[j]; - const zb = zs[j + 1]; - if (zb - za <= MIN_SPAN) continue; - const cu = (ua + ub) * 0.5; - const cz = (za + zb) * 0.5; - const inHole = holes.some(([a0, a1, hb, ht]) => cu > a0 && cu < a1 && cz > hb && cz < ht); - if (!inHole) out.push([ua, ub, za, zb]); - } - } + for (let i = 0; i + 4 <= r.length; i += 4) out.push([r[i], r[i + 1], r[i + 2], r[i + 3]]); return out; } /** - * Zieht die (ggf. überlappenden) `gaps` vom Intervall `[lo,hi]` ab und liefert - * die verbleibenden, sortierten, disjunkten Teilintervalle — 1:1 wie - * `mesh.rs::subtract_intervals` (für Deckel-/Boden-/Kappen-Lücken randständiger - * Löcher). - */ -function subtractIntervals(lo: number, hi: number, gaps: Array<[number, number]>): Array<[number, number]> { - const gs = gaps - .map(([a, b]): [number, number] => [Math.max(a, lo), Math.min(b, hi)]) - .filter(([a, b]) => b - a > MIN_SPAN) - .sort((p, q) => p[0] - q[0]); - const out: Array<[number, number]> = []; - let cursor = lo; - for (const [a, b] of gs) { - if (a > cursor + MIN_SPAN) out.push([cursor, a]); - cursor = Math.max(cursor, b); - } - if (hi > cursor + MIN_SPAN) out.push([cursor, hi]); - return out; -} - -/** - * Prüft, ob ein Mesh eine GESCHLOSSENE, KONSISTENT NACH AUSSEN gewundene Fläche - * ist (bounds ein Volumen ohne Löcher) — über das Gauss-/Divergenz-Kriterium - * statt eines Kanten-Manifold-Zählers: - * • ∮ n dA = 0 ⟺ Σ (v1−v0)×(v2−v0) = 0 über alle Dreiecke (jede offene - * Lücke ODER jedes falsch gewundene/fehlende Dreieck verletzt die Summe). - * • signiertes Volumen Σ v0·(v1×v2)/6 > 0 ⟺ Normalen zeigen NACH AUSSEN. - * - * BEWUSST NICHT der naive „jede ungerichtete Kante genau 2×"-Manifold-Check: - * dieses Mesh nutzt (wie die Rust-Referenz) VOLLE Deckel/Boden-Streifen über die - * ganze Breite, während die Langseiten an den Loch-Spalten unterteilt sind — das - * erzeugt legitime T-Stösse (eine lange Kante trifft mehrere kurze), die KEINE - * echten Lücken sind. Der naive Kantenzähler würde diese korrekte, wasserdichte - * Geometrie fälschlich als „offen" melden; das Gauss-Kriterium ist T-Stoss-robust - * und misst genau die Eigenschaft, auf die es ankommt (dichtes Volumen + Aussen- - * Orientierung — die Ursache des „hohl/offen"-Bugs war eine invertierte Wicklung - * im IFC-Export, nicht eine fehlende Fläche). + * Ob ein Mesh eine GESCHLOSSENE, nach aussen gewundene Fläche ist — Gauss- + * Kriterium (∮ n dA = 0 und signiertes Volumen > 0) statt eines Kanten-Zählers, + * damit die legitimen T-Stösse der vollen Deckel/Boden-Streifen nicht als + * „offen" gelten. Rechnet im Kern; die Übergabe-Puffer werden wiederverwendet + * (frische Typed Arrays je Aufruf kosteten mehr als die Rechnung selbst). */ export function isWatertight(mesh: CutMesh, eps = 1e-6): boolean { const p = mesh.positions; - let ax = 0; - let ay = 0; - let az = 0; - let vol6 = 0; - for (let t = 0; t < mesh.indices.length; t += 3) { - const i0 = mesh.indices[t] * 3; - const i1 = mesh.indices[t + 1] * 3; - const i2 = mesh.indices[t + 2] * 3; - const e1x = p[i1] - p[i0]; - const e1y = p[i1 + 1] - p[i0 + 1]; - const e1z = p[i1 + 2] - p[i0 + 2]; - const e2x = p[i2] - p[i0]; - const e2y = p[i2 + 1] - p[i0 + 1]; - const e2z = p[i2 + 2] - p[i0 + 2]; - const cx = e1y * e2z - e1z * e2y; - const cy = e1z * e2x - e1x * e2z; - const cz = e1x * e2y - e1y * e2x; - ax += cx; - ay += cy; - az += cz; - // v0 · (v1 × v2) = v0 · (e1 × e2) (die reinen v0-Terme heben sich auf). - vol6 += p[i0] * cx + p[i0 + 1] * cy + p[i0 + 2] * cz; - } - return Math.hypot(ax, ay, az) < eps && vol6 > eps; + const x = mesh.indices; + if (scratchPos.length < p.length) scratchPos = new Float64Array(p.length * 2); + if (scratchIdx.length < x.length) scratchIdx = new Uint32Array(x.length * 2); + for (let i = 0; i < p.length; i++) scratchPos[i] = p[i]; + // Ungültige Indizes (negativ, gebrochen, NaN) zeigen ins Leere ⇒ „nicht dicht". + for (let i = 0; i < x.length; i++) scratchIdx[i] = Number.isInteger(x[i]) && x[i] >= 0 && x[i] < 0xffffffff ? x[i] : 0xffffffff; + return core().is_watertight_flat(scratchPos.subarray(0, p.length), scratchIdx.subarray(0, x.length), eps); } +let scratchPos = new Float64Array(1024); +let scratchIdx = new Uint32Array(1024); + /** - * Erzeugt das Wand-Mesh EINES RWall-Bandes mit ECHTEN Loch-Ausschnitten — der - * TS-Port von `mesh.rs::extrude_layer_segment_with_holes` (ohne Gehrung, siehe - * Moduldoc). Aufbau: - * • Langseiten (+n / −n): Flächen-Rechteck MINUS der Löcher, per {@link - * solidSubrects} in Teilrechtecke zerlegt (je 2 Dreiecke). - * • Deckel (y1) / Boden (y0): voller Streifen minus der u-Intervalle rand- - * ständiger Löcher (z. B. eine Tür am Boden). - * • Stirnkappen (a=0 / a=length): volle Höhe minus z-Intervalle randständiger - * Löcher. - * • Laibungen je Loch: bis zu vier Quads (links/rechts/unten/oben), nur für die - * im Wand-Inneren liegenden Seiten. - * - * Ohne `holes` (undefined/leer) liefert das die volle Box (Regressionsfall); - * Aufrufer, die für lochlose Bänder die klassische 8-Ecken-Box wollen, prüfen - * das selbst (siehe exportMesh.ts). + * Loch-Ausschnitt-Meshes vieler Bänder in EINEM Kern-Aufruf (Reihenfolge wie + * `walls`). Aufbau je Band: Langseiten (Gitter minus Löcher), Deckel/Boden und + * Stirnkappen minus randständiger Löcher, Laibungen je Loch. Ohne Löcher die + * volle Box; entartete Bänder liefern ein leeres Mesh. */ -export function wallCutMesh(w: RWall): CutMesh { - const mesh: CutMesh = { positions: [], indices: [] }; - const [sx, sy] = w.start; - const [ex, ey] = w.end; - const dx = ex - sx; - const dy = ey - sy; - const length = Math.hypot(dx, dy); - if (length < 1e-9 || w.height <= 1e-9 || w.thickness <= 1e-9) return mesh; - const ux = dx / length; - const uy = dy / length; - // Links-Normale n = (−uy, ux) — dieselbe Konvention wie mesh.rs::left_normal. - const n: [number, number] = [-uy, ux]; - const y0 = w.baseElevation; - const y1 = w.baseElevation + w.height; - const offA = w.thickness / 2; - const offB = -w.thickness / 2; - - const off = (p: [number, number], s: number): [number, number] => [p[0] + n[0] * s, p[1] + n[1] * s]; - const axisPoint = (a: number): [number, number] => [sx + ux * a, sy + uy * a]; - // Plan-Punkt bei Achsen-Position `a`, Dicken-Versatz `offv` (keine Gehrung). - const gAt = (a: number, offv: number): [number, number] => off(axisPoint(a), offv); - const wpt = (g: [number, number], y: number): V3 => [g[0], y, g[1]]; - - // Löcher auf [0,length]×[y0,y1] klemmen, entartete verwerfen. - const hs: Array<[number, number, number, number]> = []; - for (const h of w.holes ?? []) { - const a0 = Math.max(h.from, 0); - const a1 = Math.min(h.to, length); - const zb = Math.max(h.zBottom, y0); - const zt = Math.min(h.zTop, y1); - if (a1 - a0 > MIN_SPAN && zt - zb > MIN_SPAN) hs.push([a0, a1, zb, zt]); +export function wallCutMeshes(walls: readonly RWall[]): CutMesh[] { + const w = new FlatWriter().num(walls.length); + for (const b of walls) { + const holes = b.holes ?? []; + w.num(b.start[0], b.start[1], b.end[0], b.end[1], b.thickness, b.baseElevation, b.height, holes.length); + for (const h of holes) w.num(h.from, h.to, h.zBottom, h.zTop); } - - // ── Langseiten (+n / −n): Rechteck-Gitter minus Löcher. ──────────────────── - const np: V3 = [n[0], 0, n[1]]; - const nn: V3 = [-n[0], 0, -n[1]]; - for (const [ua, ub, za, zb] of solidSubrects(0, length, y0, y1, hs)) { - pushQuadOriented( - mesh, - wpt(gAt(ua, offA), za), - wpt(gAt(ub, offA), za), - wpt(gAt(ub, offA), zb), - wpt(gAt(ua, offA), zb), - np, - ); - pushQuadOriented( - mesh, - wpt(gAt(ua, offB), za), - wpt(gAt(ub, offB), za), - wpt(gAt(ub, offB), zb), - wpt(gAt(ua, offB), zb), - nn, - ); + const buf = core().wall_cut_meshes_flat(w.done()); + const out: CutMesh[] = []; + let i = 1; + for (let k = 0; k < walls.length; k++) { + const len = i < buf.length ? buf[i++] : 0; + const positions = new Array(len); + for (let j = 0; j < len; j++) positions[j] = buf[i + j]; + i += len; + const indices = new Array(len / 3); + for (let j = 0; j < len / 3; j++) indices[j] = j; + out.push({ positions, indices }); } - - // ── Deckel (y1) / Boden (y0): voller Streifen minus randständiger Löcher. ── - const topGaps = hs.filter(([, , , zt]) => zt >= y1 - MIN_SPAN).map(([a0, a1]): [number, number] => [a0, a1]); - for (const [ua, ub] of subtractIntervals(0, length, topGaps)) { - pushQuadOriented( - mesh, - wpt(gAt(ua, offA), y1), - wpt(gAt(ub, offA), y1), - wpt(gAt(ub, offB), y1), - wpt(gAt(ua, offB), y1), - [0, 1, 0], - ); - } - const botGaps = hs.filter(([, , zb]) => zb <= y0 + MIN_SPAN).map(([a0, a1]): [number, number] => [a0, a1]); - for (const [ua, ub] of subtractIntervals(0, length, botGaps)) { - pushQuadOriented( - mesh, - wpt(gAt(ua, offA), y0), - wpt(gAt(ub, offA), y0), - wpt(gAt(ub, offB), y0), - wpt(gAt(ua, offB), y0), - [0, -1, 0], - ); - } - - // ── Stirnkappen (a=0 / a=length): volle Höhe minus randständiger Löcher. ─── - const startNormal = quadNormal(wpt(gAt(0, offB), y0), wpt(gAt(0, offA), y0), wpt(gAt(0, offB), y1)); - const startGaps = hs.filter(([a0]) => a0 <= MIN_SPAN).map(([, , zb, zt]): [number, number] => [zb, zt]); - for (const [za, zb] of subtractIntervals(y0, y1, startGaps)) { - pushQuadOriented( - mesh, - wpt(gAt(0, offB), za), - wpt(gAt(0, offA), za), - wpt(gAt(0, offA), zb), - wpt(gAt(0, offB), zb), - startNormal, - ); - } - const endNormal = quadNormal(wpt(gAt(length, offA), y0), wpt(gAt(length, offB), y0), wpt(gAt(length, offA), y1)); - const endGaps = hs.filter(([, a1]) => a1 >= length - MIN_SPAN).map(([, , zb, zt]): [number, number] => [zb, zt]); - for (const [za, zb] of subtractIntervals(y0, y1, endGaps)) { - pushQuadOriented( - mesh, - wpt(gAt(length, offA), za), - wpt(gAt(length, offB), za), - wpt(gAt(length, offB), zb), - wpt(gAt(length, offA), zb), - endNormal, - ); - } - - // ── Laibungen je Loch: nur die im Wand-Inneren liegenden Seiten. ────────── - for (const [a0, a1, zb, zt] of hs) { - // Linke Laibung (bei a0), Normale +u (in die Öffnung). - if (a0 > MIN_SPAN) { - pushQuadOriented( - mesh, - wpt(gAt(a0, offA), zb), - wpt(gAt(a0, offB), zb), - wpt(gAt(a0, offB), zt), - wpt(gAt(a0, offA), zt), - [ux, 0, uy], - ); - } - // Rechte Laibung (bei a1), Normale −u. - if (a1 < length - MIN_SPAN) { - pushQuadOriented( - mesh, - wpt(gAt(a1, offA), zb), - wpt(gAt(a1, offB), zb), - wpt(gAt(a1, offB), zt), - wpt(gAt(a1, offA), zt), - [-ux, 0, -uy], - ); - } - // Untere Laibung (bei zb = Brüstungsoberkante), Normale +Y. - if (zb > y0 + MIN_SPAN) { - pushQuadOriented( - mesh, - wpt(gAt(a0, offA), zb), - wpt(gAt(a1, offA), zb), - wpt(gAt(a1, offB), zb), - wpt(gAt(a0, offB), zb), - [0, 1, 0], - ); - } - // Obere Laibung (bei zt = Sturzunterkante), Normale −Y. - if (zt < y1 - MIN_SPAN) { - pushQuadOriented( - mesh, - wpt(gAt(a0, offA), zt), - wpt(gAt(a1, offA), zt), - wpt(gAt(a1, offB), zt), - wpt(gAt(a0, offB), zt), - [0, -1, 0], - ); - } - } - - return mesh; + return out; +} + +/** Loch-Ausschnitt-Mesh EINES Bandes (s. {@link wallCutMeshes}). */ +export function wallCutMesh(w: RWall): CutMesh { + return wallCutMeshes([w])[0]; }